12/17/2020

String Calculator

This is an example how interactive process in TDD can help you think and expand on requirements.


Here are the concrete requirements:

STRING CALCULATOR

Before you start:

Try not to read ahead and do one task at a time.

Create a simple String calculator with a method int Add(string numbers).

The method can take a string representing numbers separated by commas, and will return their sum (for an empty string it will return 0) for example “” or “1” or “1,2”.

1. Start with the simplest case of an empty string and move to 1 and 2 numbers.

2. Allow the Add method to handle an unknown amount of numbers.

3. Allow the Add method to handle new lines between numbers (as well as commas).

a. The following input is ok: “1\n2,3” (will equal 6).

b. The following input is NOT ok: “1,\n”.

4. Support different single character delimiters (case-insensitive).

a. To change a delimiter, the beginning of the string will contain a separate line that looks like this: “//[delimiter]\n[numbers…]” for example “//;\n1;2” should return three where the delimiter is ‘;’.

5. Calling Add with a negative number will throw an exception “Negatives not allowed” - and the negative that was passed in. If there are multiple negatives, show all of them in the exception message.

6. Numbers greater than 1000 should be ignored, so adding 2 + 1001 + 13 = 15.

7. Allow multiple delimiters like this: “//[delim1][delim2]\n” for example “//*%\n1*2%3” should return 6.


Doing one task at a time suggests approaching the problem interactively - one task at a time - one test at a time and then expand on the tests.


Starting with the simplest case - returning 0 if empty string.






Writing this first test, the visual studio will suggest you don't have StringCalculator class created - the SUT- system under test. So that's what we need to create first.



This is enought code so the two projects - the test project and the class library project containing the SUT can be copiled. Well they are now, but the test fails. Lets write the code that fixes the test.



This is quite simply returning 0 if the string is empty, which makes our first test pass.

You can have a look at https://github.com/velchev/CTCalculator where I have added commits on every step of the iterative process, just so you can see the way of thinking about the problem.

The next requirement is when we have a single number in the string to return the same number as a result



Here I used Autofixture for xUnit. This is just to simplify the Arrange phase of the tests and to focus more on what the test is. It supplies SUT and random positive number. I am preparing the input and asserting on the result,  very clear intent.

Again this will fail as we haven't implemented this logic yet.



The way you can think here is if is not in the test we are not writing any extra code. This basically drives the TDD - tests needs to drive the implementation and not anything else. In this way no logical path is hidden, no surprises in the way the system works and clear documentation of what SUT does.

You can go through the commits of the repository for all the further steps. It was nice to implement this pure example of TDD. Some may argue that you can even think about requirements as user requirements and demonstrate BDD here, but they are so technical, there is no user to be part of the story which translates to meaningful text.

The next time you are given story write BDD style requirement and then on the implementation of specific method write some TDD style code and you will see it allows your thinking to focus on what you need to implement and not how till you need to implement, but by the time you need to implement the failed test you will know exactly what you need to write to pass it.

I hope you enjoyed this small post. Noting unique, but is my own interpretation of an Interview Task which I did recently.

2/02/2020

Algorithms

Good Web Sites to train your algorithmic skills:
http://www.leetcode.com/
http://www.careercup.com
http://www.topcoder.com
http://codeforces.com
http://www.spoj.com
http://uva.onlinejudge.org
http://projecteuler.net
http://www.usaco.org
http://prepare.hackerearth.com

Site for collaborative coding: http://collabedit.com
Source Code of the most popular data structures and algorithms in JAVA http://code.google.com/p/java-algorithms-implementation/

All the algorithms are implementations of algorithms described in Introduction to Algorithms book A web page useful for online interviews: http://collabedit.com It allows two or more people to work on one code together, by just knowing the exact address.

11/20/2016

How to change the SSD of Mac Book Pro Late 2012

I bought my Mac Book Pro with the best parameters at its time - CPU, GPU - Video Card, Maximum allowed RAM Memory 16GB, but the only thing I made a compromise was the SSD. At that time to buy 512 GB instead of mine 256GB would cost me additional £600. I remember the overall price of the laptop was £1700 with student discount (I was a student in the University of Bristol at that time), otherwise would be more than £2000 (can't remember how much exactly). Anyway the compromise was made and after just a couple of months it proofed itself to be very a bad one - too little space - this means nothing except programs and VMWare - Windows 7 (with Microsoft Development Package Visual Studio, SQL Server and so on) and X-Code. It was a struggle. I am a Software Engineer and usually use my laptop only for work but still I wanted to listen to music, edit home videos and other staff.

In 2014 I bought this storage expansion card - SDHC:


from Amazon. That was quick and cheap solution 128GB for 80 USD.
So now I could actually store images, videos and music. But it was slow and not as fast as SSD and for sure not useful for running applications directly from there.

The last option for me was fixing the actual problem - change of SSD. That was difficult choice as it was not officially done by apple.

After a lot of googling around I decided not to do it. This year - 2016 after I sow the new MacBook pro's - the fact that they still have 16 GB RAM, not so much better processors and most importantly the price was close to 3000£ if I wanted better components, I decided I will try to postponethat buy for some years.



So my next step was - go to amazon buy SSD and change it yourself.

It was £450

Then it turns out that is quite an easy process - everything is written as part of the instructions that are coming with the memory. First from system recovery mode copy the OS on the new SSD. Open, Replace and you are ready. It turns out that is exactly this. Do not be afraid!

Some pictures of my mac during the process:

Step1: place it and prepare for change so that each screw can be placed next to it's positions. The screws are 3 types (I am not sure), so not to care place them next to the whole where they have to go to.


Step2: Remove the screws and clean the dust with cotton buds. If you have never open your mac you will find a lot of staff in there.





That was it. After I replaced the SSD I careful put back the screws in their exact positions and all done. It was working fine, although it took some time for the spotlight search to reindex the files - couple of hours. Since then it was running absolutely fine. It is worth testing with Disk Speed Test - software for mac before you change your SSD and after - to compare if the new one is slower or faster. For me (Mac Late 2012) it turns out that there is no difference. Just when you test make sure you have not much running apps - so that the whole RAM can be used to test the SSD.


I know that 2016 Mac's have some unbelievable Read and Write Speed of their SSDs, but till the price is that hight I will be waiting for some years again before making change.

That's my Mac Now - from 256 GB to 1 TB:


Hope you get just a little inspired and go and change the SSD instead of selling what you have and buying a new model for more than £3000.

4/09/2016

My first lego Mindstorm Ev3 console app

It was interesting experimenting with the intelligent brick and the software that comes with it. (EV3 PROGRAMMING SOFTWARE (PC/MAC))
Much more interesting is to get a library which allows .net developers to write c# code to "talk" directly with the device.

The library https://github.com/velchev/legoev3 is available in github but also there is a nuget package for that.

Here is my simple first app: https://github.com/velchev/LegoMindstormEv3

Now is an initial setup that moves a servo. I will try to modify it so it executes commands from the command line will see how it goes.

10/12/2014

Bootstrap Modal Dialog - Loading Content from MVC Partial View

Original content - my post in code project. From there you can download and the source code.

Introduction

I will show a simple way to display the content of partial view in a bootstrap dialog. I will also show how to fix the dialog doesn't appear issue after 3.1.0 version. There is no need to write additional Ajax calls - this is handled internally by Bootstrap.

Background 

When you have a list - table of data and want to add a record, it's one of the better ideas to use a modal dialog - just because there will be no need to go to another page. Also for the deletion of records - confirmation could be done using bootstrap modal dialogs. There are many other places where you can use modal dialogs.
I saw online many different ways to create modal dialogs... many bad ways like: 
1. Creating all dialogs on the page and then just show or hide them using JavaScript. This means adding partial views to a page - render all the information and then if the user needs to see the dialog - it will appear.
2. Making Ajax calls to display the content. This means for every dialog a call .... not effective. It is better to use a library for that.
The question now is how to do it in a nice and simple way?

  • On the main layout, you need to have a modal container - the place where the dialogs will be loaded.

  • Set some styles - I have put that in the main layout just for the example, but you can put it in the correct place in your project.
  
    </style>   -->

  • Add JavaScript - this will make an Ajax call internally and will inject the partialview content into the modal container.

<script type="text/javascript">
        $(
function () {
           
// Initialize numeric spinner input boxes
            //$(".numeric-spinner").spinedit();
            // Initialize modal dialog
            // attach modal-container bootstrap attributes to links with .modal-link class.
            // when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
            $('body').on('click', '.modal-link', function (e) {
                e.preventDefault();
                $(
this).attr('data-target', '#modal-container');
                $(
this).attr('data-toggle', 'modal');
            });
           
// Attach listener to .modal-close-btn's so that when the button is pressed the modal dialog disappears
            $('body').on('click', '.modal-close-btn', function () {
                $(
'#modal-container').modal('hide');
            });
           
//clear modal cache, so that new content can be loaded
            $('#modal-container').on('hidden.bs.modal', function () {
                $(
this).removeData('bs.modal');
            });
            $(
'#CancelModal').on('click', function () {
               
return false;
            });
        });
   
</script>

  • Create a Controller Action, that will return partial view.

 public ActionResult ViewLyubomir()
{
    
return PartialView("_Lyubomir");
 }

  • Create an action that will process the result of the post occurring in the partial view.

[HttpPost]
 
public ActionResult Lyubomir()
 {
    
return RedirectToAction("Index");
 }

  • Create a partial view:
   <div class="modal-body">
    <div class="alert alert-warning">
       
<span class="glyphicon glyphicon-warning-sign"></span>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Donec consequat nisl a nibh tincidunt condimentum.
        Nullam in augue vitae augue dictum eleifend.
        Nunc porta fermentum metus, quis efficitur lectus scelerisque ac.
        Quisque egestas sit amet nunc in interdum.
        Etiam malesuada maximus nisi, id tempus metus.
        Vivamus at sapien ut metus aliquet sodales sed id magna.
        Integer in auctor ex. Phasellus tempor, est vel placerat dapibus,
        nulla dui tempor ligula, at pulvinar libero nunc gravida metus.
        Proin non feugiat felis. Proin ut ultrices ex. Morbi aliquet lacinia elit at bibendum.
        Nunc facilisis, neque a finibus dignissim, turpis felis vulputate diam,
        a tristique tellus nibh nec nulla. Suspendisse eget augue non turpis
        dignissim euismod eget eget odio. Donec sit amet nibh cursus, efficitur
        nibh in, sodales arcu. Pellentesque pulvinar consequat lacus ac porttitor.
   
</div>
    @using (Html.BeginForm("Lyubomir", "Home", FormMethod.Post))
    {
       
<div class="row">
           
       
</div>
       
<div class="row">
           
<div class="col-md-4 col-md-offset-4">
               
<button type="button" class="btn btn-default"
               
data-dismiss="modal">Cancel</button>
               
<button type="submit" id="approve-btn"
               
class="btn btn-danger">Save</button>
           
</div>
       
</div>
    }
</div>
<script type="text/javascript">
    $(
function () {
        $(
'#approve-btn').click(function () {
            $(
'#modal-container').modal('hide');
        });
    });
</script>
   

  • The last step is to create an action link with specific attributes.
@Html.ActionLink("Lyubomir ", "ViewLyubomir", "Home",
null, new { @class = "modal-link btn btn-success" })

How Does It Work?

On point 7 when the user clicks on the link, based on the attribute - modal-link we have an attached click event for all the links with that attribute - point 3. On point 3, the default action of a link will be prevented and the content to where this link points to will be injected into the model-container div point 1. When the user posts in the modal dialog - point 6, the data will be processed in the corresponding controller - point 5.
When you open the project - Home view has a link button - Lyubomir. Click on that and you will see the magic happening.

Points of Interest

As you can see - nice and simple, no direct Ajax calls to display the content - everything is handled by Bootstrap. Just remember the changing of the versions and how this affects the example. You can search online for that but, it seems a cosmetic issue but it took me quite some time to figure out where to apply it.

11/06/2013

SQL Scripts Runner

Introduction


A simple console application, which executes all SQL files added by developers working with decentralised development environment.

For downloading the source code: Codeproject Article

PROBLEM

How do you manage SQL scripts in a decentralised development environment?

The Figure below kind of describes the what I had in mind when I refer to a decentralised development environment?


Figure 1 
Decentralised Development Environment is the one with the local storage - the dashed box
Centralised Development Environment has only centralised data storage. 

Usually there is a main database and every developer has his own copy locally.

This type of development environment allows for independent work without the need of a network connection; if there is an error with the main storage, the others will still be able to work with their local database copies.

However a great disadvantage is that during development each developer has to maintain the main database and it’s local one. This means creating a script constantly with the necessary updates. Another option is to create a backup and restore the main database locally (this would take a lot of time and is not considerate as good practice).

So how can one keep track of the Database changes?
In this article I propose two solutions.
  1. Store the script in a common storage available for all developers – for example RedMine (http://www.redmine.org).
  2. Add all the SQL scripts in the project source control.


This first option separates the DB scripts from the concrete project, but does not provide for versioning. 
The second option however allows for versioning and when the latest version of the SQL scripts have been retrieved from the source control the developer can run it as a console executable manually. (It would be ideal if there were a way to do this automatically, this I leave to the general public.). 

What the executable should do?
  • Should be configurable – this should specify the SQL scripts folder.
  • The executable should run the scripts in order.
  • If there is a syntactic error with the script, the application should display it before even running the script - validation.
  • If there is a runtime error with the script all the scripts should roll back. The file and the line at which the error occurred should be displayed.
  • When there is no error then all the scripts should be executed and the changes applied.
  • Should have a way to test the results – simple Unit Testing.

One very important thing to be mentioned is that the SQL script should be written in a way that it can be executed many times (this means having check conditions or a drop and create statement).

Implementation

Returning a list of SQL files

All the files from a directory and its subdirectories should be returned but in the right order – this means that the files from folder Ver11.0 should be not after Ver1.0 if there is folder with name Ver2.0. This means that the sort order should be based on the values of the versions, but not by the string values.
That’s very easily implemented by a LINQ expression:
foreach (var d in Directory.GetDirectories(dir).OrderBy(x => float.Parse(Path.GetFileName(x).Substring(Configuration.Configuration.Pproperties.ScriptVersionPrefix.Length))))
{

Display the execution percentage


When \r is used the cursor goes back to the beginning of the current line and then can be rewritten. 

Console.Write("\r{0}{1}% complete", message, percent);

How to find SQL compile time errors?


The parsing capabilities of SQL Server Management Studio were used for this. I have used the two assemblies: Microsoft.Data.Schema.ScriptDom; Microsoft.Data.Schema.ScriptDom.Sql;

These two assemblies can be found in: C:\Windows\Microsoft.NET\assembly\GAC_MSIL
If you have installed MS SQL Management Studio
public static bool ParseSqlFile(string file)
{
     IList errors = new List();
     bool hasErros = false;
     using (TextReader reader = File.OpenText(file))
     {
         var parser = new TSql100Parser(true);
         var script = parser.Parse(reader, out errors) as TSqlScript;
         hasErros = errors.Count > 0;
         foreach (var parseError in errors)
         {
              Errors.ProcessErrors(file, parseError);
         }
      }
      return hasErros;
}

Main method of the application

All comes together in the main method. Here after the connection to the database is open, the SQL files are returned in a collection, then for every file its SQL script is parsed and executed as part of transaction so that when the execution is unsuccessful the data can be rolled back.

Please note:
//TODO: remove
Thread.Sleep(500);

This should be removed when it is used in practice. It is good for demo purposes so that the execution percentage can be seen.

The next section is not important for the current project and can be skipped. If after you get the source code you do not understand something about it you can get back to it.

Getting the configuration in OOP way

In “Configuration” folder can be found three files, which are responsible for getting the configuration settings from the App.config in OOP way. A custom attribute defines the key of the setting and after that the attribute is applied to a property, which is set by reflection when the console application starts.

The custom attribute  class:
[AttributeUsage(AttributeTargets.Property, Inherited = false)]
class ConfigAttribute : Attribute
{
     ///

     /// The key
     ///

 private readonly string key;
Class with properties which have attributes of the custom attrubute type
public class ConfigProperties
{
   ///

   /// Gets or sets a value indicating whether [use AU s_ AIS].
   ///

   ///
   ///   true if [use AU s_ AIS]; otherwise, false.
   ///

   [Config("SQLDir")]
public string SqlDir { get; set; }
In the “Configuration.cs” file is done the reading of the attributes by reflection.
static Configuration()
{
   properties = new ConfigProperties();
   var props = typeof(ConfigProperties).GetProperties();
   foreach (PropertyInfo prop in props)
   {
       string auth = string.Empty;
       object[] attrs = prop.GetCustomAttributes(true);
       foreach (object attr in attrs)
       {
          var authAttr = attr as ConfigAttribute;
          if (authAttr != null)
          {
             string propName = prop.Name;
             auth = authAttr.Key;
          }
   try
   {
    var value = Convert.ChangeType(ConfigurationManager.AppSettings.Get(auth), prop.PropertyType);
       prop.SetValue(properties, value, null);
   }
   catch (Exception ex)
   {
    throw ex;
   }
   break;
   }
 }
}


9/12/2013

Switching between two threads in console application

I will present a very simple idea of switching between two threads. The switch can be done by user pressing the enter key or by timer.

This is an idea which I am going to use to switch between main and backup service.
In my case I am getting the data from TCP stream. It is AIS data, and if one of the streams do not receive data, should be able to switch to backup stream.

This is the example which used the user key pressing:

using System;
using System.Threading;

class Demo1
{
    /*
     * Switch between two threads. When the user presses enter key, he wakes up one of the two threads dependig on counter.
     * When the counter reaches 10, then a variable inside the threads is set to true - which indicates that the thread will finish.
     * The body of the thread is executed one more time.
     *
     *
     *
     */

    static readonly object _locker1 = new object();
    static readonly object _locker2 = new object();

    //private static EventWaitHandle _mainWait = new AutoResetEvent(false);

    static bool exit_1 = false;
    static bool exit_2 = false;

    static void Main()
    {
        new Thread(Work1).Start();
        new Thread(Work2).Start();

        int x2 = 0;

        while (true)
        {

            Console.ReadLine(); // Wait for user to hit Enter
            x2 += 1;

            Console.WriteLine(x2);

            if (x2 % 10 == 0)
            {
                //_mainWait.Set();
                lock (_locker1)
                {
                    exit_1 = true;
                    Monitor.Pulse(_locker1);
                }
                lock (_locker2)
                {
                    exit_2 = true;
                    Monitor.Pulse(_locker2);
                }

                break;
            }

            if (x2 % 2 == 0)
            {
                lock (_locker1) // Let's now wake up the thread by
                {
                    // setting _go=true and pulsing.
                    Monitor.Pulse(_locker1);
                }
            }
            else
            {
                lock (_locker2) // Let's now wake up the thread by
                {
                    // setting _go=true and pulsing.
                    Monitor.Pulse(_locker2);
                }
            }
        }

        //_mainWait.WaitOne();
    }

    static void Work1()
    {
        lock (_locker1)
        {
            while (true)
            {
                Monitor.Wait(_locker1); // Lock is released while we’re waiting
                if (!exit_1)
                    Console.WriteLine("Worker1 - Woken!!!");
                else
                    Console.WriteLine("lastly called worker1");
                //Monitor.Wait(_locker1);
                if (exit_1)
                    break;
            }
        }
    }

    static void Work2()
    {
        lock (_locker2)
        {
            while (true)
            {
                Monitor.Wait(_locker2); // Lock is released while we’re waiting
                if (!exit_2)
                    Console.WriteLine("Worker2 - Woken!!!");
                else
                    Console.WriteLine("lastly called worker2");
                //Monitor.Wait(_locker2);
                if (exit_2)
                    break;

            }
        }
    }
}

Example with automatic switch done by timer:
using System;
using System.Threading;
using System.Timers;

class Demo1
{
    /*
     * Switch between two threads. When the user presses enter key, he wakes up one of the two threads dependig on counter.
     * When the counter reaches 10, then a variable inside the threads is set to true - which indicates that the thread will finish.
     * The body of the thread is executed one more time.
     *
     *
     *
     */

    static readonly object _locker1 = new object();
    static readonly object _locker2 = new object();

    static readonly object _locker3 = new object();

    public static System.Timers.Timer HealthCheckTimer = new System.Timers.Timer();
    public static System.Timers.Timer HealthCheckTimerBackup = new System.Timers.Timer();
   
    //private static EventWaitHandle _mainWait = new AutoResetEvent(false);
   
    static bool exit_1 = false;
    static bool exit_2 = false;

    static void Main()
    {                                
        new Thread(Work1).Start();  
        new Thread(Work2).Start();
       
        int x2 = 0;
        HealthCheckTimer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        HealthCheckTimer.Interval = 100;
        HealthCheckTimer.Enabled = true;

        while (true)
        {
            lock (_locker3)
            {
                Monitor.Wait(_locker3);
            }

            x2 += 1;
           
            Console.WriteLine(x2);

            if (x2 % 10 == 0)
            {
                lock (_locker1)
                {
                    exit_1 = true;
                    Monitor.Pulse(_locker1);
                }
                lock (_locker2)
                {
                    exit_2 = true;
                    Monitor.Pulse(_locker2);  
                }

                break;
            }

            if (x2 % 2 == 0)
            {
                lock (_locker1)
                {
                    Monitor.Pulse(_locker1);
                }
            }
            else
            {
                lock (_locker2)
                {
                    Monitor.Pulse(_locker2);
                }
            }
        }
       
        //_mainWait.WaitOne();
    }

    private static void OnElapsedTime(object sender, ElapsedEventArgs e)
    {
        lock (_locker3)
        {
            Monitor.Pulse(_locker3);
        }
    }

    static void Work1()
    {
        lock (_locker1)
        {
            while (true)
            {
                Monitor.Wait(_locker1); // Lock is released while we’re waiting
                if(!exit_1)
                    Console.WriteLine("Worker1 - Woken!!!");
                else
                    Console.WriteLine("lastly called worker1");
                //Monitor.Wait(_locker1);
                if(exit_1)
                    break;
            }
        }
    }

    static void Work2()
    {
        lock (_locker2)
        {
            while (true)
            {
                Monitor.Wait(_locker2); // Lock is released while we’re waiting
                if(!exit_2)
                    Console.WriteLine("Worker2 - Woken!!!");
                else
                    Console.WriteLine("lastly called worker2");
                //Monitor.Wait(_locker2);
                if(exit_2)
                    break;
               
            }
        }
    }
}