Mutex vs Semaphore

A simple yet clear analogy on the difference between mutex and semaphore

Mutex:

Is a key to a toilet. One person can have the key – occupy the toilet – at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: “Mutexes are typically used to serialise access to a section of  re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section.”

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count – the count of keys – is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: “A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore).”

Now you got it.

Generate key pair with OpenSSL

I was playing around with OpenSSL again and here is some (hopefully) simple take to get familiarize with it’s capability.

Generate key pair and getting it’s modulus and exponent

Here are the openssl commands that operate to generate key pair and get the information about the generated key

  • Generate key pair
    openssl genrsa -aes256 -out private.pem 2048
  • Get public key
    openssl rsa -in private.pem -pubout -out public.pem
  • Get private key (warning!)
    openssl rsa -in private.pem -out private_plain.pem
    the only difference with the above option is the -pubout option dropped
  • Get the modulus from private.pem
    openssl rsa -in private.pem -modulus -noout
  • Get the modulus from public.pem
    openssl rsa -pubin -in public.pem -modulus -noout
  • Get modulus and exponent from public.pem
    openssl rsa -pubin -in public.pem -text -noout

All commands above that operating on private.pem will require you to enter a pass phrase.
Modulus from both private.pem and public.pem are the same (as it should be).

OpenSSL default format is in PEM format, how about operating in DER format? Suppose we want to convert PEM format to DER, and operating with DER format

  • Converting from PEM to DER
    openssl rsa -pubin -inform PEM -in public.pem -outform DER -out public.der
  • Get modulus from pu/blic.der (DER format)
    openssl rsa -pubin -inform DER -in pub -modulus -noout

 

Print out x509 certificate information

Now that we know how to operate with different format via -inform, and we know how to print out info via -text. We generate a self sign certificate, mycert, https://www.madboa.com/geek/openssl/#how-dnerate-a-self-signed-certificate. Input the necenformation to create a cert.

  • Print certificate information
    openssl x509 -text -inform DER -in mycert.der -noout

 

How to get a getch( )

Bummer, your small c apps compiler doesn’t have a getch().

We can overcome this by installing ncurses or create our own getch() function.

  • ncurses

If you’re using cygwin, we should install ncurses first (it’s not included in cygwin’s default setup). First of all, you have to get libncurses-devel package.

Here is example how to use ncurses


#include <stdio.h>
#include <ncurses.h>
int main( void )
{
printf( "Hello Ncurses!\r\n" );
getch( );
return ( 0 );
}

view raw

test_ncurses.c

hosted with ❤ by GitHub

Manual compile: gcc test_ncurses.c -lncurses

CMake example to compile


cmake_minimum_required(VERSION 2.8.9)
project (test_ncurses)
find_package(curses REQUIRED)
include_directories(${CURSES_INCLUDE_DIR})
file(GLOB SOURCES "*.c")
add_executable(test_ncurses ${SOURCES})
target_link_libraries(test_ncurses ${CURSES_LIBRARIES})

  • Here is the solution for creating getch() function.


#include <termios.h>
#include <stdio.h>
static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
new = old; /* make new settings same as old settings */
new.c_lflag &= ~ICANON; /* disable buffered i/o */
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character – echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
/* Let's test it out */
int main(void) {
char c;
printf("(getche example) please type a letter: ");
c = getche();
printf("\nYou typed: %c\n", c);
printf("(getch example) please type a letter…");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}

Have fun.

Vim MatchIt and FuzzyFinder

Here is my addition to my .vimrc config file this week.


" Load matchit.vim, but only if the user hasn't installed a newer version.
if !exists('g:loaded_matchit') && findfile('plugin/matchit.vim', &rtp) ==# ''
runtime! macros/matchit.vim
endif
let g:fuf_file_exclude = '\v\~$'
\ . '|\.(o|png|PNG|JPG|class|CLASS|jpg|exe|dll|bak|swp|pyc|pyo)$'
\ . '|(^|[/\\])\.(hg|git|bzr)($|[/\\])'
\ . '|(^|[/\\])venv[/\\]'

view raw

.vimrc

hosted with ❤ by GitHub

First part is to load matchit.vim that already part of Vim distribution, it aiding a great help for me to browse through html file, it extend the % vim command.

The second part is a bit tricky for FuzzyFinder plugin user, I want to exclude directory, in this case is “venv” directory, that apparently the regex matching work well with fuf_file_exclude instead of fuf_dir_exclude. You can add you excluded list by extending and following the line #9 from snippet above.

Git cheat sheet

Git: distributed repository is the new centralize.

Common used git command. I keep it brief with no/minimum explanation of each command by hoping that those commands are self explanatory. I also organize by git trifecta of Add/Modify – Branch – Remote workflow.

Add, check and publish. The basic

  1. Starting
    • git init
    • git clone <repository-url>
  2. Adding/making changes
    • git add .
    • git add <path/file.name>
    • git commit -am “”
  3. Checking status
    • git status
    • git log —-all —-graph —-oneline
    • git log branch1..branch2
  4. Getting updates
    • git fetch Fetches latest changes from origin
    • git pull Fetches latest changes from origin and merge
  5. Publishing
    • git push Push changes to origin from current
    • git push <origin> <branch> Push changes to origin from branch

 

Modify, fixing mistakes

  1. Revert commits
    • git revert HEAD
    • git revert <commit-ref>
  2. Revert/undo all changes
    • git checkout - <file>
  3. Fix last commits
    • git commit –amend [-m “updated message”]
  4. Reset modifications
    • git reset HEAD <file>
  5. Diff-erence
    • git diff
    • git diff $id1 $id2 Diff between 2 commits
  6. Resolving changes
    • git checkout –ours <path/file>
    • git checkout –theirs <path/file>
  7. Combine commits
    • git rebase -i HEAD~4

 

Branching

  1. Creating branch
    • git branch <branch name>
  2. Listing branch
    • git branch
    • git branch -a
    • git branch -v
  3. Switching branch
    • git checkout <branch-name>
    • git checkout -b <branch-name>
  4. Merging branch
    • git merge <branch-name>
    • git merge --squash <branch-name>
  5. Deleting branch
    • git branch -d <branch-name>

 

Remote

  1. Adding remote
    • git remote <remote-name> <remote-url>
  2. Listing remote
    • git remote -v
  3. Fetching/Pushing to/from remote
    • git fetch <remote-name>
    • git push <remote-name> <branch-name>
  4. Getting update without removing local
    • git stash
    • git pull
    • git stash pop

 

Also, use .gitignore file for ignore files or directories. For further reference for more detailed git usage, my go to is gitref.org.

My .vimrc

My .vimrc, vim config file that I use everyday.

I want to keep it simple by not having too much configuration in vimrc itself. There is a plugin to manage vimrc to make it cleaner and readable, however it will introduce extra configuration.

My idea with this vimrc is to share easily between machine, main machine, or remote compiler machine that we can ssh it. Only one setup is needed to modify by hand, the vundle package manager, that’s it.


set encoding=utf-8
" set guifont=Monaco:h9
" set guifont=CamingoCode:h10
set guifont=DejaVu\ Sans\ Mono\ for\ Powerline:h10:cANSI
set lines=50 columns=110
set go-=T
if has('gui_running')
set background=dark
else
set background=dark
set t_Co=256 " make sure our terminal use 256 color
let g:solarized_termcolors = 256
endif
colorscheme zellner
syntax enable
set hlsearch
set ignorecase
set smartcase
set laststatus=2
set tabstop=3
set shiftwidth=3
set expandtab
set noswapfile
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" path setup
let s:cygwin = 'C:\cygwin\bin'
" Add PortablePython's path to $PATH if running on Windows and PortablePython exists
if (has('win32') || has('win64')) && isdirectory(s:cygwin)
let $PATH .= ';' . s:cygwin
endif
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let &cscopeprg = expand('c:\cygwin\bin\cscope.exe')
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Key map
imap ;; <ESC>
nmap ;; <ESC>
nnoremap fl :FufFile **/<cr>
nnoremap ff :FufFile<cr>
nnoremap fj :FufBuffer<cr>
nnoremap <silent> <F11> :YRShow<cr>
nnoremap <silent> <F4> :TagbarToggle<cr>
" nnoremap <silent> <F5> :TagbarCurrentTag<cr>
" inoremap jj <ESC>
" nnoremap <silent> <F4> :TlistToggle<cr>
" nnoremap <silent> <F5> :TlistSync<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Python-mode
" Activate rope
" Keys:
" K Show python docs
" <Ctrl-Space> Rope autocomplete
" <Ctrl-c>g Rope goto definition
" <Ctrl-c>d Rope show documentation
" <Ctrl-c>f Rope find occurrences
" <Leader>b Set, unset breakpoint (g:pymode_breakpoint enabled)
" [[ Jump on previous class or function (normal, visual, operator modes)
" ]] Jump on next class or function (normal, visual, operator modes)
" [M Jump on previous class or method (normal, visual, operator modes)
" ]M Jump on next class or method (normal, visual, operator modes)
let g:pymode_rope = 1
" Documentation
let g:pymode_doc = 1
let g:pymode_doc_key = 'K'
"Linting
let g:pymode_lint = 1
let g:pymode_lint_checker = "pyflakes,pep8"
" Auto check on save
let g:pymode_lint_write = 1
" Support virtualenv
let g:pymode_virtualenv = 1
" Enable breakpoints plugin
let g:pymode_breakpoint = 1
let g:pymode_breakpoint_key = '<leader>b'
" syntax highlighting
let g:pymode_syntax = 1
let g:pymode_syntax_all = 1
let g:pymode_syntax_indent_errors = g:pymode_syntax_all
let g:pymode_syntax_space_errors = g:pymode_syntax_all
" Don't autofold code
let g:pymode_folding = 0
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Vundle setting
set nocompatible " be iMproved
filetype off " required!
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()
" let Vundle manage Vundle
" required!
Bundle 'gmarik/vundle'
" My Bundles here:
"
Bundle 'bling/vim-airline'
let g:airline#extensions#tabline#enabled = 1
if has('gui_running')
let g:airline_powerline_fonts = 1
else
let g:airline_powerline_fonts = 0
endif
Bundle 'flazz/vim-colorschemes'
Bundle 'freeo/vim-kalisi'
Bundle 'ninovsnino/mark.vim'
let g:mwDefaultHighlightingPalette = 'extended'
Bundle 'vim-scripts/L9'
Bundle 'vim-scripts/FuzzyFinder'
let g:fuf_enumeratingLimit = 100
Bundle 'vim-scripts/TagHighlight'
Bundle 'tomtom/tcomment_vim'
Bundle 'klen/python-mode'
Bundle 'vim-scripts/YankRing.vim'
Bundle 'majutsushi/tagbar'
Bundle 'rking/ag.vim'
Bundle 'kenng/vim-bettersearch'
Bundle 'rosenfeld/conque-term'
Bundle 'hari-rangarajan/CCTree'
Bundle 'wting/rust.vim'
Bundle 'exvim/ex-utility'
Bundle 'exvim/ex-gsearch'
silent call exgsearch#register_hotkey( 100, 0, '<leader>gs', ":EXGSearchToggle<CR>", 'Toggle global search window.' )
silent call exgsearch#register_hotkey( 101, 0, '<leader>gg', ":EXGSearchCWord<CR>", 'Search current word.' )
silent call exgsearch#register_hotkey( 102, 0, '<leader><S-f>', ":GS ", 'Shortcut for :GS' )
Bundle 'MattesGroeger/vim-bookmarks'
let g:bookmark_manage_per_buffer = 1
Bundle 'MarcWeber/vim-addon-local-vimrc'
Bundle 'yongzhy/vim-cflags'
" Update buffer with preprocessor evaluated
nnoremap <leader>bu :call cflags#SynUpdate()<cr>
" Bundle 'vim-scripts/Mark–Karkat'
" Bundle 'vim-scripts/EasyGrep'
" Bundle 'exvim/ex-colorschemes'
" Bundle 'scrooloose/nerdtree'
" Bundle 'vim-scripts/taglist.vim'
" Bundle 'ivanov/vim-ipython'
" Bundle 'vim-scripts/ifdef-highlighting'
" Bundle 'vim-scripts/highlight.vim'
" Bundle 'xolox/vim-misc'
" Bundle 'xolox/vim-easytags'
" Bundle 'Lokaltog/vim-powerline'
" Bundle 'kien/ctrlp.vim'
" Bundle 'mileszs/ack.vim'
" Bundle 'benmills/vimux'
" Bundle 'Shougo/vimshell.vim'
" Bundle 'Shougo/vimproc.vim'
" Bundle 'Shougo/unite.vim'
" vim-scripts repos
" Bundle 'L9'
" Bundle 'FuzzyFinder'
filetype plugin indent on " required!
"
" Brief help
" :BundleList – list configured bundles
" :BundleInstall(!) – install(update) bundles
" :BundleSearch(!) foo – search(or refresh cache first) for foo
" :BundleClean(!) – confirm(or auto-approve) removal of unused bundles
"
" see :h vundle for more details or wiki for FAQ
" NOTE: comments after Bundle command are not allowed..

view raw

.vimrc

hosted with ❤ by GitHub

Acquiring Knowledge

Once we’re graduate from school we are expected to learn some and rightfully knowledgeable on a certain subject we’re pursuing.

Learning broad subject in schools or books doesn’t mean we really understand it. Once my teacher said that the best way to understand is to teach someone the subject that we want to master. Teaching the same subject make her easily solve many problem variants, that makes sense.
Repetition is key.

We’re living in a continuous learning experience, once we thought that we’re mastering something there’ll be something new that comes up and have to deal with. I’d take a step back and recall that knowledge is understood.
I make 2 mental step in the back of my mind to understand a subject:

  1. I need to explain to myself what is it in the nutshell and then go into its details.
  2. I should be able to explain and make them understand the subject matter to a 5 graders or my granny.

http://www.gettyimages.com/detail/photo/grandfather-and-grandson-writing-at-desk-royalty-free-image/530682433

If I can’t make the second step, I might not grasp the nutshell or I simply don’t understand it properly. Back to square one. It might take some time but it’s worth the time invested, once we understand it – it won’t simply goes away.

The best endeavor

There are memes that showing contrast on approach to result.

One picture showing old and wrinkle vegan activist, and other picture showing old yet looks lively, vibrant actress coming with tag line she eats meats.

There’s also story telling that one lady did her diet, strictly controlling her food intake, take vitamins and supplements under professional supervision, did all health checks regularly. On top of that she also did her exercises. She died in her 50s. On the other hand, this guy eats everything, no control on his food intake, be it junk food or salt and sugar, walk and commute are counted as exercise. He’s in his 80s now, well and energetic with no signs of him slowing down.

Another familiar story that we have experienced it before is one students burning midnight oils for exams ended up with C grades, other lucky fella glance through textbook minutes before ended up with A.

Those stories present one facts and deliver opinions that minimal effort triumphant in the end of the day. Case by case basis, of course, but let sink in for a while, does it make a better version of you? Most probably not, it will make us depends on luck a lot.

http://www.gettyimages.com/detail/photo/young-hispanic-girl-doing-homework-on-the-floor-royalty-free-image/71554675

Skimming get you A in Data Structure 1, might not be the case in Data Structure 2. Keep eating unhealthy might still you long life expectancy, but don’t you think it’s better if we have healthy lifestyle? Imagine if that 80 years old guy if he have healthy lifestyle, he might broke oldest man alive. That lady who passed away in her 50 might not reach 30 years if she didn’t have healthy lifestyle.

We control our own life. Be a better person, you know what best for you. Strive hard to that direction. This is one value that I want to instill in my family.

New year, new look. Hello 2016

I’m trying to back again. And this time, I promise to myself to come back here often and write often. I know, I said the same line couple years back.

It’s tough to maintain consistency, tough if we’re not make it as a habit. So here I am want to get better on that by setting up an attainable goals, and more importantly, I’ll make writing as a habit.

Sigh. That’s tough, I don’t know what I’m sign up to.

Oh well, life is tough, just do it and move on. To start off, let’s do makeover, by giving fresher look it will keep the writing spirit high.

Here are couple themes that I’d like to give it a go:

I pick none of them, I do really consider it though. Theme and look in the end it’s a matter of personal taste, I picked Independent Publisher, it has good typography, simple layout, and it looks good in both desktop and phone.

Now here come the hard part, writing.

Hello 2016. 🙂

Dealing with failure

Our next failure could be an unwritten script in our life, yet failures sometime open up other opportunities.

I’d like to refer into this post the next time I burden myself with a success Ivory tower, I failed to get into an IIT and 10 years later I could not be happier. This story should give us a moment of pause in pursuing a single objective, then to be prepared in facing failure.

Most of the time we’re not equipped when dealing with failure.