Google Ads

Linux and Software: News, Reviews, Tutorials

October 19, 2021

Extracting / retrieve plot data in Scilab

Oftentimes you would like to extract data points from the plots as this is extremely useful to do so especially in Engineering and Science analysis. This is especially the case when we are manipulating plot data using some editing method. A similar application MATLAB has a function that allows synchronising of what is being shown in the plotting window to what is stored in the variables. But this function is buggy and can oftentimes CORRUPT the original data stored as unique variables for later processing. Also, it is a good practice not to modify the original variables for comparing with the plot data later. In Scilab, it is really simple to extract information about what is being shown in the plot window as Scilab stores everything in the plot as different object variables which are easily accessible from the Scilab console command prompt. Just with the help of few statements in the command prompt we can easily dump the plot data into the console and copy them over to a spreadsheet or any other editor for saving the plot data separately. Let's assume we have plotted some variables Scilab and the plot window show up. Once the plot window shows up and shows the data we can enter the following commands to dump the plot data into the console:

h = gca()
p = h.children
c = p.children
c.data
Copied!


The first command as shown above retrieve and stores a reference to the graphics object which is holding the plot. The subsequent commands get handles of objects residing in the graphics object. The final command dumps the plot data into the console using the handle which points to the plot data object variable. The following figure shows the result where variable y data what plotted and the above commands dumped the plot data into the console:



Cheers!
Imam

January 31, 2019

Create a stylish button in GTK+ (Custom widget creation)

Often times we want to create our own form of buttons and widgets when using widget libraries such as GTK+. Although, we could achieve this by creating theme files but sometimes it is just easier to implement such widget using drawing routines available. In this tutorial, I am going to show you how to create a stylish button in GTK+ by not using widget provided button but by using drawing routines available for GTK+ library like shown below:




First, we create four png images for the button for hover, normal, pressed states and mask. We are going to use Cairo library for drawing our button state images into its container. All the functions required for creating this button are part of Standard GTK+ 2 package, so no external dependencies! for the button creation.

Second, we load button png images using cairo_image_surface_create_from_png function.

Third, we prepare a mask for the button as the button can have any shape where some parts of the button are transparent. We create a pixmap as button mask using gdk_pixmap_new function and format the mask according to mask png file using Cairo drawing functions. Our style button contain would be a GTK+ drawing widget. Finally, we set the mask using gtk_widget_shape_combine_mask function.

Fourth, we have to be able to update the button look according to its state which is achieved by connecting different signals to button container and updating button state variable in the signals callback functions and finally drawing the button images using Cairo functions. The callbacks functions can also be used for achieving normal button operations.

That's it! 

Watch the tutorial:



Cheers,
Imam

October 1, 2018

OpenGL texture compression library for Ubuntu for better graphics experience

If you are using Intel graphics chip for your graphics needs on Ubuntu then probably you need to install OpenGL texture compression library to gain proper graphics performance and quality out of your graphics card. By default this library is not available on Ubuntu due to license, IP or distribution restrictions. The library provides the following OpenGL extensions under Mesa3D OpenGL implementation:
  • GL_EXT_texture_compression_s3tc
  • GL_S3_s3tc
These OpenGL extensions provide support for efficient graphics texture uploading to your graphics processing unit making graphics applications utilize its memory bandwidths efficiently and productively to deliver best performance. Consequently, almost all games and applications make use of these OpenGL extensions. The library can be compiled from the source code under a GNU Linux distribution of choice easily. For Ubuntu based distributions the pre compiled and ready to be installed 32 Bit and 64 Bit libraries packages can be downloaded from the following link:

http://onthim.blogspot.com/p/onthim-downloads.html

Cheers,
Imam

April 8, 2018

Free secure file sharing using Snap Image Share

Sometimes we want to share files with our friends, colleagues and mates but also want to limit the access someway like how long the file will be available, number of downloads for the file, and so on. We can easily share files on Facebook and Instagram too, but to share files on these platforms the people you are sharing files to also need to have accounts on these platforms. Snap Image Share is a new free file sharing platform by SALHOS Engineering with which you can share as many files as you want with file size up-to 100 MB without any accounts or signup and also limit file sharing access like availability and downloads. Just like Google Drive and Dropbox file sharing services people do not need any account in Snap Share Image to download images. So, start sharing files now with Snap Image Share:

Snap Image Share

Cheers!
Imam

February 20, 2018

Use Python objects to process and store csv file data

In Python data from csv files can be easily loaded and processed for analysis or automating other jobs. In this tutorial, we will see how data from a csv file can be stored easily in Python objects and spit out the processed data from an object as necessary. For this exercise, we assume we have a csv file containing temperature data for 28 days where the first column contains days records and the second column contains temperatures records. First we will load the csv file's temperatures data into an object and then show the data and temperature average from the object. After that, we find and store the differences in days temperature from the object to another object. Finally, we save the differences in days temperature data from the object to a csv file. A sample of the csv file contents is shown below:

1 27
2 25
3 23
4 30
5 19
6 20
7 13
8 30


Now, in Python first we will have to create an object for holding these data from the csv file. For this, in the Python object we need to have two lists, one for days records and the other one for temperatures records. Now, we define the Python object as below:
# define object for holding a set of temperature data
class TempData():
  def __init__(self):
    self.day = [] # list of days
    self.temp = [] # list of temperature
Now, we create two object instance variables of this type where one will hold temperatures data as in the csv file and the other one will hold temperature differences data.
csv_imported_data = TempData() # create object for holding csv file temperature data
processed_data = TempData() # create object for holding processed data
Now, we can open the csv file and load the csv columns data into the object lists for days and temperatures data.
csv_file = open('data.csv', 'r') # open the csv file for reading
reader = csv.reader(csv_file) # pass the file to csv reader object for extracting data

for row in reader: # get the row data from the csv file
  csv_imported_data.day.append(float(row[0])) # get the first column data
  csv_imported_data.temp.append(float(row[1])) # get the second column data

csv_file.close() # close the csv file
Now, lets show the temperature data from the object:
# print temperature data from the temperature object
for i in range(len(csv_imported_data.day)):
	print(csv_imported_data.day[i], csv_imported_data.temp[i])
Now, lets show the average temperature from the object's temperature data:
# show average temperature from the temperature object
print('Average temperature for', len(csv_imported_data.day), 'days was', sum(csv_imported_data.temp)/len(csv_imported_data.temp))
Now, lets find the temperature difference from the object's temperature data and store difference data into another object of same type:
# find difference between temperatures and store in temperature data object
for i in range(len(csv_imported_data.day)):
  if (i == 0): # no difference for first data
    processed_data.day.append(csv_imported_data.day[i])
    processed_data.temp.append(0)
  else:    
    processed_data.day.append(abs(csv_imported_data.day[i] - csv_imported_data.day[i-1]))
    processed_data.temp.append(abs(csv_imported_data.temp[i] - csv_imported_data.temp[i-1]))
Now, we show the temperature difference data from the object:
# print temperature difference data from the temperature object
for i in range(len(processed_data.day)):
  print(processed_data.day[i], processed_data.temp[i])
Finally, we save the temperature difference data from the object to a new csv file so that we can retrieve the temperature difference data without running the Python script again:
csv_file = open('processed_temp_data.csv', 'w', newline='') # create a new csv file for writing
csv_writer = csv.writer(csv_file) # pass the file to csv writer object for writing data

for row in zip(processed_data.day, processed_data.temp): # create the row data from the the temperature object
  csv_writer.writerow(row)

csv_file.close()
Download the full example code and CSV files:


Cheers!
Imam

December 16, 2017

Ubuntu improve WIFI performance and reliability

If you need a stable internet connection through WIFI then it is important that WIFI performance remains consistent and WIFI connection is reliable at any given time. This is vital if you are running any kind of server or using torrents. Unfortunately, the power management feature exists for different devices within Ubuntu promotes unstable and slow WIFI connection which is enabled by default for WIFI devices. This creates problems such as automatic turning of WIFI and loosing of WIFI connectivity randomly while the system stays idle for a while or there is no inbound packets coming to your system. To check whether you have power management active for your WIFI device execute the following command into the terminal:

iwconfig | grep -w "Power Management"

Now if it is active then you can easily turn it off by executing following command:

sudo iwconfig wlan0 power off

Where you have to replace wlan0 word with your WIFI device name which can be found by executing following command:

ifconfig -a

The above command will list all the network devices present in the system including WIFI devices. If the terminal says that command not found then install the program by installing the package net-tools. To do that, execute the following in the terminal:

sudo apt-get install net-tools

Now to make this setting persistent between the boots you can do several things. First, make changes to the /etc/pm/config.d/blacklist file. To do that, in the terminal execute the following to open the file:

sudo gedit /etc/pm/config.d/blacklist

Add the following line in the /etc/pm/config.d/blacklist file:

HOOK_BLACKLIST="wireless"

Second, make changes to the /etc/pm/power.d/wifi_pwr_off file. To do that, in the terminal execute the following to open the file:

sudo gedit /etc/pm/power.d/wifi_pwr_off

Now add the following lines in the /etc/pm/power.d/wifi_pwr_off file:

#!/bin/sh 
/sbin/iwconfig wlan0 power off


Do not forget to replace the word wlan0 with your WIFI device name and save the file. Now, execute the following command it make the file executable upon every boot:

sudo chmod +x /etc/pm/power.d/wifi_pwr_off

Third, make changes to the /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf file. To do that, in the terminal execute the following to open the file:

sudo gedit /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf

Now in the /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf file, replace wifi.powersave = 3 with wifi.powersave = 2 and save the file.

That is it!

Cheers!
Imam

December 3, 2017

Yet another HTML cache busting technique

If you are coding your web application or web site from the ground up then you may be already facing problems where changing individual files does not get reflected immediately. This is due to browsers caching some of the files to speed up loading performance and also to save bandwidths. The process of avoiding caching in the browsers is called cache busting. There are already a ton of solutions out there which can be applied to your HTML code to avoid caching where some are tedious to maintain and others are a breeze. Although not very well known technique here I am presenting how to use hashing technique to do HTML cache busting. This technique can be well applied to both client side or server side scripting languages as well as using any cryptographic hash functions. The method I have selected for my web development is client side PHP scripting language and SHA-1 hash function. Using this method the following HTML code shows how to import external CSS file with cache busting feature:
<link rel="stylesheet" <?php echo "href=\"style1.css?v=" . sha1_file('style1.css') . "\"" ?>>
In the above code, PHP script will inject HREF attribute into the link tag. The ?v=" . sha1_file('style1.css') code fragment will change each time the CSS file is modified as well as add a argument to the CSS file name which will force browsers to load the CSS file. As the SHA-1 hash function is unique each time for a particular CSS file data set the above code works well as intended.

The following code snippet shows that the same technique can be applied to import JavaScript files with cache busting feature:
<script <?php echo "src=\"load.js?v=" . sha1_file('load.js') . "\"" ?>></script>
Cheers!
Imam


July 4, 2017

Stop Ubuntu from freezing completely with Intel Bay Trail

Ubuntu and Linux kernel seem to suffer from a cpu state bug which completely freezes the system when doing graphics intensive tasks such as playing games or videos. Many processors suffer from this bug including the following Intel processors:
  • Celeron J1900
  • Celeron N2940
  • Celeron N2840
  • Celeron N2930
  • Pentium N3520
  • Pentium N3530
  • Pentium N3540
To see whether you have one of the above processor put the following command in the terminal:

cat /proc/cpuinfo | grep 'model name'


This bug can easily be fixed by installing proper Microcode files and changing c-state flag for Linux kernel.

First step is to make sure you have Ubuntu microcode package installed by putting the following command in the terminal:

sudo apt-get install intel-microcode


Then, remove the existing microcode files by running the following command in the terminal as they are not recent:

sudo rm /lib/firmware/intel-ucode/*


After then, install Intel Microcode files by downloading Microcode package from the following site:

https://downloadcenter.intel.com/download/26798/Linux-Processor-Microcode-Data-File


Download the microcode*.tgz file and extract it in the Home folder. Now copy the extracted microcode files to system folder by opening a terminal in intel-ucode folder and running the following command:

sudo cp * /lib/firmware/intel-ucode/


Now edit the grub file to change c-state kernel flag by opening grub file in /etc folder by putting the following command:

sudo gedit /etc/default/grub


In the grub file under the line containing GRUB_CMDLINE_LINUX_DEFAULT=, add the following intel_idle.max_cstate=2, so the line should look like the following line:

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_idle.max_cstate=2"


Now, save and close the grub file and put the following command in the terminal to update boot loader to reflect kernel flag:

sudo update-grub


Done! Now just reboot the system and check whether microcodes are loaded properly by running the following command in the terminal:

dmesg | grep microcode


You should be able to see something like following as output of above command:

[ 3.168100] microcode: CPU0 sig=0x30678, pf=0x8, revision=0x829
[ 3.168138] microcode: CPU1 sig=0x30678, pf=0x8, revision=0x829
[ 3.168445] microcode: Microcode Update Driver: v2.01 <tigran@aivazian.fsnet.co.uk>, Peter Oruba


Cheers!
Imam

May 30, 2017

Assigning Binary Value to a Variable in C and C++

If you are programming in C and C++ then you may already know that C and C++ do not have native support for binary literal. So you can not simply write the following statement to give a variable a binary value:
int signal = 1110;
However, C and C++'s bitwise operators such as Left Shift operator << and Or operator | can be easily utilised to achieve binary value assignment like shown below:
int signal = 1 << 3 | 1 << 2 | 1 << 1;
The above statement assigns binary value 1110 to the variable signal. The way it works is the very first expression 1 << 3 creates a binary value 1000, and then the expression 1 << 2 creates a binary value 100 and finally the expression 1 << 1 creates a binary value 10. When all these three binary values are combined using the Or operators we get the binary value 1110 like shown below:

Expression        Binary equivalent
1 << 3                1000
1 << 2                0100
1 << 1                0010
                          1110 (after or operations of three expressions)

One advantage about this method of binary assignment is that there is no need for external libraries and such. The example program demonstrating the above method can be downloaded from the following link:

binary_assignment.c

There is also a convenience functions library called imamB which I wrote recently which can be used for getting binary values of variables as a string and vice versa. To use the functions from imamB all you need to do is to include header and source files from imamB package to your project directory. imamB can be download from the following link:

imamB-1.0.zip

Cheers!
Imam

March 19, 2017

Windows Install and use Python without admin rights

Sometimes it is useful to install Python in a preferred directory other than to a default Windows partition directory. The main reasons for doing this are given below:

Have multiple Python versions and run them as per requirements (use Python versions 2.7 and 3 simultaneously on the same system)
Have Python Interpreter on a portable disk (Python on the go)
Tryout experimental and latest Python versions and Python packages/libraries (leave the default system Python Interpreter unaltered)
Installing Python without admin rights:

Step 1: Download Python installer(msi file) from official website https://www.python.org/


Step 2: Open up Windows Command Prompt where msi file is downloaded and execute the following command,

msiexec /a python-2.7.10.msi /qb TARGETDIR=G:\Python27

Here, TARGETDIR specifies the target folder where Python will be installed.

Once setup is finished you should be able to find python.exe (Python Interpreter) and IDLE (Python Integrated Development Environment) in the G:\python27 and G:\Python27\Lib\idlelib folders respectively.

Step 3: Install pip Python utility script for installing Python packages/libraries by downloading get-pip.py file and executing the following command from the G:\Python27 folder,

python.exe get-pip.py

Step 4: Install Python packages/libraries using pip by executing the following commands from G:\Python,

python.exe -m pip install numpy

Here, numpy is Python package/library name which will be download and installed to Python Interpreter directory by the pip utility. If a package/library is not available in the standard Python pip repository then you can download pip install-able (whl files) Python packages/libraries from pythonlibs and install them by executing following command from G:\Python27, assuming whl files are placed in the same folder,

python.exe -m pip install numpy‑1.11.3+mkl‑cp27‑cp27m‑win32.whl

Cheers!
Imam

February 22, 2017

Linux .desktop file run a executable file from the same directory

Desktop files in GNU/Linux define shortcuts for conveniently launching installed applications in the system from system menus and file managers. They can be found in many different places such as in /usr/share/applications directory for system wide applications and in ~/.local/share/applications for user applications. These files can be opened in any text editor program to edit application executable file names or for adding new options to application executables. A typical desktop file may look like below:
[Desktop Entry]
Name=Install
GenericName=Package Installer
Comment=Copy package files to your system
Exec=Install.sh
Terminal=false
Type=Application
Encoding=UTF-8
Each key and value pair defines different attributes of the application launcher. For example the Name key assigns a name for the application launcher which would appear in the system menus and file managers. The most important key is Exec which tells the name of the application executable file. The value of the Exec key can be either just the application executable file name or absolute address of the application executable file like shown below:

Exec=App.sh

Or

Exec=/opt/ApplicationX/App.sh

However, sometimes it is preferable to tell Exec key that the application executable file is located in the same directory as the desktop file. This can be easily achieved with the %k code which is available to the Exec key. The %k code in the Exec key value gives us the absolute location of the desktop file as either a URI (if for example gotten from the vfolder system) or a local filename or empty if no location is known. Now, to run a application executable in the same directory as desktop file, Exec key can have the following value:

Exec=xdg-open "%k"/App.sh


The above Exec key value also ensures portability across different GNU/Linux distributions and can be used for many different application scenarios such as shipping portable application packages.

That's all for today.

Cheers!
Imam

January 1, 2017

Blender Game Engine aligning objects to standing surface using material settings

When using Blender Game Engine there are several methods for aligning objects orientations to sitting surface. One such popular method is to use Ray sensor and Python codes to align objects. With newer Blender for Dynamics objects, it is actually possible to align objects just by using Physics settings in object’s Material tab to orient sitting objects without using any Python codes. To do that you have to change values in the Physics of Material tab of the surface object you want objects to be orient to, especially values of Force, Damp and Distance like shown below. And for objects which should be oriented you have to tick Rotate from Normal in the Physics tab. If all set your objects will follow the orientation of the surface. Check out the sample blend file to see how it works, press A and D keyboard keys to move the object.

Download blend file: object_alignment.blend


Physics settings in the material tab

October 10, 2016

Associating different Google AdSense account with your YouTube channel

If you have ever wondered if you can associate a Google AdSense account which is linked to a different email account than your YouTube channel account well then here is the good news for you, yes you can do that. I have done it several times and it has worked every time. The process is pretty simple and straightforward once you try it by yourself. The description below about how to make it work is valid and verified as of today. There is no guarantee that it will work for you as well and the information provided below comes with no implied warranty. The author(me) not responsible for any situation arising from use of this instruction so follow it at your own risk.

Steps 1:

Log in to your YouTube channel by using your email account and then go to Creator Studio. Now find the Monetization page under CHANNEL. Click on Review or change AdSense association and then click on Change button appeared inside the new Monetization page.

Step 2:

Now you should see Welcome to AdSense page. Now leave Welcome to AdSense page open and open up a new browser tab or window where you will sign out from your Google account / Youtube channel account (I have Google account linked to my Youtube channel so I just logged out from my Gmail account to have the same effect). Now switch back to Welcome to AdSense page and Sign in using your email account which is different from YouTube channel account. Now Just follow the on line instruction to complete the Google AdSense account association to your YouTube channel.

Step 3:

After association process is completed, sign out from email account which is different from YouTube channel account and sign in again using YouTube channel email account. Now on the Monetization page you should be able to see that your AdSense account is changed to the new one that you just associated.

August 8, 2016

Ubuntu synchronise Google calendar and contacts and view & edit google drive files with GNOME applications

If you are using Ubuntu 16.04 then you can easily integrate Google apps experiences into your Ubuntu Desktop by using GNOME desktop applications. Which means you can easily view and edit your Google account calendars and contacts books right from your Ubuntu desktop without needing to open-up a web browser and sign-in to google account every-time you have to amend something.

Now fire up a terminal and put the following command into to install GNOME control center, Calendar, and Contact applications and GNOME online accounts package:

sudo apt-get install gnome-control-center gnome-contacts gnome-calendar gnome-online-accounts


If everything is installed properly, you should be able to find corresponding applications icons into Dash applications tab. Now, in the Dash search for Settings icon and click to launch All Settings window like shown below:


Now goto Online Accounts and click on the plus sign which will open Add Account dialog. Select Google and sign into your google account. Finally, click Allow button to give GNOME applications access to your Google services. Now you should see which Google services will be synchronised with the GNOME applications like shown below:


From here you can easily toggle the services you do not like to be synchronised with the Desktop applications. Turn on Calender, Contacts and Files which will in turn let you access Google Calender, Contacts and Drive from GNOME Calender, Contacts and File applications.

Accessing Google Calendar:

Search for Calendar icon in the Dash and open it. Click on the Manage your Calendar icon and select Calendar Settings from the popup menu. Now in the Calendar Settings dialog window click add button and select from web if your Google account calendars are not showing in the Calendars list like shown below:






Every time you change calendars you have to click Synchronize from the GNOME Calender application.

Accessing Google Contacts:

Search for Contacts icon in the Dash and open it. From Change Address Book dialog window select your Google account, like shown below:


The application will automatically synchronise your contacts upon change.

Accessing Google Drive files:

When you open Nautilus file manager (GNOME Files), you should be able to see your Google account email with other storage drives like shown below:


With GNOME Files, you will be able to access Google Drive files just like any other local disk partitions. To reflect any changes to the Google Drive do not forget to Unmount from the GNOME Files application.

Cheers,
Imam

October 5, 2015

Using OpenCV in GTK+ applications

Although OpenCV comes with it's own windowing system for displaying any OpenCV images, for fully functional applications with user interface elements such as buttons, menus, and radio buttons, maybe you would find it useful to use widget libraries such as GTK+ or QT. Drawing OpenCV image surfaces in GTK+ applications is not much of a difficult task than adding a couple of extra lines in your existing GTK+ applications. And again there are plenty of ways to accomplish the same results, but here I will show how I have achieved it. The sample program here is written using GTK+ C++ binding GTKmm, but the technique and functions should be same across all the GTK+ bindings.

As usual we create a GTK+ top level window by creating a MainWindow object. MainWindow, which is itself a GtkWindow widget contains one GtkFrame and one GtkDrawingArea widgets. The class definition of MainWindow is shown below:
class MainWindow : public Gtk::Window
{
  protected:
    Gtk::Frame video_frame;
    VideoArea video_area;
  public:
    MainWindow ();
    virtual ~MainWindow();
};
In the above code, VideoArea is the GtkDrawingArea widget object defined as follows:
class VideoArea : public Gtk::DrawingArea
{
  protected:
    cv::VideoCapture cv_cap;
    bool cv_opened;
    virtual bool on_draw (const Cairo::RefPtr<Cairo::Context> &cr);
    bool on_timeout ();
  public:
    VideoArea ();
    virtual ~VideoArea();
};
We are going to use GtkDrawingArea widget for the purpose of displaying OpenCV image surface. To do that, we have to put OpenCV related functions in the GtkDrawingArea on_draw function. This on_draw function will be called every time draw signal is emitted from GtkDrawingArea widget. As can be seen from the VideoArea object definition, we also have a timer function on_timeout to call on_draw function in a regular manner by invalidating GtkDrawingArea widget. So when a VideoArea object is created in the MainWindow object OpenCV is initialized like shown in the code below:
VideoArea::VideoArea() : cv_opened(false)
{
  cv_cap.open(0);
  
  if (cv_cap.isOpened() == true) {
    cv_opened = true;
    Glib::signal_timeout().connect(sigc::mem_fun(*this, &VideoArea::on_timeout), 50);
  }
}
Here, we connect a glib timeout signal, which will call on_timeout function every 50 milliseconds interval. The functions for on_timeout and on_draw are shown below:
bool VideoArea::on_timeout()
{
  Glib::RefPtr<Gdk::Window> win = get_window();
  
  if (win) {
    Gdk::Rectangle r(0, 0, get_allocation().get_width(), get_allocation().get_height());
    win->invalidate_rect(r, false);
  }
  
  return true;
}

bool VideoArea::on_draw(const Cairo::RefPtr<Cairo::Context> &cr)
{
  if (!cv_opened) return false;
  
  cv::Mat cv_frame, cv_frame1;
  cv_cap.read(cv_frame);
  if (cv_frame.empty()) return false;
  
  cv::cvtColor (cv_frame, cv_frame1, CV_BGR2RGB);
  Gdk::Cairo::set_source_pixbuf (cr, Gdk::Pixbuf::create_from_data(cv_frame1.data, Gdk::COLORSPACE_RGB, false, 8, cv_frame1.cols, cv_frame1.rows, cv_frame1.step));
  cr->paint();
  
  return true;
}
In the on_draw function, we convert OpenCV surface to RGB channel by using cvtColor, since GTK widgets uses RGB format. Finally, we use Gdk::Pixbuf::create_from_data to fill Cairo surface with OpenCV surface pixel buffers.
Download the complete program source code and test it by yourself!

gtkcv.zip

To compile the files in gtkcv.zip, you need to have OpenCV and gtkmm development files installed on your operating system. On Ubuntu just follow the instructions below:

Installing OpenCV:

Downloading OpenCV and creating compile directory,

From http://opencv.org/ grab opencv-3.0.0 and extract the opencv-3.0 archive file. Then, create a folder named build inside the opencv-3.0.0 folder. Then, open a terminal into the build folder. Then, in the terminal put the following commands:

First, setup compile environment for OpenCV
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr -D WITH_OPENMP=ON -D WITH_CUDA=OFF .. 

Now, compile sources in 4 threads
make -j 4 

Now, install OpenCV
sudo make install

Installing gtkmm:

sudo apt-get install libgtkmm-3.0-dev

That's it!, now extract the gtkcv.zip file and open a terminal in the gtkcv folder and execute the following command:

g++ -o gtkcv main.cpp MainWindow.cpp VideoArea.cpp `pkg-config --cflags --libs gtkmm-3.0 opencv`

This will produce gtkcv executable file.

Cheers,
Imam

July 11, 2015

imamLL linked list library store struct elements

As imamLL (imamLL-1.3.tar.gz) is very versatile in storing any type of data into a list, you can store an struct as an element like shown in the following code example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "imamll.h"

struct Person {
    char name[24];
    double age;
    double weight;
    double height;
};

struct imamLL *People_list = NULL;          /* Pointer to hold list */
struct imamLL_element *person = NULL;       /* Pointer to hold individual element */
unsigned long c;

int main (int argc, char* argv[])
{
    printf ("Allocating memory for list\n");
   
    People_list = imamLL_list_create();

    if (People_list == NULL) {
        printf ("Can not create the list\n");
        exit (1);
    }
   
    if ((person = imamLL_element_add (People_list, sizeof(struct Person), AT_END)) == NULL) {
        printf ("Can not add element");
        printf ("Freed list, returned %d\n", imamLL_list_destroy (People_list));
        exit (1);
    }
    strcpy (((struct Person *)person->data)->name, "Md Imam Hossain");
    ((struct Person *)person->data)->age = 27.0;
    ((struct Person *)person->data)->height = 180.0;
    ((struct Person *)person->data)->weight = 67.0;

    printf ("Allocated: %lu Bytes\n", People_list->size);
   
    if ((person = imamLL_element_add (People_list, sizeof(struct Person), AT_END)) == NULL) {
        printf ("Can not add element");
        printf ("Freed list, returned %d\n", imamLL_list_destroy (People_list));
        exit (1);
    }
    strcpy (((struct Person *)person->data)->name, "Md Salim Hossain");
    ((struct Person *)person->data)->age = 22.0;
    ((struct Person *)person->data)->height = 182.0;
    ((struct Person *)person->data)->weight = 75.0;

    printf ("Allocated: %lu Bytes\n", People_list->size);
   
    while (1) {
        person = imamLL_element_get_next (People_list);
        if (person == NULL) break;
        printf ("*Person*\n");
        printf ("Name: %s\n", ((struct Person *)person->data)->name);
        printf ("Age: %lf\n", ((struct Person *)person->data)->age);
        printf ("Height: %lf\n", ((struct Person *)person->data)->height);
        printf ("Weight: %lf\n", ((struct Person *)person->data)->weight);
    }
   
    printf ("Freed: %d elements\n", imamLL_list_free (People_list));
    printf ("Freed list, returned %d\n", imamLL_list_destroy (People_list));
   
    return (EXIT_SUCCESS);
}

July 9, 2015

Fix Ubuntu shutdown and suspend problem on HP 250 G3

If you have a HP 250 G3 notebook and use Ubuntu based GNU/Linux then you may be experiencing problems such as the system will halt at shutdown and will hang when you try to suspend. All these problems are related to each other. You can easily fix these problems by just changing some settings in your BIOS.

First thing you can try if you have Windows operating system, then you can try installing the latest vendor BIOS program and see if the problems persist. After installing latest BIOS if the problems still occur then just go into your BIOS setup screen and look for USB 3 configuration in pre-OS option and then change the USB 3 configuration in pre-OS state to be in enabled. BIOS is the operating system neutral system settings program you can get into when the computer starts. To enter BIOS just try to press Esc key on the keyboard and press one of the F1-F12 key to enter BIOS settings. And if you have done everything correctly, hopefully, you will no longer experience any of the above problems anymore :)

July 5, 2015

imamLL a simple C linked list library

C programming language does not have a linked list implementation like other programming languages such as java. Since C program gives more control to it's users, it is up to users how they implement their own linked list for their programs. imamLL is a linked list implementation library for C designed to be efficient and flexible. Some of the features of imamLL library are
  • Dynamically allocate data at any given point in the program runtime
  • Add elements of arbitrary sizes into the lists
  • Navigate through the elements in both forward and backward
  • Add, remove, modify and get elements from the lists
In this tutorial, we are going to build a simple program using imamLL library.

First, we download imamLL library from the following link:

imamLL-1.3.tar.gz

After extracting the file we run ./build.sh in the terminal to install the library into the system.

Now, we create a blank text file and name it num_list.c

The content of the file is shown below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <imamll.h>        /*header for imamLL */

struct imamLL *num_list = NULL;
struct imamLL_element *element = NULL;

int main (int argc, char** argv)
{
    num_list = imamLL_list_create();
   
    if ( num_list == NULL) {
        printf ("Can not create the list\n");
        exit (EXIT_FAILURE);
    }
   
    element = imamLL_element_add (num_list, sizeof (int), 0);

    if (element == NULL) printf ("Error allocating memory for an integer element\n");
    else *((int *)element->data) = 10;
   
    element = imamLL_element_add (num_list, sizeof (int), 0);

    if (element == NULL) printf ("Error allocating memory for an integer element\n");
    else *((int *)element->data) = 20;

    element = imamLL_element_add (num_list, sizeof (int), 0);

    if (element == NULL) printf ("Error allocating memory for an integer element\n");
    else *((int *)element->data) = 30;
   
    imamLL_list_rewind (num_list);

    while ((element = imamLL_element_get_next(num_list)) != NULL) {
        printf ("%d\n", *((int *)element->data));
    }
   
    imamLL_list_destroy (num_list);

    return 0;
}
Now to compile the num_list.c, in the terminal:

gcc -Wall -o num_list num_list.c -limamll

The program above program can be easily understood by reading the Intro.html file found in the imamLL directory. There are also few more example programs located in the examples directory of imamLL.

Cheers,
Imam

June 29, 2015

Linux system call fork() to create new process with example code

If you ever wanted to do multiple tasks at the same time in your C/C++ program then Linux fork () system call function is for you. When your C/C++ compiled binary program begins execution, it creates a main process in which all the program instructions are executed. In Linux every program you run will create one or more processes. Inside each process the program instructions will be executed sequentially. Which means inside one process without completing one task the program will not be able to do another task and that is where fork () function comes in handy. The fork () function will let you create a new process which is a exact copy of the main process but completely independent and run alongside the main process. For example, if you are copying a file in the main process then the new process created by fork () can be used to update the user interface for the copy operation.
  • Things to remember about processes are:
  • Processes are one of the building blocks for multitasking in Linux
  • Each process has it's own unique id provided by the Linux kernel by which the process can be tracked for different purposes
  • Processes can run independently to each other, therefore closing or terminating one process does not effect the other processes
  • Any process will have their own memory space, therefore variables from stack and heap from one process are not accessible by other processes
Now, lets build a simple C program to see how fork () can be utilized

In the program we call the main process as parent process , and the new process created from inside main process as child process. This naming convention for processes is very typical, since one process can create another new process by using fork().

We build a simple program where, parent process counts to 10 while at the same time child process counts to 20. After finishing counting the parent process waits for the child process to end.

Code:

#include <stdio.h>
#include <stdlib.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main (int argc, char *argv[])
{
    pid_t child_id;
   
    child_id = fork ();
   
    if (child_id == -1) {
        printf ("Creating new process by fork() failed!\n");
        return 1;
    }
    else if (child_id == 0) {
        /* code block for child process */
        int count;
        for (count = 1; count < 10; count++) {
            printf ("Child counting: %d\n", count);
            sleep (1);
        }
        _exit (0);
    }
    else {
        /* code block for parent process */
        int child_exit_status;
        int count;
        printf ("Child process id: %d\n", child_id);
        for (count = 1; count < 5; count++) {
            printf ("Parent counting: %d\n", count);
            sleep (1);
        }
        printf ("Waiting for child to end\n");
        wait (&child_exit_status);
        printf ("Child exited with %d\n", child_exit_status);
    }

    return EXIT_SUCCESS;
}
The above code should print the following output in the terminal:

Child process id: 7225
Child counting: 1
Parent counting: 1
Parent counting: 2
Child counting: 2
Child counting: 3
Parent counting: 3
Child counting: 4
Parent counting: 4
Child counting: 5
Waiting for child to end
Child counting: 6
Child counting: 7
Child counting: 8
Child counting: 9
Child exited with 0


Now, let's go through the most important elements in the code:

We need to include unistd.h for the fork function. The other two header files types.h and wait.h are required by the wait () function. First, we create a variable of type pid_t for storing child process id which will be returned by the fork () function. The fork function returns -1 if the function can not create a new process and if successful fork() returns 0 to the child process and the process id of created process (child) to the parent process (main process). Therefore, inside the child process the value for child_id would be 0 and it would be child process id inside parent (main) process. Inside the child process block the _exit function is used to terminate the child process. The sleep function inside the for loop blocks will suspend the respective execution for specified amount of seconds given in the parameters, in our case it is one second. And finally the wait function will suspend the parent (main) process until state of one of the child processes changes, in our case when the child process exits. And finally, the exit status of the child process is retrieved by using the wait function which is stored in the child_exit_status variable.

Hopefully, this tutorial helped you learn basic about processes.

Download the fork() example source file and test it by yourself:

fork.c

Cheers,
Imam

June 20, 2015

Install Ralink RT3290 Wi-Fi driver on Ubuntu based distributions

Note: Ubuntu 17.10 or above has a builtin driver (rt2800pci) which performs good and usable.

Ralink. RT3290 is a PCIe device which combines 802.11bgn Wi-Fi and Bluetooth 3.0 devices in a single chip. Currently, Linux kernel has experimental support for RT3290 wireless through the module named rt2800pci. The state of this module is such that in many circumstances you will have very weak wireless signals.

Ubuntu 15.04 comes with Linux kernel version 3.19 and the problem of weak RT3290 wireless signals is still prevalent since by default Ubuntu 15.04 will be using Linux kernel rt2800pci module. However, there is a official driver available for Linux from MediaTek for Ralink RT3290 STA wireless device. This driver will fix weak signal and many other problems on Ubuntu 15.04 based distributions. To install this driver simply download the following file and after extracting the file in the Home directory of your Ubuntu, follow the instructions in the ReadMe file inside the extracted RT3290 folder (You may need to shutdown computer and boot again to get it working).

RT3290 Linux Driver (Ubuntu 15.04)

After installing the driver hopefully you will have better wireless experience in your Ubuntu system :)

For fedora users, please try the following:

RT3290 Linux Driver

*Updated package for latest Ubuntu based distributions (tested against Ubuntu 17.04). Also suitable for Ubuntu 15.04 based distributions:

RT3290 Linux Driver (Ubuntu 16.04 or latest)

*If you update Linux kernel then you will have to run the following commands from the RT3290_u16 directory to compile and install the driver for new kernel:

./compile.sh
sudo ./install.sh


*If you do not see Wi-Fi network, you may need to activate it manually by executing the following command from RT3290_u16 folder or reboot computer:

sudo ./activate-net-rt

*If you are able to see WIFI interface but can not connect to any WIFI network then you should try wicd Network manager instead of default network manager for connecting to WIFI networks. To do that, on Ubuntu first install wicd network manger by entering following command in the terminal:

sudo apt-get install wicd

And then remove default gnome network manager of Ubuntu by entering following command:

sudo apt-get remove network-manager-gnome

Finally, restart computer and use Wicd Network Manger to connect to WIFI networks.

Cheers!
Imam