Sunday 29 May 2016

Yo! - I'm a Lambda.

I've just been reading up on the new JavaScript/ECMAScript 6 features and in particular the new fat-arrow syntax for lambdas.

It's funny, but whenever I see this syntax () => { } in C# code, my mind always shouts to me "Yo!! - I'm a Lambda". - Okay, I understand that might sound weird... It is weird and I don't know how to stop it!

Let me explain!

What I mean is, as programmers, when we read code our brain automatically identifies the cryptic string of characters and converts them to a mental model of what the code will do on the fly. For example, when scanning code, if you come across a for or while keyword your brain automatically tells you: "oh... there's a loop coming". If you see an if you automatically know there is a condition and a branch coming.

This happens instantaneously without fore-thought. It's like words on a poster. Your mind reads the words even if you're not interested in what the poster is advertising. In fact, put anything in front of yourself with words and your mind just reads it without asking you! It just happens!

In C#, whenever I see the the following syntax () -> {}, my mind always shouts to me "Yo!! - I'm a Lambda" because when I was learning the arrow syntax I engraved that sentence into my sub-conscious. And now... I can't shake it!!

So there I was, reading the new JavaScript syntax for lambda's and it happened again! This is when I thought it would be interesting to write a blog post on lambda's and compare the different lambda syntax's from various languages. You know, to see if my mind would play this phrase across languages.

Quick n Dirty Overview of Lambda's


Way back in the day, when I first saw a lambda I remember thinking, "what the smeg is that?" - It was weird looking code like this: x => { return x + 1; }. I didn't know what the X was doing on the left hand side. It just looked funny... Turns out, it is a lambda!

This is how you read a lambda expression:
  • Everything to the LEFT of the arrow is the function parameters.
  • Everything to the RIGHT of the arrow is the function body.
Remember good old-fashioned functions like this:
int AddOne(int x)
{
   return x + 1;
}
To write that as a lambda it becomes:
(int x) => { return x + 1; }
Notice above, that you can see the outline of the function still. You can still see the function takes an int as a parameter named x. Okay, its on one-line, and the name has gone but the outline is still there. The additional punctuation/syntax that's been added is the => which is where my "Yo!! - I'm a Lambda" gets triggered.

Turns out though that we can simplify this even more. If the compiler can determine the type that's passed in, you don’t need to put it there. So it becomes:
(x) => { return x + 1; }
Now, as this function only takes 1 parameter it turns out you can also leave out the parenthesis which gives you:
x => { return x + 1; }
Finally, you can simplify it even more and leave out the return statement (and remove the parenthesis). Then it becomes:
x => x + 1
This is the transformation:
// From this traditional Function
int AddOne(int x)
{
   return x + 1;
}

// ...to this Lambda expression!
x => x + 1

That's all good and easy to understand but when I used to see the code below it used to throw me.
var sum = () => 1 + 2;
It was the empty parenthesis that did it. But that's just a lambda expression that takes zero parameters and returns the sum of 1 + 2. But it looks odd.

Want to see what lambdas look like in other languages? Turns out, so did I. Read on!

C# Lambda Syntax

Okay, we already know what the C# code looks like. Below is the AddOne function as a lambda expression.

class Program
{
    public delegate int AddOne(int value);

    static void Main(string[] args)
    {
        AddOne lambdaFunc = (int someVar) => { return someVar + 1; };

        lambdaFunc(2);
    }
}

You can test this out with the online C# compiler here: http://csharppad.com/

JavaScript Lambda Syntax

As I mentioned earlier, it was whilst reading up on JavaScript Lambda functions that prompted me to write this blog post. The JavaScript code looks something like this:

var lambdaFunc = (someVar) => someVar + 1;
lambdaFunc(2)

To test this out, simply press F12 in your browser, navigate to the console tab and enter the above code.

C++ Lambda Syntax

In C++ they don't use the fat-arrow. They use the array index operators [] as the lambda operator. This allows you to capture the surrounding variables by reference or by value and is my "Yo!! - I'm a Lambda" trigger. The code looks like this:

int main()
{
    auto lambdaFunc = [&] (int someVar) { return someVar + 1; };
    lambdaFunc(2); // now call the function
}

You can try this out using the online C++ compiler here: http://cpp.sh

Rust Lambda Syntax

This one's a bit weird. The syntax looks funny as they use the pipe operator | which is something I am not familiar with.

fn main() {
    let lambda_func = |some_var: i32| return some_var + 1;
    lambda_func(2);
}

You can try this out using the online rust compiler here: https://play.rust-lang.org. Incidentally, the rust compiler forced me to change all my variables to snake_case which I thought was interesting. I like the way you can enforce variable names to keep the code consistent.

Python Lambda Syntax


I like the way Python is all in your face by putting the keyword lambda front and centre. Here's the code:
lambdaFunc = lambda someVar: someVar + 1
lambdaFunc(2)

Again, you can try this out here: https://repl.it/languages/python3

Ruby Lambda Syntax

Ruby is quite similar to JavaScript, with a couple of subtle differences. Instead of the fat-arrow they use a thin-arrow! Also the thin-arrow comes before the function parameter list, whereas other languages put the arrow operator in the middle. Here's the code:

lambdaFunc = -> (someVar) { someVar + 1 }
lambdaFunc.call(2)

Here is the online compiler to check it out for yourself: https://repl.it/languages/ruby

Swift Lambda Syntax


Unfortunately, I have not tested this code but from the documentation, the Swift definition of a lambda is as follows: Lambdas are typically enclosed in curly braces { } and are defined by a function type () -> (), where -> separates the arguments and the return type, followed by the in keyword which separates the closure header from its body.
{ (params) -> returnType in
  statements
}

Notice, here you define the return type for the function where other languages put the function body. Swift also has the in keyword which proceeds the function statements. Our example would look like this:

{ (someVar) -> Int in
  someVar + 1;
}

Go Lambda Syntax

Strangely it looks like Go doesn't support the lambda syntax and the language designers have no intention to add the functionality to the language.

See here: https://groups.google.com/forum/#!topic/golang-nuts/Kfm4t3TShTY

Wrapping up

If you throw a dart in the direction of a modern programming language today, chances are it will support lambdas! More and more languages are borrowing concepts from functional programming. Lambdas are a great way to pass around functions and simplify code.


Contact Me:  ocean.airdrop@gmail.com

Saturday 21 May 2016

Windows Command Line Goodies

With the news that Microsoft is bringing Bash to Windows (what a crazy world we live in!), it looks like I'm going to add "bash" to my "one more thing to learn" list.

In the meantime, I thought it would be good to list the common daily windows cmd.exe tools that I use and find useful. You can't beat the command line for performing fast, repeatable, scriptable actions that you might need to schedule or run ad-hoc.

Let's start the list:

Get the hostname of the computer you are on

If you are like me and can be logged into many remote desktop sessions, then it can be useful to find out the hostname of the computer you are on. To do that, the command is: hostname. This means you will never get caught deleting files from the wrong server again! :)

Another simple command is the whoami command which will tell you the user you are logged on as for this session

Change the title of the command prompt window

Okay, you might laugh, but this is more useful than you think. If you have many cmd prompts open doing different tasks, changing the title of the command window helps you quickly identify the window you need.

List all processes running on the local machine

Ensuring that processes are running is essential bread and butter stuff. The tasklist command will give you what you need.

You can also list all processes running and their loaded DLL’s with the -m switch: tasklist -m

List all processes running on a remote machine

The tasklist command above can also list processes that are running on remote machines. Again, very useful. The command is: tasklist /s 10.10.10.10 /u domain\username. You will, of course, be prompted for the user's password

Kill a process running on the local machine

I use this all the time. There is no faster way of closing chrome.exe and all its tabs than from the command line. The command is: taskkill /F /IM pcocessname.exe.

Kill a process running on a remote machine

To kill a process on a remote machine you just need to supply the /s and /u flags to the taskkill command. For example: taskkill /s 10.10.10.10 /u domain\username /IM "appname.exe"

Display all services running on a machine

If you have services that you know should be running, then running net start shows you all services that have been started on your machine.

Pinging and IP addresses

This is the simplest of all diagnostic commands: ping 10.20.30.40. If you want to keep a constant ping going add the -t flag like so: ping 10.109.200.3 -t. I also like the utility fping by Kwakkelflap. You can download it from here.

It allows you to add a date and time to the ping, as well as log the pings to a file. You can even specify the amount of time to wait in-between each ping.

For example, the following command: fping 10.20.30.40 -D -T -c -t 10000 -L hello.txt will ping 10.20.30.40 logging the date and time to a file named hello.txt. It also waits 10 seconds in-between each ping. I like this utility, but one problem I have found is, it doesn't flush the file. This means you need to stop the execution before it writes everything out.

If you want to get your own IP address run ipconfig /all.

Display all IP addresses connected to a machine

If you want to display all IP addresses that are connected to a machine and what process they are connected to then run netstat -a -n. If you want to display all IP addresses connected on a specific port then pipe it through the find command. E.G: netstat -na | find "1234"

PSTools

This should probably be at the top of the list. The PSTools suite is great and my stand out favorite is the psexec tool. It allows you to run any dos command you issue on a remote computer.

For example, if you wanted to run netstat –n to display all IP addresses connected to a remote machine then you could run the following command: psexec.exe \\10.10.10.10 -u domain\username -p password netstat –n

Elevate

Have you ever tried modifying the hosts file only to be greeted with this dialog?

If so, then Elevate is the command line tool you need. This is just one example, but there can be many cases where you need to run something with elevated rights.

Connect to SQL Server database

If you have an SQL server instance you can run queries straight from the command line by using the osql command. For example: OSQL -S 10.10.10.10\SQLExpress -U username -P password -d dbname -Q "select * from [dbname]..[tablename] where columna = 'blah-de-blah'"

You can even send the result to a text file OSQL -S 10.10.10.10\SQLExpress -U username -P password -d dbname -Q "select * from [dbname]..[tablename] where columna = 'blah-de-blah'" >c:\textfile.txt

IP routing and adding a fixed route to your routing table

To view your routing table simply run route print. This will show you all the routes that are setup on your machine. You can add a fixed route to your routing table by running the "route add" command. This can be useful if you want to route traffic in a certain IP address range to a specific destination server. This has been useful to me in OpenVPN environments when I needed to force specific IP packets to a gateway.

To do this, first delete the route before adding it (just to make sure it doesn't already exist). For example: route delete 172.16.0.0. Then add the permanent route by running "route add" with the -p flag set. The -p flag says "make this permanent". For example route -p add 172.16.0.0 MASK 255.255.0.0 10.20.30.40 will create a route whereby and traffic that is destined for the IP range 172.16.x.x will get routed/pushed to the server 10.20.30.40.

Test if a remote server is listening on a specific port number

If you have a server listening on a remote port and you want to check it is accepting incoming connections, then you can use telnet to connect to the server and port. If it fails you will get the following error message back: "Could not open connection to the host, on port 25: Connect failed". This is very useful.

For example, the following command will try and connect to a server on port 80: telnet 10.20.30.40 80

Remote shutdown a SERVER!!!!

Naturally, use this one with caution! It's always a bit scary waiting for the server to come back up. When I do a remote-boot of a server, I keep a constant ping going so I can see when it comes back up

Don't forget, its obligatory when remote booting any server to mutter the Samuel L Jackson line from Jurassic Park: "hold onto your butts!"

Here's the command: shutdown -t 0 -r -f -m \\10.10.10.10

Find out users Logged onto a machine and logging them off

Under certain situations, you might find that you can't rdp onto a server because there are other users logged on. If this is the case you can issue the following command: quser /server:10.10.10.10. This will return a list of username's and and user id's. Following on from this, if you want to log a user off then run the logoff command, like so: logoff 1 /server:10.10.10.10. The 1 here is the user id returned from the quser command.

Time how long it takes a web page to load

cURL is a command-line tool that can communicate over a network using TCP, HTTP, etc. It includes metrics which means you can use it to time how long it takes for a web page to load.

Use it like so: curl -3 -k "https://oceanairdrop.blogspot.com"

Summing up

These commands are all bread and butter stuff but are useful to know to get diagnostic information about your environment. If you are responsible for a number of servers some of these commands can be a life saver. If you are unable to log onto a remote machine (using mstsc.exe) for whatever reason, don't forget about the command line. Being able to run these commands remotely (psexec.exe) is a godsend.

That's about it.... Remember, when issuing any of these commands, don't forget to "hold onto your butts!"


Contact Me:  ocean.airdrop@gmail.com

Sunday 15 May 2016

Observations on Software Package Managers

It’s interesting to watch the landscape of software development evolve over time.

One of those evolution's is the advent of package managers. As an application developer, having access to a global library of code packages which can be pulled down in an automated way, is such a valuable addition to the development experience.

They are everywhere! For example:

Package managers are here and they definitely increase productivity by making common code easier to include in your project.

When I first uploaded my projects to Github, I mistakenly included all my third party Nuget packages and forgot that one of the other jobs of a package manager is to install/restore missing packages when required.

Beautiful… That, is of course, until it goes wrong…

For example, if you don’t pin a specific version of a library, there is nothing to stop the owner of that third party library from making breaking changes to your code. This means you will not be able to successfully build your project in the future.

For example, in JavaScript with NPM, if you just list all your dependencies (in the package.json file) without specific versions, this will pull down the latest version(s) automatically.

So pinning to a specific version is good practice.

But, on the flip-side, recently I was trying to download a C# project from GitHub that required a Nuget restore. The problem was, the version that the C# project relied on didn't exist in Nuget! Nuget failed to retrieve the version that was pinned. This meant I couldn't build the code.

However, even with these subtle observations/gotcha’s aside, package managers are a great addition to the software developer’s toolkit.

If you are a C# developer and use Nuget you might want to check out the NuGet.CommandLine package by running "Install-Package NuGet.CommandLine". Instructions are here. This can be handy for automated builds and will enable you to run commands like "nuget delete", "nuget restore" and "nuget update"

Now, I would love to see a C++ package manager but it doesn’t look like there is one yet. Maybe thats because it still uses #includes and doesn't have the concept of a package! - Maybe when modules make it into the language there will be some hope there. I don't know if it’s out of scope for the guys over as https://isocpp.org/ but it would be good if there was an official one!

One can hope…

By the way, this website https://libraries.io/ monitors "open source libraries across 32 different package managers", which could be a great way to search for new libraries to include in software projects.


Contact Me:  ocean.airdrop@gmail.com

Popular Posts

Recent Posts

Unordered List

Text Widget

Pages