Author Archives: brandonio21

Visualizing my Operating System Use

In my work, home, and play life, I constantly switch operating systems. If I want to play games, I use Windows. If I want to get some hardcore development done, I use Linux. If I want to casually browse the internet, I use my mac. But the question remains: How often do I use each operating system?

The Tool

Being a software developer, I thought that the best approach to answering this question would be to create a tool to do it for me. I would call it OSTracker (Short for Operating Systems Tracker – An extremely advanced acronym that definitely required this parenthetical explanation). Originally, the plan was to have a service that could run on any operating system that tracked how long I was on the computer. These metrics would then be uploaded to a centralized remote repository and would be parsed and analyzed by some sort of scripting language, that would then display the results in a semi-pretty format.

In order to create something that could easily be run on any operating system that I would pickup, I thought of creating the service in Java. The service could then be called with the following calling conventions:

java ostracker <login/logoff>

This would be extremely useful because this would also allow me to easily port the project from Linux to Windows, Android, or any other modern operating system that I may come across.

The Unfortunate Lack of Direction

Unfortunately, my laziness got the best of me. After all, I did not need to worry about having a constantly running service, as all I needed to keep track of was the name of the operating system, the time of the event, and whether or not the event was a log off or a log on. Since all I needed to do was push these metrics once, I decided that it would be better if everything was handled on the remote repository itself.

Thus, I created a PHP Servlet that would process all events. The servlet is pretty simple, it essentially accepts the aforementioned details as parameters and plops them into a file on the server if they should be there.

How does the servlet know if the information should be there? Well, if the previously tracked action is one that makes sense in relation to the new action. For instance,

  • You just logged off Windows, your last action was logging off Windows. This pair of events doesn’t really make sense.
  • You just logged off Windows, your last action was logging on Windows. This pair of events makes perfect sense.
  • You just logged onto Linux, your last action was logging off of Windows. Again, this makes perfect sense. I just switched operating systems.

Now, I wanted to give the system the ability to track when I was on many operating systems at the same time (assuming multiple computers, I suppose), so the servlet handles that case well.

  • You just logged onto Linux, your last action was logging onto Windows. No problem.

The datafile is arranged in a format of <operatingSystem><time><action> and different events are delineated with a newline character. Thus, the PHP file just has to use all the information from the last event in order to determine if the next event is able to be processed. If so, a 1 is returned. If not, a 0 is returned. Here’s the code:

$actions = explode("\n", file_get_contents($filename)); 
$actions_count = count($actions) - 2; 
$lastAction = $actions[$actions_count]; 
 
if (strstr($lastAction, $os) == FALSE || strstr($lastAction, $action) == FALSE)
{ 
  $resp = file_put_contents($filename, "$os$time$logaction\n");
  echo 1; 
} 
else 
{ 
  echo 0; 
}

As you can see, it’s extremely simple.

The Client-Side

Linux

Now that I had something that was running on the server, I needed something to actually call the PHP file in order to push the metrics onto the server. Again, I considered writing this in Java as it would provide me with the ease of portability. However, laziness got the best of me. I decided to write proprietary scripts.

For UNIX, I wrote a bash script. The script is extremely simple. In order to account for a possible lack of internet connection, I decided to essentially “spam” the script until I got a proper response from the server. The PHP file is navigated to using the curl utility (in quiet mode, so that I don’t notice any spam whatsoever).

Again, nothing too hefty at all. All of the meat is handled by the curl utility.

#!/bin/bash

time=`date +%s`
action=$1

response=`curl -s# ${url}?system=${operatingsystem}&time=${time}&action=${action}
while [[ ${response} != 1 ]]; do
        response=`curl -s# ${url}system=${operatingsystem}&time=${time}&action=${action}
        if [[ ${resonse} == 0 ]]; then
                exit 0
        fi
        printf ${response}
done
exit 0

Windows

On Windows, it is essentially the same story. In order to recover from a lack of internet connection, I decided to plop the whole thing in a while loop so that it ran until it found a response. Not sure whether or not having a broken pipe would throw an exception, I also wrapped the whole thing in a try/catch that when caught simply looped back to the beginning of the method.

All of this was implemented in C#.Net and uses a WebClient to do the heavylifting and post the data to the server. The code is almost identical to that of the BASH script:

class Program
{
 static void Main(string[] args)
 {
 
 try
 {
 string action = "logout";
 WebClient wc = new WebClient();
 string time = ConvertToUnixTimestamp(DateTime.Now).ToString();
 string resp = wc.DownloadString(url + "?system=windows&time=" + time + "&action=" + action);
 while (int.Parse(resp) != 1)
 resp = wc.DownloadString(url + "?system=windows&time=" + time + "&action=" + action);
 }
 catch (Exception e)
 {
 Main(args);
 }
 
}

public static double ConvertToUnixTimestamp(DateTime date)
{
 DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
 TimeSpan diff = date.ToUniversalTime() - origin;
 return Math.Floor(diff.TotalSeconds);
}
}

Getting the Scripts To Run

Getting the scripts to run at the right time was probably the most challenging part. I didn’t have to worry about running the scripts many, many times since the PHP servlet took care of any situations that didn’t make sense (If we logged in twice, per se); however, automatically executing the scripts when the computer is turned on or off is a daunting task.

Linux

In order to get this to work on Linux, I called the script from my /etc/rc.local file, which launched the script on the computer’s start with no problems whatsoever.

Shutdown was a different story, however. Since during shutdown the network adapter is shut down very early, I had to make sure that my script would run before anything else in the shutdown process. I learned that in order to get something to run on shutdown, there is a small process to go through:

1) Copy your script to /etc/init.d
2) Make a symlink of it in /etc/rc0.d
3) Make a symlink of it in /etc/rc6.d

Then, within rc?.d, the symlinks are actually executed in ASCIIbetical order, so in order to make sure that my scripts executed first, I made sure to insert ‘A01’ at the beginning of the symlink names. I think that did the trick, since everything works properly!

Windows

Getting things to automatically start in Windows is a bit trickier. There were some suggestions on the internet to use the Group Policies Editor in order to add my programs as Startup/Shutdown scripts; however, these did not work for me for whatever reason.

To solve the startup issue, I made a shortcut to my script’s executable and plopped it into the startup folder in order to make sure that it got launched when Windows started.

Shutdown, however, is a bit more complicated. Since there is no way that  I know of to control Windows shutdown process, I decided to make a simple wrapper script for shutting down my computer. Instead of simply shutting it down, it calls my OSTracker script and then tells the computer to shut down. A easy, two line, batch script. The only caveat? It’s sitting on my desktop and I need to be sure to double click it whenever I need to shutdown my Windows machine. Shouldn’t be too hard to remember!

The Display

Now comes the fun part. How do I display this information to the public? I decided to go with a line graph. Although it’s probably not the best choice, it looks cool, and with a ‘1’ representing logged in and a ‘0’ representing logged off, it’s definitely easy to decipher a line graph like such.

In order to implement the graph, I used Chart.js. As a bonus, Chart comes with some pretty cool animations, so it made my page look just a tad nicer than I had originally intended.

Basically, the JavaScript page makes use of regular expressions to find the operating system, time, and action taken on each line of the statistics file. Nothing too interesting, so I’ll just skip the ramble.

The Product

As you could probably deduce if you actually read any of my rambling, this system is extremely hacked together. Nothing was really planned out and it took me about 6 hours to complete. However, this is my first spur-of-the-moment project in quite some time. It feels great.

Here are the results: https://brandonio21.com/OSTrackerStats/

A Rant About Startup Growth

A bit of background

I very recently began working at a software development company that has grown very, very fast. Its profits have grown tremendously, its employee count has grown, its project count has grown, and even the amount of buildings it owns has grown. From the outsiders perspective, this is a great thing. When talking to those that are in charge of the business side of things (sales, management, hiring, etc..), everything is going just as according to plan; however, the tech side of the company definitely has a different story to tell. The company has grown so rapidly, in fact, that the technology and routines of the company cannot keep up with the ever-changing environment that the company lives in.

A Quick Example

Take, for instance, version control. This is probably my biggest gripe about how the company operates. The company consists of many, many teams doing many, many different things. None of these teams can agree on a single method of version control. Each team does something different with their own little twist. Many teams use an internal clone of GitHub, Many others use Perforce. This doesn’t seem so bad at first, however, with each side of version control comes its own integration of code review, submittal processes, and checkin/checkout procedures. There have been several occasions where I needed to grab code from another team that was in GitHub and attempt to sync it with my code that is stored in Perforce. It’s a logistical nightmare.

It doesn’t stop there, though. Each method of version control has its own story. I won’t go too far in depth, but let’s just say that the goal of the company was once something along the lines of “We need to push code that works“. Now, the company is leaning more towards a philosophy of “We need to push code that works and is efficient, modular, and understandable“. This makes fixing bugs on older products or adding features to older products a logistical nightmare.

A Resolution?

One of the problems that I have found with Perforce is that its local repository management is more than complicated. There have been several times where I quickly want to branch a directory full of code so that I can play around with a  possible new feature, but be able to quickly switch back to the main devline of code. With Perforce, this is much more complicated than a simple git checkout -b feature.

So, in order to solve this problem, I have resorted to keeping all of my copies of the company’s source code within my own local git repositories. I then sync all of the Perforce checkouts into a branch and then merge that branch into all of my feature branches, resolving all conflicts along the way.

The Message

Although this post seems to have gone nowhere at all and made no constructive points whatsoever (that was definitely not the purpose of the post), it did point out something that I never expected. The internal infrastructure of large companies can be a serious mess. This being my first position at a large software development company, I honestly did not expect things to be as messy as my code directory on my home computer. But it’s also much, much worse. I believe that the problem arose from the fact that the company simply expanded very, very fast and that the internal tech employees were unable to adapt to newer tools quickly enough.

What does this mean? It means that now developers are stuck at a crossroads of bad naming conventions and commented-out blocks of code. They’re forced to use project-specific version control and they’re constantly deciding on which of the hundreds of branches they should push their code to.

Honestly, in situations like this, I think it is best for the company to stop working on new features for a small while, and fix their current infrastructure disaster.

A Short Discussion of Life

What is different?

There are some people who have told me that life is mundane. Once you leave
school, you get into the daily grind of things. Life gets repetitive, work gets
boring, and people all seem to do the same thing over and over again. What is to
differentiate the neverending stream of tedious day to day life? The life of the party,
the life of the free spirit, the life of someone who lives with no regrets even though
in his dreams he regrets every night of his life.

I always thought that this is what life would turn into. I was dreading the day when
I graduated from high school because then what would I do? I would go to college, sure!
But that’s just another round of the daily grind with classes that are much more difficult
than they were in the last round.

But then I thought about the reality of existence, if you will. Although we are all teh same
on a biological level and a chemical level, each one of us has our own personality, our own
hobbies, our own likes and dislikes, our own pasttimes and our own will to think about whatever we please. Knowing this, I have created a small goal for myself: be different.

Being different doesn’t have to be extreme. Some people seem to come to the conclusion that
being different consists of dressing in bold colors and flaunting every wacky thing about one’s personality. What if that’s not being different, though? What if being different is just doing the small things that no one else does. For instance, what if someone actually cared about your day when they asked how you were doing. What if that person standing next to you
on the subway decided to talk to you? What if someone walked tall and proud and seemed
to ignore the troubles that were happening within the world. What if somebody’s sole
goal in life was not to participate in the society that we have created, but by rebelling against it,
change it. This is what I want to do.

The Process

Currently, I sit atop a hill in Dolores park in San Francisco. I am alone. I am on my laptop.
I am typing in vim. I am not smoking, I am not drinking, but merely taking in the atmosphere,
admiring the city, and writing my thoughts on life. I think that this on its own is different.

But it’s also insipiring. As I sit, I realize that life is a very short adventure that each
individual is forced to live. Although there is definitely a pessimistic side to that story,
I think it is in everyone’s best interest to make the best of every event that comes their way. By
doing so, one will unintentionally change the world. For instance, if everyone around you is complaining about the cold weather, be the one to suggest that the cold bring everyone together in the warmth of your own home. It may not seem like a change, per se, but let’s take a moment to analyze it. Each person within that scenario seems to mull within their own depression. Everyone’s sadness is being reflected onto the people around them, making the situation even worse. Although it is definitely easy to give into the sadness and agree with everyone that cold days are indeed something worth complaining about, why not be the one to change everyone’s viewpoint, feelings, and day?

This, I think, is the best way to go about any situation.

The Bigger Picture

Imagine if everyday you went about your daily events in this fashion. Imagine if you looked at
every event and asked yourself what you truly felt, what made you happy, and what you could
do that you wouldn’t regret in the morning. With this viewpoint, life is a neverending adventure
that is to be discovered. You never know whose life you will be able to change by simply being
different. Of course, the difference here is not that you’re boasting your unusually positive spirit, but it is instead that you are being genuine. You are saying what you are actually thinking. That, believe it or not, is one of the rarest traits that I have come across in a person.

If something as simple as picking up trash can start an environmental movement, speaking
and acting in accordance with your thoughts and feelings is more than likely to start
something else. A social revolution perhaps? Maybe., but only if you stick to your goals
and continue to work hard.

The Work

I think that the main determining factor of the success of this life philosophy is not how much
work you put into it, but rather, how passionate you are about the work. As long as you are passionate about being positive, affecting the lives of others, and making an impact in your small world, things will change. If the passion is not there, however, it is quite easy to picture how quickly the kindness will lost its effect.

This is not only true with this particular aspect of life, but it remains true in the world
of careers as well. For instance, a person who is passionate about their work is more likely
to create a unique product that does not yet know its market. A person who is passionate is willing to take more risks when it comes to the development of a product. To them, however, it is not development, but rather the materialization of a dream.

Often times, people say that I have passion. That is what separates me from those around me.
I am passionate about computer science, the world, those that I love, and thoe around me. I
want to make a lasting impact on the world, and I think all of the work described above is
worth the risk of having a very rewarding outcome of a world that was influenced by my actions.

The Outcome

Each person has roughly 85 years to live. During this time, the first eighteen are spent
stuck in a path of life that is predetermined by the governments of our country. Because of this, I believe it is necessary to truly work hard in life. What makes me say this? Let’s put it this way: Hundres of people die every day, but it is only once in a while that you hear of someone actually passing away.

Why? Because this person has made an impact on the world as a whole. Whether it be Michael Jackson, Carl Sagan, or Martin Luther King Jr, these people are remembered long after their passing because their time on earth was not wasted, but very well spent. I think that the moments of their lives that were spent changing the world are the moments that we should all channel into our own lives.

Think about it. If someone spent their entire lives contributing to something as much as Carl Sagan did to the fields of astronomy and astrophysics, the chances of them accomplishing something worthwhile are very, very high. After their death, their accomplishments and contributions to the world will surely be rewarded.

At the age of 19, people have told me that I am too young to be thinking about this. I should
instead be enjoying life, having fun, and doing things that will make for crazy stories in the
future. By this, of course, people mean that I should be socializing, partying, and voiding the
morals that I have upheld for the past 19 years of my life. However, crazy stories don’t have
to fall into the same categories as everyone elses’ stories. How boring would it be if everyones’
crazy stories were nearly identical. For instance, how boring would it be if all people had to
boast about followed the template of last night I got so drunk I did X. Well, although it may not be true, that is what I see. I see a world in which most people do the same thing as one another. Thus, these crazy stories aren’t so crazy afterall. That lack the one thing that would make them crazy: uniqueness.

Thus, I want to be that person with the unique stories. I want to always be able to say that I
have accomplished something that most people have not even thought of accomplishing. I want to say that I’m unique. I want to say that I’m different. If this is done for a long
enough period of time, I believe that it will be a very rewarding experience.

Not only that, though. I believe that I truly will change the world. Because let’s face it,
a world without change is boring. So why not work to turn it into something you will always enjoy?

 

I Have Finally Discovered the Meaning of Cookies

Everyone that browses the web has heard the term cookies thrown around every once in a while. Whether it is originally defined as data, evil little programs that hackers use, annoying things that cause popups, everyone has heard of cookies.

I, too, was once one of the people that thought they knew what cookies were. I thought that it was data that the WebBrowser stored to keep track of things. For example, remembered usernames and passwords and addresses were stored in cookies. Cookies were my friend and sometimes I needed to clear them in order to get a website to function properly.

I was only half-right, however. The other day I was assigned the task of making a JavaScript page that automatically refreshed itself every 5 seconds. Easy enough. I created the HTML layout, added in a few dynamic Java calls to get some data, and then added in the JavaScript method that would refresh the page. For reference, the method looked a little something like this:

function StartTime(){
        setTimeout("RefreshPage()",5000);
}
    
function RefreshPage(){
        if(document.Refresh.auto.checked)
        window.location.reload();
}

 

All was well and the page functioned as it should. That is, until I needed to add a toggle switch that would hide or display a <div> HTML tag. That’s when things got really tricky. The problem was not building the toggle button or the JavaScript function that changed the style=display property of the tag, but rather, after making this, I realized that every time the page was refreshed, the toggle would be flipped again.

So how could the webpage memorize the user’s choice on whether or not the toggle should be flipped? My initial thought was to make something like a global boolean variable that kept track of the state. Something like so:

<%! boolean hideDiv = false; %>

Then the thought occurred to me. What if many, many users are visiting the page at one time and they are all toggling this variable? Since the page is being rendered on the server, a toggling of the variable means that all users are affected by any toggle that one user makes. So how could I store the user’s preference in their browser locally without affecting any other user?

A-ha! So that’s what cookies are for! After some research, a website’s cookies are essentially stored in a semi-colon delineated string that contains many key-value pairs. For example, a cookie string could look like:

fruit=apples;vegetable=corn

This information is stored locally by the user and is stored specifically for the website that stores the cookies. The website can also get the cookies as well. So, in order to solve my problem, I created a cookie that tracked whether or not the div needed to be displayed. Something like:

displayDiv=false

This cookie was then saved every time the user pressed the toggle button (with its respective value, of course) and was retrieved every time the page needed to refresh.

Cookies are surprisingly fast, too. I expected the page load times to slow down significantly since data was being retrieved from the disk, but it didn’t seem to have much slowdown. Of course, this could be because we are running machines with huge amounts of memory and processing power and all we are trying to retrieve is a few bytes of text (don’t quote me on that — that’s not the exact filesize whatsoever).

So, until very, very recently I did not know exactly what cookies were. Hopefully this helps you discover their true meaning. In short,

cookies are a set of key-value pairs, specific to a website, that are saved and managed by the user’s browser. They come in a semi-colon delineated list and have the ability to expire after a certain amount of time. They are used to store data locally that is usually specific to the user.

For those that are curious, my implementation of saving and getting cookies looked a little something like this:

function setCookie(cname, cvalue) {
    var d = new Date();
    d.setTime(d.getTime() + (50*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
  }

  function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i=0; i<ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1);
      if (c.indexOf(name) != -1) 
      {
        if (c.substring(name.length, c.length).contains("="))
          return c.substring(name.length, c.length).split("=")[1]
        else
          return c.substring(name.length, c.length)
      }
    }
    return "";
  }

Note that by default, my setCookie method sets the cookie to expire after 50 days.

Working From Home

I worked from home for the first time today.

It was actually just because I woke up late, and even then, I had a very, very bad headache. I rolled out of bed, hopped in the shower for 10 minutes, made myself a hot cup of coffee, roamed around in my underwear, and sat down with three toaster waffles and syrup for breakfast. I finished my breakfast within 5 minutes, pulled out my work laptop, and logged on.

It was weird working for home — seeing everyone on GChat who is at the office, where you’re supposed to be, doing things that you’re supposed to be doing. There is an overwhelming sense of guilt. I needed to get something done and fast. I opened up my code and made some changes. All was well. I just had to compile.

Normally, at the office, during compile time I sit around waiting for a good 30 minutes while the entirety of the company’s codebase combines into single executables. I usually just listen to music, read documentation, or tap my fingers. At home, though, it was a whole new experience.

I started the compile, got up, did dishes, made my bed, cleaned the table, got myself another cup of coffee, and then began reading tech news. There was no overwhelming sense of “You should be doing something corporate related”. I chatted with friends, read some documentation, and experimented a little with tools I’ve never used. It was the most fun I’ve had working in a while.

Why? All because it was from home. Granted, as the day went on, I continued this trend, and I think I ended up being a little less productive than I would have normally been because of this. However, I was able to truly get absorbed in my work since there was no pressure to get stuff done. It was a great feeling.

I always thought that working from home sounded like a bad idea. You would get distracted and wouldn’t get much done. My experience was completely different. Although I did get distracted, I got more done around the house than I would have ever gotten done if I was at the office. On top of this, my extra long lunch break was rewarding and delicious. Things just went well.

The only problem with working from home is, well, the fact that you’re at home. I got several requests from coworkers to go to certain locations within the office building to meet or look at something. The problem was that I wasn’t there. It is always a bad thing to tell your coworkers “Sorry! How about tomorrow”, and that was the worst part about working from home.

 

All in all though, it was a great experience. I would highly recommend it atleast once to anyone whose job does not involve a necessary physical presence at the office.