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