Friday, June 7, 2019

CSS tricks

Mixed paint in background:
background: linear-gradient(to right, #b6e358, #38b143)


Grid view:
display: grid;
grid-template-columns: auto auto;
justify-content: space-around;

Thursday, March 9, 2017

Javascript, How to find object types

In some cases we can't use typeof to find object of Object and object of Array.

You can use Object.prototype.toString to find object types in Javascript


Monday, March 6, 2017

Git frequent usage commands

git create new branch
git checkout -b 'branchName'

git switch to existing branch
git checkout branchName

git Tag with version
git tag -a v0.0.1 90a5435 -m ' Your Message'
git push origin v0.0.1

v0.0.1 - Version that you want to create
90a5435 - Commit id of the branch the you want to tag

git delete Tag
remote
git push --delete origin tagname

local
git tag --delete tagname

Git merge

git checkout master
git pull origin master
git merge test
git push origin master

Git delete branch
git push origin --delete branchname
git branch -d branchname

Thursday, February 2, 2017

PHP simple google OAuth in Linux

Steps involved!

1. Create a parent directory php-google-signin
2. Download google-api-php-client  library from Github to parent dir
3. Obtain OAuth 2.0 client credentials from the Google API Console. Save the json file as key.json  in to parent dir
4. Set your redirect URL in google api key console

Create a file index.php

<?php
    require_once __DIR__.'/google-api-php-client-2.1.1/vendor/autoload.php';
    date_default_timezone_set('asia/kolkata');
    session_start();

    // to find localhost and production server https
    if ($_SERVER['SERVER_NAME'] == "localhost") {
        $protocol = "http://";
    }else{
        $protocol = "https://";
    }
    $redirect_uri = $protocol . $_SERVER['HTTP_HOST'] . "/index.php";
    $client = new Google_Client();
    $client->setAuthConfigFile('key.json');
    $client->setRedirectUri($protocol . $_SERVER['HTTP_HOST'] . "/index.php");
    $client->setScopes('email'); // You want to retrieve email and domain name
    

// on logout
    if (isset($_REQUEST['logout'])) {
      unset($_SESSION['id_token_token']);
    }

// once you get code after auth success
    if (isset($_GET['code'])) {
      $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
      $client->setAccessToken($token);
      $_SESSION['id_token_token'] = $token;
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    if ( !empty($_SESSION['id_token_token']) && isset($_SESSION['id_token_token']['id_token']) ) {
      $client->setAccessToken($_SESSION['id_token_token']);
    } else {
      $authUrl = $client->createAuthUrl();
    }
    // success
    if ($client->getAccessToken()) {
      $token_data = $client->verifyIdToken();

// print all the data related after auth
      print_r($token_data)
    }
?>

Wednesday, January 18, 2017

Convert sec to hh:mm:sec in Javascript


Convert seconds to hour:minute:seconds in javascript

This pattern can be used to calculate call duration

Number.prototype.calltimer = function () {
    var sec_num = parseInt(this, 10);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}

var time = 120; 
time.calltimer()

will give you "00:02:00"


Wednesday, November 2, 2016

linux find and cp/mv to a path

If you want to find for a particular string/date and then do list/copy/move, then below command will help you out

Find .wav files created on Dec 30th
 find . -type f -name "*.wav" -newermt 2016-12-30 ! -newermt 2016-12-31 -exec ls -l {} \;

If above cmd shows proper output then try
find . -type f -name "*.wav" -newermt 2016-12-30 ! -newermt 2016-12-31 -exec cp  {} /dest/path/ \;


Wednesday, October 19, 2016

Node render html file and pass json data to html

Create a server.js file with below code
var express = require('express'),
app = express(),
        http = require('http'),
        httpServer = http.createServer(app);

app.use('/',express.static(path.join(__dirname, '/public')));
app.set('view engine', 'ejs'); // send HTML files
app.engine('html', require('ejs').renderFile);

app.get('test',function(req, res){
 res.render('hello.html',{ 'id' : 'w8m4r9vdfm' });
});

httpServer.listen(8000,"0.0.0.0",function(){
    console.log('http on 8000');
});

Folder structure:
app
  server.js
  public/hello.html

Friday, August 12, 2016

Exclude a folder while copy in linux

let's say you have main Folder application with 3 folders inside
folderA  folderB folderC and want to exclude folderA the you can simply execute below command

rsync -av --progress application /destinationfolder --exclude folderA  

Tuesday, August 2, 2016

Shared library support linux

Shared libs are know by linking its path in /etc/ld.so.conf.d/

Recently i came across an error in asterisk while trying to compile OPUS codec as shared lib support to asterisk

asterisk: error while loading shared libraries: libopus.so

But OPUS was install under /usr/local/lib

Now to make it available to asterisk do

echo '/usr/local/lib' > /etc/ld.so.conf.d/usr_local.conf

then update ldconfig by
ldconfig && ldconfig -v

Thursday, June 23, 2016

Monday, June 13, 2016

WebRTC STUN check and adding multiple STUN servers

var pc = new RTCPeerConnection({iceServers: [
    {urls: 'stun:stun1.l.google.com:19302'},
    {urls: 'stun:stun2.l.google.com:19302'}
]});
pc.createDataChannel("testchannel");
pc.onicecandidate = function(e) {
  if(e.candidate){
    console.log(e.candidate.candidate);
  }
};
pc.createOffer().then(offer => pc.setLocalDescription(offer));

Thursday, May 26, 2016

Adding alias in windows like in Linux

Here doskey cmd is used to set alias.
All alias set using 'doskey' are temporary, once you reopen a new cmd window its gone.

Let see how to set alias like in linux we save it in .bashrc file

IN WINDOWS
First open a notepad and past below commands to test

doskey ls=dir
doskey !=ping google.com -t
doskey mv=ren

save it as alias.cmd,
Open your run window and type %appdata% then enter. Copy the alias.cmd file to this Appdata-Roming folder.

Open regdit from your run window.
Go to HKEY_CURRENT_USER\SOFTWARE\Microsoft\Command Processor
Select 'Command processor' Folder and on the right side of window, Right click - New-Expandable string value
Give 'Name' as AutoRun, then right click and modify value as  "%AppData%\alias.cmd"

That's it! Now go to cmd prompt and do
ls and see it its working.

Tuesday, February 23, 2016

Install asterisk 1.8.* in Ubuntu 14.04

Get the latest version of 1.8 * from asterisk download

Install dependencies
apt-get install build-essential libxml2-dev ncurses-dev libssl-dev subversion

--prefix is optional if you want to install asterisk in particular source directory
./configure CFLAGS=-pg LDFLAGS=-pg --prefix=/usr/local/

To do minimum or selected installation
make menuconfig 

make && make install
make samples && make config

To start asterisk
asterisk -i  or  /etc/init.d/asterisk start

connect to cli
asterisk -rvvvvvvvv

Sunday, February 7, 2016

Adding/pasting your HTML codes on Google blogger.

Thanks to http://hilite.me/

Paste your code here http://hilite.me/, it just converts your code to html highlighted format. Then you can copy paste it in compose mode and click on preview to see the magic!

<?php
    require_once __DIR__.'/google-api-php-client-2.1.1/vendor/autoload.php';
    date_default_timezone_set('asia/kolkata');
    session_start();

    // to find localhost and production server https
    if ($_SERVER['SERVER_NAME'] == "localhost") {
        $protocol = "http://";
    }else{
        $protocol = "https://";
    }
    $redirect_uri = $protocol . $_SERVER['HTTP_HOST'] . "/index.php";
    $client = new Google_Client();
    $client->setAuthConfigFile('key.json');
    $client->setRedirectUri($protocol . $_SERVER['HTTP_HOST'] . "/index.php");
    $client->setScopes('email'); // You want to retrieve email and domain name
    

// on logout
    if (isset($_REQUEST['logout'])) {
      unset($_SESSION['id_token_token']);
    }

// once you get code after auth success
    if (isset($_GET['code'])) {
      $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
      $client->setAccessToken($token);
      $_SESSION['id_token_token'] = $token;
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    if ( !empty($_SESSION['id_token_token']) && isset($_SESSION['id_token_token']['id_token']) ) {
      $client->setAccessToken($_SESSION['id_token_token']);
    } else {
      $authUrl = $client->createAuthUrl();
    }
    // success
    if ($client->getAccessToken()) {
      $token_data = $client->verifyIdToken();

// print all the data related after auth
      print_r($token_data)
    }
?>

 

Thursday, February 4, 2016

PHP asynchronous Http call using curl,shell_exec


?>php

for ($i = 0; $i &lt; 100; $i++){

  $cmd = 'nohup curl -H "Authorization: Basic yourRandomIOhere==" -H "Content-Type:        application/json" -X POST -d "{yourjson: "value"}" https://example.com/Message/ &gt; status.out &amp;';

  shell_exec($cmd);

}

print 'job done!';

?>


here:
100 : No of times you want to make this call
nohup:  to run in background
POST: http method, POST or GET
Authorization and content type is your option.

SIP,RTP capture with tshark and TCPdump

Tshark command to capture both SIP and RTP on media servers

This is useful if you don't know on which port SIP and UDP packetes comes from and can dump in pcap

tshark -i eth0 -w capture.pcap -f "(udp port sip) or (udp[1] & 1 != 1 && udp[3] & 1 != 1 && udp[8] & 0x80 == 0x80 && length < 250)"

-i  : specify your interface, If not use "any" to capture on all interfaces
-w : file to save


TCPdump to capture SIP on specific port! 
tcpdump -nqt -s 0 -A -i eth0 port 5060

Grep both SIP and UDP at same time.
tcpdump -n -i eth0 | grep 'SIP\|UDP'

Friday, December 4, 2015

Javascript tips and tricks

You can access a HTML element id by

Type the id name directly in broswer console eg, my div id = makeCall
makeCall
Suppose if id with '_' , like make_Call it won't work

Use getElement, Works in all case
document.getElementById('makeCall')

or Query selector, it doesn't like id with numbers at start :P
document.querySelector('#makeCall')










If you want to use script or a function in HTML form action you can use 'javascript:myFunction();'



action="javascript:myFunction();

Javascript access functions and variables inside Jquery

(function($) {
$.fn.mainFunction = new function (){
var testVal = "Test";
this.test = function(){
console.log('inside test');
}
}
}(jQuery));

Now you can access testVal and mainFunction.test()

Tuesday, December 1, 2015

Moniter/Listen/Load test http request Linux

There is a simple tool tcpflow to capture the actual headers coming to your host

tcpflow port 80

To be more specific use.
tcpflow -p -c -i eth0 port 80 | grep -oE '(GET|POST|HEAD) .* HTTP/1.[01]|Host: .*'

Capture only number of hits: 
tcpflow -p -c -i eth0 port 80 | grep 'Date'


Use ab tool (apache2-tools) to benchmark the load on apache or any other http server like pyhton,node etc

ab -n 1000 -c 10 http:ipaddresss:port/                    / is important after port number 

-n number of request to send
-c total request to send per sec / concurrent req


You can use rate limit to allow number of connection per sec/min/hr with --limit module in IPTABLES

Iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m limit --limit 10/second --limit-burst 10 -j ACCEPT

CSS tricks

Mixed paint in background: background: linear-gradient(to right, #b6e358, #38b143) Grid view: display: grid; grid-template-columns: a...