Saturday, July 21, 2018

C++ Member Selection Technique using Type Traits and C++17 feature!

It has been quite a while since I last posted on  JVL blog! As my daily activities at work involve coding, I want my free time to have as little to do with programming as possible! (which I hope is understandable).

However, this is inevitable: I do occasionally come across cool and interesting findings that I might find worthy of blogging and sharing (but sometimes just don't find the energy nor the time...). Most of these findings should now be a bit more in-depth and geared more towards C++ and Python, as those are my main and secondary "weapons". =)

Recently at work whilst refactoring our code base, I have introduced a cool technique (which I don't know if it has been publicly shared) to apply a class member selection. My initial purpose was to reduce the amount of repeated code, and make the compiler generate them for us. Basically, I wanted to template a few things, but to achieve this fully, it was necessary to have a kind of member selection technique. I accomplished this in 2 variants: a template specialization (pre-C++17) and another one using a C++17 feature, namely constexpr if() else statements. But let's first talk about the straightforward implementation.

The "Naive" Straightforward Implementation

I will present the problem differently, in light of keeping information internal, obviously. Say we have some produce classes as shown in helper_classes.cpp and a Cart class which, has a addToCart() function that adds different types of produces into their corresponding baskets, as shown in cart_naive.cpp. Please ignore printSizes() for now.



Lines 12 -15 are basically doing the same thing, just for different types (kind of like copy-paste no?) How could this be improved? Read on...

Template Specializations (Pre-C++17 Solution)

It seems that addToCart() could be templated! So, let's first try that. But after templating it, we would need a function that could return the correct basket from the Cart based only on the typename T. The resulting templated function would look like in Line 12-13, cart_template_specialization.cpp.



The getBasket<>() function will do exactly that: return the corresponding basket based on input typename T. To achieve this, we have to template the function and specialize it for each type! Lines 21-22 show the function signature, while Lines 26-29 show the different specializations.

Seems a bit better now no? Hope you agreed =), but that's not all. Now let's see a yet nicer solution.

C++17 Features Solution

The next improvement lies in the templated function getBasket<>(). With a combination of the auto return type (C++14 feature) and constexpr if() else statements (C++17 feature), the getBasket<>() could be further refactored to look nicer, in a self-contained function body.

Let's look at it in Lines 21-28cart_cpp17_feature.cpp. The function takes in the typename T, goes through each if statement comparing against each type until it matches, and generates the code within that if block. The std::is_same_v<> is a type trait function that checks and returns true if the input types are the same. Because the return type varies depending on typename T, we have to return an auto type.


Notice that all the described steps are done at compile time, which results in compiler generated code.  Do all the presented variants actually work? Yes of course, let's see how we could test them.



Testing

In the Cart class,  the printSizes() does exactly what it promises, print sizes. Then the main function would look like this:


As you may have already guessed, all the variants should produce the same result:

Size of AppleBasket    << 2
Size of PearBasket      << 0
Size of TomatoBasket << 2
Size of PotatoBasket   << 1


Conclusion

The technique presented here shows a practical use for some modern C++ features that may not be so widespread. I hope the example illustrates succinctly the different applications and the possibilities of code improvement/refactoring. Some may argue that a better solution may be to use Type Erasure to have a single basket instead of the different types of baskets. This may be true (can't say I would agree yet as I haven't explored it myself...). but the key idea is to use a couple of modern C++ features to illustrate how a specific programming problem could be solved (or improved).

Here is the link to my Github repository if you want to try out the code:  https://github.com/jamseams/jvl_memberselection


Sunday, November 5, 2017

Git Offline Versioning (Through USB Stick)

Following up on the latest topic on Git versioning, this editorial presents a neat trick to work with Git in an offline computer through a USB Drive.

During a project I had worked on in the past, I was provided with a computer for which access to the Internet was not allowed. Since I was working on a software project, I wanted to source control it and upload it to my private repository. And the handiest method was to do it through a USB Drive.

This article will walk you through the basic setup for this little trick. As most of the articles in this blog, the content will be based on Ubuntu.

Introduction

The basic idea is to setup a Git repository in a USB Drive, which will be used as a "bridge" between your offline computer and another computer with internet access. This way you could push changes into your favorite online repository host, while being able to develop and source control with Git seamlessly.

What you will need..
  1. The offline computer where you'll be developing.
  2. Computer with access to internet (if changes shall be uploaded)
  3. USB Drive, 4 GB (Size depends on project size, but USB Drives are inexpensive nowadays)
  4. Account in Git Repositories hosting ( eg. BitBucket, GitHub, GitLab)
Setup Git Online Repository

If you don't already have an online repository created from your Git host, then I recommend you go here and follow the instructions in "1. Starting a Repository".
Once you have an online Git repository setup and its address copied into the clipboard, you could continue on.


Preparing the USB Drive

1. Formatting the Drive

First of all, we need to format the USB Drive. With the USB Drive plugged in, open "Disks" in Ubuntu.

Figure 1. Screenshot of Disks on Ubuntu's Dashboard

 

On the left panel of the screen, select your USB Drive. Then click on the setting button and select "Format..." as shown in screenshot below.

Figure 2. Disks Interface

The following window will appear. Just click "Format..." and an additional dialog window will also show asking if you're sure, just click on "Format"

Figure 3. Format Options in Disks

2. Partitioning the Drive

Back to the screen shown in Figure 2, click on the "+" button to create a new FAT partition. Set the settings as recommended in the following screen and click "Create".

Figure 4. Partition Creation in Disks

Note: The "Name" set in this screen will be used later, so save it.

3. Cloning Online Repository
 
Navigate to your USB disk. It should be automatically mounted once plugged in.
Clone the previously created online repository as shown below. (I will continue using the example repository from previous tutorials.)

Figure 5. Cloning Repository into USB

Since I have set the "Name" of the partition in Figure 4 as "GitUSB", the command is basically to navigate to this partition.

Note: Blacks rectangles are just to cover my username. This should be your username.

Then we just clone the repository as usual plus the "--bare" option: "git clone --bare". This option makes the created directory contain administrative files.


The preparation of the USB is now finished and ready to be used... Now let's take the USB and plug it into the offline computer...


Using the USB Drive

1. Cloning USB Repository @ Offline Computer

Once the USB is detected and mounted, open a terminal (Ctrl + Alt + Del). Know the path to the USB, it's usually similar to the one shown in Step 4, above.

Now, navigate to your workspace directory and clone the repository from the USB, as shown below.

Figure 6. Cloning with --bare Option

As mentioned above, you need to know the path of the USB Drive, since this is where you will be cloning from.

2. Making, Committing, and Pushing changes to USB

Go into the project working directory, make some changes, and commit them, as usual.


Figure 7. Making, Adding, and Committing Changes

Once the changes are committed. Run the "git push" command. Notice that the push automatically pushes it to the USB.


Figure 8. Pushing Changes to the USB Drive


Voila! Now developments in your offline computer are pushed into the USB Drive.

3. Push Changes to Online Repository.


Now, plug the USB back into the computer with internet access. Navigate to the repository in the USB, and execute the command as shown in the screenshot below.


Figure 9. Pushing Changes to the Online Repository

The USB Drive can now serve as a "bridge" between the offline computer and the one connected to the internet. Better yet, it could be used as a "travel development USB, or whatever application you find for this.


Conclusion

I hope you find this little trick quite handy. This is actually how I coped with developing in a computer without internet access and still wanted to keep a  backup of the code in an online, private repository. It doesn't require so much time, and it's quite inexpensive. So I think it should be the most viable solution for mentioned case.

Feel free leave comments and suggestions! Cheers, and till next time.




Friday, December 16, 2016

GIT Software Versioning

In this edition of  JVL blog, we will look into Git Versioning basics.

As programming projects become inevitably complex and extensive, it is imperative and also logical to keep control of your source code while being able to work in a collaborative team. Sometimes even keeping track of changes in your own source files becomes a very difficult task as the project scales. Then imagine having to work with a team of 3 or more people! It becomes hardly manageable. Software Versioning tools such as SVN, Git, ClearCase, Mercurial exist to help alleviate this problem.

Of the mentioned examples, I have had experience with SVN and Git, which are both quite similar, and Clearcase, which is a very powerful source control tool more suitable for very large-scale projects. As I prefer Git, I will be writing about it.


An Introduction to Git

Git is an open-source source code versioning utility that is both powerful and quite easy to learn. Despite its intended use for software source codes, Git could be similarly used to version control any project that handles files such as VHDL (Very High-Speed Hardware Description Language) projects, circuit schematics, graphics designs, documentations, etc... It is sub-optimal to handle graphics with Git, because the information contained is not text-based. Nonetheless, taking snapshots of graphics is equally possible with Git. Many GUI programs exist for Git, but I will be focusing entirely on working with Git in the command lines (either under Linux or Windows).

The idea of versioning control of Git is creating snapshots of your source codes during the span of the project and storing those snapshots into repositories, which could be locally saved or hosted by providers like Github, BitBucket, and Gitlab. The snapshots contain the state of the different files at the moment the snapshot was taken. In other words, it saves the changes of the files up to the point the snapshot was taken. Of course, the user can specify which files to keep track of by Git. These snapshots, or in Git's lexicon commits, could be later examined, retrieved, reused, deleted....


Getting Started

I will not go into the details of Git installation nor account setup in a Git repositories-hosting provider. The intention is to recommend a good tool for all programmers or creators in general and getting started with the basics.

The basic, general workflow is shown as follows:


Figure 1. Git Versioning Basic Workflow

1. Starting a Repository


The way I prefer to do it is to first log in into my repository-hosting provider (BitBucket) and create a repository from there, as shown below:


Figure 2. Creating Repository in Bitbucket

Then copy the address of the repository to the clipboard.


Figure 3. Copying the Repository Address to your Clipboard

Open a terminal, navigate to your desired location, and clone the repository locally with the "git clone" command.

Figure 4. Cloning the Repository from the Hosting Provider

2. Making Changes

Basically, just work on your project by adding or modifying files. In my example, I copies two files into our project's folder.


Figure 5. Copying two Files into the Project Folder.

Bonus: use "git status" to view the current repository changes. I use this a lot; sometimes I think way too often.


Figure 6. Viewing the Status of the Repository
The RED filenames are files that have been modified or added in your project, but not yet staged for commit, or in other words, saving a snapshot.


2. Staging Changes

Staging changes simply tells the program which files or changes to actually take a snapshot of. We do this by using "git add ." to stage all files to be committed. Instead of using "." to stage all files, one could specify individual files.

Figure 7. Staging Changes
Note that the "git status" now returns GREEN filenames as they are now staged and ready to be committed.


3. Confirming Changes

Committing is the same as taking a snapshot of current staged files. This is done with "git commit" command.

Figure 8. Committing Staged Changes
The "-m" option specifies a message between "" describing briefly the current snapshot, so to speak.

Bonus: use "git log" to view a history of your commits, or snapshots. The most recent commit is now visible in the log.

Figure 9. Viewing Commit History
4. Updating Server

Lastly, we have to "git push" so that the local changes are updated on the server.


Figure 10. Pushing Changes to the Server

If you encounter a message as shown in Figure 10 after issuing the "git push" command, then follow as it has been done in the same screenshot. Afterwards, you should be able to successfully push the changes. You might also be asked for credentials of your account with the repository hosting provider.

At this point, the steps just repeat in a cycle as was shown in Figure 1. This workflow can get you started just as essentials. Obviously, there are tons of other actions and features of Git that are not exposed here. From here on, you could seek some more advanced topics and features from Git. Google is your best friend, and the sky is the limit...


Conclusion

This post served ultimately to recommend a tool that would make your life much easier, and organized, regardless of whether you are a script writer, a web developer, graphics designer, or embedded software engineer. It also got you started with the basic workflow, its uses, and the benefits. For more Git tutorials, a Google search for "git tutorial" will be more than enough to find very instructive articles.

I hope this was as instructive as I had anticipated it to be and also hope that Git will make your life much easier and productive!


Sunday, December 4, 2016

Thesis on Convolutional Neural Network!

After a while of inactivity from blogging in the JVL blog, I finally got new material to post something relevant to the previous publication on Convolutional Neural Networks (CNN). The previous post presented a small literature review on CNN; this time I present a thesis project on the same topic.

If the material of the previous post caught your attention, then this thesis will certainly sparkle further interest. In trying to further strengthen my knowledge on CNN, I decided to take a thesis topic on Resource-aware CNN exploration on CPU-only implementations for image classification that was offered to me. This topic evidently offers that additional research and practical component that would well complement my acquired theoretical understanding. It offers a reinforcement to my learned skills. Furthermore, this project would enable me to work with different tools, libraries, and open-source projects related to machine learning and image processing. I was also looking forward to improving my coding skills in C++, especially when forking from open-source projects.

I must also say, I had quite a difficult time deciding between this CNN topic and another topic that I also found very interesting and was qualified for. The alternative was to work on a faster error correcting scheme for PUF's (Physically Unclonable Fnctions) and to implement the algorithm in an FPGA (Field Programmable Gate Array). This topic actually embodies many of my main interests: information theory, channel coding, scripting and simulations, VHDL implementation on FPGA's, and Embedded Security. As you could readily infer, it was quite a difficult choice to choose the CNN topic over this alternative.

The Thesis

The document presented here is the final document as a result of this project. This is put together with as much relevant details as possible with the purpose of making the experiment repeatable for the reader. Hopefully, the simulation benchmark results and some of the ideas exploration for reducing computation of the CNN algorithm may actually help others.




Closing lines...

After finishing this project, I feel substantially more competent in this area of machine learning. The research and exploration experience from this project gave me an opportunity to exercise as a research engineer, to benefit from and to contribute to open-source, and to compose a document that is useful to the reader, especially for sharing results and for repeating the experiment. The even more valuable take-away skills were the use of several Latex packages to produce a professional-looking documents and the improvement on coding skills and styles.

As is (generally) common to human nature, even after finishing my thesis, I still sometimes wonder "what if" I had taken the other route I described above. Where could that have taken me? What could have gone differently?


Sunday, May 29, 2016

Convolutional Neural Networks - Seminar

In this edition of the JVL blog, I want to present yet another small literature review, but this time on Convolutional Neural Networks (CNN) in the area of machine learning for image processing.

Similar to the previous post about Nanophotonics Interconnects, this write-up was also an obligatory part of my current masters program. This literature review on the topic of Convolutional Neural Networks gives an introductory knowledge about what neural networks are, how they are extended to be convolutional networks, and how they can be used for image processing and other applications.

Again, the requirements were similar to those of the document presented in the previous post: a brief 4 pages literature review about the topic. This serves as an extension to and further practice on understanding and writing scientific papers especially about a foreign topic. Writing a technical paper on a topic foreign to me was demanding as it required the extra effort to get acquainted with the fundamentals. Nonetheless, it was quite an interesting topic and a worthwhile task, and so I will like to share it here.


The Literature Review

The following document introduces fundamental concepts on and recollect my understanding of Convolutional Neural Networks. This is in NO WAY an officially published paper nor does it contain any new contributions from my part. It serves as a technical literature review and writing exercise.



Products that apply Deep Learning

If you wondered where and in what products you see artificial intelligence, then checkout the well-known Amazon products, Echo Dot (2nd Generation) or the Amazon Echo.


Lastly...

As was briefly mentioned, working on a topic that's different from one's own technical area of expertise does require more effort. I reckon CNN wasn't an easy topic to grasp at an instant, but once the fundamentals are there, the rest is basically just feeding to that curiosity. There are a plethora of resources out there, and there is much more being worked on as far as CNN is concerned (different applications, architecture, parameters, etc...).

If you are interested in the topic, I encourage you to look around for more resources and projects about CNN...Even try and play with some of the widely-known Machine Learning frameworks such as Caffe, Torch, Theano, mxNet, TensorFlow, DSSTNE...


As usual, leave a comment if you have one!



Monday, March 28, 2016

Nanophotonics Inteconnect - Literature Review

In this post of  JVL blog, I want to publish a small literature review in the area of Photonics Interconnects.

In partial fulfillment of one of my advanced topics course in IC (integrated circuits) Design during my current masters program, I had to write a small literature review on the topic of photonics interconnects. As it is usual for our advanced topics courses, the lecturer for this course was a guest professor from a foreign institution ( this case from UT Austin, my former alma mater). The guest lecturer was a leading expert in the area of IC Design and who is a researcher interested in nanometer VLSI physical design.

He has published few papers focusing on using nanophotonics, a fairly premature technology, as interconnects in nanometer integrated circuits. We were required to write a brief 4 pages literature review of about 4-5 papers on the topic. On the one hand, we gained some experience in reading and understanding very specific and complex scientific papers in trending research areas of IC Design. On the other hand, we were exposed to and gained practice on writing a technical paper. Although it was not required, I have done it in Latex, which is a compiled word processor very useful in any kind of write-ups. This has been proven very useful in academia.


The Literature Review

The following paper review posted here tries to summarize key concepts and my understanding of the different papers. This is in NO WAY an officially published paper nor does it contain any new contributions from my part. It serves as a technical writing exercise. As usual, leave a comment if you have one! 




And a few final words...

Although it was only a 4 pages write up, it does require a good understanding of the technically-dense and jargon-full scientific papers we had to read. And precisely because it was only 4 pages long, it was also a challenge to pack all the key points and concepts into a highly limited space and still make sense out of it.  

Although technical writing skills was heavily tested during my bachelors, reviewing such novel and complex scientific papers was not. It is worthwhile mentioning the importance of this exercise for future tasks as it paves the way for further interesting assignments...


Sunday, August 30, 2015

Pin Memorization and Storing Technique

In this post, I introduce you to a very simple, yet efficient technique to memorize and secretly store PIN (Personal Identification Number). I want to do this by using an Android App that I have created some time ago to illustrate the concept. Please take note that this technique is not new nor is it my invention; I have just created the App from an old, known concept. I have personally learned this "old-school" technique from an ex-boss who is a wise, old man with myriad of old, yet efficient tricks and hacks. Please click on the following link to check out the App in the Playstore!



Figure 1. Pin and Code Memorizer Logo

I have initially developed this for my personal use. As I have found how useful it was for me (true, no marketing jambalaya), I thought it would be nice of me to share it and teach people about it! =]  But I have to admit that I haven't done a great job at explaining the concept when I talk to people about it. So hopefully, I do a much better job with this post here!

Let's move forward...

Motivation: Why would I need a secured PIN memorization and storage technique?

It is fair to say that people nowadays are deeply submerged into the virtual 'world' and heavily rely on technology to be productive... well, for leisure too. There is simply too many different sources of data and information, accounts that we have to manage, personal data that we want to protect, and passwords we have to remember to protect these information. Just take PIN's for example, how many PIN's do you have to memorize to secure your 'virtual' data and accounts. I could easily point out the PIN for your phone and its SIM Card, for debit and credit cards, some online accounts, and possibly for Identification Smartcards too!! And who knows, maybe you'll need a couple of PIN's more in the near future when the Internet of Things emerges.


Figure 2. SIM PIN Prompt Screenshot

Yes sure, you could encrypt the PIN's and save them in a virtual private vault, or write them on a piece of paper. But keep in mind that you will secure those PIN's with an additional password; if you forget it, you might not be able to recover your PIN's! Needless to say, writing them on a piece of paper is not safe at all. Memorize them all you say? Well this is the safest way!, but good luck memorizing them all... and not forgetting them. Use only one PIN for all your credit cards? What if the PIN is accidentally discovered by a third party? Then you would have to change all your PIN's to re-secure the accesses if he/she has not already gained access to the accounts.

For these reasons, the need of low-complexity and safe PIN storage technique is warranted. The technique that I am proposing actually deals with all problems and drawbacks mentioned above. Whether you choose to use the app (or any other similar app) or plain-old hard copy, you may have the risk of losing the PIN's if you don't have a backup!

Concept: So how does it work?

The concept relies on using some charts composed of blocks with random colors and numbers as shown below.


Figure 3. Example Chart Screenshot

Essentially, you would want to conceal your PIN inside this chart in a pattern that only you know. Even if a person for one reason or another gets access to your chart, without your secret pattern he/she won't be able to decipher the PIN from this random-looking chart. So, don't worry if your charts are stolen!

Basically, you are hiding your PIN inside a chart that others would view as a bunch of blocks with random numbers and colors. For you to make sense out of it, you will have to memorize one pattern of your own. Your pattern can be based on position, color, and numbers. You could apply this same secret pattern to different charts to conceal different PIN's!

Not convinced? Well, let's look at a couple of examples to let the concept sink in...

Example 1: Using Colors as Pattern

Let's look at the chart in Figure 4, below. A PIN of mine (not really) is concealed in the chart with a pattern that I have memorized. I can tell you my pattern is based on color. Could you guess what my PIN is? I doubt it.


Figure 4. Example Chart 1

Now I need to retrieve the PIN, and I know that each digit of my PIN is placed to the Left of the first 4 Blue blocks. Looking at the chart, I find my PIN to be 4267, as shown in Figure 5.

 

Figure 5. Example Chart 1 with PIN Selected


The pattern is ultimately your protection against other viewers. You are obviously not constrained to choosing a pattern based on color. Let's look at another example.

Example 2: Using Positions as Pattern

Let's do the same exercise as before. I have a very important PIN concealed here based on position. What is my PIN?


Figure 6. Example Chart 2

Well, the digits of the PIN are placed at the Top and Bottom of every Fourth Column. So, my PIN is 6061. This pattern was a bit complicated and uninteresting, but it is here just to illustrate the point. You may choose a simpler one, or even a more complex pattern.


Figure 7. Example Chart 2 with PIN Selected

Now, let's look at the last example...


Example 3: Using Numbers as Pattern

As usual, I have the PIN of my credit card (maybe?) concealed here based on numbers. What is my PIN?

Figure 8. Example Chart 3
My PIN's digits are found after the first 4 multiple of 3 numbers scanned from Left to Right, Top to Bottom. So scanning through we find 9 is multiple of 3, our first digit is 6. The next multiple of 3 number is 9, so the second digit is 2, and so on to find that our PIN is 6245, as shown in Figure 9.

Figure 8. Example Chart 3 with PIN Selected

Conclusion


I hope the previous examples have illustrated the concept of this technique (and the App). Please feel free to try it out if you like the concept. If you don't like to use Apps, you could easily make the same chart on excel and print a hard copy out in colors! Of course, there are tons of possibilities you could use as pattern by mixing the different criteria for pattern. Use your own creativity!

And If you are still not convinced of the level of security that this simple technique offers, then I would really appreciate if you share other methods you use or know of! Hope you are satisfied with this simple trick, and it serves useful to you!