Setting up Basic Node.JS Server

Hey guys, I haven’t posted in a while, but I have been learning to mess around with node js now. Been watching and reading some tutorials online, and I wanted to post something basic.

This tutorial will allow you to create a website, and pretty much allow users to go onto different pages of your site.

 

var http = require('http');
var fs = require('fs');

function send404Response(response){
    response.writeHead(404, {"Context-Type": "text/plain"});
    response.write("Bad page");
    response.end();
}
function onRequest(request, response){

    if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200, {"Context-Type": "text/html"});
        fs.createReadStream('./index.html').pipe(response);
    }
    else{
        return send404Response(response);
    }
}

http.createServer(onRequest).listen(8888);
console.log("Server is now ready");

Querying using LINQ and the Entity Framework

When using the Entity Framework and if you want to query using LINQ, this is how it is done:

Make sure to have your Context set up. My context is ListofRestaurantsContext, and my table name is List_Of_Restaurants
context.TableName.SqlQuery

Raw SQL Query: (Dangerous)


                using (var context = new ListofRestaurantsContext())
                {
                    var blogs = context.List_Of_Restaurants.SqlQuery("Select * from List_Of_Restaurants").ToList();
                    foreach (var test1 in blogs)
                    {
                        var assasa = test1.Address;
                    }
                    var test3 = "";

                }

Using simple “where”:

context.TableName.Where(n => n.Name == “Blah”);

  using (var context = new ListofRestaurantsContext())
                {
                    var blogs = context.List_Of_Restaurants.Where(n => n.restaurant_id == 1).ToList();
                    foreach (var test1 in blogs)
                    {
                        var assasa = test1.Address;
                    }
                    var test3 = "";

                }

Round up or down to the nearest decimal

I have been building a fully functional Web Scraper for a client of mine, and they wanted me to increase all prices in an excel sheet by 18% and then round it up to the nearest quarter (.00, .25, .50, .75). I was struggling for this with a while, and was determined to solve it by myself. After a few hours of messing around on my calculator I finally figured out a solution that works for rounding up or down to the nearest decimal, so an eight, a fourth, a third.. anything. It’s pretty cool, so I thought I’d share it with ya’ll.

Let’s say you start out with $3.00, and want to multiply that by 18%, and then round it up to the nearest quarter.

3 x 1.18 = 3.54, and rounding that up to the nearest quarter makes it 3.75. Let’s see if we can figure out some type of formula to do this so we can do it programmatically.

Step 1: Multiply 3 x 1.18 = 3.54

Step 2: Multiply result (3.54) by the decimal type that you want to reach. So if you want to round up/down to the nearest eight, you’d multiply by 8. In this case we want to round up/down to the nearest quarter, so you multiply by 4. (3.54 x 4) = 14.16

Step 3: You need to choose whether you want to round up or round down. If you want to round up, use Math.Ceiling/Ceil depending on your programming language, and if you want to round down use Floor. Since we are rounding up in this case, the result is 15.

Step 4: Divide the result (15) by the decimal type you used in Step 2. So if quarter (4), eight (8), etc. In this case we are using quarters, so I multiplied 15 / 4 = 3.75.

There you go, stay tuned for more posts/tutorials.

Replace Specific Words in C#

I’ve been working on a decent size project and I have been learning a lot of new things that I thought I’d share with you guys. This will go over how to replace specific words using Regex in C#. For example if your string contains “Let’s add this pizza because adding pizza is a fad,” if you use normal removal tools such as string.Replace(“add”, “”) it would make the string “Let’s this pizza because ing pizza is a.”

Obviously, we don’t want that to happen, so the best tool to use is boundary.

What is a Boundary?
There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Source: http://www.regular-expressions.info/wordboundaries.html

In simple words, boundary allows you to set it so that you only replace the word that has the string you want. You can use something simple such as String.Replace(@”\badd\b”, “”).

Remember to place

using System.Text.RegularExpressions;

on the top of your class/form.

I came up with a nice little class to remove a specific word:

    public static class LetsDoThis
    {
        public static string ReplaceWords(this string variable, string findit, string getridofit, bool findspecificword)
        {
            string finding_the_text= findspecificword? string.Format(@"\b{0}\b", findit) : findit;
            return Regex.Replace(variable, finding_the_text, getridofit);
        }
    }

Geospatial Tracking using the haversine formula

So today I was given the task of finding locations of store’s, addresses, or just places based on a radius. This is useful to find near by store locations, or searching for things based on a radius. For example, if you want to find the closest dominos from your house you should use this tutorial!

First things first, you need to have some type of familiarity with PHPMyAdmin/MYSQL. If you have a web server, all you have to do is go to PHP My Admin, and create a new table. For this tutorial, I will be using MySQL and not the PHPMyAdmin features.

 
1. Go to MySQL inside your server, and create a new table that has ID, Name, Address, Lat, Lng columns:

CREATE TABLE `test` (
  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `name` VARCHAR( 60 ) NOT NULL ,
  `address` VARCHAR( 80 ) NOT NULL ,
  `lat` FLOAT( 10, 6 ) NOT NULL ,
  `lng` FLOAT( 10, 6 ) NOT NULL
) ENGINE = MYISAM ;

2. After that you need to import into your table, Name’s, Addresses, Latitudes, and Longitudes of the stores/restaurants/addresses that you want to search with. For this example, I use 4 different places.

INSERT INTO `test` (`name`, `address`, `lat`, `lng`) VALUES ('Lindbergh School Park','Lindbergh School Park, Costa Mesa, CA','33.652188','-117.900172');
INSERT INTO `test` (`name`, `address`, `lat`, `lng`) VALUES ('US Post Office','2230 Fairview Rd, Costa Mesa, CA','33.655459','-117.906958');
INSERT INTO `test` (`name`, `address`, `lat`, `lng`) VALUES ('Orange Coast College','2701 Fairview Rd, Costa Mesa, CA','33.671890','-117.912086');
INSERT INTO `test` (`name`, `address`, `lat`, `lng`) VALUES ('LMU','1 LMU Drive, Los Angeles, CA','33.970407','-118.417423');

3. Now after this comes the actual search portion, where you put in your own address to see how far away one of the locations you added above is from your own address.

I am using “33.650800, -117.891729” that lat/lng as my own address.

SELECT name, id, ( 3959 * acos( cos( radians(YOUR LATITUDE) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(YOUR LONGITUDE) ) + sin( radians(YOUR LATITUDE) ) * sin( radians( lat ) ) ) ) AS distance FROM test HAVING distance < 25 ORDER BY distance; 

The 3959 should never be changed as that is the radius of the Earth in MILES. Where it says "YOUR LATITUDE" you replace with your latitude, and where it says "YOUR LONGITUDE" you replace with your longitude. The 25 after "HAVING distance" is the mile radius that you are searching. So if you want to search in a 10 mile radius, you replace 25 with 10.

So since I am using "33.650800, -117.891729" and want to search using a 10 mile radius, the SQl search will look like this:

SELECT name, id, ( 3959 * acos( cos( radians(33.650800) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-117.891729) ) + sin( radians(33.650800) ) * sin( radians( lat ) ) ) ) AS distance FROM test HAVING distance < 10 ORDER BY distance;

4. Your result shows, LMU was more than a 10 mile radius, so it doesn't show up when I search it:

View this article to see more details/further implementation: https://developers.google.com/maps/articles/phpsqlsearch_v3#findnearsql

 

Hello world!

I am very excited about this blog. Coding, and being able to share your code is a lot more fun than working on side projects by yourself. Even if no one reads it, it is exciting that I can share my events and projects with the internet! Hopefully over time I will gain some random followers.

In addition.. anyone who judges my web development skill based on this website should know that I created this website to simply be a blog for myself. I didn’t design it myself, and used WordPress so I could focus on one thing: posting blogs! I will evolve this website to include my resume and portfolio, but for now all I want to do is work on little projects and post them here to increase my programming knowledge.

Enjoy!