Monday, December 16, 2013

CMake - basic tutorial

This is a short tutorial about CMake with a practical example. CMake is a tool to generate build files but does not compile! So, if you use Linux, CMake creates Makefile which make tool uses it to actually build your C++ application. The advantage of CMake over the standard make, is writing a CMake script is relatively easy comparing to a Makefile script. Another advantage is, CMake can generate build files for other platforms, so if you want to build your application for another platform like MS Windows, CMake does that for you just by telling which platform you want to build for.

Unfortunately a lot of examples found on the internet is based on one simple Hello World file, which doesn't represent the real power of CMake and also doesn't represent a realistic directory structure of real projects.

Ok, below we see how a typical project folder looks like:
Project_folder
             |__ src
             |       |__ main.cpp
             |       |__ xxx.cpp
             |       |__ yyy.cpp
             |       |__ zzz.cpp  
             |__ include
             |__ libs
             |__ build
             |__ CMakeLists.txt
  
Now, we want to tell CMake that in the folder 'src' there is the source files, in 'include' there is the include files (in case of C/C++) and in the 'libs' we have the libraries. The build folder will contain the build files that CMake generates.
CMakeLists.txt is the script CMake will read to know how to build the project.
So, how would our CMakeLists.txt look like?
Below we have an example of CMakeLists.txt:



#------------------------------------
# Minimum CMake version required.

cmake_minimum_required(VERSION 2.6)


#------------------------------------
# Not necessary, but recommended, projectname:

project(MyBoostTest)

#------------------------------------
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)

set (CMAKE_CXX_FLAGS "-g -Wall")

#------------------------------------

# Declare var names for source path
#------------------------------------
set (INC ${PROJECT_SOURCE_DIR}/include)
set (SRC ${PROJECT_SOURCE_DIR}/src)
set (LIBS ${PROJECT_SOURCE_DIR}/libs)

#------------------------------------

# Add source files to SRCS variable
#------------------------------------
list(APPEND SRCS ${SRC}/main.cpp
${SRC}/xxx.cpp ${SRC}/yyy.cpp ${SRC}/zzz.cpp)
#------------------------------------

# Tell CMake where the include files are
#------------------------------------
include_directories(${INC})
#------------------------------------

# is the same as include_directories
# in this case, we have no real lib files
#------------------------------------
link_directories(${LIBS})
#------------------------------------


# name the executable 'MAIN' and tell
# CMake which files are used
#------------------------------------
add_executable(MAIN ${SRCS})
#------------------------------------

# Tell CMake what libraries to link
# with. For example the BOOST's regex

# but it could also a library in the libs folder,
# which can be built with:
# add_library(mylib ${LIBS}/lib_x)
#------------------------------------
target_link_libraries(MAIN boost_regex)
#------------------------------------


 
If we run CMake in the same directory as where the above CMakeLists.txt resides, a bunch of files and folder will be created in that same directory. This will clutter up our project folder, to prevent that we tell CMake to put the generated build files in the build folder:

cmake -Bbuild -H.
If everything went well, we'll see the build folder with the generated build files. If we than move to the build folder, we can run the following command to compile the sources (assuming this is a C++ project on a Linux machine with the 'make' tool):
make .
If your sourcecode is successfully compiled, you'll see the MAIN executable in the build folder.

So, it's quite easy, you just need to tell CMake where the source files and libraries are, what to build and CMake is doing the ugly work for you.
We also use just one CMakeLists.txt, normally you should have CMakeLists.txt in every sourcecode folder, but for the sake of simplicity, we use only 1 CMakeLists.txt. I'll punt another CMake example next time with multiple CMakeLists.txt. 

Thursday, December 12, 2013

Vim - Reminders part 1

On this page I show some commands which you might forgot. For me it's to quickly look up how to do it again. So let's start.

Thursday, December 5, 2013

Vim - Nice little handy tips and tricks

I found some nice little tricks to perform some actions a little bit faster

Toggle toggle toggle...
If you want to set line numbers you do like this:
:set number
you can even make it a bit shorter"
:se nu

To disable line numbers:
set no number
or
set no nu

But you can also toggle by adding an exclamation mark '!'
:se nu!



Another toggle:
:se cul!
This is to put a line under the cursor, some like it, some not. I really like it!

Sources: http://learnvimscriptthehardway.stevelosh.com/


Another one:
I often like to load a bunch of files at once and when I'm done editing with a file, I'll get another buffer to edit (":h buffer" for more information). But sometimes I want 2 files next to each other, just to see if they look similar (but not identical). In that case I'd like to have 2 files open next to each other, so I want the window split in two vertical windows. This is how we can do that:
:vert sb x
Where x is the buffer number you want, assuming you already loaded a bunch of files. Now you get two windows with current buffer on the right window and buffer x on the left. Cool!

Compare 2 buffers:
Ok, so the above one creates 2 windows, each containing a buffer. Suppose you have a big file like a few thousand lines and want to check the difference, no problem with Vim. On each window you execute the command:
:diffthis
or shorter,
:difft
To turn off:
:diffoff!
With the exclamation mark, it turns off for all windows.

To jump to the next difference:
]c
read as "go to the next compare". The other way around is:
[c

To obtain the difference from the other file to the current file:
do
Note, this is per difference, so not the whole file at once. The other way around:
dp
Exercise with it, you'll love it!
By the way, I mapped diffthis and diffoff as:
nmap [Leader]d :diffthis
nmap [Leader]dd :diffoff!
replace [ with <, this blogger automatically removes '<', I guess because of security point of view (xss).



Other cute commands:
If you have multiple windows, you can close them all except the current one by this:
:only
There is also:
:hide
which closes the current window, but than I rather use Ctrl+w c, which is faster.


Follow the breadcrumbs:
One of the important things an editor should have is navigating forward and backwards my cursor positions. Say you edited a function or a method in your source code, than you jump to another function to do some other editions there or copy a snippet of code, the next thing you want to do is go back to the previous position. In normal mode you type:
Ctrl+o
for jumping back to the previous position, to jump forward again:
Ctrl+i
This is a very useful and powerful Vim command, a must-have desperately tool.


Forgot to sudo:
Very often I forget to add sudo if I want to edit a file with root permission, here is the remedy:
:w !sudo tee %
This one is hackish :)


Let's hex :
As a programmer, coder or hacker you need to check the binary data of a file. For example, you want to check the jfif segment (wiki-jpeg) of a jpeg file. To analyze the data, you can issue the command:
:%!xxd
to go back to the original view:
:%!xxd -r
So light, yet so powerful.


Load multiple files from within Vim:
Sometimes when writing code in Vim, I just need some other files to edit or maybe just to look at some code. Here's how you can do that:
:args somefolder/*.php
or if you want to browse to a folder and than load you can do the following:
:e .
This makes Vim as file browser, than you go to a certain folder, i.e. 'somefolder', than select those files with regular expression by first typing:
mr
than type:
*.php
and than type:
me
So by typing mr you open a regular-expression shell to select the matching files, than type the matching expression and than me to edit the files that match with the regular expression.


Insert date:
I like this one too, inserting date in the current file on the current cursorposition:
:r !date


Are you ready for this:
I sometimes accidentally close a file I was working on and to type
:e myfolder/subfolder/somecrazyfile.crz is just too annoying. But check out the power of Vim:
:ls!
shows you the recently closed files, than type:
:xb
and boom! Your recently closed file is back, where x is the id number of one of the closed files.

But this can be done faster! Check this, really amazing, hit the following keys:
Ctrl+o
You're back to the last cursor position in you last closed file! Amazing, just ONE key combination, amazing!
No plugins, just Vim! I'm sorry, I don't know if Emacs can do that :P


Copy/paste tricks:
I was a bit frustrated to copy a word and than replace another word with the copied one. I don't know why I didn't figured it out much earlier, but check this how to do it:
yiw is to copy the word where your cursor is on it, than do:
viwp this selects the word and than paste it with the yanked word earlier. Cool huh.
If you want to do this for another word, do this:
viw"0p meaning replace it with the word from register 0. When you yank or delete a word, the word is automatcially saved in register 0. You select the register by " and than a number. And of course, p is for paste.


When you yank a complete line with yy, you can than replace another line with:
Vp
To do this again for another line:
V"0p
I found this handy trick on: http://vim.wikia.com/wiki/Replace_a_word_with_yanked_text

Friday, July 5, 2013

Microcontroller - Which microcontroller to choose

For a long time I was thinking about building a robot, but never started to build one, until recently. A week ago me, my wife an my kids visited the Robocup2013 event in Eindhoven, the Netherlands. It was great to taste the enthusiasm during the event. So many young kids have built their little robots challenging other robots. 40 countries participated to the event but unfortunately Morocco was not one of the participants.

So I thought if I build a robot with very cheap components and share the result and knowledge with students from Morocco (and the rest of the world of course), maybe the schools and universities in Morocco will think about to participating to such events as the Robocup2013. We live in an era where knowledge is shared with the rest of the world over the internet. So the Moroccans have no excuse that they can't gain knowledge because it's expensive. Nowadays, knowledge is free and available on the internet.

To build at least an intelligent robot, I need a microcontroller to start with. But which microcontroller is suitable? Some criteria should be met, tom my opinion are I think:
  • it must be cheap, as cheap as possible
  • great community to ask for help and lots of tutorials
  • good development environment, like IDE, compiler, debugger (very important)
  • cheap microcontroller programmer
Since I already have some experience in mircocontroller programming, I found that ARM based microcontrollers are a bit overkill. I mean, just to use for controlling DC/Servo/Stepper motor and read some input pins is a waste to use an ARM based microcontroller. I have also worked with TI microcontrollers a long time ago, but you need to buy an IDE, I've used an IDE at college time that was free. However, the TI microcontroller was a nice one, it looks good, works good, nothing to complain about it. It's just that the compiler is not free. A PIC microcontroller is a popular one too, but it lacks of a good C compiler for free, it does provide a free Assembler . However, I want to realize a project and don't want to waste time in studying assembly, so PIC, no matter how nice this thing is, is no option to me.

After some time I found some projects based on Arduino. Arduino's are openhardware systems based on Atmel's AVR microcontroller, which also has a simple to use IDE including C compiler. The code can be flashed to an Arduino device through usb cable. There is no need for a special JTAG interface or self-built serialport loader. It supports also C++ and it's really easy to write code for it, to me it feels like writing code in Java. The builder of Arduino's really managed to create a microcontroller platform that is accessible to a large audience with no experience of microcontrollers. They really did a tremendous job to achieve that.

Another great advantage of Arduino is they are cheap comparing to others, people with low budget that want to learn or build a microcontroller project, are able to buy one. To program the controller, one just has to download the software for free and need an appropriate usb cable.
If you want to have more control over the AVR microcontroller, there is also a free compiler for it, free IDE and so on. So Arduino is a great way to jump to AVR, because Arduino is based on AVR.

Because as a father, husband and employee I have little free time, my choice is to start with Arduino and next AVR.That's my choice b.t.w. ;-)

Monday, July 1, 2013

Robots - Robocup2013

Last weekend I went to the Robots event Robocup 2013 in the city Eindhoven, in the Netherlands. I went there together with my wife and 3 kids and it was a bit fun. It was more fun for the participants of the event. There were participants from about 40 countries, including Turkey, Iran, China and so on... As a visitor you can only see the robots from a distance on a stand. So finally it wasn't more than watching to a bunch of robots who try to score with a colored ball. There were different leagues, categorized from small simple robots to artificially intelligent robots.

The more interesting robots are those humanoid robots, these robots look like humans, or they try to be.
Also there's some interaction, that makes a robot always interesting, especially for the kids. We saw the famous autonomous robot Asimo too, but it was very crowded and couldn't see much, so it wasn't a great success, but at least we saw something.

If you see how much research, effort and technology it was needed to build a robot like Asimo, how difficult and knowledge is needed to build a real human? That's why I believe in God as our creator and that there's a reason why we we're built.

I really hope the kids like it and that they're interested in building a robot too :-) Who knows, someday I'll post a robot built with my family.

Wednesday, June 19, 2013

Java - Mail

How to send mail from Java sourcecode?
First you need to download the library mail.jar from oracle and add it to your Java project.
You can get it on the link below:
http://www.oracle.com/technetwork/java/index-138643.html

Than try out this code:
final String username = "username@gmail.com";
final String password = "password";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
  });

try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("from-email@gmail.com"));
    message.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse("to-email@gmail.com"));
    message.setSubject("Testing Subject");
    message.setText("Dear Mail Crawler,"
        + "\n\n No spam to my email, please!");

    Transport.send(message);

    System.out.println("Done");

} catch (MessagingException e) {
    throw new RuntimeException(e);
}


It's quite easy and it should work, unless your firewall blocks it, in that case open the port 587.
This is working for GMail accounts, but it should work with other accounts too, with just a little modification in the code.
This example code is copied from mkyong's website:
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/comment-page-4/#comment-135038

Thursday, June 6, 2013

Promising gadgets - Apple's Smartwatch vs. Google's Glass

Though smartwatches or smartglasses are not new, just like tablets before the iPads, they're still not a huge success. But Apple and Google are working hard to launch a new success device.

Apple, according to rumors on the internet, is working hard on a smartwatch, while Google is already demonstrating their smartglass called Glass. But which one will succeed?

Smartwatch
The advantage of a smartwatch is it's wearable as an ordinary watch. If you receive an sms or a whatsapp message,  you can simply read it from your watch. Of course, if you just want to know what time it is, use your watch. You can even check photos and other viewing stuff
The disadvantage is it has a small display, so entering a text using your fingers is not a good idea. Also it's not a good idea to take a picture with your watch.

To summarize a smartwatch we could list the advantages and disadvantages as follows:
Advantage:
  • easily wearable
  • coverable
  • readable for messages and notifications
  • viewable for photos
  • see who's calling
  • streaming video (or live video)

Disadvantage:
  • small battery size
  • small display size
  • not useful for entering text
  • not useful for taking pictures or recording videos
  • not useful for calling session, like talking to your phone and using headphones connected to the smartphone.

Seeing these advantages and disadvantages we can make following conclusions, a smartwatch should :
  • work as a client for a smartphone using bluetooth connection to communicate.
  • have low energy consumption because of small battery capacity. It would be very annoying to charge your watch everyday.
  • an api to write widgets for smartwatches.
  • have a side trackpad for vertical scrolling, because of small display size, your finger will easily cover the display and thus not user friendly.
  • copy UI from older gsm devices like the Ericsson G700. Cause these UIs were based on small display sizes.

Smartglass
The big advantage of smartglasses is you have your hands free while recording videos with an integrated camera. Because a smartglass is mounted on your head, it works also as a headset. The big disadvantage is, you have to wear a smartglass the whole day and not everybody likes to wear such a device that's not coverable.

To summarize a smartglass we could list the advantages and disadvantages as follows:
Advantage:
  • easily wearable
  • readable for messages and notifications
  • viewable for photos
  • see who's calling
  • streaming video (or live video)

Disadvantage:
  • small battery size
  • not useful for entering text
  • not coverable
Seeing these advantages and disadvantages we can make following conclusions, a smartglass should :
  • work as a client for a smartphone using bluetooth connection to communicate.
  • have low energy consumption because of small battery capacity. It would be very annoying to charge your smartglass everyday.
  • an api to write widgets for smartglasses.
  • have a side trackpad for scrolling.
  • have a suitable UI. Cause it's not a touch based device (i.e. a smartphone).

My personal opnion
I think the smartwatch will be a success for normal people, because it's like a watch, but a smart one. Like there was a normal phone before, now you have a smart one. A glass is not an electronic device, wearing glasses is only for necessity (to be able to see better). So I think for the normal people, a Google's Glass won't be a huge success. However, it could be a success in the business industry or in the world of sport and games. For example, a referee of a soccer game could see real life video of an incident before taking real decision. Or in a hospital, a nurse could see a patient's dossier, take a quick picture and send it to the doctor. There are great possibilities with a smartglass, but I doubt it will be successful for the normal people.
My conclusion is, smartwatch will be successful for normal consumers and smartglass will be successful in the business industry.

Tuesday, June 4, 2013

Soccer - Best soccer player of the world

Every year the FIFA soccer organization announce the best player of the year, the so called Ballon d'Or. It's often Messi, Christiano Ronaldo, Ronaldinho, Iniesta, Xavi and so on... If you see the big names, it's not fair to elect just the attackers. An attacker is not a defender, a defender is not a keeper, so it's not fair that Messi is the best football player of the year. I mean, Messi would not be so great without Xavi or Iniesta around him.

To make a fair election, the award should be divided into different groups. For example:
  • best keeper award
  • best defender award
  • best midfielder award
  • best attacker award
  • best free kick award
  • etc...
Maybe you can add an award for the best player award from the public audience.
However, to me, Messi is NOT the best player of the world, he's the best attacker of the year.

In my opninion Diego Maradona is the best soccer player ever!

Tuesday, April 9, 2013

Android - When a process gets killed.

According to http://developer.android.com/guide/components/processes-and-threads.html,
the Android OS weighs the relative importance of processes to the user to determine which process is candidate for killing, if system resource (like memory) gets low.


For example, if a process has no visible activity running, it is than assumed to be less important to the user and so likely to get killed, when necessary. So depending on the state of components within a process, the OS makes a decision upon it to kill.

The theory is that Android OS tries to maintain a process as long as possible, but eventually needs to remove or kill old processes to reclaim system resource for a more important process. So the OS somehow holds a list of processes based on importance of components and the state of the components. And so a process with the lowest priority gets killed first and than next and next...

There seems to be 5 levels of importance:


1. Forground process

  •     It hosts an Activity that the user is interacting with (the Activity's onResume() method
    has been called).
  •     It hosts a Service that's bound to the activity that the user is interacting with.
  •     It hosts a Service that's running "in the foreground"—the service has called startForeground().
  •     It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
  •     It hosts a BroadcastReceiver that's executing its onReceive() method.

2. Visible process

  •     It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it.
  •     It hosts a Service that's bound to a visible (or foreground) activity.

3. Service process

  •     A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing music in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.
   
4. Background process



  •     A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state.
5. Empty process


  •     A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.
   
But what if you want your service not to be killed by the OS, well there is a trick for that.
To do this, you need to call startForground() method of the Service. You have to pass a notification ID and a notification object. Like this:

startForeground(NOTIFICATION_ID, mNotification);
 

This tells the OS not to kill the service, though the OS will kill it in extreme situation. You can image that when you're listening to music, you don't want the OS to disrupt the music for some reason.

Monday, March 11, 2013

A quick Git tutorial part 3

Link to a well explained git tutorial
gitref.org

git remote
If you clone a project from another machine, Git automatically sets the remote machine as the origin of the project. So when you want to update with the latest updates of the project you simply do:
git pull

With 'git remote' you can list your remote aliases, so this also means you can add remote machines that has the same git repo:
git remote add alias url
 
This way you can push new changes to a specific machine by giving the remote alias argument, for example:
git push yozef

Of course, you can also remove the alias:
git remote rm yozef

To show the remote list with extra information:
git remote -v

You can change url of an existing alias:
git remote set-url origin git://some.remote.machine/repo.git

To remove untracked files and folders after hard reset:
git clean -f -d

Tuesday, March 5, 2013

A quick Git tutorial part 2

git rm
With 'git rm' we remove a file from the staging index AND from disk. So be careful if you don't want to remove it from disk! If you only want to remove a file from the staging index, you should use:
git rm --cached file

This will remove a file from the staging index and leaves the file on the disk. Sometimes you accidentally added a file you don't wish Git to track it. So the most simple procedure is to perform 'git rm --cached file', than add this file name in the .gitignore file and than finally commit. But what if you have like hundreds of files added in a folder you don't want Git to track them. For this, you can get them out of the staging index like this:
git rm --cached -r folder

Don't forget to add a line in .gitignore file to tell Git to ignore all the files in that particular folder, something like: sources/somefolder/*


git reset
With 'git reset' you actually reset your changes back to the original HEAD (the last commit revision before adding changes). Sometimes you don't know what happened and you get frustrated as everything seems to go wrong. In that case, your last action to the rescue is to go back to HEAD and everything gets wiped out. There is no way in turning back, so be careful.
With 'git reset --hard', the changes in the staging index will be undone and thus completely removed. It's the same as going back to the last commit and no changes are made yet. Notice that HEAD could also be a commit revision. If you want to go back to a previous commit, you could also do:
git reset --hard HEAD^
or
git reset --hard b45ac81

The latter brings you back to the commit with the first seven characters of the sha (in that case ' b45ac81').
If you want to go to a previous commit BUT you want the changes stay in de staging index, than you can do:
git reset --soft HEAD^

With the --soft argument, the changes stays in the staging index.


git stash
Suppose we were editing some files and suddenly a bugfix need to be done. We could create a new branch from the current branch and fix the problem or we can save our work on a stack to get back later. The latter one is called stashing. By performing 'git stash' all the edits will be saved on a stack and you get a message like:
Saved working directory and index state WIP on master: 56490c0 cool stuff with git
HEAD is now at 56490c0 cool stuff with git

You can do some more edits and save this on a stack too. To see what work we have save, we can list them with the following command:
git stash list
result:
stash@{0}: WIP on master: c761ca7 experimenting with git
stash@{1}: WIP on master: 56490c0 cool stuff with git

The top of the stack is 0 and the stack is a LIFO.
WIP could mean Work In Progress, seems logic to me, but it could mean something else.
The master means the master branch, so the message is quite clear.
Anyway, now we want to get the edits back we saved earlier, as we solved a bugfix, this is how we do:
git stash apply
This will get the 'changes' back where we left off. We could also use:
git stash pop
The difference is that the latter one will remove WIP from the stack, while the first one keeps the WIP on the stack. After putting back the saved WIP, we can remove it from the stack with:
git stash drop
This will remove a WIP from the top. If you want to remove them all, you could also issue the following command:
git stash clear


git commit --amend
Oops, you wrote a wrong message for a commit and you want to change that?
git commit --amend -m "my new message"


git cherry-pick
This commands can be useful if you want to add a commit from another branch to your master branch. You can imagine that while you're working on a separate branch, you already want to commit some of the work already done and not waiting until you finished your big changes on the separate branch.
We can do this by 'picking' a commit from another branch and 'insert' it in the master branch.
So suppose we are in a branch called 'test' and we've already done some commits and we're still busy doing some edits in some files. We can merge the last commit that's already done to the master branch. So we switch to the master branch:
git checkout master
Than we pick a commit, i.e. '93e8ab7', from the 'test' branch and insert it in the master branch like this:
git cherry-pick 93e8ab7

You can do this multiple times, but chances are you'll get conflicts if the same files will be committed again. To solve this, we 'git rebase' the branch on to the master branch. It's like making a custom branch compatible with the master branch. You will see that the commit hashes are changed after a rebase. From there on, you can switch to the master branch and merge the commits from your custom branch to the master.

To rebase, you go to your custom branch and do the following:
git rebase --onto master 1234abcde^
where 1234abcde^ is the commit from where you want to rebase to the master branch.
After that, you'll notice that commit sha's from 1234abcde to the last commit, will be changed, so it fits to the master branch. Now, if we switch back the master branch and do: git merge custombranch
Than all the changes will be merged to the master branch.
Play with it, cause it's a bit confusing and you better should avoid cherry-picking if not necessary.

git format-patch, git apply
When developing with a team on a project, there is often the case that you have one central source repository (based on Git) where the latest source codes maintains. It would be a mess if all developers of the team starts pushing the new codes and bugfixes. To keep the situation organized, there should be some kind of source code maintainer who checks the new codes and bugfixes before it updates the repository. What you get is developers are forced to send patches of codes to the maintainer and the maintainer checks whether it's ok or not, this way you get a controlled process of developing on a project with a team.
Well, to create a patch in Git, it's best to create a seperate branch and do your editing there. If you made a little fix, or added a new feature and you tested well, you finally create a patch, to do this you do as follows (assuming you're on a different branch):
git format-patch master
This means, make a patch from the difference between master branch and the current branch.
We could also do this:
git format-patch HEAD^^...HEAD
This means, make a patch from two previous commits ago to the last commit.(^  means previous).
We could also use commit revisions instead of HEADs.
Often you want to give a patch a name, so others have an idea what the patch is about:
git format-patch master --stdout > fix_bug_123.patch

On the other side, if you want to apply a patch in your master branch, it's just simply this (assuming you're on the master branch):
git apply fix_bug_123.patch

Understanding difference between cherry-pick and merge
When you have a custom branch to do some edits on it, you might have made multiple commits. So when you're satisfied with the final result, you want to merge it to the master branch. So you switch to the master branch and do 'git merge custombranch'. What happens is all the commits are copied to the master branch, you can see them with 'git log --oneline'. If you want to cherry-pick a commit, you actually want to copy the changes of one commit to your master branch (or whatever branch you are). So you get a new commit based on the 'changes' of your custombranch which is a different hash!
I'll add some images to get a better understanding, as there is a saying "a picture says more than thousand words".

git diff
To show what files have changed, 'git diff' shows the content of the changes, for example:
git diff
this will show the difference between the last commit and the added changes that are NOT added in the staging index
To show the changes in the staging index, do this:
git diff --cached
If you want to show both of the changes, meaning the changes in your working directory, do this:
git diff HEAD

To show the difference between two commits:
git diff HEAD^ HEAD
Note that the HEAD's could also be the sha's of the commits.




Tuesday, February 26, 2013

WiringPi: IO control for Raspberry Pi

WiringPi
Is a C library to control the IO pins, like the GPIO, I2C, SPI and so on...
WiringPi also has a commandline tool to control the GPIO from a shell script, which is cool and makes
writing small simple scripts very easy to automate certain stuff.
I'll handle here only the WiringPi utility, as that's all I need for now.
For more information about WiringPi, take a look at this link:
https://projects.drogon.net/raspberry-pi/wiringpi/

Installation:
First we need git tool to download the sources:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install git-core


(clone the project)
git clone git://git.drogon.net/wiringPi

(got the wiringPi folder and build the project)
cd wiringPi
./build


To install the executable in i.e. /usr/bin/ you need sudo for that.
Try the following command to see if all went well:
gpio -v
gpio readall


GPIO Utility:
Now, if we want to use GPIO pin 1 to be the output, we do as follows:
gpio mode 1 out
Here we say, make GPIO pin 1 as output.

To make pin 1 HIGH:
gpio write 1 1
This is translated as write pin 1 as 1.

The GPIO has also an internal pull-up/down resistor, this can be controlled too:
gpio mode 1 up
gpio mode 1 down
gpio mode 1 tri

Streaming webcam with Raspberry Pi

I'll write soon my own experience with streaming video from a webcam with RaspberryPi, but until than, here are some links that can help you to do the same thing. The result depends on the support of the webcam by the RaspberryPi.
http://wolfpaulus.com/journal/embedded/raspberrypi_webcam
http://www.palebluedot.nl/jml/index.php/computer-stuff/33-webcam-streaming-with-raspberry-pi
http://blog.ianrenton.com/raspberry-tank-day-14-video-streaming/
http://blog.davidsingleton.org/raspberry-pi-webcam-a-gentle-intro-to-crontab/
http://sirlagz.net/category/raspberry-pi/
http://www.thisismyrobot.com/2012/08/getting-logitech-c270-webcam-working-on.html
http://www.slblabs.com/2012/09/26/rpi-webcam-stream/

ssh, scp, rsync, ftp, ...

Tuesday, February 19, 2013

Wifi autoconnect RaspberryPi

I wanted my RaspberryPi to autoconnect through wifi on a spcified Access Point (AP).
To do this, first I copied /etc/wpa_supplicant/wpa_supplicant.conf to /etc/ .
You need to tell RaspberryPi to connect to your wifi hotspot (for example, your wifi router).
You can than output the wpa_passphrase to /etc/wpa_supplicant.conf by issuing the following command:
sudo wpa_passphrase myssid "this is test" >> /etc/wpa_supplicant.conf 
myssid could be your wifi's ssid and "this is test" could be your wifi's password or code.

In /etc/wpa_supplicant.conf I added the following lines after the psk line:
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN


...so it will look something like:
network={
        ssid="myssid"
        #psk="this is test"
        psk=fa5d92f2b069636fd3fe65e2376f2061b37467f8908ca373bbf10f7c92cd37b9

        proto=RSN
        key_mgmt=WPA-PSK
        pairwise=CCMP
        auth_alg=OPEN
}


So that's the part of wpa_supplicant.conf part, now we have to modify /etc/network/interfaces.
We add the following lines:
allow-hotplug wlan0
iface wlan0 inet dhcp
pre-up wpa_supplicant -Dwext -i wlan0 -c /etc/wpa_supplicant.conf -B


So, this is it. I have an Android phone, which has a wifi hotspot feature. If you turn a wifi hotspot on (or your own wifi router at home), your RaspberryPi should automatically connect. Make sure you rebooted your Raspberry and make sure you used the right SSID and passphrase of your wifi AP.

A small problem I encountered is that I had no connection on the tcp/ip layer when turning off and on my AP while RasPi was running. There was a physical connection though, but somehow the upper layers was dead. It turns out that wpa_supplicant wasn't cleaned up properly (not killed) and there somehow went wrong. After googling around for solutions, I could only find selfmade scripts which I don't really like (like checking for connection status every 60 sec. or something). I also didn't try netcfg, because I was afraid it will conflict with other default network managers (I'm not sure about that).
The solution I found is as follows:
  • Copy /etc/wpa_supplicant/ifupdown.sh to /etc/ifplugd/action.d/ifupdown (make sure you make a copy of /etc/ifplugd/action.d/ifupdown, before you overwrite it).
  •  sudo reboot
That's it! I do see some error messages in /var/log/syslog, but besides that, it works. Now I can turn off and on AP, my RasPi will automatically reconnect with a working the tcp/ip layer.

Crontab

With cron you can execute scripts or commands based on a schedule.
For example, if I want to run a script every 5 minutes, I have to do as follows: 

crontab -e
This will bring you in the edit mode, than we specify that a script must be executed every 5 min.
*/5 * * * * /home/geek/myscript.sh

From now on, every 5 min. the script myscript.sh will be executed.
Crontab works as follows, you have to tell it according to a certain format what time interval to execute a command.
The format is as follows:
minutes (0-59)    hour (0-23 0=midnight)    day (1-31)    month (1-12)    weekday (0-6 0=Sunday)
So the following will run at 01:15 every Sunday.
15 1 * * 0 /usr/bin/date

Another one is to run a script every 30 min. on every day.
*/30 * * * * movelogfiles.sh
or
0,30 * * * * movelogfiles.sh


To remove the 'cronjob' we issue the following command:
crontab -r

To list the cronjobs (so you can see what jobs it has):
crontab -l

Webcam on Linux

Camera commandline tools on Linux
  • fswebcam
  • streamer
  • uvccapture
  • motion

Example to use fswebcam:


fswebcam -d /dev/video0 -r 320x240 mypic.jpg
 

This will use webcam video0 as a camera device with a resolution of 320x240 pixels and outputs it to the file mypic.jpg.

Another nice feature is to use fbi (on Ubuntu) to display the picture in a terminal.
If you don't have fbi, install it with:
sudo apt-get install fbi
Than show an image as follows:
fbi mypic.jpg
or all available pictures:
fbi *.jpg
With  PgDn or PdUp you can go to the next or previous picture.
If it doesn't work for you, you should google for it, it has something to do with vga setting.

Another very useful tool is ImageMagick for processing images. I'll cover that next time.

Thursday, February 14, 2013

Crosscompiling for Raspberry Pi


Linux crosscompile for the Raspberry Pi

I was looking for a crosscompiler to compile executables for the RPi.
On google I found links about how to build your own toolchain, but I rather have a ready made toolchain instead of cooking my own. So I found the following link:
https://github.com/raspberrypi/tools

According to http://qt-project.org/wiki/RaspberryPi_Beginners_guide, it's based on 32 bits machines, so you also need
to install ia32-libs if you work on a x64 based machine.

...and I assume you use a Linux system like Ubuntu or some other flavor.

If you want to cook your own toolchain, this might be a good link for you:
http://www.kitware.com/blog/home/post/426

Wednesday, January 23, 2013

Pathogen, the Vim plugins manager

Pathogen
After installing a few plugins I started to get a little bit annoyed by copying the plugin files to the .vim folder after downloading. It's not a big problem though, but after some plugins, it starts to get messy. You can't see directly what plugins you've installed or what could cause problems and so on...

So to manage the plugins in a proper way, I use Pathogen to do the job. What you have to do is download the plugin from:
https://github.com/tpope/vim-pathogen

Copy the 'autoload' folder to your .vim folder. Actually, the first time you use Vim you should  install pathogen. Create another folder in .vim and call it 'bundle'. The bundle folder is where  you put all your future Vim plugins:
/.vim
   |___ autoload/
   |___ bundle/
              |___  snipmate/
              |___  taglist/
              |___  .../

So every time you download a plugin, you just copy the complete plugin folder in .vim/bundle/
You could also go in the .vim/bundle/ folder and download a plugin using Git, like this:
Assuming you're in the .vim/bundle/ folder.
# git clone https://link.to.vimplugin.git

You just need a small piece of script added in your .vimrc:
execute pathogen#infect()
syntax on
filetype plugin indent on

That's it! Try this out with snipmate plugin, as this plugin doesn't need any other configuration in your .vimrc file. If it works for you, than you can download all your favorite plugins and all are hierarchically structured.

Tuesday, January 22, 2013

Vim plugins for C/C++ development

To use Vim as an editor for C/C++ (and other programming languages as well), we need to extend Vim with some handy plugins. Vim is a powerful editor, it really is, but you need some plugins to make it more powerful to your needs. Vim is not a code editor out of the box, so you can not expect to have cool stuff like Visual Studio's intellisense, or jumping to definition of a function and so on. So to make our coding life easier, we can install Vim plugins to have more fun while coding.

First, here's a list of Vim plugins below I use it for writing code:
  • Surround
  • Matchit
  • Snipmate
  • Clang_complete
  • NERDTree
  • TagList

Matchit
This is a nice plugin too, especially when dealing with html files. It searches for matching tags using the existing % key. In a C file, if you're on one of the brackets like {}, [], () and so on, you'll see those brackets highlighting in pairs. When hitting % the cursor jumps to the matching pair, but normally this won't work for a html tag. Without this plugin this won't work for a html tag.

Put cursor on head tag and enable V mode


Hit % to jump to the matching tag


Link: http://www.vim.org/scripts/script.php?script_id=39

 
SnipMate
Snipmate is really one of my favourite, it's simple but yet so powerful, it's brilliant. You simply download the plugin, copy it to your .vim folder and you're ready to go, just that simple! No, extra additions to .vimrc, no long docs reading, just download, copy and start playing. When you've done that, open a C file and type as follows:
for and than hit the tab key, voilĂ ! A complete for loop snippet is placed and we're not finished yet! You can replace the default words by hitting tab again, change the word in the selected field, than hit tab again, edit the selected field until you're done. This is fantastic!

Typing 'for' before hitting TAB




Result after hitting TAB


Link to download snipmate plugin: https://github.com/garbas/vim-snipmate

Surround
This plugin is a must-have when writing html code, it surrounds a selected block of text/code with div tags (in case you're writing html code) or brackets (in case you're writing C code). It's also very easy to use.
For example, type a simple text and than go back to normal mode and type: yss"

Before typing yss" in normal mode

After typing yss" in normal mode

After typing yss} in normal mode

After typing cs}) in normal mode

When using visual selection (v or V) than use capital S for surrounding, i.e. veS' is the same as ysw'.
The first one is in visual mode and the second one is in normal mode.
The key combinations can be seen as follows:
ysmn surround word m with tag n
csmn change surround with tag m to tag n
dsn delete surround with tag m

For more detailed information go to link: https://github.com/tpope/vim-surround


NERDTree
This plugin works as a file browser, you open it, search the file you want to edit and than hit enter. The file will be displayed and you can edit all along. So, you don't have to get out of Vim to look for files to edit, you simply stay in Vim, open NERDTree and look for the files. But I tell you this, a real good experienced Vim user doesn't even need NERDTree to do such a magic.

I've seen die-hard Vim users loading a whole bunch of files at once and switch buffers as they drink coffee and do crazy stuff! Vim is so powerful, you can't call it just an editor, it's actually an editor that you have a conversation with. When you say, 'dd', it responds with "listen baby, if you want I can also delete multiple lines", than you move 4 lines down and Vim says "baby, just say 4j and I do what you want, but anyway sweety, you want me to delete this line too? Just press . and I'll do it for you". This is Vim and I'm also a beginner, Vim is just incredibly good, you just need to be patient with her and once you have control over her, you can let her do whatever you want ;-)

By adding this line .vimrc, you can toggle NERDTree on or off by pressing on the F4 key:
:noremap   :NERDTreeToggle

Example of NERDTree

Link: https://github.com/scrooloose/nerdtree


TagList
TagList plugin is a sourcecode browser, it shows you a list of classes, defines, global variables, functions, methods etc. for the currently displayed file. This a very useful feature, this way you have an overview of all the functions and you can navigate to a function or a method easily. If you want to jump to a function and edit right away, you simply move to the function name in the taglist and hit enter. If you just want to view the function without jumping to it, you simply press 'p' key (which means preview), this way you stay in the taglist window.
It supports most programming languages, so it's a simple and useful plugin without putting a bunch of tweaks in the vimrc file.

I added these lines in the .vimrc script, to enable and disable TagList with F5 key:
:noremap :TlistToggle
:let Tlist_Show_One_File = 1
:let Tlist_Exit_OnlyWindow = 1
:let Tlist_Use_Right_Window = 1
The last line tells TagList to show on the right side of the window.


TagList example on the right side





Clang_complete
This plugin is important when developing C/C++ code. Clang_complete together with clang and libclang-dev is the best replacement for omnicppcompletion, the old completion plugin which doesn't work well. omnicppcompletion uses ctags to perform completion of code, but it's not perfect like Visual Studio's intellisense or Eclipse. But clang is here to save us, developed by llvm (www.llvm.org). First you  need to install clang, I did the following:
#sudo apt-get install clang
#sudo apt-get install libclang-dev

Than download clang_complete from:
https://github.com/Rip-Rip/clang_complete

Copy the files to your .vim folder and you're done. That's actuall all I did.
I tested with BOOST C++ and it works without tweaking or adding creepy scripts, it just works! See below for an example:



NSNotification example