Friday, April 3, 2015

Javascript drag/drop event listener

It is a cool feature that file processing is triggered when you drag a file and drop it onto a web page.

For example, the midi player demo page index.html from [1] has this in header javascript:

    if (FileReader){
        function cancelEvent(e){
            e.stopPropagation();
            e.preventDefault();
        }
        document.addEventListener('dragenter', cancelEvent, false);
        document.addEventListener('dragover', cancelEvent, false);
        document.addEventListener('drop', function(e){
            cancelEvent(e);
            for(var i=0;i            var
                file = e.dataTransfer.files[i]
            ;
            if(file.type != 'audio/midi' && file.type != 'audio/mid'){
                continue;
            }
            var
                reader = new FileReader()
            ;
            reader.onload = function(e){
                midiFile = MidiFile(e.target.result);
                synth = Synth(44100);
                replayer = Replayer(midiFile, synth);
                audio = AudioPlayer(replayer);
            };
            reader.readAsBinaryString(file);
            }
        }, false);
    }


What this does is, when you drag and drop a midi file on the page, it'll be read and played.

HTML5 has native support for drag/drop event. See [2].

[1] https://github.com/gasman/jasmid
[2] Native HTML5 Drag and Drop

Tuesday, March 31, 2015

Javascript OOP

Javascript is a prototypical langaage. Its OOP is achieved by prototype instead of class. Prototype is kind of like decorator patten, that decorates a initially bare object with more functionalities.

Some links to Javascript OOP:
The most common syntax for defining a class is [3]:

if (typeof (classA == "undefined")) {

    // Another short-hand way of defining this class:  function classA() { ... }
    var classA = function() {
        this.property1 = 1;  // A public variable. Defined with "this.". To access, use "this.".
        var secret = 2;  // A private variable. Defined with "var". To access, don't use "this.".

        // A private method.
        // Another short-hand way of defining this:  function dec () { ... }
        var dec = function() {
             if (secret > 0) {
                secret -= 1;
            }
        }

       
        // A privileged method. Can access private variables and methods. Accessible to outside.
        // Defined with "this.".
        // Another way of defining this:  function getInfo() { ... }
        this.getInfo = function() {
            return secret + this.property1;
        }     
    }

    // A public method.
    classA.prototype.getColor = function() { return 'green'; }
}

To create an instance you do:

var objectA = new classA();

To inherit from classA you do something like this [2]:

function classB() {
    this.setValue(value);

classB.inherits(classA);

Promiscuous multiple inheritance is possible but hard and may suffer from name collision.

Other related concepts include swiss inheritance, parasitic inheritance etc.


Sunday, March 29, 2015

Shell scripts to start and stop a server

Now I have a working Python|Authbahn websocket server. To start and stop both there are several steps to do.  The scripts here help to simplify the job.


== start_server.sh ==

export PYTHONPATH=.
export DJANGO_SETTINGS_MODULE=my_project.settings
daemonize  -c /django_projects/my_project  /django_projects/my_project/server/my_server.py

#
# Note here there is a need to setup PYTHONPATH and django project setting, since we have
# customized modules to use in the server.
# After setting up the path, when use daemonize then you need to specify
# the working directory with -c.
#

== stop_server.sh ==

output=`ps ax|grep my_server.py | grep -v grep`
echo killing process my_server.py
if [[ -z $output ]]; then
    echo 'this process doe not exist'
    exit 0
fi

set -- $output
pid=$1

echo killing proces $pid
kill -9 $pid
#sleep 2
#kill -9 $pid >/dev/null 2>&1


#
# Reference:
# [1]
# http://stackoverflow.com/questions/6437602/shell-script-to-get-the-process-id-on-linux
# The backticks allow you to capture the output of a comand in a shell variable.
# The set -- parses the ps output into words, and $2 is the second word on the
# line which happens to be the pid. Then you send a TERM signal, wait a couple
# of seconds for ruby to to shut itself down, then kill it mercilessly if it
# still exists, but throw away any output because most of the time kill -9 will
# complain that the process is already dead.
#
# [2]
# http://www.cyberciti.biz/tips/grepping-ps-output-without-getting-grep.html
# when ps aux | grep something, to avoid getting the line of grep, do either of
# 1) ps aux | grep something | grep -v grep
# 2) ps aux | grep [s]omething
# 3) ps aux | grep '[s]omething'
# for 2) and 3), it's actually a regular expression, [s] matches to s.
#

Saturday, March 28, 2015

How to Install and Use Screen on an Ubuntu Cloud Server

Screen is a console application that allows you to use multiple terminal sessions within one window. The program operates within a shell session and acts as a container and manager for other terminal sessions, similar to how a window manager manages windows.

This is like the console version of Mac and Linux's multiple desktops. Very handy.

To run a program (say a server) in a screen session, detach it without killing the session:
     screen -d -m python server/server.py 80

This is like running the "daemonize" command, can make the program an independent daemon process.

[1] How to Install and Use Screen on an Ubuntu Cloud Server

Monday, March 16, 2015

Websocket

Websocket can be used to create real time chat and game services.

Autobahn|Python [3] is a WebSocket / WAMP library for Python 2 (using Twisted) and 3 (using asyncio). It's easy to setup and use.

Websocket and browser support [1]:

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request.[1] The WebSocket protocol makes more interaction between a browser and a website possible, facilitating live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server. A similar effect has been achieved in non-standardized ways using stop-gap technologies such as Comet.

In addition, the communications are done over TCP port number 80, which is of benefit for those environments which block non-web Internet connections using a firewall. The WebSocket protocol is currently supported in most major browsers including Google Chrome, Internet Explorer, Firefox, Safari and Opera. WebSocket also requires web applications on the server to support it.



Turn on websockets in firefox [2]:

1. Type about:config in address bar, and continue by clicking “I’ll be careful, I promise”
2. Set network.websocket.enabled  value to ‘true’ and set network.websocket.override-security-block preferences to ‘true’.
3. Restart Firefox browser.

== Change a websocker server to daemon ==

Each time you can run this to start a websocket server: python ./server.py

To change it to a daemon you can do this:
- add "#!/usr/bin/python" to top of server.py
- install daemonize [4]
- use absolute path of server.py, run this: daemonize /../server.py

Now server.py is started as a daemon. To find out which process it's running as and to shut it down, do:

- ps -aux | grep server.py

This will (usually, if you don't have other process with the name "server") find 2 entries, one for the server.py process, one for the grep command. Pick the former, you can watch its activity by:

- top -p [pid]

To kill it:

- kill -9 [pid]


[1] http://en.wikipedia.org/wiki/WebSocket
[2] http://techdows.com/2010/12/turn-on-websockets-in-firefox-4.html
[3] http://autobahn.ws/
[4] http://software.clapper.org/daemonize/ 
[5] websocket browser support

Monitor Linux (Ubuntu) network traffic in real time

== Monitor incoming network traffic in real time:
[http://manpages.ubuntu.com/manpages/lucid/man1/tcptrack.1.html]

ifstat
iftop
iptraf
tcptrack

== Commands to verify ports:
[https://www.serverpronto.com/accounts/knowledgebase.php?action=displayarticle&id=11]

nmap IP#
nmap localhost
netstat –ntulp

== to verify single port

netstat -nap | grep 

== to list all current rules in iptables

iptables -L

== For opening a TCP port:

iptables -A INPUT  -p tcp –dport -j ACCEPT

== For opening a UDP port:

iptables -A INPUT -p udp –sport   -j ACCEPT

== Save changes:

iptables-save > /etc/iptables.rules

== If you need to disable the firewall temporarily, you can flush all the rules using:

iptables -F

Blog Archive

Followers