Docker

I’ve been working on Docker for about a week now and I am amazed. I need to write about Docker more on my blog for my own notes and to share with the engineers in the world.

This is in Japanese but I need to re-watch it to get the big picture. Docker is really cool!

https://www.youtube.com/watch?v=5d8O7jm7Q5c

My Convenient PowerShell Stuff

I like a few convenient PowerShell functions that I like to keep in my $profile file. I should start to add more as I find more useful functions.

Function Prompt
{
	"$ "
}

Set-Alias -Name ll -Value Get-ChildItem
Import-Module ActiveDirectory
Import-Module Pester

<#
.Synopsis
   Searches files.
.DESCRIPTION
   Finds files that contains search string.
.EXAMPLE
   Find-InFiles -FindInDir "C:\Temp" -SearchString "Test"
#>
Function Check-LockedAccounts
{
	Begin{}
	Process
	{
		Search-ADAccount -LockedOut
	}
	End{}
}

Function Find-InFiles
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)] 
        [string] $FindInDir,

        [Parameter(Mandatory=$true,
                   Position=1)] 
        [string] $SearchString,

        [Parameter(Mandatory=$false, Position=2)]
        [string] $FileFilter = "*.*"

    )

    Begin
    {
    }
    Process
    {
		Get-ChildItem -File -Filter $FileFilter -Path $FindInDir -Recurse -Force -ErrorAction Ignore | Where-Object { Select-String $SearchString $_ -Quiet }
    }
    End
    {
    }
}

Function Get-SamAccountName
{
	[CmdletBinding()]
    [OutputType([string])]
    Param
    (
        [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$true, Position=0)] 
        [string] $FullName
    )

    Begin
    {
    }
    Process
    {
		$user = Get-ADUser -filter {DisplayName -eq $FullName} | Select Name, SamAccountName
		Return $user
    }
    End
    {
    }
}

 

Thoughts on Open Source

I think open source is great. Open source doesn’t necessarily mean that the software is free but 99% (just my guesstimate) of them are free. I use some great open source software on a daily basis, and I really appreciate those companies and individuals who contribute their time, energy and even some money to make it possible.

Let’s imagine a situation where a developer created a very useful piece of software. The software doesn’t have any proprietary data but it’s a reusable piece of software. When it happens, companies should make it open source or at least have a policy that allows developers to do it.

The first reason is to give back some to the world. I know many companies utilize open source software for free. If you come up with a good shareable software, why not give back a little?

Moreover, what if the developer who created the software leaves the company? It’s very possible in this fast pace industry. As a matter of fact, I just left my company yesterday for another opportunity. If that happens, the possibility is that the software is left unmaintained and forgotten. If you open source the software, not only it can be improved and maintained by the developer who created it, but also more people can jump in to make it even better. It’s beneficial not only to the world but also to the company and the individual who created the software.

Yeah, I can already hear some people say, “The developer used the company paid time, so the software belongs to the company!” Sure, I can understand the argument and I’m not saying that you should open source your proprietary software, but some shareable tools which won’t affect your business.

I intend to publish a piece of software as an open source software on GitHub. That’s all I’m going to say right now.

Robocopy

When I need to do some xcopy type of operation, I use robocopy. Robocopy is a tool that comes with Windows and it’s basically a replacement to the old xcopy in my opinion. I’m taking a note on it because I tend to forget the options I usually use.

robocopy C:\source C:\dest /E /R:1 /W:1

This one retries just once in case of an error after 1 second. It also copies sub directories even if they are empty. These options are good enough for me unless I’m working more on critical operations. 

Returning multiple values (Groovy)

I sometimes find myself wanting to return multiple values from a function. Here is what can be done with Groovy. I’m pretty sure that the same syntax can be applied to Java code as well though not sure if you can use the def keyword in Java.

    @Test
    void test_ReturnMultipleValues()
    {
        def (String var1, String var2) = return_multiple_values_function()
        assertTrue("The var1 variable should have hoge1", var1 == 'hoge1')
        assertTrue("The var2 variable should have hoge2", var2 == 'hoge2')
    }

    def return_multiple_values_function()
    {
        return ['hoge1', 'hoge2']
    }

What I think developers should not do is overuse this technique. What if you had 10 values you want to return from a function. I would not use this type of technique, but rather create a class that has all those 10 values and just return an instance of the class from the function. This technique is convenient for a quick function that does some validations or something like that.

DevOps

Quote from RackSpace YouTube.

DevOps integrates developers and operations teams in order to improve collaboration and productivity by automating infrastructure, automating workflow and continuously measuring application performance.

I agree with the statement 50% because there is one important aspect that is missing from it. I believe that DevOps should have a connotation that you or your team owns the whole process from design, code, test, deploy, monitor to maintain.

Regardless though, automation and integration is the key.

Python for C# Developers (control flow 1)

There are some differences in control flow in C# and Python though the concept in both languages is pretty much the same. Let’s take a look at them.

  1. Entry point
    The entry point to Python program can be expressed like the following. class is NOT necessary in Python, so if you are working on a simple script, I would just start to write logic in the file without a class. That said, I still like to encapsulate everything classes.

    class Main:
        def __init__(self):
            pass
    
        def say_hello(self):
            print('hello Python!')
    
    
    if __name__ == '__main__':
        entry_class = Main()
        entry_class.say_hello()
    
  2. if elif else
    Let’s think about the function that returns month name in a string.

        def get_month_name(num):
            if num == 1:
                return "January"
            elif num == 2:
                return "February"
            elif num == 3:
                return "March"
            elif num == 4:
                return "April"
            elif num == 5:
                return "May"
            elif num == 6:
                return "June"
            elif num == 7:
                return "July"
            elif num == 8:
                return "August"
            elif num == 9:
                return "September"
            elif num == 10:
                return "October"
            elif num == 11:
                return "November"
            elif num == 12:
                return "December"
            else:
                return "Invalid number" # Could throw an error

    I know the sample is ugly, but you get the idea. switch statement is NOT available in Python unfortunately but there is a workaround. I will write about in a separate blog post.

  3. while
    i = 0
    while i < 100:
        print(i)
        i += 1

    Not so elegant but while is still a necessary control statement.

  4. for
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    for n in nums:
        print(n)

    for in Python acts like foreach in C#. If you want to express something like for (int i = 0; i < nums.length; i++) {}, you can do something like the following.

    for n in range(1, 10):
        print(n)

    The sample shows that range function can be used to mimic “for (int i = 0; i < nums.length; i++) {}” in C#.

Python for C# Developers (try catch finally)

 

try, catch/except, finally is a necessary control flow in any modern programming language. Here is one in C#.

var obj = new MyObj();

try
{
    obj.func1("bad data"); // This line can cause an error.
    // Do some other work here if error didn't happen.
}
catch(SomeException exp)
{
   ExceptionHandler(exp);
}
finally
{
    obj.CleanUp();
}

Here is the sample in Python.

obj = MyObj()

try:
    obj.func1("bad data") # This line can cause an error.
except SomeError as exp:
    exception_handler(exp)
else:
    # Do some other work here if error didn't happen.
finally:
    obj.clean_up()

Notice that Python can have else clause but it’s not necessary to use it. I would use it if I want a very clear separation between “trying code” and the process after it.

There may be situations where you need to raise errors. You can simply use raise keyword like the example below.

raise ValueError("Entered value is not valid.")

There are quite a bit of builtin error types. They can be found in this document.

Lastly, if you need to create your own exception type, you can create a class that inherits from Exception class.

class MyError(Exception):
    pass