Chitika

Tuesday, November 12, 2013

my grails cheat-sheet

Environment

set $GRAILS_HOME=path to grails
set $JAVA_HOME=path to java
set $PATH=include $JAVA_HOME/bin and $GRAILS_HOME/bin

Init

grails create-app App1

Run

grails run-app

Create Domain

grails create-domain-class d1

path: grails-app/domain/d1.groovy

Data Constraints

class d1 {

String name
String address
Date dob
d2 linkedData

static constraints = {
   // order of fields in constraints are used in scaffolding
   name(size:1..48, unique:false)
   address(maxSize:128,blank:true)
   dob(blank:true)
   // linkedData of custom type nullable as in the case linked data doesn't exist,
    // then d1 can't be created
   linkedData(nullable:true)
}
}

Create controller

grails create-controller c1

path: grails-app/controller/c1.groovy

Scaffolding

class c1Controller {
    def scaffold = d1
}

Testing

grails test-app -unit
grails test-app -integration

Friday, November 1, 2013

mongo db

Setup:

run as root > mkdir -p /data/db

run as root > mongod
(--rest switch starts with rest interface)

create database abcdb:

> mongo abcdb
>_ (prompt will appear)
(db won't be persist unless data inserted)
insert data, into a collection coll:

> db.coll.insert( "lang": "english", "alphabets": ["a","b","c"...], "style":"ltr")
json object will be created in db as follows:
"book":{
                "coll":[
                              { "lang": "english", "alphabets": ["a","b","c"...], "style":"ltr" }
                            ]
              }

to see rows in collections:

> db.coll.find()

to see all the functions of any object use help() function

> db.help()
> db.coll.help()

to see all databases

> show dbs

to see the definition of function, enter function name without parenthesis

>db.coll.find

custom function
> function myFunctionLanguage(lang, style) {
... db.towns.insert(lang:lang, style:style);
... }

find function may take object Id as first argument or condition filter, and columns to show in result in second argument

find time taken by query to execute (need of index?)

> find(...).explain()

create index:

>db.coll.ensureIndex(...)

queries profiling:

> db.setProfilingLevel(2)
>db.system.profile.find()

Thursday, October 24, 2013

Wednesday, October 2, 2013

mplayer side by side to anaglyph viewing

mplayer -vf stereo3d,scale sbs.mp4

where, sbs.mp4 is side-by-side stereoscopic movie

linux 3D side-by-side to anaglyph video conversion


mencoder -vf stereo3d,scale sbs.mp4 -o anaglyph.mp4 -oac pcm -ovc x264

where:
sbs.mp4 is input file
anaglyph.mp4 is output file

Wednesday, September 18, 2013

ffmpeg encode dvd to mp4

ffmpeg -i "concat:tmpDev/VIDEO_TS/VTS_01_1.VOB|tmpDev/VIDEO_TS/VTS_01_2.VOB|tmpDev/VIDEO_TS/VTS_01_3.VOB|tmpDev/VIDEO_TS/VTS_01_4.VOB" -acodec copy -vcodec libx264 ./out.mp4

Monday, September 16, 2013

gnu c/gcc exception handling

man setjmp states:

"setjmp() and longjmp(3) are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. setjmp() saves the stack context/environment in env for later use by longjmp(3). The stack context will be invalidated if the function which called setjmp() returns."

man lngjmp states:

"longjmp() and setjmp(3) are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. longjmp() restores the environment saved by the last call of setjmp(3) with the corresponding env argument. After longjmp() is completed, program execution continues as if the corresponding call of setjmp(3) had just returned the value vallongjmp() cannot cause 0 to be returned. If longjmp() is invoked with a second argument of 0, 1 will be returned instead."

Example at wikipedia:

#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
 
enum { SOME_EXCEPTION = 1 } exception;
jmp_buf state;
 
int main(void)
{
  if(!setjmp(state))                      // try
  {
    if(/* something happened */)
    {
      exception = SOME_EXCEPTION;
      longjmp(state, 0);                  // throw SOME_EXCEPTION
    }
  } 
  else switch(exception)
  {             
    case SOME_EXCEPTION:                  // catch SOME_EXCEPTION
      puts("SOME_EXCEPTION caught");
      break;
    default:                              // catch ...
      puts("Some strange exception");
  }
  return EXIT_SUCCESS;
}


#include <stdio.h>
#include <setjmp.h>

#define TRY do{ jmp_buf ex_buf__; if( !setjmp(ex_buf__) ){
#define CATCH } else {
#define ETRY } }while(0)
#define THROW longjmp(ex_buf__, 1)

int
main(int argc, char** argv)
{
   TRY
   {
      printf("In Try Statement\n");
      THROW;
      printf("I do not appear\n");
   }
   CATCH
   {
      printf("Got Exception!\n");
   }
   ETRY;

   return 0;
}


Advanced Try...Catch...Finally: (source: http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html)

#include <stdio.h>
#include <setjmp.h>

#define TRY do{ jmp_buf ex_buf__; switch( setjmp(ex_buf__) ){ case 0: while(1){
#define CATCH(x) break; case x:
#define FINALLY break; } default:
#define ETRY } }while(0)
#define THROW(x) longjmp(ex_buf__, x)

#define FOO_EXCEPTION (1)
#define BAR_EXCEPTION (2)
#define BAZ_EXCEPTION (3)

int
main(int argc, char** argv)
{
   TRY
   {
      printf("In Try Statement\n");
      THROW( BAR_EXCEPTION );
      printf("I do not appear\n");
   }
   CATCH( FOO_EXCEPTION )
   {
      printf("Got Foo!\n");
   }
   CATCH( BAR_EXCEPTION )
   {
      printf("Got Bar!\n");
   }
   CATCH( BAZ_EXCEPTION )
   {
      printf("Got Baz!\n");
   }
   FINALLY
   {
      printf("...et in arcadia Ego\n");
   }
   ETRY;

   return 0;
}

Monday, September 2, 2013

grails db-reverse-engineer

Create application:

> grails create-app

Reverse engineer DB, following is the great tutorial for it:

http://grails-plugins.github.io/grails-db-reverse-engineer/docs/manual/guide/single.html

> grails db-reverse-engineer

Remember following points:

1. every thing in db should be in small case, separating words with underscore ("_"), instead of camel notation.
2. when joining tables, foreign key should be named as follows: table_name + underscore + id, e.g. foreign key for table "data" should be named: data_id, in all the tables joined with data table

Generate controllers:

> grails generate-all "*"

Run application:

> grails run-app

NOTE: if error occurred, set JDK path:

> export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")

Wednesday, August 21, 2013

linux: secure, quick and easy sock5 proxy over ssh

Connect to remote server using following ssh command:

> ssh -D 12345 remote-server.com

a sock5 server will started on localhost:12345, port is 12345.

install tsocks package, as sock5 client

> sudo apt-get install tsocks

edit /etc/tsocks.conf

> vi /etc/tsocks.conf

remove everything, and enter following lines:

server = 127.0.0.1
server_type = 5
server_port = 12345

save and quit

Now to run firefox (or any other network application), using sock5, execute following command:

> tsocks firefox

enjoy, secure, quick and easy sock5 proxy over ssh.

Tuesday, July 2, 2013

C/C++ Profiling

Compilation
compile and link program using gcc/g++, without using ld command, with flag -pg

Autotools
for auto tools, clean project (make clean),
execute $> CFLAGS=-pg ./configure && make && sudo make install

Generation
execute the program /bin/prog.exe (or test suite), gmon.out file will be created in working directory

NOTE: gmon.out file will be created on program exit, killing the process, would not generate gmon.out

Post Processing
In order to generate profiling information from gmon.out, execute following command:
$> gprof /bin/prog.exe gmon.out > analyse.txt

Profiling information will be generated in analyse.txt file.

NOTE: provide complete path to program and complete path to gmon.out (here gmon.out is present in current directory)

Tuesday, June 25, 2013

GDB debugging

Following are the useful commands to debug:

debug with program arguments:

    gdb --args prog arg1 arg2 arg3 

Debugging an application with complex configuration files setup in different directories:

    compile the program with -g switch, and install it
    debug the installed program as follows:
    sudo gdb --args prog arg1 arg2 arg3

add break point to function:

    b func_foo

add break point to line in file:

    b file:line_num

step into:

    s

step over:

    n

continue program execution:

    c

start/restart program:

    r

print variable:

    p var
    x/s str_var

print 10 bytes in hex

    x/10x str_var

list program statements being in debug
  
    l

get call stack: (backtrace)
 
    bt

get value of some variable in function call in back in call stack at row 2:

    f 2
    p var

get all break points (info break):

    i b

delete a break point 3:

    d 3

watch a variable for change:

    wa var

get threads list (info threads):

    i th

change to different thread context (e.g. thread 2):

    t 2

attaching to an already running process for debugging (first get process id using ps -ef):

    at process_id

detaching to debugging process:

    det

debugging save state (checkpoint, only for single threaded application):

   checkpoint

   info checkpoint

restore program state to the checkpoint (e.g. 2):

   restart 2

GDB hex dump

Create file in home folder, named '.gdbinit', and put following contents in it:

define xxd
dump binary memory dump.bin $arg0 $arg0+$arg1
shell xxd dump.bin
end


during debugging execute following command to get hex dump of any memory area, by specifying starting address (or name of variable) and length:

(gdb) xxd var 112
0000000: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000010:
aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000020:
aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000030:
aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000040:
aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000050:
aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000060:
aabb ccdd eeff 0011 2233 4455 6677 8899 ................



Ref:

http://stackoverflow.com/questions/9233095/memory-dump-formatted-like-xxd-from-gdb
http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_chapter/gdb_18.html#SEC195

Thursday, May 16, 2013

Sets Difference algorithm

Lets assume you have two sets as follows:

example sets:

Set A

1
2
3
4

Set B

3
4
5
6

now we want to get difference of these sets:

(assume a cleared (0) flag "added" for each element of set B)

algorithm:

1. for each element E in set B, iterate over elements in set A
    i. if value of element E is found in set A, remove that entry from A
   ii. if value of element E is not found in set A, set (1) "added" flag of element E
4. Remaining elements in set A, represents set difference A-B
5. elements in set B, having flag "added" set (1), represents set difference B-A
6. elements in set B, having flag "added" cleared(0), represents set intersections
7. All remaining elements in set A and value of all elements in set B represents union of set A and B

result:

Set A

1
2

Set B

3
4
5 -> added
6 -> added

A-B = 1,2
B-A = 5,6

A intersection B = 3,4
A union B = 1,2,3,4,5,6

optimizations:

if set A is sorted, iterated over elements of set A, until element value in set A is less than element E of set B
similarly, further optimizations are possible when both sets are sorted.

Monday, May 13, 2013

perl cpan install module


> perl -MCPAN -e shell
> install module_name

e.g.:
> install Net::DNS::Check

Monday, May 6, 2013

update perl modules to latest versions

Ubuntu environment:

Execute:

> sudo apt-get install cpanminus

> sudo cpanm App::cpanoutdated

> sudo cpan-outdated -p | cpanm

Update single module from CPAN: download, build and install

cpanm Net::DNS
cpanm LWP

Wednesday, February 13, 2013

linux enable sftp

To enable sftp on linux (having openssh-server installed), one have to uncomment/open following line in /etc/ssh/sshd_config file, and restart sshd server (this line is already enabled in all the distributions by default, means sftp is already working):

Subsystem       sftp    /usr/lib/ssh/sftp-server


To connect to linux sftp, use sftp user@server from command line and use normal ftp (put/get/mput/mget) commands to retrieve and send files to server.

Tuesday, February 12, 2013

C# Cross thread GUI update issue

Following is the pattern to handle C# cross thread GUI update issue (ref: stackoverflow)


delegate void SetTextCallback(string text);

private void SetText(string text)
{
  // InvokeRequired required compares the thread ID of the
  // calling thread to the thread ID of the creating thread.
  // If these threads are different, it returns true.
  if (this.textBox1.InvokeRequired)
  { 
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
  }
  else
  {
    this.textBox1.Text = text;
  }
}

Monday, February 11, 2013

debug c++ activeX control of different project

Sometimes solutions are big, consisting of different project. When we have to debug these projects we get the notification that: Breakpoint will not currently be hit. No symbol loaded for this document.

To debug such project, following are the steps:

  1. Clean solution
  2. Rebuild solution
  3. Run the executable project (by setting it as startup project)
  4. When the said activeX just launched by the executable, go to debug and attach to the executable containing the activeX
  5. now, easily debug the activeX project.

Thursday, February 7, 2013

JNI NDK for android developers (and casual c programmer)

  1. Download NDK
  2. extract NDK on c drive (no space in path)
  3. create jni folder in eclipse android project, put c file(s), make file and libraries (.a/.o) in this folder
  4. c file should be as follows (lowlevelfunctions.c), note signature of function:
#include <string.h>
#include <jni.h>
#include "thirdpartylib.h"


jstring Java_com_example_LowLevelFunctions_getInfo(JNIEnv* env, jobject javaThis) {

return (*env)->NewStringUTF(env, "hello world");
}

/************************************
*** and make file as follows (Android.mk): ***
************************************/


LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := lowlevelfunctions
LOCAL_MODULE_TAGS := lowlevelfunctions
LOCAL_SRC_FILES := lowlevelfunctions.c
LOCAL_ARM_MODE := arm

LOCAL_LDFLAGS = $(LOCAL_PATH)/thirdpartylib.a
#LOCAL_STATIC_LIBRARIES := thirdpartylib

include $(BUILD_SHARED_LIBRARY)

5.  on cmd, navigate to jni folder
6. on the jni folder, execute ndk-build executable directly from NDK root path
7. liblowlevelfunctions.so will be created to the parent folder's lib folder
8. to include it in the java, note the function name in c file, it should be added in the class LowLevelFunctions of com.example package, named getInfo, as follows:

package com.example;

class LowLevelFunctions {

static {
System.loadLibrary("lowlevelfunctions"); // as defined in make file LOCAL_MODULE
}

public static native String getInfo();

}

9. If you want to create executable, include int main() function in c file and include $(BUILD_EXECUTABLE) in last line of make file.




Wednesday, February 6, 2013

Editing dot net resource .resx file

.Net Resource Editors are third party programs/freewares, which could be used to edit resource files (having extension .resx).

Following is similar utility:

http://fishcodelib.com/files/ResourceNet2.zip

C# get fully qualified domain name

Use following code snippet to get fully qualified domain name of current machine:



string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
string fqdn = "";

if (!hostName.Contains(domainName))
    fqdn = hostName + "." + domainName;
else
    fqdn = hostName;

C# Auto detect default IP Address


Use following code snippet to automatically detect the default IP address:



  IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
                    if (localIPs != null &&
                        localIPs.Length > 0)
                    {
                        tbServerName.Text = (from localIP in localIPs
                                             where localIP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
                                             select localIP.ToString()).FirstOrDefault();
                    }
                    else
                    {
                        tbServerName.Text = "";
                    }