Saturday, May 2, 2020

Demystifying pass by value & pass by reference

Here's a simple code block. Try to figure out the possible output.


When you run this, the test1.Name will still write "original" to the console. If you thought that accessing test1.Name after it being set to null will throw a NullReferenceException, then you definitely need to keep on reading :)

If you got the correct answer, then good for you but you might also be wondering why I pulled out a silly question like this which the outcome is fairly obvious. Well, it turned out that it's not fairly obvious to an untrained eye, despite how many years it might have looked at code.

I had a somewhat heated argument with one of my colleagues regarding this phenomenon, who happened to be a seasoned programmer. And finally, I had to type the above code in Visual Studio to prove my point. So I believe that this is a tricky area where most programmers tend to trip sooner or later. Hopefully, this post will set things straight.


Back to Basics
So what are value types and reference types? In .NET, value types are derived from System.ValueType and reference types are derived from System.Object. While value types are generally stored in the stack, reference types are stored in the managed heap. Examples of value types are Int, Char, DateTime, Enum or Struct whereas String, Delegate, Interface or Class are examples of reference types.

You can think of a variable as a container. When the variable is of a value type, the variable's value is stored inside the container itself. But when the variable is of a reference type, what the container contains is not its actual value but a light-weight meta value pointing to a different place where you would find the actual value.

The best analogy I can think of is the meta redirect tag on an HTML page. When you access this page's URL from a browser, some HTML would be rendered. But due to the meta redirection, what's rendered would be fetched from a different URL. The original page is the container of your reference type variable. However, when you access it, it will bring you the value from a different place.

I hope I didn't make it sound more confusing. I'm trying my best to explain without talking about pointers.

Ok so if you've been following me thus far, you would still scratch your head why on earth a reference type variable still holds its value even after being set to null. For that, you have to understand what happens when you pass variables around.


Pass by value & pass by reference
When you pass a variable to a method by value, you pass a copy of that variable. So whatever you do to that variable does not affect the original. But when you pass by reference, you work with the same copy and therefore all changes are sort of "global".

In the above example, what you saw is an example of a variable passed by value.

Wait, what? Isn't that a reference type variable? Don't they get passed only by reference? You may ask.

Well, that's what you used to believe because whenever you manipulate an object's properties via a passed in variable, the original object retains those changes throughout. But if that was passed by value as I say, how could those changes persist? Yes, it's highly confusing when the phrase "objects are passed by reference" is already baked into your head.

Back to basics. Go back and read how I explained the variables using a container analogy. When you pass a reference type variable to a method, by value, shown in the example above, a copy of the variable is passed in just like for any value type. In this cause, what do we have inside the variable's container? A meta value pointing to a different place.

Was a copy of the value which it points, created? No. Then? Only a copy of the variable with its content was created. A reference type variable does not contain its value inside it, so now we just have two variables pointing to the same actual value. What happens when we set this new copy to null? Does it change what it pointed earlier? No. Just like when you change the meta redirect tag in an HTML page. Just because it redirects to a new URL now, it doesn't magically delete the HTML page which it redirected earlier. That page will still continue to exist.

If you want to change the original content of a variable from inside a method which it was passed in, you need to pass in by reference using ref, out or in keyword.

Woah, wait. Then how did my code work all this time? I happen to mutate my objects all over the place without a problem not worrying about how I passing them in.

Err... well yeah that's probably because most of the time, if not all that you did was the dot (.) dance on your objects. Back in the day, we had to explicitly say go fetch data using the arrow (->) notation when dealing with reference type variables, so this confusion was not commonplace I suppose. But now, dotting on a reference type variable or on a value type variable (think of a Struct) works more or less the same way, thanks to the compiler.

Retrospect
If you take the above example and change the line inside ModifyTest1 method to test1.Name = "fake"; the output would print "fake" instead of "original". Because as soon as you do test1.(something) it applies to the destination object instance. But when you do test1 = null; or even test1 = new Test1("fake"); for that matter, you are basically changing your variable's (container's) content, not what its previous content was pointing at. Since the calling code still has a test1 variable pointing to the original content, setting the copy of the test1 variable to point to null or to a different instance by the ModifyTest1 method does not affect the original content.

Running the above code would have resulted in a NullReferenceException if the method signature happened to be ModifyTest1(ref Test1 test1) and the call was done as test2.ModifyTest1(ref test1);. And that's the same way you generally pass your value type variables, as reference, at times (Remember int.TryParse()?).

I sincerely wish that I have not made you completely go nuts with this explanation. This is just my understanding of how value types and reference types work when you pass them around. I wish I could include how string type behaves like a value type even though it's a reference type, but this post has become too long already so maybe that's for another day. Cheers!

Wednesday, April 22, 2020

How to sort divs based on visitor's country


Recently I've got an opportunity to participate in revamping our company's official website.

One of the suggestions that came up there was to sort the clients' testimonies according to their relevance. And how would you know that you may ask? Well, one way to infer that is by capturing the visitor's geolocation and arranging the testimonials so the closest would show up first. Time to get to work!

To get the visitor's geolocation, initially, I tried the following service:
https://www.geoplugin.com (BTW later I ended up using this instead)

Well, that was the easy part. You just include their script and call a method to get country information.

<html>
 <head>
  <script src="http://www.geoplugin.net/javascript.gp"></script>
 </head>
 <body>
  <script> 
    alert(geoplugin_countryName()); 
  </script>
 </body>
</html>


The hard part was rather to get the testimonies sorted. Here's what I did.

We have clients from europe, america, middleast and australia. If someone from Norway visits our site, testemonies by Norgegian clients should show up first, then may be Swidish ones and so on.









So it's not just sorting by one country. You need something like "ORDER BY this, this too, this as well" which should work up to many degrees. I was much more interested in writing the sorting algo, overlooking the mechanism to compute the order by sequence. So the order by sequence was merely hardcoded for each potential geographic:
let computeSortOrder = function(countryCode) {
 switch (countryCode) {
  case 'NO':
   return ['NO', 'SE'];
   break;
    
  case 'SE':
   return ['US', 'CA'];
   break;
    
  ...

  default:
   return [countryCode];
   break;
 }
}

Now we got ourselves an array of counties that we would like our testimonies to be recursively sorted. How would you implement that? Custom sort with recursion!




 1. let sortClients = function(sortOrder, containerId) { 
 2. let divs = $('#' + containerId).find('.testimony');
 3. let orderedDivs = divs.sort(
 4.  function(a, b) {
 6.   let index = 0;
 7.   return innersort();
 8.   function innersort() {
 9.    var matchA = getMatch(a);
10.    var matchB = getMatch(b);
11.    if (matchA && !matchB) {
12.     return -1;
13.    } else if (!matchA && matchB) {.
14.     return 1;
15.    } else if (!matchA && !matchB) {
16.     index++
17.     if (index < sortOrder.length) {
18.      return innersort();
19.     }
20.    }
21.    return 0;
22.   }
23.   function getMatch(item) {
24.    return $(item).data('country') === sortOrder[index];
25.   }
26.  });
27. $('#' + containerId).append(orderedDivs);
30. }
Let me explain. The "sortOrder" is the array of countries returned from my earlier (ugly) function. The "containerId" is the id of the div which encloses all testimonies. Each testimony div is tagged with a class called "testimony".





In line 2, we get hold of all testimony divs we are interested in sorting. From line 3, the custom sort starts.
Basically the sorting function takes two arguments, essentially two adjacent items in the unsorted array say a & b and returns an integer where a negative value means a < b, positive means a > b and 0 means a = b. It is repeated many times for many pairs until all the elements in the array are in sorted order. The algorithm used will depend on your browser's implementation of ECMAScript. Does anyone still remember how bubblesort works? :) Here's some headsup.



So here, the modification to the general sort is we do the matcing recursively for everything in our sortOrder array. In line 15, when we don't find a match for the currently sorted country, we try to find a match for the next potential country in line at the sortOrder array. And it's repeated till the array is exhausted. The beauty is, it's not depending on any fixed degree of sorting. You can pass in an array of all the countries in the world and still get your divs sorted accordingly.



Alright, I hope you got some idea of the code now. By the way, the "data('country')" is how I tagged a testimony to a country in its div. Example below.



<div class="testimony"  data-country='NO'>
 bla bla bla
 ...
</div>

That's all for now. Stay safe and don't forget to wash your hands! #covid19

Friday, March 20, 2020

COVID-19 Status - Sri Lanka

COVID-19 is rapidly spreading in Sri Lanka at the moment. The Epidemiology Unit, Ministry of Health in Sri Lanka publishes a report at 10AM every day with data collected from all hospitals treating COVID-19 cases. I thought of creating a timeline using ArcGIS map to better visualize this data. 

Currently, it's hosted here: https://srilanka-covid19.netlify.com/


PS: Now it's showing the realtime counts too, thanks to the API provided by the Health Ministry.

Monday, August 11, 2014

Google Charts: How to change axis, legend styles beyond what is provided by the API

If you are familiar with Google Charts, you know that you need to pass a 'Configuration Options' object when drawing a chart. Properties of that object for bar charts are found here.

For a recent project I worked, I needed to show the axis and legend labels as 'clickable' links hence I needed to show the cursor as a 'hand/pointer' when hovered above them. But Google Charts API only provides a limited set of styling for axis and legend labels. More precisely it only supports color, fontName, fontSize, bold, italic & underline styles.

But after inspecting the generated HTML DOM for the charts, I figured out a simple way to manipulate the elements properties and change the styling the way you want.

I prefer jQuery so here goes how the vertical axis labels were manipulated:
 $('text[text-anchor=end]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

Here's how the horizontal axis labels were manipulated:
 
 $('text[text-anchor=middle]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

Here's how the legend labels were manipulated:
 
 $('text[text-anchor=start]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

If you are a plain JavaScript guy, here you go:
 
 var labels = document.querySelectorAll('text[text-anchor=end]');
 for (var i = 0; i < labels.length; i++) {
  labels[i].setAttribute('cursor', 'pointer');
  ...
 }

Make sure you understand that the above hacks basically set the styling to every matching element found on the page. So if you have multiple charts on the same page and you need styling done individually, you will have to check additional properties of those elements inside the loops to determine which chart they belong to.

If you need further clarification on this, post it as a comment :)

Sunday, August 10, 2014

Android: Implementing a One-Way Lockable View Pager

While implementing a fun Android app, I came across a scenario where the ViewPager should only be swiped right-to-left. Visiting back should be restricted. Also at some points, I needed to lock the whole view pager so that it cannot be swiped at any direction.

The following code shows how I did it by extending the ViewPager class. Note that I was using the support library.


 
 import android.content.Context;
 import android.support.v4.view.ViewPager;
 import android.util.AttributeSet;
 import android.view.MotionEvent;

 public class OneWayLockableViewPager extends ViewPager {  
   private boolean enabled;  
   private float lastX;  

   public OneWayLockableViewPager(Context context, AttributeSet attrs) {  
     super(context, attrs);  
     this.enabled = true;  
   }  

   @Override  
   public boolean onTouchEvent(MotionEvent event) {  
     if (this.enabled) {  
       boolean lockScroll;  
       switch (event.getAction()) {  
         case MotionEvent.ACTION_MOVE:  
           lockScroll = lastX <= event.getX();  
           break;  
         default:  
           lockScroll = false;  
           lastX = event.getX();  
           break;  
       } 
       return lockScroll ? false : super.onTouchEvent(event);    
     }  
     return false;  
   }  

   @Override  
   public boolean onInterceptTouchEvent(MotionEvent event) {  
     if (this.enabled) {  
       return super.onInterceptTouchEvent(event);  
     }  
     return false;  
   }  

   public void lock() {  
     this.enabled = false;  
   }  

   public void unlock() {  
     this.enabled = true;  
   }  
 }  

It is quite easy to change it if you want to reverse the allowed direction of swiping. Just change the less than or equal sign to a greater than sign in line number 21.

Also when you want to lock down the whole view pager, just call the lock() method and swiping will be disabled.

Wednesday, June 25, 2014

SLT Usage Meter goes Android!

Get the Android App here:
https://play.google.com/store/apps/details?id=lk.elnino.sltusagemeter

Finally I had time to spare on this pet project, which the idea was originally coined by one of my colleagues who writes cool Android apps. Initially I thought this wouldn't be any use to have as a mobile app but then again when I thought that it could be useful as a widget on the home screen, I got motivated to try. Simply because I have not written any widgets for Android before :)


I got to say that this ain't the only app on the play store which can check your SLT broadband usage. I've seen a couple of others which basically does the same thing. So why I wrote yet another one? Because none of them had a home screen widget or notifies you when the limit is reached.


Let's have a look at the party piece.

This widget is shown at the bottom. I just cropped the home screen. The green and yellow bars show the percentage used. When you touch the widget, the numbers change to either show the percentages, used GBs or unused GBs. No surprise there, it works just like the browser widgets.

When you touch the icon, the usage is updated. Anyhow the app updates the usage automatically in the background, but if you want you can turn off that feature.



When you reach the end of your monthly limit, you will get notified whether you had the widget or not. Then again that'll also work if the auto updates are enabled.






The main app looks like this. Nothing to brag though.

 

So there you have it. Try it out and let me know how it is.
As always, it's free and not adware.

Enjoy!


Monday, February 3, 2014

Android: How to embed Google Map

Well here I am specifically talking about getting it done with Android Studio and with Maps API v2.

First of all you need the Google Play services downloaded using the SDK Manger.


Then add the Google Play services version to your app's manifest file.
<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
Get your Google Maps API key.

  • Go here: https://code.google.com/apis/console/?noredirect and click 'Cloud Console' link.
  • Register a project there and turn on your Google Maps Android App v2 Service
  • Create a new key under APIs & auth -> Credentials
  • Add the key information to the manifest. See below.
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AasdJHJHKSDHfcFJLbZhndBC_fdsd1KEHk"/>
Add permissions in the manifest to access Internet.
<uses-permission android:name="android.permission.INTERNET"/>
Add a map fragment to your layout. Note that I have used SupportMapFragment. That comes with Android Support Repository.
<fragment 
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          class="com.google.android.gms.maps.SupportMapFragment"/>
Check device compatibility. If Google Play Services are not up-to-date on the phone, this will let the user to update then and there.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
int mapResult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (mapResult != ConnectionResult.SUCCESS) {
    GooglePlayServicesUtil.getErrorDialog(mapResult, this, 0).show();
} else {
    mapFragment.getMap().animateCamera(CameraUpdateFactory.zoomIn());
}
That's about it. Now the map should be visible on your app. If not, patiently go through the above check-list again and see what you have missed :)

Arduino Line Following Robot: Cracking the shortest/fastest path on a grid with loops

I'm sure you've created a line following robot at some point, if you've been exposed to Arduino (or any other programmable elec...