Friday, December 2, 2016

Python Swap Function

In the coming semester it is likely that I will T.A. a course in Python. Lately I've been researching the language and using it for my pet projects that never get finished, interviews, etc...

One thing I found interesting is writing a swap in function. For some sorting algorithms we often have to swap the values at two indices in an array, so this does come up fairly often. What I found especially interesting was that you could do this in one line using Python. Where in most programming languages you have to write something like...

In Python, this can be written as... 

This is because Python evaluates assignments right to left. When the right hand side gets evaluated, Python creates a tuple (val_i, val_j) then assigns the variables in the left their corresponding tuple values. 

Most experienced Python programmers already knew this, but I found it pretty cool. All credit for the knowledge goes to this stack overflow post.

Wednesday, November 23, 2016

Researching Encryption in Windows and C# .NET

I was recently tasked with researching different methods of encryption for a license management module within my company and thought it might be useful to write down some of my findings. 

Cryptography has been around for a long time. Some of the more famous forms of old cryptography are in the Roman army, which used the "Caesar Cypher" to shift all letters to the left by three. "A" would become "X", "B" would become "Y", etc.

These days there are many more forms of data, and different ways to intercept it. Specifically we have data in-transit, and data at-rest.

For data-in-transit we use a public key private key method. The actual encryption of this method involves factoring extremely large numbers into their primes. If you're interested, this is a great video to watch.

With data-at-rest we use more complicated algorithms. In the Microsoft .NET library, these encryption methods are very well documented and held within the System.Security.Cryptography namespace. This includes methods for both in-transit and at-rest cryptography. 

Within the namespace there are two main encryption methods, Rijndael and Aes. The Microsoft Recommended method of encrypting data-at-rest is the AES method because Rijndael will not work when the FIPS-compliant security setting is enabled on a windows operating system. 

In conclusion, if you are encrypting a file, database, or some data on disk in a windows environment you should be using either the AesManaged, or AesCryptoServiceProvider classes from the System.Security.Cryptography namespaces. 

Tuesday, September 27, 2016

Fermat's Near Miss

A lot of people have heard about Fermat's last theorem. Originally proposed in the 1600s, the theorem was finally solved in the 20th century by a mathematician named Andrew WIles. 

Fermat's theorem says that there are no solutions (x,y,z) to the equation x^n + y^n = z^n for n > 2. If you've studied math or physics at a university or in some cases high school level you have likely heard of it. Today I was reminded of an example from the Simpsons which is purported to show a solution where x^n + y^n = z^n. Specifically...


There we see 3987^12 + 4365^12 = 4472^12. And if you were to plug this into a handheld calculator, it would be correct!

So what is going on? How could Homer Simpson have a counter-example to Andrew Wiles proof? In fact, these numbers are so large that most calculators round the error off and they appear to be the same! X, y, z combinations like this that "solve" Fermat's last theorem are known as near misses. I was reminded of this interesting example by this video, but have also read it in this book.

Also of note, in the holy doughnut to filled in doughnut progression along the bottom of the chalkboard, Homer is "solving" a question in topology! Unfortunately, in topology, a doughnut and a sphere do not equate... 

Monday, August 15, 2016

C# .Net Utility in WPF

I very recently had the opportunity to develop a simple tool in wpf and C# .Net to execute some procedural actions necessary to quickly make copies of our application. Surely there is an "easier" way to do this with windows system scripting, but for the sake of education and usability (we don't want our clients running windows scripts) we chose to write an executable. 

Several things surprised me during the development. First, wpf has become much easier. The most useful resource I found was WPF MVVM In Depth by Brian Noyes. In his tutorial he builds WPF up from code-behinds and simple applications that take inputs and generate outputs. The most essential parts for me were the building blocks of implementing INotifyPropertyChanged and ICommand. This was good enough for my current application, but more complex applications meant to display and manipulate data will probably go into using ObservableCollections and defining sql server data sources. 

This project, along with other personal things kept me very busy the last few weeks, though I hope to return to posting more frequently. I've now changed the blog name from "Daily Blog" to simply "Blog".

Thursday, July 7, 2016

C# .NET and WPF

I recently had a terribly boring project in which I had to go through 27 pdf documents and compare copies word for word. That means reading a total of 54 documents and comparing for exact word for word copies. And no, they could not be done with pdf comparison tools, it was required that human eyes search through each document at some point.

In order not to burn out, I started a project in C#.NET and WPF on the side. What I found was that C# is one of the easiest languages there is. I was able to create classes and structures using the .NET toolset to model my data in about two hours. Then I tried to connect it to a WPF interface.

WPF is ridiculously difficult to "jump into". I found it really hard to get resources online, then half the resources said you need to use the prism library to do WPF correctly and encountered similar difficulty in finding prism examples. All the examples I found used code-behinds to bind data, which, from the Microsoft examples, are an antipattern. I really felt like there were more contradictory and dated examples of WPF and C#.NET code than there are of javascript (though I'm sure that isn't true).

Sunday, May 15, 2016

Python SimpleHTTPServer

I went and wrote the python simplehttpserver myself, just for kicks...

edit: here's the github

Friday, May 13, 2016

Simple Python Server

This is how you make a simple python server. It'll server index.html if you request the root, or whatever html file you request.

Wednesday, May 11, 2016

Node JS Static Server

I was interested to see how hard it was to write a static file server in pure node js, meaning without express.js. Turns out it's quite easy, but the real point of this was to familiarize myself further with using node and reading the node documentation.

Monday, April 18, 2016

Apply XSLT to XML in Visual Studio

With the XSLT file open, right click anywhere and go to file properties. Set the input to the file you'd like to apply your xslt to, and output to the file you'd like it to output to.

Simple as that, I just always forget the input option is in the right click > properties menu.

Wednesday, March 23, 2016

Sample Configuration File

Bittorrent sync is awesome. End of story. 

I am syncing different directories between my work computer, home computer, raspberry pi, and cell phone. Mostly the pi is the "source" of my files, and external backup in case one of my drives dies. 

One problem I ran into was that for some reason, if I ran btsync at startup of the pi it would "forget" all the directories I had shared. I don't know why. I decided instead to run with a config file containing all the directories I was syncing since that wouldn't change from shutdown to startup and such. However, I couldn't find any good examples online! So once I got mine working I posted it to my github.

I left the fields secret and dir, under shared folders blank. To generate a read-write secret, run ./btsync --generate-secret within the folder that the btsync executable is in. In the dir field, enter the directory you'd like to sync. Keep in mind that btsync cannot merge non-empty directories.

Go check it out for a decent example or starting point to bittorrent sync config files.

Thursday, March 10, 2016

Linux Networking Commands

netstat - shows you the state of all active sockets
ping - sends packets to another ip address
ifconfig - shows your computers networking information
traceroute - displays the route that a packet takes
hostname - set or display the current host/domain name
nslookup - query name servers directly
netcat - set up a connection between two computers, almost looks like a messaging application.

Wednesday, March 9, 2016

Networking

Networking, like onions, comes in layers. Unlike onions, networks have about 5 layers

layer 1: Physical. The lowest layer, the physical connection. This could be something like wifi, ethernet, radio connection. Learn physics.

layer 2: Link. Next to lowest, this layer contains information about the physical layer, and allows you to send bytes over it.

layer 3: Network. This layer assigns addresses to different communicating things on the network. Most people are familiar with IPv4 and IPv6, but there are less popular alternatives.

layer 4: Transport. This is what the T in TCP stands for. TCP basically guarantees that all your bytes have been transferred, and that they look like a single stream.

layer 5: Application. This is a two byte internal identifier that your computer uses to know which application made which request. (PORT number).

Tuesday, February 23, 2016

Sayre's Law

Here's something I read about recently, seems to apply pretty universally. I love it when little bits of wisdom like this are declared "such and such's law", "xyz's paradigm", "joe's theory of blank". I don't know why I find it funny.

Wednesday, February 10, 2016

PNG's and DPI's

PNG's are a web image format, and as such try to be independent of the device dpi so you can set the resolution and image size in your css or let the browser handle it. However, we use pngs for some desktop applications. Because of inconsistent dpi settings on different pngs we had some weird behavior where wpf was blowing up our save icons, but not our open file icons. The result in wpf was to set the width, height, and stretch attributes to our image element manually, as well as the SnapsToPixels to true for antialiasing (though at that image size I couldn't see the difference).

To be sure the png's had different dpi's and that was the problem, I had to install gimp, open the png, look at the image properties and the resolution. It would have been nice if this was just in the details tab of the properties window of the image, but if I'm right that png's don't worry about dpi it would make sense that dpi is excluded there.

Friday, February 5, 2016

My Favorite Math Joke!

A farmer has 100 ft of fencing and wants to enclose as large an area as possible, so he does the obvious thing, and hires an engineer, a physicist, and a mathematician to consult him. The engineer quickly pens in a square with the 100 ft and says voila! The physicist, knowing he can optimize this, goes to the blackboard and finds that a circle would enclose a larger area. The mathematician, after much deep thought, pulls out two feet of fencing, wraps it around his waist, and yells "I declare myself to be on the outside"!

Sunday, January 31, 2016

Euclidean Algorithm for GCD

The Euclidean algorithm is a cool little way to find the GCD of two integers. 

Say you have 46 and 90...

Then 95 = 46 * 2 + 3
And 46 = 3 * 15 + 1
3 = 1 * 3 + 0

so the GCD of 95 and 46 is 1. Maybe not the best example, but I'm hungover so you can google it.

Friday, January 29, 2016

Memory And Hex

As you may know I'm taking a class in C and C++ this semester (Spring of 2016) and have found C to be the best language ever (revised 2017: it's great and all, but not THIS great). It's really fun because of it's simplicity, the lack of functionality and user interface makes it easy and demanding of creativity. 

I just started reading up on pointers and memory addresses when I got curious about just how memory addresses are stored in pointers. Try compiling and running the simple function below to see how memory addresses are stored as hex values.


Monday, January 25, 2016

Probably Handy

Since I'm taking a class in C now I think the table below that I found here will come in useful at some point...

PrecedenceOperatorDescriptionAssociativity
1++ --Suffix/postfix increment and decrementLeft-to-right
()Function call
[]Array subscripting
.Structure and union member access
->Structure and union member access through pointer
(type){list}Compound literal(C99)
2++ --Prefix increment and decrementRight-to-left
+ -Unary plus and minus
! ~Logical NOT and bitwise NOT
(type)Type cast
*Indirection (dereference)
&Address-of
sizeofSize-of
_AlignofAlignment requirement(C11)
3* / %Multiplication, division, and remainderLeft-to-right
4+ -Addition and subtraction
5<< >>Bitwise left shift and right shift
6< <=For relational operators < and ≤ respectively
> >=For relational operators > and ≥ respectively
7== !=For relational = and ≠ respectively
8&Bitwise AND
9^Bitwise XOR (exclusive or)
10|Bitwise OR (inclusive or)
11&&Logical AND
12||Logical OR
13[note 1]?:Ternary conditional[note 2]Right-to-Left
14=Simple assignment
+= -=Assignment by sum and difference
*= /= %=Assignment by product, quotient, and remainder
<<= >>=Assignment by bitwise left shift and right shift
&= ^= |=Assignment by bitwise AND, XOR, and OR
15,CommaLeft-to-right

Thursday, January 21, 2016

Two's Compliment

Today I'm reading about two's complement and the difference between signed and unsigned integers. In the near future I'm expecting to know a bunch of random stupid (and probably useful) info about ascii, utf, and hex representations of different characters... Starting by reading here.

Saturday, January 16, 2016

Calculator

Remember that shunting yard algorithm post? Well I turned it into a calculator demo on my website. I made this alongside the implementation of redux that I've been posting about.

check it out here

Tuesday, January 12, 2016

Javascript Objects

Often, Javascript objects are used as a hashtable with a string being the key value. I was curious if this is how they were implemented behind the scenes and found that I was clearly not the first one. Check out this quora question... 

I think it's pretty cool they're not done with hashtables in the V8 engine.

Monday, January 11, 2016

Instanceof String

I was playing with javascript error handling and understanding where to use try/catch today when I ran into an interesting problem. As part of my error handling I tried to include a type check on the key portion of a key-value pair, just to ensure that the key is actually a string and not null, undefined, numeric... 


That's when I noticed the following...


According to MDN (ctrl + f "Primitives and string objects") javascript handles string primitives differently from string objects. When creating a string with single or double quotes, or the global String object, javascript returns a primitive string. However, when creating a string with the new keyword, javascript returns a new string object. This makes sense when you read it, but if you're unaware or unfamiliar it could easily bite you. 

Finally, the documentation does say that "JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings". The problem is that Javascript only does this for String object methods, but instanceof is not a string object method. Instead, since instanceof is a global relational operator, the string created by quotes remains a primitive string and fails the instanceof String test.

Saturday, January 9, 2016

TrainShunting

For ages now I've been trying to implement the Shunting Yard Algorithm to take an expression and evaluate it. Yesterday I finally did it! I completed an iterative Shunting Yard Algorithm along with an evaluation function. The current calculator application is just using the built in javascript eval() function, but now that my shunting yard algo is finished I can use that!

The reason my algorithm is special is that it doesn't just return the prefix statement, but also returns the operator stack and output stack after each pass through the loop! This was actually a little tricky because I needed to make copies of the array at each stage rather than just make a reference to the array. If I had not used Array.from() to make a copy at each stage, I would end up with an array of references to the same object. In other words I would end up with a javascript object containing the final prefix expression, an array of multiple copies of the final prefix expression, and an array of empty arrays.

Another problem I ran into was that, since I was doing this algorithm so infrequently, I never actually took the time out to learn it. I was trying to implement it from pure pseudo-code rather than understand what was actually happening. Understanding what was happening wasn't easy either though, I had never heard of operator associativity or precedence (maybe they're worth a short post in and of themselves). Once I finally had a grasp on it thought, the implementation was fast.

One improvement I want to make is to my evaluate function. I think there must be a way to evaluate the prefix expression recursively (like a recursive in order tree traversal), but right now I'm evaluating it iteratively.

Here's the code, it's got a lot of cleaning up and commenting to do, but what I've got now is in functioning order. Also notice that it currently doesn't handle sin, cos, tan functions.

Friday, January 8, 2016

FFR: Pizza Theorem

In the case that two people are sharing a pizza in which no cut divides the pizza directly in half, apply the Pizza Theorem. Alternate slices chosen to ensure people eating get exactly half the pie.