Monday, October 6, 2014

Custom HTTP Server and adding 'custom http header attribute' while POST request

Well, python is used here to create a custom HTTP server which will behave like normal HTTP server for GET request but for POST request, it will send the received POST request header information back in response. Why done?  Just for fun but it can be used to do a lot more.

Python script:

import SimpleHTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
import logging

class GetHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    
    def do_GET(self):
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
        return

    def do_POST(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(self.headers)
        return

if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('', 8000), GetHandler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()

Say script name is 'basehttp.py', you can run it using 'python basehttp.py'.

Here is the HTML Page  which play-around with this script.

<html>
<head>
<style>
div {
  border: 5px solid green;
}
</style>
</head>

<body>
<h1>This page will add the below 'Label(s)' into HTTP request header</h1><br>
<table>
<tr><td>Label1</td><td><input type="text" id="api-code1"></input></td></tr>
<tr><td>Label2</td><td><input type="text" id="api-code2"></input></td></tr>
<tr><td>Label3</td><td><input type="text" id="api-code3"></input></td></tr>
<tr><td></td><td><input type="submit" value="Submit" onClick='dojob()'></input></td></tr>
</table>
<br>
<div id="response"></div>
</body>

<script>
function dojob()
{
    xmlhttp=new XMLHttpRequest();

    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("response").innerHTML = "<h2> Header received on server was:</h2>";
        document.getElementById("response").innerHTML += "<pre>" + xmlhttp.response + "</pre>";
      }
    }

    xmlhttp.open("POST","test.html?t=" + Math.random(), false);
    xmlhttp.setRequestHeader("api-code1", document.getElementById("api-code1").value);
    xmlhttp.setRequestHeader("api-code2", document.getElementById("api-code2").value);
    xmlhttp.setRequestHeader("api-code3", document.getElementById("api-code3").value);
    xmlhttp.send();
}
</script>


Guess what is test.html here ? nothing, we just not using it in our POST request. Math.random() is used to invalidate the browser cache.

Thursday, September 18, 2014

The Linux Programming Interface - Kick Start

Well, for my Linux OS better understanding, I decided to learn it more using below book



It has around 63 chapters and 1556 pages. I target to read around 30 pages per day. Let's see how it goes ...

Target Start Date: 18th Sep
Target End Date:  18th Nov  ... Happy Reading :)

Wednesday, August 27, 2014

Three.js, first animation

So, i tried my hand on three.js to have a small animation... basically a CUBE having shadow, and camera is moving in a circular fashion around the cube.
Very basic but first one.

important points,
1) lights are very important, without that it will be black.
2) high light number produce more bright light

Code is here,
https://github.com/tapeshmaheshwari/JavaScript/blob/master/initial_experiment/first_example.html

Sunday, August 24, 2014

window.onload and addEventListener usage

main.html:
<script src="main.js"></script>
<input type="button" id="test" value="click here"></input>
<div id="display"></div>

main.js:
var button = {
counter : 0,
click : function() {
button.counter++;
document.getElementById("display").innerHTML = button.counter;
}
};

window.onload = function()
{
var b = document.getElementById("test");
b.addEventListener("click", button.click, false);
}


Important notes:

Without this onload function, putting 'addEventListener()' directly in global scope will give error, because we are attaching <script src="main.js"> before the <input type> for 'test'. So, JS will not get this element in DOM tree. hence, onload function will wait till document is not getting loaded fully and all elements are available in DOM tree.

Friday, August 22, 2014

Handmade UnitTest framework for JavaScript

Well, I was also needing a UT framework (a very simple one) and decide to write my own in JS.

At the same time, i realize that i need to have a public GIT repository to keep all my sample code, hence i have created this link,
https://github.com/tapeshmaheshwari/JavaScript.git


So, i wrote my first JS program which is a Unit Test Framework.
@ https://github.com/tapeshmaheshwari/JavaScript/tree/master/unittest


It looks like below and based on 'assert' function.


JavaScript Unit Test Framework



  • The first pass test case simulation
  • The first fail test case simulation
  • Add two numbers.
  • GitHub file/folder addition/deletion CLI

    Launch Git Bash program installed on your system.

    To connect to sum GIT repository
    git init
    git remote add origin https://github.com/tapeshmaheshwari/JavaScript.git

    To add a file/folder into repository
    git add test.html
    git commit
    git push

    To remove a file from repository
    git rm test.html
    git commit
    git push

    To checkout full repository
    git clone https://github.com/tapeshmaheshwari/JavaScript.git

    Thursday, August 21, 2014

    JavaScript ... first post

    I have decided to learn JavaScript a bit seriously. Why? because I think there is a lot of potential in this language. From mobile apps to gaming and animation to pretty dynamic UI, all can be done with JS.

    In short, JavaScript future is bright and if someone interested in web programming, it's the must language.

    Here are some good resources i found for Web programming:

    cofee console - fast way to write js code
    sublime editor - nice editor to write JS code

    Some code example,
    http://github.com/tkmagesh => "repositories" => Cisco-AdvJs-Aug-2014

    Some JS libraries:
    http://underscorejs.org/
    http://backbonejs.org/
    https://angularjs.org/

    Books:
    secretes of the java script ninja - reading this book now a days
    speaking java scripts
    A journey through java script mbc jungle 

    Unit test and tools:
    unit test: grant.js (complete echosstem for application workflow)
    bower - dependency managment
    unit test - jasmin , mokka , signon

    Extra:
    html5 websockets - a way for server to push data/event to client
    http://www.csszengarden.com -> cool example of same html and multiple css
    http://todomvc.com/  -> same program, multiple JS scirpt

    Sunday, August 17, 2014

    How to run a simple HTTP server using python

    python -m SimpleHTTPServer
    
    
    Just run this and root directly from wherever you are running this will become the core root directly and search for index.htm (or otherwise just do the file listing)

    Sunday, July 27, 2014

    My Suggestion to government (mygov.nic.in)

    Hi Sir,
    Thanks for initiating such a unique platform. My idea is for ‘accessing the digital services and technologies’ and how to make the change happen for good.

    Problem:
    1)      Physical/mental and economical harassment are always involved when dealing with most of the government departments/office.
    2)      There is huge corruption in almost all department and there is no ‘tracking/complaining’ system exists. Complaining in same department by approaching the next level senior is not a feasible solution as most of the times department has good terms among them (or they themselves may have share in corruption).
    3)      As of now, our government department process are not transparent. There are very few tracking system and ‘aam admi’ can’t raise much voice against the existing working style  and they don’t get proper information.
    4)      Aam admi has no idea of ‘clear rules and regulation’ and whatever is dictated by concerned department, becomes the rule. This system is prone to misusage and misguide the aam-admi.

    I see other views on this topic, but lets’ go step by step. First of all, we need to make the information available. Educating people or say providing terminal to every municipal is not a bad idea but needs lot of effort, investment and most importantly maintains to keep such things functional. In our country where even a ‘automatic railway platform ticket m/c’ is not maintained well (and I am talking about well-developed cities like Bangalore and Delhi), it’s difficult to see that such things can be maintained well at municipality level.

    So, what’s the first solution?
    1)      Provide the information at some centralized website/cloud/server. Advertise its purpose and potential usage on TV and with other media.
    2)      Educate the people on the same website on how to access the information.
    3)      Make sure accessing the information is very easy. Make sure logging issues in accessing information is also very easy.
    4)      Make it available via public internet. Let the people try to access the information on their own expense on either mobile/cyber café/office internet/home internet or from friends/neighbors.
    5)      As the ‘provided information’ is centralized, maintain it well (it means maintain the website function always UP and FAST). Let the people believe that ‘this system always works’. Faith is very important specially during initial stage of such programs.
    6)      Let the people upload what they see/feel on the same website even @ municipality/small government branch office level with proofs like ‘photos/videos’ (need more thought on proofs, I have few but they are more expensive. With the help of mobile now a days, it’s very easy to click PIC or generate video of incident).
    7)      Create a centralized monitoring team. Let them validate/verify the uploaded issues from public all over the place and generate a ‘automatic notice’ asking ‘give reasons’ to those government branch offices while keeping the complainer informed but hidden (if possible) from concerned department.
    a.       Hiding the identity (if possible) will make sure that people will not be afraid of complaining generic issues as they are anonymous to the department. There could be issues which were individual specific and for that it might be necessary to expose the identity of the person (which should be OK as the issues is specific to that identity).
    b.      Sending notice to department should made significant changes in the behavior of the staff as now they are ‘questionable for their act’. This is the biggest things missing in our system that government servants are not questionable by ‘aam admi’ if they are not doing their duty properly.
    c.       As it’s a ‘centralized team’ which is monitoring the complains, chances of biased ness is very less as the department and monitoring comity will not have any link.
    d.      The term ‘notice’ can be further discussed. In my opinion, government should prefer to raise a ‘bug’ for all such complaints (online), assign those bugs to ‘department in question’, and it’s department duty to keep a track of ‘issues logged’ against their department. Department should be able to provide the reasoning directly on logged bug (online and evident as well if possible). Complainer should be able to see them (so give ‘bug id’ to complainer as well), he should be able to do ‘cross arguments’ with concern department (with evident if needed). Let the ‘monitoring staff’ should be silently see their conversation till both provided all ‘pending information’ and ‘cross response’ to each other query (may be multiple rounds). The biggest advantage of such approach is that now ‘department and individual aam admi are discussing one-to-one, monitoring team is not busy in their case, and in-the-last based on their discussion and evident provided during discussion, they can easily reach to a conclusion of ‘which party is legally correct’ or if ‘further evidents are required’.
    e.      As it’s all happening online (no paper work or transfer of real document in 90% cases (if any party object the truthiness of uploaded Xerox proof, it might be important to show the real proof but in that case one party will lose immediately if found guilty)), both parties should be reply with-in a given time period, absence of that will considered as advantage of ‘up-to-date’ party. There might be some relaxation policies which can be further discussed.

    What all it takes to make it happen:
    1)      A online server provided by government (like mygov) where people can upload their issues and can generate the complaint number and discuss with concern department directly in the observation of ‘monitoring department’.
    2)      Individuals has to use internet on their personal expense (cyber café/personal gadgets) . But see, it’s very cheap by even travelling to concerned department. Mobiles are available everywhere, even in villages. Website should be light weight so that It can function in 2G network so that anyone can use it.
    3)      The main officer of all government branch department can be held responsible to keep a track of all the ‘bugs’ logged against his department. His duty could be to reach out the real officer (as they work in same office or phone), and provide the response. May be every department can take a normal internet connection (from private companies like airtel/vodaphone etc) with monthly 200/- (two hundred rupees plan, as of now it’s avilable), with a basic 2G/3G plan. Use a wifi modem, so that everyone on office can use their mobile to access the government website for bugs. Make the firewall rule on ‘router modem’ that people can access only ‘bug website’ to stop any misuse at all.

    I understand their might be many questions/challenges/difficulties in executing this plan, but I am open to discuss and provide further deep solutions if required. It’s just a basic idea and can be further refined.


    Regards,
    Tapesh Maheshwari.


    Tuesday, February 4, 2014

    How to redirect traffic from one IP to another IP


    /sbin/iptables -t nat -A PREROUTING -p icmp -d 10.106.210.176 -j DNAT --to-destination 10.20.1.2


    To view whatever is configured:

    /sbin/iptables -t nat -vnL --line-number  (with nat)
    /sbin/iptables -vnL --line-number           (without nat)



    To Delete/remove :
    /sbin/iptables -D FORWARD 1   (without nat and 'FORWARD' is the policy, replace accordingly from whatever is listed from above command output)

    another example to delete with nat:
    /sbin/iptables -t nat -D PREROUTING 1   (here 1, 2 ..3 are the line-numbers which will get listed from view command)

    .VIMRC file



    :set nocompatible
    :set bs=2
    :set expandtab
    :set tabstop=4
    :set shiftwidth=4
    :set showmatch
    :set mouse=a
    :set virtualedit=all
    :set nu
    syntax enable
    set hlsearch
    set incsearch
    set ignorecase
    set smartcase


    set t_Co=128
    highlight DiffAdd cterm=NONE ctermfg=Black ctermbg=Green gui=NONE guifg=Black guibg=Green
    highlight DiffDelete cterm=NONE ctermfg=Black ctermbg=Red gui=NONE guifg=Black guibg=Red
    highlight DiffChange cterm=NONE ctermfg=Black ctermbg=Yellow gui=NONE guifg=Black guibg=Yellow
    highlight DiffText cterm=NONE ctermfg=Black ctermbg=Magenta gui=NONE guifg=Black guibg=Magenta