Tuesday, 30 September 2014

DFS

public class Node
    {
        public int Id { get; set; }

        public String Name { get; set; }

        public String Parent { get; set; }

        [JsonIgnore]
        public bool Visited { get; set; }

        [JsonIgnore]
        public List Children { get; set; }
    }

   public static class TreeManager
    {
        static Node tree = null;

        static TreeManager()
        {
            tree = new Node();
        }

        public static Node Get()
        {
            return tree;
        }
    }

    public static class TestData
    {
        static int id = 1;

        public static Node Initialise()
        {
            var root = TreeManager.Get();

            root.Id = Identifier;
            root.Name = "Root";

            root.Children = CreateDepartment();

            CreateChildren(root.Children, "aisle");
            CreateChildren(root.Children.SelectMany(c => c.Children).ToList(), "shelve");
            //CreateChildren(root.Children.SelectMany(c => c.Children).SelectMany(c => c.Children).ToList(), "sub_shelve");

            return root;
        }

        private static int Identifier
        {
            get
            {
                return id++;
            }
        }

        private static List CreateDepartment()
        {
            string[] departments = new string[]
                        {
                            "Fresh Food", "Level 1 Mos Test", "Food cupboard test",
                            "Frozen food", "Drinks", "Drugstore", "Baby", "Pets", "Home and entertainment"
                        };

            return Create(departments);
        }

        private static void CreateChildren(List nodes, string childName)
        {
            Random seeder = new Random(1);

            foreach (var node in nodes)
            {
                int looper = seeder.Next(1, 10);
                List names = new List();

                while ((looper--) > 0)
                {
                    names.Add(node.Name + "-" + childName + looper.ToString());
                }

                node.Children = new List();

                node.Children.AddRange(Create(names.ToArray()));
            }
        }

        private static List Create(string[] names)
        {
            List nodes = new List();

            foreach (var name in names)
            {
                nodes.Add(new Node { Id = Identifier, Name = name });
            }

            return nodes;
        }
    }

    //http://www.codeproject.com/Articles/32212/Introduction-to-Graph-with-Breadth-First-Search-BF
    //http://stackoverflow.com/questions/687731/breadth-first-vs-depth-first

    public static class DFSTraverse
    {
        static List orderedNodes = new List();

        public static void Traverse(Node tree)
        {
            orderedNodes.Clear();

            Stack stack = new Stack();

            tree.Visited = true;
            Push(stack, tree);
            Print(stack.Peek());

            while (!stack.IsEmpty())
            {
                Node node = GetChildNode(stack.Peek());

                if (node == null) stack.Pop();
                else
                {
                    node.Visited = true;
                    Push(stack, node, stack.Peek().Name);
                    Print(stack.Peek());
                }
            }
        }

        public static string OrderedList()
        {
            return JsonConvert.SerializeObject(orderedNodes);
        }

        public static Node RebuildHierarchy(Stack stack)
        {
            Node root = stack.Peek();

            BuildHierarchy(stack, stack.Pop());

            return root;
        }
       
        private static void BuildHierarchy(Stack stack, Node parent)
        {
            if (parent == null) return;

            Node addedNode = null;

            while (!stack.IsEmpty())
            {
                if (stack.Peek().Parent.Equals(parent.Name))
                {
                    if (parent.Children == null) parent.Children = new List();

                    addedNode = stack.Pop();
                    parent.Children.Add(addedNode);
                }
                else if (stack.Peek().Parent.Equals(addedNode.Name)) BuildHierarchy(stack, addedNode);
                else return;
            }
        }

        private static void AddToOrderedList(Node node)
        {
            orderedNodes.Add(node);
        }

        private static void Push(Stack stack, Node node, string parent = null)
        {
            stack.Push(node);

            node.Parent = parent;
            AddToOrderedList(node);
        }

        private static Node GetChildNode(Node node)
        {
            if (!node.Visited) return node;
            if (node.Children == null) return null;

            return node.Children.FirstOrDefault(n => n.Visited == false);
        }

        private static void Print(Node node)
        {
            Console.WriteLine(node.Id + ":" + node.Name);
        }

        private static bool IsEmpty(this Stack stack)
        {
            return stack.Count <= 0;
        }
    }

   class Program
    {
        const string file = "Naviagtion.txt";

        static void DemoDFSTraverse(Node root)
        {
            DFSTraverse.Traverse(root);

            if (File.Exists(file)) File.Delete(file);
           
            File.WriteAllText(file, DFSTraverse.OrderedList());
        }

        static Node RebuildHierarchy()
        {
            var result = JsonConvert.DeserializeObject(File.ReadAllText(file));

            Stack node = new Stack(result.Reverse());

            return DFSTraverse.RebuildHierarchy(node);
        }

        static bool AreEquals(Node node1, Node node2)
        {
            if (node1.Id == node2.Id && node1.Name.Equals(node2.Name))
            {
                int item = 0;

                if (node1.Children == null && node2.Children == null) return true;

                foreach (var node in node1.Children)
                {
                    var otherNode1 = node1.Children[item];
                    var otherNode2 = node2.Children[item];

                    item++;

                    return AreEquals(otherNode1, otherNode2);
                }
            }

            return false;
        }

        static void Main(string[] args)
        {
            Node originalNode = TestData.Initialise();

            DemoDFSTraverse(originalNode);
            Node rebuilededNode = RebuildHierarchy();

            Console.WriteLine(AreEquals(originalNode, rebuilededNode));
           
            Console.Clear();
            DemoDFSTraverse(rebuilededNode);

            Console.ReadLine();
        }


Monday, 1 September 2014

Json.Net - Sample functions

Just for my reference

namespace MyJsonExample
{
    public class Movies
    {
        public Movie[] All { get; set; }
    }
    public class Movie
    {
        public String Name { get; set; }
        public DateTime ReleasedOn { get; set; }
        [JsonIgnore]
        public String Director { get; set; }
        public MovieRating Rating { get; set; }
    }
    public enum MovieRating
    {
        R,
        U,
        PG
    }
    public static class Demo
    {
        public static string Serialize()
        {
            Movie m = new Movie { Director = "Suresh", Name = "First Movie", ReleasedOn = DateTime.Now, Rating = MovieRating.PG };
            return JsonConvert.SerializeObject(m);
        }
        public static string SerializeArray()
        {
            Movie m1 = new Movie { Director = "Suresh", Name = "First Movie1", ReleasedOn = DateTime.Now, Rating = MovieRating.PG };
            Movie m2 = new Movie { Director = "Suresh", Name = "First Movie2", ReleasedOn = DateTime.Now, Rating = MovieRating.R };
            Movie[] movies = new Movie[] { m1, m2 };
            Movies ms = new Movies { All = movies };
            return JsonConvert.SerializeObject(ms);
        }
        public static void Deserialize(string m)
        {
            var movie = JsonConvert.DeserializeObject(m);
            movie.ToString();
        }
        public static void ParseMovie(string m)
        {
            var movie = JObject.Parse(m);
            var name = movie["Name"];
        }
        public static void ParseMovies(string m)
        {
            var movies = JObject.Parse(m);
            var all = movies["All"];
            var name = all[0]["Name"];
            name = all[1]["Name"];
        }
        public static void ParseMoviesUsingLinq(string m)
        {
            var movies = JObject.Parse(m);
            var all = movies["All"];
            var movienames = (from movie in all
                              select (string)movie["Name"]).ToList();
            var movienames2 = (from movie in movies["All"]
                              select new { N = (string)movie["Name"], R = movie["Rating"]});
            foreach (var moviename in movienames)
            {
                Console.WriteLine(moviename);
            }
            foreach (var moviename in movienames2)
            {
                Console.WriteLine(moviename.N + ":" + moviename.R);
            }
        }
        public static string SerializeEnum()
        {
            Movie m1 = new Movie { Director = "Suresh", Name = "First Movie1", ReleasedOn = DateTime.Now, Rating = MovieRating.PG };
            return JsonConvert.SerializeObject(m1, new Newtonsoft.Json.Converters.StringEnumConverter());
        }
    }
}

Wednesday, 7 May 2014

EclipseLink SqlExpress Connection Refused error

if you encounter this error “java.sql.SQLException: Network error IOException: Connection refused: connect SQL Express” while using EclipseLink to connect to SQL Express, just specifying the default SQL Port 1433 in SQL Server Configuration Manager


Tuesday, 15 April 2014

Multi-Tenant Architecture - References

Just for my reference

http://msdn.microsoft.com/en-us/library/aa479069.aspx
http://msdn.microsoft.com/en-us/library/aa479086.aspx

Appium for Apps developed using Cordova

We need to do two things differently(IMO) when we want to automate Cordova apps

1. Switch to web view

          for(String winHandle : driver.getWindowHandles()){
              driver.switchTo().window(winHandle);
          }

2. 'By.xpath' may not work always, use 'By.name'

Wednesday, 9 April 2014

Cordova build command WshShell.Exec file not found

In windows 7, when you try to execute Cordova build you might receive WshShell.Exec not found error, try executing Cordova commands from Visual Studio command prompt.

Tuesday, 18 March 2014

Simple Login Screen using StoryBoard

https://docs.google.com/file/d/0B4h1L6UWmdivUHJXaHVRN2tsT0k

Asynchronous download using Coroutine - Lua

require("socket")

function download()
    local host, file, port = "www.w3.org", "/TR/REC-html32.html", 80
    local connection = assert(socket.connect(host, port))
    local count = 0    -- counts number of bytes read

    connection:send("GET " .. file .. " HTTP/1.0\r\n\r\n")

    while true do
        local response, status = receive(connection)

        if(response ~= nill) then count = count + string.len(response) end
        --print(response)
        if status == "closed" then break end
    end

    connection:close()

    print(file, count)
end

--[[function receive(connection)
    connection:settimeout(0)
    return connection:receive(2^10)
end]]--

function receive(connection)
    connection:settimeout(0)   -- do not block

    local response, status = connection:receive(2^10)

    if status == "timeout" then
        coroutine.yield(connection)
    end

    return response, status
end

threads = {}    -- list of all live threads

function get ()
  -- create coroutine
  local co = coroutine.create(function ()    download()  end)
  -- insert it in the list
  table.insert(threads, co)
end

function dispatcher()
    while true do
        local count = table.getn(threads)

        if(count <= 0) then break end

        for i = 1, count do
            local status, ret = coroutine.resume(threads[i])

            if not ret then table.remove(threads, i) break end
        end
    end
end

get()
get()
get()
get()
get()

dispatcher()

Tuesday, 4 March 2014

Permutations using Coroutines in Lua

First let's look at the algorithm for Permutations using recursion

algorithm Permutation(array, count)
              if array index is 0, display the array

              for each item in array until count
                     swap last and first item                    
                     Permutation(array, count -1)
                     swap last and first item                    
              end
end

now the code

function permuterate (a, n)
      if n == 0 then
        --printResult(a)
        coroutine.yield(a)
      else
        for i=1,n do

        --print("iteration=", i, "n=", n, "last=", a[n], "i th=",a[i])
          -- put i-th element as the last one
          a[n], a[i] = a[i], a[n]

          -- generate all permutations of the other elements
          permuterate(a, n - 1)

          --print("i=", i, "n=", n, "last=", a[n], "i th=",a[i])
          -- restore i-th element
          a[n], a[i] = a[i], a[n]

        end
      end
end

function printResult (a)
    for i,v in ipairs(a) do
        io.write(v, " ")
    end
    io.write("\n")
end

function createPermuterate(list)
    local pick = table.getn(list)
    local co = coroutine.create(function () permuterate(list, pick) end)

    return function()
                local _, value = coroutine.resume(co)

                return value
            end
end

function createPermuterate1(list)
    local pick = table.getn(list)
    return coroutine.wrap(function () permuterate(list, pick) end)
end

for p in createPermuterate{"1","2","3";n=3} do
    printResult(p)
end

for p in createPermuterate1{1,2,3;n=3} do
    printResult(p)
end

Coroutine in Lua - Consumer driven Producer-Consumer implementation

function send(task)
    coroutine.yield(task)
end

function receive()
    return coroutine.resume(co)
end

function consumer()
    while true do
        local _, task = receive()

        if(task == nil) then break end

        print("Processed item", task)
    end
end

co = coroutine.create(function ()
    local file = io.open("io.txt", "r")

    while true do
        local task = file:read("*line")

        if(task ~= nil) then
            send(task)
            print("waiting for consumer to signal")
        else
            break
        end
    end
end)

consumer()

Friday, 14 February 2014

Closure, Coroutine, Idempotent and Reentrancy

Closure - First class function that have access to free variables in a lexical environment
Coroutine - is a subroutine that have multiple entry points for suspending and resuming at certain locations - ex, C# we can use yield.
Idempotent - is an operation that be called multiple times without changing the result beyond initial application - ex, Cancel Order/Change address are idempotent, but Placing an order is not.
Reentrant - a re-entrant block of code is one that can be entered by another actor before an earlier invocation has finished, without affecting the path that the first actor would have taken through the code. That is, it is possible to re-enter the code while it's already running and still produce correct results.
Virtual Machine - Software emulation of a computer, two types - System VM and Process VM. Process VM provides portability and flexibility, and is bound to a single process. Loads when process load, and unloads when process goes out of scope. Process will be restricted to the resources/abstraction provided by VM. CLR is an example of Process VM

Thursday, 13 February 2014

C# Closure

As per wiki, Closure is a first class function with free variables that are bound in the lexical environment.

First class function is function that are treated as variable. C# we have delegates.
Free variables, are ones that are accessible to function which are not either passed as argument or defined locally.
Lexical environment means scope.

We call it closure because, first class function closes the variable it refers. In the example below, though myVar goes out of scope after first inc(), it is closed by the first class function(inc). It would print 7 & 9.

static void Main(string[] args)
{
    var inc = GetAFunc();
    Console.WriteLine(inc(5));
    Console.WriteLine(inc(6));
}
 
public static Func<int,int> GetAFunc()
{
    var myVar = 1;
    Func<int, int> inc = delegate(int var1)
                            {
                                myVar = myVar + 1;
                                return var1 + myVar;
                            };
    return inc;
}