Saturday, 10 February 2018

Adding Field Logic in Microsoft Text Recognition

Use Case

Let suppose we have an image of a bill recipt and we want to extract the texts in linear. Maestro 11.45 from the image below.

But by using computer vision api we are able to identify text as a two region and not in a continuous line.

Here we are interested in extracting data in linear and not in two separate group. So after debugging we found the Top and Height Coordinated of (Region 1) Maestro and (Region 2) 11.45

So using the Top value which has the nearest common value of each. We can try to write some code to checks whether the difference between the top value of each word is close enough.

In other word we can check the difference of <= 15 pixels to consider those two text is in a same line.

Source Code

You can view full source Code at my Github Repo.

Code Explanation

public static void TextExtraction(string fname, bool wrds, bool mlines)
{
    Task.Run(async () =>
    {
        string[] res = await TextExtractionCore(fname, wrds, mlines);

        if (mlines && !wrds)
            res = MergeLines(res);

        PrintResults(res);

        Console.WriteLine("\nDate: " + GetDate(res));
        Console.WriteLine("Highest amount: " + HighestAmount(res));

    }).Wait();
}
    

In the above method TextExtraction third paramater mlines will let us know where we want to merge the line from two different regions.

public static string[] MergeLines(string[] lines)
{
    SortedDictionary dict = MergeLinesCore(lines);
    return dict.Values.ToArray();
}
    

In order to merge line we created method MergeLines which invokes another method MergeLinesCore that will return a sorted dictionary.

public static SortedDictionary MergeLinesCore(string[] lines)
{
    SortedDictionary dict = new SortedDictionary();

    foreach (string l in lines)
    {
        string[] parts = l.Split('|');

        if (parts.Length == 3)
        {
            int top = Convert.ToInt32(parts[0]);
            string str = parts[1];
            int region = Convert.ToInt32(parts[2]);

            if (dict.Count > 0 && region != 1)
            {
                KeyValuePair item = FindClosest(dict, top);

                if (item.Key != -1)
                    dict[item.Key] = item.Value + " " + str;
                else
                    dict.Add(top, str);
            }
            else
                dict.Add(top, str);
        }
    }

    return dict;
}
    

The above method MergeLinesCore loops through all the line in all the regions and find Closest line on the other reagion. Once it is found both line ate combined into a dictionary into single entry.

Saturday, 22 April 2017

Replace Conditional with Polymorphism

Replace Conditional with Polymorphism

Problem Code

foreach(Employee in _emp)
{
    if(emp.IsManager)
    {
        emp.bonus = totalFreight/10m;
    }
    else
    {
        emp.bonus = totalFreight/10m;
    }
}

Solution Code

public class Employee
{
    public string Name;
    public bool IsManager;
    protected decimal bonus;
    public decimal Bonus { get{ return bonus;}}
    public virtual void SetBonus(decimal freightUsedForBonus)
    {
        bonus = freightUsedForBonus/1000;
    }
}
public class Manager : Employee
{
    public override void SetBonus(decimal freightUsedForBonus)
    {
        bonus = freightUsedForBonus/10;
    }
}

Benefits

  • Tell-Don't-Ask Principal instead of asking an object about its state and then performing actions based on this, it is much easier to simply tell the object what it needs to do and let it decide for itself how to do that.
  • Do Not Repeat (DRY) Principal we get rid of many almost identical conditionals.
  • Open/Closed Principle If we need to add a new variant, all you need to do is add a new subclass without touching the existing code

Tuesday, 11 April 2017

Some inheritance Cases in Objected Oriented Programming in CSharp

Inheritance by using Virtual and Override Keyword

Parameterized Constructor Inheritance

Common Errors while Inheritance

Friday, 17 March 2017

Priceless SOLID Principal Posters

SOLID

Software development is not a Jenga game.

Single responsibility principle (SIP)

Open closed principle (OCP)

Liskov substitution principle (LSP)

Interface segregation principle (ISP)

Dependency inversion principle (DIP)

Thursday, 16 March 2017

Top 3 thing of interest introduced in Angular 4 RC

if...else syntax in component HTML templates

 <ng-template #fetching>
   <p>Fetching...

</ng-template> <p *ngIf="auth | async; else fetching; let user"> {{user.username }} </p>

Saperate library for Animation

In Angular 2 Animation were in library @angular/core since angular 4 it separately maintained in @angular/animations

Strict Null check in Typescript

 let x = String | null
 let y = Number | undefined
 let z = Array<String> | null | undefined

Friday, 10 March 2017

Types of Grant Workflows

Resource Owner Password Grant

The User Credential are stored at client and sent to the token service which returns the token. Collecting and storing credential is the job of the token service doing it in client is consider not safe.The User Credential are stored at client and sent to the token service which returns the token. Collecting and storing credential is the job of the token service doing it in client is consider not safe.

This grant is only used in legacy scenario.

Implicit Grant

Implicit flow is commonly user when a client is javascript application a browser.

Here browser issue for Token to Token Service without explicitly providing client credential then a redirection occurs to a login page that is served by Token Service.

This approaches often has a security issue

Authorization Code

Authorization Code solves the security problem. It needs a web server Application i.e. the client.

Hear browser get a code back from Token Service and that browser send that code to Client(Web Server) Then client sends the code to Token Service and get the Token back.

Hybrid

Thursday, 16 February 2017

Improving Angular 2 Performance while using ngFor

When you iterate over an array or collection most probably you use ngFor directive to bind the data of collection into your DOM elements.

Problem !

Here the big problem is, If at some point of time you wish to change the data in the collection, for example maybe as a result of an API request, Then the Angular can’t keep track of items in the collection and has no knowledge of which items have been removed or added as a results it creates the DOM again. That means this has a lot of DOM manipulations.

Solution ..

Here comes the solution, ngFor directive has a property called track by.

So what do these do? They help Angular to associate key with the DOM elements and tracks which items are added or removed.

Angular’s ngFor defaults tracks object identity for you, which is fast, but it can be more faster if we use track by unique object ID in ngFor. Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the things that changed.

   <li *ngFor="let student of students; trackBy: student.id;">
    ...
   </li>

Optionally, we can use track by index but that is not advisable as the index may be subject to change if you reorder your collection. Using a unique identifier allows Angular to locate that DOM node associated with the object much faster

Toggle String Lower to Upper and Upper to Lower

You have been given a String S consisting of uppercase and lowercase English alphabets. You need to change the case of each alphabet in this String. That is, all the uppercase letters should be converted to lowercase and all the lowercase letters should be converted to uppercase. You need to then print the resultant String to output.

using System; 
using System.Numerics;
public static class InvertStringExtension
{
    public static string Invert(this string s)
    {
        char[] chars = s.ToCharArray();
        for (int i = 0; i < chars.Length; i++)
            chars[i] = chars[i].Invert();
            
        return new string(chars);
    }
    public static char Invert(this char c)
    {
        if (!char.IsLetter(c))
            return c;
 
        return char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
    }
}
class MyClass {
    static void Main(string[] args) {
        var line1 = System.Console.ReadLine().Trim();
        System.Console.WriteLine(line1.Invert());
    }
}

Tuesday, 14 February 2017

Maintaining Relationship in NoSQL

The decision "What database to use" is a bit difficult. Most Startup rely on NoSQL Database. MongoDB is the most popular NoSQL DataBase. NoSQL Database has grown in popularity due to it's open source, flexible in nature and ease to use.

But what about relationship

As Database is mostly representation of real world entities relationship is very important to be maintain among database. While MongoDB is not a relational database, there are two recommended approaches to representing relationships between entities.

Modeling Embedded Relationships

In this approach we embed the related document inside its parent document.

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   ...
   "address": [
      {
         "building": "22 A, Indiana Apt",
         ...
      },
      {
         "building": "ABC Apart",
         ...
      }
   ]
} 

This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. But The drawback is it is not Consistent. And if the embedded document keeps on growing too much in size, it can impact the read/write performance.

Modeling Referenced Relationships

In this approach the two related table are maintained saperatly and the reference of one table is maintained in another table by its document id

{
   ...
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
}

The benefit of this approach is whenever a document is updated, there is no overhead of managing other document because the reference ids does not change and the problem of Consistency is solved.

Monday, 23 January 2017

Setting and getting Session values in Asp.NET Core 1.0

Session is accessed through the Session property on HttpContext. Session is an ISession implementation.

Simple Get Set Session in Core 1.0

The following extension methods, we can set and get serializable session objects:

Session Extensions Method

Implementing Session Extensions Method

Sunday, 15 January 2017

Detect a Loop in Singly Linked List and Remove Loop

using System;
namespace ConsoleApplication1
{
    class Program
    {

        public class LinkedListNode
        {
            public LinkedListNode() { }
            public LinkedListNode(T value)
            {
                Value = value;
            }
            public T Value { get; set; }
            public LinkedListNode Next { get; set; }
        }

        static void Main(string[] args)
        {
            LinkedListNode Llist = new LinkedListNode();
            Llist.Next = new LinkedListNode(1);
            Llist.Next.Next = new LinkedListNode(2);
            Llist.Next.Next.Next = new LinkedListNode(3);
            Llist.Next.Next.Next.Next = new LinkedListNode(4);
            Llist.Next.Next.Next.Next.Next = new LinkedListNode(5);
            Llist.Next.Next.Next.Next.Next.Next = new LinkedListNode(6);

            Llist.Next.Next.Next.Next.Next.Next.Next = Llist.Next.Next.Next.Next;
            Console.WriteLine(FloydCycleDedection(Llist).ToString());
            Console.WriteLine(FloydCycleDedection(Llist).ToString());
            Console.Read();
        }

        public static bool FloydCycleDedection(LinkedListNode node)
        {
            LinkedListNode slow = node, fast = node;
            while (slow != null && fast != null && fast.Next != null)
            {
                slow = slow.Next;
                fast = fast.Next.Next;
                if (slow == fast)
                {
                    removeLoop(node, slow, fast);
                    return true;
                }
            }
            return false;
        }

        public static void removeLoop(LinkedListNode node, LinkedListNode slow, LinkedListNode fast)
        {
            /* If loop exists */
            if (slow == fast)
            {
                slow = node;
                while (slow != fast.Next)
                {
                    slow = slow.Next;
                }
                fast.Next = null; // remove loop
            }
        }
    }
}

Thursday, 12 January 2017

Kadane's algorithm to find subarray with the maximum sum 2D array in C#

using System;
using System.Linq;

namespace test2
{
    class Program
    {

        static void Main(string[] args)
        {
            int[][] int1 = new int[][] {
                new int[] {1, 2, -1, -4, -20},
                new int[] {-8, -3, 4, 2, 1},
                new int[] {3, 8, 10, 1, 3},
                new int[] {-4, -1, 1, 7, -6}
            };
            findMaxSubMatrix(int1);

            //int[] kk = kadane(new int[] { -3,-2,-1 });
            //foreach(var item in kk)
            //{
            //    Console.WriteLine(item);
            //}
            Console.Read();
        }

        public static int[] kadane(int[] a)
        {
            //result[0] == maxSum, result[1] == start, result[2] == end;
            int[] result = new int[] { int.MinValue, 0, -1 };
            int currentSum = 0;
            int localStart = 0;

            for (int i = 0; i < a.Length; i++)
            {
                currentSum += a[i];
                if (currentSum < 0)
                {
                    currentSum = 0;
                    localStart = i + 1;
                }
                else if (currentSum > result[0])
                {
                    result[0] = currentSum;
                    result[1] = localStart;
                    result[2] = i;
                }
            }

            // all numbers in a are negative
            if (result[2] == -1)
            {
                for (int i = 0; i < a.Length; i++)
                {
                    if (a[i] > result[0])
                    {
                        result[0] = a[i];
                        result[1] = i;
                        result[2] = i;
                    }
                }
            }

            return result;
        }

        /**
        * To find and print maxSum, (left, top),(right, bottom)
        */
        public static void findMaxSubMatrix(int[][] a)
        {
            int cols = a[0].Length;
            int rows = a.Length;
            int[] currentResult;
            int maxSum = int.MinValue;
            int left = 0;
            int top = 0;
            int right = 0;
            int bottom = 0;

            for (int leftCol = 0; leftCol < cols; leftCol++)
            {
                int[] tmp = new int[rows];

                for (int rightCol = leftCol; rightCol < cols; rightCol++)
                {

                    for (int i = 0; i < rows; i++)
                    {
                        tmp[i] += a[i][rightCol];
                    }
                    currentResult = kadane(tmp);
                    if (currentResult[0] > maxSum)
                    {
                        maxSum = currentResult[0];
                        left = leftCol;
                        top = currentResult[1];
                        right = rightCol;
                        bottom = currentResult[2];
                    }
                }
            }
            Console.WriteLine("MaxSum: " + maxSum +
            ", range: [(" + left + ", " + top +
            ")(" + right + ", " + bottom + ")]");
        }
    }
}

Thursday, 15 December 2016

Passing data from Parent to Child Component

Passing data to a nested component

In Angular 1 we used $broadcast, $emit, $on to communicate between controllers. But now in angular 2 we have different approach.

In Angular 2, If you want to flow data from Parent Component to Child Component we use @Input Decorator or "inputs" property inside @Component decorator or in a Class. Hear we will discuss the former approach.

Our Directory Structure

Parent Component

//our root app component
import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormsModule }   from '@angular/forms';
import { ChildComponent } from './child.component';
import { Character } from './character';

@Component({
  selector: 'my-app',
  template: `
  <h1>@input</h1>
  <div style = "border:2px solid orange; padding:5px;">
    <h2>Parent Component</h2>
    <input [(ngModel)] = "characters[0].name"/>
    <button (click)="select(characters[0])">Input</button>
    <br/><br/> 
    <child-component [character]="selectedCharacter"></child-component>
  </div>
  `,
})
export class App {
  characters = [
    {
      "id":11,
      "name":"Name"
    }];
     
    selectedCharacter: Character;
    
    select(selectedCharacter : Character){
      this.selectedCharacter = selectedCharacter;
    }
}

@NgModule({
  imports: [ BrowserModule,FormsModule  ],
  declarations: [ App, ChildComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

Child Component

import { Component, Input} from '@angular/core';
import { Character} from './character';
@Component({
  selector: 'child-component',
  template:`
  <div style="border:2px solid orange; padding:5px">
    <h2>Child Component: <span *ngIf="character">{{character.name}}</span></h2>
  </div>
  `
})
export class ChildComponent {
   @Input() character: Character;
}

Full source

Find full source from my github

Friday, 11 November 2016

platform-browser VS platform-browser-dynamic

In angular2. We must have seen in every project there is plugin called platform-browser and platform-browser-dynamic.

 "@angular/platform-browser": "2.0.0-rc.4",
 "@angular/platform-browser-dynamic": "2.0.0-rc.4",
  

Let us understand the difference.

The difference between platform-browser-dynamic and platform-browser is the way your angular app will be compiled.

@angular/platform-browser

  • It contains code shared for browser execution (DOM thread, WebWorker)
  • Ahead-of-Time pre-compiled version of application being sent to the browser. Which usually means a significantly smaller package being sent to the browser.

@angular/platform-browser-dynamic

  • It contains the client side code that processes templates (bindings, components, ...) and reflective dependency injection.
  • Uses Just-in-Time compiler and make's application compile on client-side.

When the offline template compiler is used, platform-browser-dynamic isn't necessary because all reflective access and metadata are converted to generated code.

Saturday, 22 October 2016

Javascript Modules VS Angular2 Modules

Javascript Modules Angular2 Modules
Code file that import or export something Code file that organise the application
Organize our code file Organize our application
Modularize our code Modularize our application
Promote Code Reuse Promote Application Boundaries


Angular2 Architecture in Breif

The architecture diagram identifies the eight main building blocks of an Angular application:

  • Modules
    • Angular apps are modular and Angular has its own modularity system called Angular modules or NgModules.
  • Components
    • A component controls a patch of screen called a view.
  • Templates
    • You define a component’s view with its companion template. A template is a form of HTML that tells Angular how to render the component.
  • Metadata
    • Metadata tells Angular how to process a class.
  • Data binding
  • Directives
    • @Component requires a view whereas a @Directive does not. Directives add behaviour to an existing DOM element.
  • Services
    • Service is a broad category encompassing any value, function, or feature that your application needs.
  • Dependency injection
    • Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services.

Wednesday, 31 August 2016

IEnumerable VS ICollection

Enumerable

First of all, it is important to understand, that there are two different interfaces defined in the .NET base class library. There is a non-generic IEnumerable interface and there is a generic type-safe IEnumerable interface.

The IEnumerable interface is located in the System.Collections namespace and contains only a single method definition. The interface definition looks like this:


    public interface IEnumerable
    {
        IEnumerator GetEnumerator();
    }
    

It is important to know that the C# language foreach keyword works with all types that implement the IEnumerable interface.

IEnumerable

Let’s now take a look at the definition of the generic and type-safe version called IEnumerable which is located in the System.Collections.Generic namespace:


    public interface IEnumerable<out T> : IEnumerable
    {
        IEnumerator GetEnumerator();
    }
    

As you can see the IEnumerable interface inherits from the IEnumerable interface. Therefore a type which implements IEnumerable has also to implement the members of IEnumerable.

ICollection

As you can imagine, there are also two versions of ICollection which are System.Collections.ICollection and the generic version System.Collections.Generic.ICollection.

Let’s take a look at the definition of the ICollection interface type:


    public interface ICollection : IEnumerable
    {
        int Count { get; }  
        bool IsSynchronized { get; }
        Object SyncRoot { get; }
     
        void CopyTo(Array array, int index);
    }
    

ICollection inherits from IEnumerable. You therefore have all members from the IEnumerable interface implemented in all classes that implement the ICollection interface.

ICollection

When we look at the generic version of ICollection, you’ll recognize that it does not look exactly the same as the non-generic equivalent:


    public interface ICollection<T> : IEnumerable<T>, IEnumerable
    {
        int Count { get; }
        bool IsReadOnly { get; }
     
        void Add(T item);
        void Clear();
        bool Contains(T item);
        void CopyTo(T[] array, int arrayIndex);
        bool Remove(T item);
    }
    

Which type should you depend on?

Tuesday, 30 August 2016

What is Yield in CSharp

Short Answer

Yield keyword helps us to do custom stateful iteration over .NET collections. There are two scenarios where yield keyword is useful:-

  • Customized iteration through a collection without creating a temporary collection.
  • Stateful iteration.

Long Answer

First Scenario:- Customized iteration through a collection

Let's try to understand what customized iteration means with an example. Consider the below code.

Let say we have a simple list called as "MyList" which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is iterated from console application from within static void main method.

For now let's visualize the "main()" method as a caller. So the caller i.e. "main()" method calls the list and displays the items inside it. Simple…till now".

  static List MyList = new List();
  static void Main(string[] args)
  {
    MyList.Add(1);
    MyList.Add(2);
    MyList.Add(3);
    MyList.Add(4);
    MyList.Add(5);
    foreach (int i in MyList) // Itterates through the list
    {
      Console.WriteLine(i);
    }
    Console.ReadLine();
  }

Now let me complicate this situation let's say the caller only wants values greater than "3" from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than "3" and return the same to the caller. The caller can then iterate through this collection.

  static IEnumerable FilterWithoutYield()
  {
    List temp = new List();
    foreach (int i in MyList)
    {
        if (i > 3)
        {
            temp.Add(i);
        }
    }
    return temp;
  } 

Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where "yield" keyword comes to help. Below is a simple code how we have used yield. "Yield" keyword will return back the control to the caller, the caller will do his work and re-enter the function from where he had left and continue iteration from that point onwards. In other words "yield" keyword moves control of the program to and fro between caller and the collection.

static IEnumerable FilterWithYield()
{
  foreach (int i in MyList)
  {
      if (i > 3) yield return i;
  }
}  

So for the above code following are details steps how the control will flow between caller and collection. You can also see the pictorial representation in the next diagram shown below.

  • Step 1:- Caller calls the function to iterate for number's greater than 3.
  • Step 2:- Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than "3" i.e. "4". As soon as the condition of value greater than 3 is met the "yield" keyword sends this data back to the caller.
  • Step 3:- Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from "5". The iteration continues further as usual.

Second Scenario:- Stateful iteration

Now let us add more complications to the above scenario. Let's say we want to display running total of the above collection. What do I mean?.

In other words we will browse from 1 to 5 and as we browse we would keep adding the total in variable. So we start with "1" the running total is "1", we move to value "2" the running total is previous value "1" plus current value "2" i.e. "3" and so on.

In other words we would like to iterate through the collection and as we iterate would like to maintain running total state and return the value to the caller ( i.e. console application). So the function now becomes something as shown below. The "runningtotal" variable will have the old value every time the caller re-enters the function.

Tipical implementation

  1. Caller calls the GetRunningTotal method.
  2. Running total of all items in Numbers list is calculated at returned to caller.
    Initital Sum = [0] [0] + {1} => [1] [1] + {2} => [3] [3] + {3} => [6] [6] + {4} => [10] [10] + {5} => [15] [15] + {6} => [21] [21] + {7} => [28] [28] + {8} => [36] [36] + {9} => [45]
  3. Caller iterates over each running total and prints it on console.
    Print [1];
    Print [3];
    Print [6];
    Print [10];
    Print [15];
    Print [21];
    Print [28];
    Print [36];
    Print [45];
    Where list items are in {} brackets and running total (at some point) is in [] bracket.
class Program
{
        static List Numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        static void Main(string[] args)
        {
            int itemsTraversed = 0;
            foreach (var item in GetRunningTotal())
            {
                Console.WriteLine("Running total of first {0} items is {1}", ++itemsTraversed, item);
            }
            Console.ReadKey();
        }

        static IEnumerable GetRunningTotal()
        {
            List runningTotals = new List();
            int runningTotal = 0;
            foreach (int number in Numbers)
            {
                Console.WriteLine("Adding {0} in running total", number);
                runningTotal += number;
                runningTotals.Add(runningTotal);

            }
            Console.WriteLine("\n\nReturn Running Total\n\n");
            return runningTotals;
        }
}

Please note that GetRunningTotal method is called only once and it returns all the subsequent running totals to the caller.

Yield Implementation

  1. Caller calls the GetRunningTotal method.
  2. Running total of first n items is calculated and returned to caller.
    [n-1]th running total + {n}th item => [n]th running total
  3. Caller prints it on console.
    Print [n]th running total;
  4. Control is given back to GetRunningTotal method which remembers it’s running state.
  5. Repeat step 2 , 3 and 4 untill all items are iterated.
class Program
{
        static List Numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        static void Main(string[] args)
        {
            int itemsTraversed = 0;
            foreach (var item in GetRunningTotal())
            {
                Console.WriteLine("Running total of last {0} items is {1}", ++itemsTraversed, item);
            }
            Console.ReadKey();
        }

        static IEnumerable GetRunningTotal()
        {
            int runningTotal = 0;
            foreach (int number in Numbers)
            {
                if (number > 1)
                    Console.WriteLine("Control is back and next item to be summed is {0}\n\n", number);
                runningTotal += number;
                yield return (runningTotal);

            }
        }
}

The above code will output the values 1,3,6,10,15,21,28,36,45. Because of the pause/resume behavior, the variable total will hold its value between iterations. So it can be very handy to do stateful calculations using yield keyword.

Monday, 22 August 2016

Function Overloding, Polymorphism, Method Overloding in Javascript

I often do this...

C#

In CSharp

   public string CatStrings(string p1)                  {return p1;}
   public string CatStrings(string p1, int p2)          {return p1+p2.ToString();}
   public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}

   CatStrings("one");        // result = one
   CatStrings("one",2);      // result = one2
   CatStrings("one",2,true); // result = one2true
                

JS

In JavaScript

 function CatStrings(p1, p2, p3)
 {
   var s = p1;
   if(typeof p2 !== "undefined") {s += p2;}
   if(typeof p3 !== "undefined") {s += p3;}
   return s;
 };

 CatStrings("one");        // result = one
 CatStrings("one",2);      // result = one2
 CatStrings("one",2,true); // result = one2true
                

What most developers do is...

JS

JavaScript

The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

 function foo(a, b, opts) {

 }

 foo(1, 2, {"method":"add"});
 foo(3, 4, {"test":"equals", "bar":"tree"});
                

Then you can handle it anyway you want in your method. [Switch, if-else, etc.]

Friday, 12 August 2016

Connect Mongodb on a Microsoft Azure VM from Remote Machine

Create Directory for MongoData

    C:\> mkdir \MongoData
    C:\> mkdir \MongoLogs

Install mongod.exe as a service

    C:\Program Files\MongoDB\Server\3.2\bin>mongod --dbpath C:\MongoData\ --logpath C:\MongoLogs\mongolog.log --logappend  --install

Start the Service

    start the service
Now that MongoDB is installed and running, you'll need to open a port in Windows Firewall so you can remotely connect to MongoDB. From the Start menu, select Administrative Tools and then Windows Firewall with Advanced Security.

Inbound Rules

Configure Endpoint for MongoDB in Azure

Test your Mongodb from Local Machine