Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

Saturday, January 8, 2011

[TIP] Daily Repository Diff via Mail

If your 200 mail every morning are still not enough, you can add this script to your daily cron.

The following scripts that you can find here, allows you to send diffs of repositories that you follow. The  bash scripts below allows you to update your git/svn/hg repository and keep a diff in a plain and html format (using ansi2html).

git_diff() {
    cd $repo_url/$1

    git_repo_url=`git remote show origin | grep "Fetch URL" | cut -d ' ' -f 5-`
    echo "GIT Diff $1 ($2) - $git_repo_url"

    git fetch
    git diff --color HEAD origin/HEAD | $ansi2html > $diff_dir/$2.html
    git diff HEAD origin/HEAD > $diff_dir/$2.diff
    git merge origin/HEAD
}

hg_diff() {
    cd $repo_url/$1

    hg_repo_url=`hg showconfig | grep paths\.default | cut -d '=' -f 2-`
    echo "HG Diff $1 ($2) - $hg_repo_url"

    hg incoming --patch --git | $ansi2html > $diff_dir/$2.html
    hg incoming --patch --git  > $diff_dir/$2.diff
    hg pull -u
}

svn_diff() {
    cd $repo_url/$1

    svn_repo_url=`svn info | grep URL | cut -d ' ' -f 2-`
    svn_repo_rev=`svn info | grep "Last Changed Rev" | cut -d ' ' -f 4-`
    echo "SVN Diff $1 ($2) - $svn_repo_url"

    svn di $svn_repo_url -r$svn_repo_rev | $ansi2html > $diff_dir/$2.html
    svn di $svn_repo_url -r$svn_repo_rev > $diff_dir/$2.diff
    svn up
}

# Fetch my repos (xxx_diff repo_path diff_name)
git_diff "linux/linux-2.6" "linux-2.6"
svn_diff "apache/lucene" "lucene"
hg_diff "java/jdk" "hotspot-jdk7"

After running repo-diff script that allows you to update your favorites repositories and saving diff files, you can send them using he send-mail script.

diff_dir="~/.repo-diffs"
mail_address="th30z@localhost"

for html_file in `ls -1 $diff_dir/*.html` ; do
    repo_name=`basename $html_file | sed 's/\.html$//g'`
    diff_file=`echo $html_file | sed 's/\.html$/\.diff/g'`

    boundary="==`echo $repo_name | md5sum | cut -d ' ' -f -1`"
    alt_boundary="==`echo $boundary | md5sum | cut -d ' ' -f -1`"

    echo "Send Repo Diff $repo_name - $html_file"
    (
        echo "MIME-Version: 1.0"
        echo "Subject: Repo-Diff: $repo_name"
        echo "To: $mail_address"
        echo "Content-Type: multipart/mixed; boundary=$boundary"

        echo "--$boundary"
        echo "Content-Type: multipart/alternative; boundary=$alt_boundary"
        echo

        echo "--$alt_boundary"
        echo "Content-Type: text/plain"
        echo
        cat $diff_file

        echo "--$alt_boundary"
        echo "Content-Type: text/html"
        echo
        cat $html_file

        echo
        echo "--$alt_boundary--"
        echo "--$boundary"
        echo "Content-Type: Application/Binary_Attachment; 
                            name=\"`basename $diff_file`\""
        echo "Content-Disposition: attachment; 
                                   filename=\"`basename $diff_file`\""
        echo "Content-Transfer-Encoding: uuencode"
        echo
        uuencode $diff_file $diff_file
    ) | sendmail $mail_address
done

This script, for each file generated from the repo-diff script sends you a mail with the diff as body and attachment.

Scripts are available on my github repository under blog-code/repo-mail-diff.

Saturday, December 12, 2009

Backups and Files Deduplication

Yesterday, I've heard about a "No Space Left" on Backup Machine, obviously the first solutions arrived was like "Buy a new disk, they don't cost so much" or "Try this ultra branded backup product"... and then there's my custom and easy solution that was rejected. :)

So, If you're a little bit brave and you're able to write a couple of lines in Python you can have a very flexible backup system with files deduplication.

The main idea is...

  • Foreach home directory that you've to backup, store a key/value list with file_path/shasum (or an hash function that you trust).

  • Foreach file in the home directory check if the file is already on the backup server (Store files on Backup Server with shasum as name). If the file was not present upload it.


In this way on the Backup server there're "two folders" one that contains all the backed-up files (storing by shasum, means that one file was on server just once), and one that contains home-th30z-10-Nov-2009.list, home-th30z-11-Nov-2009.list, and so on.

In this way you can say... Hei, fully restore my home at "specified date" or just peek a file that you've in another specified date.. and maybe all the features that you want.

This is a easy and flexible way to store your backup, without wasting space and have a great granularity level of restore...

If you've really groked the idea, you can start your start-up company focused on backups. :D

Saturday, September 26, 2009

[TIP] XCode Header Search Path

For many of you, this sounds like a stupid thing. But for those that just use gcc -I from command line, can be a pain find how to do it.

So, the problem is. How can I specify my Include path in XCode (gcc -I./mypath).


Tap on your project target, and click "Get Info", tap on "Build" tab and search "Path" as showed in the figure above. Then click on the "Header Search Paths" options and add your favorite include paths for selected target.

Tuesday, August 11, 2009

[TIP] Generic Binary Format

I Love use Binary formats, instead of XML, and JSON. Here is my Generic Binary Format for data transmissions or serializations. Data is composed by three blocks. The first one 1byte that describe all information about the object, like "is a single Int object" or "is a list", then tells you the second block length. The second block contains the size of the third block (The Data-Block) or the Number of Items in List.

Monday, August 10, 2009

[TIP] Generic Key Comparer

I'm back to code on my "Cloud" FileSystem, and distributed tools. And here is a little tip.

When you're working on Data, probably you store it as a Key-Value Pair on a BTree or something similar, and maybe this key is an aggregation of information... Maybe you've one bit of flag, N bytes of ParentKey, and others...

Now, the problem is... How can a "foreign" server sort correctly my keys? The solution is to send to the server the information on how to sort.. or a method to do it... but today, I'm focusing on the first one.



The code below show an implementation in Python of the Generic Key Comparer. At the end of the source code you can find an usage example. The Full Source Code is available here. Generic Key Comparer Source Code.



def __indexOfOne(data, tokens, offset):
  for i in xrange(offset, len(data)):
    if data[i] in tokens:
      return i
  return -1

def rawComparer(data1, data2, comparer):
  typeIds = [ 's', 'u', 'c', 'i', 'f', 'x' ]
  pyBinMap = { 
    ('u', 1): 'B', ('u', 2): 'H', ('u', 4):'L', ('u', 8):'Q',
    ('i', 1): 'b', ('i', 2): 'h', ('i', 4):'l', ('i', 8):'q',
    ('f', 4): 'f', ('f', 8): 'd'
  }

  p = i = 0
  while i < len(comparer):
  nextIdx = __indexOfOne(comparer, typeIds, i + 1)
  if (nextIdx < 0): nextIdx = len(comparer)

    format = None
    length = 1 if (i + 1) == nextIdx else int(comparer[i+1:nextIdx])      
    if comparer[i] == 's':
      format = str(length) + 's'
    elif comparer[i] == 'c':
      format = 'c'
    elif (comparer[i], length) in pyBinMap:
      format = pyBinMap[(comparer[i], length)]         

    if format != None:
      d1 = struct.unpack(format, data1[p:p+length])[0]
      d2 = struct.unpack(format, data2[p:p+length])[0]

     if d1 < d2:
       return -1
     elif d1 > d2:
       return 1 
     p += length
     i = nextIdx
     return 0

# Usage Example
if __name__ == '__main__':
  data1 = struct.pack('4sLch', 'test', 10, 'A', -3)
  data2 = struct.pack('4sLch', 'test', 10, 'A', -3)
  print 'Equal (test 10 A -3)', rawComparer(data1, data2, 's4u4ci2')

  data1 = struct.pack('4sLch', 'test', 10, 'A', 1)
  data2 = struct.pack('4sLch', 'test', 10, 'A', 0)
  print '(test 10 A 1) > (test 10 A 0)', rawComparer(data1, data2, 's4u4ci2')

  data1 = struct.pack('4sLch', 'test', 10, 'A', 0)
  data2 = struct.pack('4sLch', 'test', 10, 'A', 1)
  print '(test 10 A 0) < (test 10 A 1)', rawComparer(data1, data2, 's4u4ci2')

Monday, May 11, 2009

[TIP] Non Blocking C Read

This is Just a simple code that maybe all the Linux C Developer knows, but if someone is still learning, This is a function that wrap the standard read function adding the non blocking feature. It's Really useful in relation with Sockets.


int nonblock_read (int fd, char *buffer, size_t bufsize, int timeout) {
if (timeout > 0) {
struct timeval tv;
fd_set rfds;

FD_ZERO(&rfds);
FD_SET(fd, &rfds);

tv.tv_sec = 0;
tv.tv_usec = timeout * 1000;

if (select(1, &rfds, NULL, NULL, &tv) <= 0)
return(-ETIME);
}

return(read(fd, buffer, bufsize));
}

Friday, April 24, 2009

[TIP] Words Tokenization

Sometimes is useful to split the input text in a list of words to Indexing or Searching data.
Here is how to extract words from a sentence in C.


char str[] = "Hi, I'm a test. (This is just a test). "
"Join The #qt IRC Channel!"
"GNU/Linux - theo@gmail.com";
char delims[] = " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~";

char *result = NULL;
result = strtok(str, delims);
while(result != NULL) {
printf("%s\n", result);
result = strtok(NULL, delims);
}


...and this is the Qt way.


QString str = "Hi, I'm a test. (This is just a test). "
"Join The #qt IRC Channel! GNU/Linux - theo@gmail.com";
QString delim = QRegExp::escape(" !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~");
QRegExp regexp(QString("[%1]").arg(delim),Qt::CaseSensitive,QRegExp::RegExp2);
qDebug() << str.split(regexp, QString::SkipEmptyParts);

Wednesday, November 26, 2008

OpenSSL: License Key with RSA

In the last days I've played a bit with C libraries like OpenSSL and SQLite. The first post after Site downtime is dedicated to OpenSSL.
how do can you create your own license system for your application? With OpenSSL and less than 10 lines of code, you can do it. Take a look at the code below.



...
unsigned char checkDigest[SHA_DIGEST_LENGTH];
unsigned char shaDigest[SHA_DIGEST_LENGTH];
const char *userKey = "Matteo License";
unsigned char *signature = NULL;
unsigned int signatureLength = 0;

/* Generate Your RSA Key Pair */
RSA *rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);

/* Generate SHA1 of User Key */
SHA1(userKey, strlen(userKey), shaDigest);

/* Create License Key for the User Key */
signature = OPENSSL_malloc(RSA_size(rsa));
signatureLength = RSA_private_encrypt(SHA_DIGEST_LENGTH, shaDigest,
signature, rsa, RSA_PKCS1_PADDING);

/* Check if User Signature is a valid License Key */
if (RSA_public_decrypt(signatureLength, signature, checkDigest,
rsa, RSA_PKCS1_PADDING) != SHA_DIGEST_LENGTH)
{
/* Valid License Key */
} else {
/* Invalid License Key */
}

free(signature);
RSA_free(rsa);
...

You need to store the RSA Public Key in your app and then give to each user a generated signature, and it's all.
Ok, this is a really base example (less than 10 lines of code) if you don't want reinvent a License Key system, take a look at AquaticPrime Framework (http://www.aquaticmac.com/).

Friday, September 26, 2008

[TIP] Test TCP Port with PHP

I need to test if specified TCP Port on specified Host is opened or Not, and i need to do it from a Web Service... This is my Solution a simple "ping" method written in PHP.


function qPing ($host, $port, $timeout = 5) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) return(1);

if (!socket_set_nonblock($socket))
return(2);

$time = time();
while (!@socket_connect($socket, $host, $port)) {
$err = socket_last_error($socket);
if ($err == 115 || $err == 114) {
if ((time() - $time) >= $timeout) {
socket_close($socket);
return(3); # Connection timed out.
}
usleep(500);
continue;
}
echo $err . ' ' . socket_strerror($err) . "\n";
return(4);
}

socket_close($socket);
return(0);
}