Wednesday, April 20, 2016

Tmux Comfortable Shortcuts

Working with tmux is all about short cuts.  To find out existing shortcuts in tmux, you can use
$ tmux list-keys
Usually tmux key configs are stored in ~/.tmux.conf file. By modifying this file, you can override these commands. Tmux has a prefix key which is ctrl + shift + b which is the default. But we can change it to an ergonomically comfortable position. Lets see how we can modify tmux.conf file. Following are some notations used in this file.

C    means ctrl
M   means alt
C-"    means ctrl + shift + "
M-Down means alt + down arrow key
-n means you can run this command without tmux prefix

Note that mouse mode is also enable in following file. You can scroll up through the pane.
If you want to select and copy text, then while holding select the text, relese shift copy the text.

# Tmux should be pretty, we need 256 color for that
set -g default-terminal "screen-256color"


# remap prefix from 'C-b' to 'C-a'
unbind C-b
set-option -g prefix C-a
bind-key C-a send-prefix

# change prefix
bind-key -n C-q detach

# split panes using right and down
bind -n M-Right split-window -h
bind -n M-Down split-window -v
unbind '"'
unbind %

# switching between sessions
bind -n C-] switch-client -p
bind -n C-[ switch-client -n
unbind )
unbind (

# switch panes using Alt-arrow without prefix
bind -n C-Left select-pane -L
bind -n C-Right select-pane -R
bind -n C-Up select-pane -U
bind -n C-Down select-pane -D

# Enable mouse control (clickable windows, panes, resizable panes)
set -g mouse-select-window on
set -g mouse-select-pane on
set -g mouse-resize-pane on


# command delay? We don't want that, make it short
set -sg escape-time 1

# Set the numbering of windows to go from 1 instead
# of 0 - silly programmers :|
set-option -g base-index 1
setw -g pane-base-index 1

Monday, April 18, 2016

Linux Command Line - Mean Stack

This article is going to be about setting up a development environment on a Linux machine. Have you ever watched a coding tutorial and saw a really slick editing interface with terminal split screens and a gorgeous color scheme? Well, I am not only going to show you how to configure and setup something impressive but I will also give you the insight into how to configure it as you see fit.

All the codes mentioned here are linux terminal commands and scripts.

Mean Stack

Let’s talk about the tools stack are going to be using.

Zsh

When you open up a terminal on your machine, you are most likely going to find that you are running a Bash shell.

Bash is a nice default but we’re not here for defaults, we’re here for the best we can get and that means Zsh and all the bells and whistles that come along with it. In a nutshell, Zsh gives us a much more user friendly experience on the command line, it gives us things like better auto-completion, Vim key bindings and smart guesses when you write a command wrong. Zsh has a huge user community behind it and those smart people have added many, many customisations. We can discover those as we go.


Tmux

Tmux is a terminal multiplexor. Sounds scary right? Well, it isn’t at all. Tmux is a tool that allows you to split your terminal screen into any layout you want as well as run multiple terminal instances that are easily accessible. Tmux has become the go-to tool for some of the biggest neckbeards out there.

Vim

Vim is a text editor and if you haven’t heard of it before, well, you’re either going to love it or hate it. I do hope you will love it of course as it is an extremely versatile, customisable and powerful text editor. Now, for the sake of diversity, there is another extremely powerful text editor out there called Emacs which I would suggest you look into in your spare time and decide whether you would like to learn it. Yes, I said learn, Vim and Emacs have an extremely steep learning curve in terms of how they allow you to manipulate text. I chose Vim and I will be providing links, tips and customisations to get you where you need to be ASAP.

Here is a preview of the configuration you will end up with after configuring this mean stack



















Prerequisites and Assumptions

A final comment before diving in head first is that I am making some small assumptions about your setup. They are the following:

You’re computers operating system is Debian based.

‘Debian based’ in simple terms simply means that you are using Ubuntu or a variant like Kubuntu or Lubuntu. The reason for this is that we need to be using the same package manager. Also, things are a lot more user friendly on the Ubuntu side of life.

You need some things installed to get up and running. Here are the prerequisites:

Git

You need to install git before you continue with this as git will be the primary source of packages, plugins etc. that we will be using as well as you will be using when you need to customize this. Follow the command to install git.

sudo apt-get install git


Zsh

Let’s get started. We’re going to install Zsh and kit you out with a decent terminal. Run

$ sudo apt-get install zsh


You now need to switch your default shell from whatever you have now to Zsh, Run:

$ chsh -s /bin/zsh

Close that terminal and open another and you should be looking at a lovely new Zsh prompt. We’re not done yet, remember all those customization I talked about? In order to give us a head start let’s get the community managed Zsh framework called oh-my-zsh. Let’s get it installed.


$ git clone git://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh


Now that we have oh-my-zsh installed, we can customise as much as we want, let’s start by setting up our .zshrc. The .zshrc is a configuration file that is read by Zsh every time you open up a new terminal session. In other words, we can put all our customization in this file and it will be run in the background for us. Let’s create that file:

# take us back to our home directory
$ cd

# create an empty file called '.zshrc'
$ touch .zshrc

Now, I am going to assume you don’t have Vim installed yet, so we can use a simple text editor that comes as default: nano.

$ nano .zshrc

You can type in text simply like with any text editor you are used to. Let’s start off by choosing a theme. Head over to oh-my-zsh themes Choose one you like (take a look at “3den”, that is the one I use), and then add the following line to your .zshrc

ZSH_THEME="3den"

Save the file by hitting Ctrl-x, and then y to confirm that you want to write to the file. Close that terminal and open another up. Brilliant, you should have a new and shiny prompt. I’ll take this moment to point out why I use the 3den theme. 3den gives me Git and Ruby information on the command line. It also gives me my current working directory and the time. The colors aren’t that bad either. Feel free to experiment with many different themes!

When you want to customise you Zsh installation, you’ll mostly be working in your .zshrc file. I am going to list some more things you might want to include in your .zshrc, feel free to test them, use them or not. Remember, this is your setup!

# want your terminal to support 256 color schemes? I do ...
export TERM="xterm-256color"

# if you do a 'rm *', Zsh will give you a sanity check!
setopt RM_STAR_WAIT

# allows you to type Bash style comments on your command line
# good 'ol Bash
setopt interactivecomments

# Zsh has a spelling corrector
setopt CORRECT

That is enough for now, we’ll come back to add more later on. Let’s move onto Tmux.

Tmux

Grab Tmux with the following:
$ sudo apt-get install tmux

Now, Tmux can be a tricky one to figure out at the beginning, but bear with me, we will get there. I have customised my installation with the help of the very great book Tmux – Productive mouse-free development which I totally recommend. Let’s not bore you with the defaults, (although you can find them here) go ahead and create the Tmux configuration file, called .tmux.conf:

$ cd
$ nano .tmux.conf

Add the following lines:

# set Zsh as your default Tmux shell
set-option -g default-shell /bin/zsh

# UTF is great, let us use that
set -g utf8
set-window-option -g utf8 on

# Tmux should be pretty, we need 256 color for that
set -g default-terminal "screen-256color"


# Tmux uses a 'control key', let's set it to 'Ctrl-a'
# Reason: 'Ctrl-a' is easier to reach than 'Ctrl-b'
set -g prefix C-a
unbind C-b

# command delay? We don't want that, make it short
set -sg escape-time 1

# Set the numbering of windows to go from 1 instead
# of 0 - silly programmers :|
set-option -g base-index 1
setw -g pane-base-index 1


# Allow us to reload our Tmux configuration while
# using Tmux
bind r source-file ~/.tmux.conf \; display "Reloaded!"

# Getting interesting now, we use the vertical and horizontal
# symbols to split the screen
bind | split-window -h
bind - split-window -v

OK, Ctrl-x to save the file and then run:

# the '-s' flag specifies a name (we use to attach to it later on)
$ tmux new -s myfirsttmux

Great, you see your lovely Zsh terminal, now let’s play around with those bindings you set in your .tmux.conf. Try and run them all in sequence and you will have gotten the basics of Tmux in a few minutes!

# split the screen in half
Ctrl-a |

# jump over to the right hand split
Ctrl-a 

# split that right hand side pane in half
Ctrl-a -

# jump down to that lower pane
Ctrl-a 

# Close the window
Ctrl-d

# Open up another window
Ctrl-a c

# Go to the next window
Ctrl-a n

# disconnect from Tmux
Ctrl-a d

# Check what Tmux sessions are running
$ tmux ls

# Attach back into the session
$ tmux attach -t myfirsttmux

# Escape and kill session
Ctrl-a d
$ tmux kill-session -t myfirsttmux


OK, lots of information there but you get the gist of it, You can split vertically and horizontally to your hearts content! You also have the ability to reload your Tmux configuration file whilst still in a Tmux session, so you can add a line, then hit

Ctrl-a r

You have your new configuration options loaded. Now, I mentioned I would be leaving a link to a fully customised configuration file, and I am going to keep my promise, check out my personal tmux config file . Remember, don’t just drop it all in at once, incrementally add options and test them by reloading your config!

Close Tmux, get back to a vanilla terminal and let’s move on. You’ve got the basics here.

Next, it will be Vim, the Big one. I will publish about it in my next article.



Sunday, September 13, 2015

Power of Web RTC - Simple example NodeJS + WebRTC

What is Web RTC ?


WebRTC is a free, open project that provides browsers and mobile applications with Real-Time
Communications (RTC) capabilities via simple APIs. The WebRTC components have been optimized to best serve this purpose.

As of 2014 December, WebRTC is still a new and untamed beast. As such, I found that there is a lack of simple and easy to understand examples for someone getting started with WebRTC. My goal was to create my own, as simple as possible, proof of concept WebRTC video conference page that achieved the following goals.

  1. Peer to peer data transfer with fair bandwidth to such as video chat.
  2. No external libraries needed. Only browser support for Web RTC.
  3. Works on many popular browsers now. (http://iswebrtcreadyyet.com/)

Before getting into the actual WebRTC APIs, it’s best to understand a simple signaling server. For those unaware, WebRTC requires that peers exchange information on how to connect to one another before the actual connection can be begin. However, this exact method is left up to the developer. It could be anything from a very complicated server to peers emailing one another. For my purpose, I chose to write a short and sweet Node.js server that communicates with clients via websockets.


Let’s take a look at the server. It uses the ws module which can installed with: npm install ws.




And that’s the whole server. For the finer details of the syntax it’s best to refer to the ws documentation, but let’s go over what’s going on here at a high level.

First we create a WebSocketServer on port 3434 (chosen completely arbitrarily) and then create a function that given a message will broadcast said message to all connected clients as such:



Lastly, whenever we recieve a message from a client, we simply broadcast the message to all other clients (including itself. And that’s all there is to it. Like I said, keeping it super simple.

Now for the client side (where things get more complicated unforunately). That said, rather than dumping a whole mess of code, let’s go through it piece by piece. It’s a good idea to reference the WebRTC documentation while reading. I’ve found that the MDN documentation is the most complete.

The HTML is short and sweet. Take note of the two video element’s IDs.


Now for the Javascript. First up, we create a few globals.


  • localVideo will refer to the video and audio stream from the local computer.
  • remoteVideo will refer to the video and audio stream from the remote computer.
  • peerConnection will be the WebRTC connection between the local and remote computers.
  • peerConnectionConfig is a dictionary of configuration options for the peerConnection object. In this case, we only specify the public STUN servers operated by Mozilla and Google. More on this later.

Because WebRTC is still new, many of the class names are prefixed. Many examples will use adapter.js which accounts for these prefixes. Given that there’s only one function and three classes we need for this example, I opted to not use adapter.js as it eliminates a dependency. That said:


With those at the top of the file, we don’t have to worry about those prefixes anymore.

Finally time for something fun! Next, we need to get our local video and audio stream. This is accomplished with the getUserMedia function. When the page is ready, we’ll call a function aptly named pageReady which will connect to our signaling server and request a stream from the user’s webcam and microphone.


Let’s talk about the getUserMedia callbacks first. On success, we assign the given video stream to the global localStream variable we created. Then we attach that stream to the localVideo video element. This will display the video stream from the webcam in the video element. Note that the local video element has the muted attribute set in the HTML. For local video we don’t want to output our local audio stream, otherwise this will cause echos and feedback. On error just log it to the console.


Note: If you plan to open a local file in Chrome you’ll need to start Chrome with the --allow-file-access-from-files flag in order to use the getUserMedia() call.

Now for the really fun part: WebRTC.

The way this demo is structured is that both participants load the page and then one clicks the Start button. The reason for this is that after clicking the button, we’re going to start firing off messages to the signaling server in order to connect to the other client. If the other client isn’t already connected to the server, these messages will never reach their destination. Of course, there are methods that allow for participants to “drop-in” to a WebRTC connection, but that’s more complicated so we’ll skip it here.

The first action we need to perform is to create an RTCPeerConnection object. RTCPeerConnection is the primary class used in WebRTC connections. For our purposes, we only have a single RTCPeerConnection since we’re only connecting to one other client.

Next, we’re going to assign some callback functions. So what’s an ICE candidate? An ICE candidate is essentially a description of how to connect to a client. In order for anyone to connect to us, we need to share our ICE candidates with the other client. Once an RTCPeerConnection object is created, it will start gathering ICE candidates. As you can imagine, it doesn’t take much time for the browser to determine how another client on the same LAN can connect to it, but determining how to traverse a NAT can take a little bit longer. Thus, we have an onicecandidate callback that will be called whenever the browser finds a new ICE candidate. At this point, we send the candidate to our signaling server so it can sent to the other client. A NULL candidate denotes that the browser is finished gathering candidates.

onaddstream is relatively straightforward. It will be called whenever we get a stream from the other client. This is excellent because it means that our connection succeeded! Upon getting a remote stream, we attach it to the remote video element.

Lastly, if we’re the caller (we clicked the start button), we create an offer which tells the other client how to interact with us once the network connection is established. This includes info about ourselves such as video and audio formats. The formal name for this called Session Description Protocol or SDP; hence the callback gotDescription. Once we have an offer (gotDescription was called), we set the local description to it and then send it to the signaling server to be sent to the other client.


We handled the client doing the calling, but what about the answering client?

Whenever we get a message from the server, we first check if the RTCPeerConnection object has been created yet. If not, call the start function, but not as the caller since we need to answer the incoming offer, not create a new offer.

Next we determine if the message is a description or an ICE candidate. If a description, we set it as the remote description on our RTCPeerConnection object and then create an answer. Note that we are sending the answer back through the signaling server. After all this work, we’re ready to let the browser directly connect to the other client.

If the message is an ICE candidate, all we need to do is add the candidate to the RTCPeerConnection object. If we have created an answer already, but haven’t successfully connected to the caller, the browser will continue trying candidates until a connection is made or it runs out of candidates.


At this point, we’ve set everything up so we let the WebRTC internals take over and if everything went well, the onaddstream callback will be called and we’ll get our remote stream. If you’ve been putting this together piece by piece, go ahead and fire it up. If you want a full example already ready to go, see below.

That’s the essentials of WebRTC. Of course, this was a very basic example, but it can be extended to allow for “drop-in” calls, a more sophisticated signaling server, handling multiple clients, and whatever other use you find for it.


Thursday, January 15, 2015

Useful and Lesser know Linux commands.


Linux command line is attractive and fascinating, and there exists a flock of Linux user who are
addictive to command Line. Linux command line can be funny and amusing. If you really get used to it and become expertise on it, you can control and almost anything in your Linux system. By referring this article, you use Google no longer to search for suitable Linux commands to complete a particular task.





Basics
cal - get calendar
date - get date
df - get disk space
free - get free space
cd - - changes working dir to previous
ll - list all including hidden files


File handling
ls
-a - list all
-t - sort by time
-s - sort by size
-r - reverse order
-d - details of current directory


file - determine files type
less - print file content
stat - print file statistics
touch - create a file
cp, mv, rm
cp dir1/* dir2 - copy all in dir1 to dir2
-i - interactive
-u - update
-v - verbose
-f - force
-r - recursive


Input Output
ln dir/file link
wc - print line, word, byte count
man
alias name=”command”
; - use to execute multiple commands at once
> - write to a file
>> - append to a file
less - show file content in editor
cat - print file content in std output
| - pipeline
sort - sort lines
unique - get unique lines


Cursor movements
ctrl + A - move to beginning
ctrl + E - move to end of the line
alt + F - one word forward
alt + B - one word backword
history -  see command history (history | grep )


file permission
id -  find out about identity
chmod - change mode
chown - change owner
chgrp - change group
chown
octal parameters - 755, 777
u, g, a, o - user types
r, w, x - operation type


Processes
ps - list snapshot of the processes
top - list updating table of processes
\ps x - show all processes
& - allows us to open a program without terminal instance
fg % - allows us to view job or program name and assign the terminal to it
kill <1> xlogo - kill a process
killall - kill all instances of a program
pstree - show process tree


Environment
printenv - print environment variables
set - shows env vars and functions
env vars
echo $USER - print username
~/.profile - this file should contain all the custom variables
source .bashrc - adding new changes done to the file to the terminal session


VI Editro
vi - open text file to edit
i - enter insert mode
esc - enter command mode
: - enter save mode
:wq - write and quit
:q! - quit without writing
h, j, k, l- move cursor left and right
x - delete character
dd - delete new line
o - get a new line and start writing
/ - search for a particular word
:$s/line/line/g -search and replace


Package Management
apt-get update
apt-cache search
apt-get install
dpkg --install - install/update from file
apt-get remove - remove a particular package
dpkg --list - listing installed package
dpkg --status - check package installed
apt-cache show - show more details about the package
dpkg --search - which package is responsible for the file name


Mounting and Unmounting
mount - show all the mounted media
df -h - shows storage details of disks in mb
fdisk - show details of disks and format them
sudo fdisk -l - show connected devices
umount - unmount from mount point


Networking
ping - send packet to particular host
tracerout
--ftp--
ftp - file transfer protocol
ftp - connect to file server
cd - change directory in file server
lcd - change directory in local server
get - download file to local directory


wget


--ssh--
ssh - connect to ssh host
scp - download a file
sudo lsof -i :5432 - port binded process


Searching for files
locate /etc/bin | grep data - locate all pathe matching the string
find -type f -name “*.png” -delete - find and delete matching files


Archiving files
gzip -tv - archive file in zip format
tar -xvf - archive file to a specific directory


Grep
grep -i ‘regexp’ - search file by ignorecase