Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

"openterminal" contextual menu item with Automator

Right-click on a file or folder in a Finder window and select Automator -> openterminal to open it in Terminal.app.
(i.e. cd to the folder or open the file in the nano text editor)

open -a Automator

#--------------------------------------------------

Drag or add actions here to build your workflow:
Library: Finder -> Action: Get Selected Finder Items
Library: Automator -> Action: Run Shell Script
                                 - Shell: /bin/sh
                                 - Pass input: as arguments


if [[ $# -gt 1 ]]; then exit 0; fi

if [[ -d "$@" ]]; then

   printf "%s" "$@" | /usr/bin/pbcopy
   #/usr/local/bin/cpath # cf. http://osxutils.sourceforge.net

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; cd \"$(/usr/bin/pbpaste)\"; /usr/bin/clear" in (first window whose name contains " ")'

# alternative without /usr/bin/clear (experimental)
# requires:
# defaults write com.apple.Terminal Autowrap NO
# or:
# Terminal menu -> Window Settings ...  -> Buffer -> in the Scrollback 
# section check the box next to "Wrap lines that are too long" 
# -> click "Use Settings as Defaults"

#   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "cd \"$(/usr/bin/pbpaste)\"; /usr/bin/tput cup 0 0; /usr/bin/tput dl1; /usr/bin/tput el; /usr/bin/tput dl1; /usr/bin/tput el" in (first window whose name contains " ")'

   exit 0

elif [[ -r "$@" ]]; then 

   printf "%s" "$@" | /usr/bin/pbcopy

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; /usr/bin/clear; /bin/sleep 0.3; /usr/bin/nano \"$(/usr/bin/pbpaste)\";" in (first window whose name contains " ")'

exit 0

fi

exit 0


#--------------------------------------------------


open -a Automator ~/Library/Workflows/Applications/Finder/openterminal.workflow

Cross-platform file encryption with TrueCrypt

# first download & install the free, open-source TrueCrypt program from http://www.truecrypt.org/downloads.php

ls -ld /Applications/TrueCrypt.app
ls -l /Applications/TrueCrypt.app/Contents/MacOS/TrueCrypt

open -a TrueCrypt

1. click "Create Volume"
2. TrueCrypt Volume Creation Wizard: select "Create a file container"
3. click Next
4. Volume Type: select "Standard TrueCrypt volume"
5. click Next
6. Volume Location: click "Select File ..."
7. navigate to ~/Desktop with the file browser, then click "New Folder"
8. enter "Name of new folder": TrueCrypt, then click Create
9. enter in "Save As": MyTrueCrypt, then click Save
10. Volume Location: the "Select File ..." field should contain /PATH/TO/Desktop/TrueCrypt/MyTrueCrypt
11. click Next
12. Encryption Options:
    Encryption Algorithm: AES
    Hash Algorithm: RIPEMD-160
13. click Next
14. Volume Size: 3 MB
15. click Next
16. Volume Password: *********************  (more than 20 characters recommended)
17. click Next
18. Format Options: Filesystem Options: Filesystem type: select FAT
19. click Next
20. Volume Format: Move your mouse as randomly as possible within this window
21. click Format
22. "The TrueCrypt volume has been successfully created."
23. click OK
24. Volume Created
25. click Exit
26. click Close (to quit TrueCrypt)

open -a TrueCrypt

1. click "Select File ..."
2. navigate with the file browser to /PATH/TO/Desktop/TrueCrypt/MyTrueCrypt
3. click Open
4. click Mount and enter your password: *********************
5. double-click: Slot 1 : Volume: /PATH/TO/Desktop/TrueCrypt/MyTrueCrypt  Size: ...

touch '/Volumes/NO NAME/file.txt'    # or copy a text file to '/Volumes/NO NAME'
echo 'This is a test!' >> "$_"
cat '/Volumes/NO NAME/file.txt'
ls -l "$_"
# hdiutil unmount '/Volumes/NO NAME'

6. click Dismount
7. click Close


# References:
# Beginner's Tutorial, http://www.truecrypt.org/docs/?s=tutorial
# http://www.truecrypt.org/faq.php
# http://blogs.oreilly.com/digitalmedia/2008/03/truecrypt-51-open-source-file.html
# http://www.askstudent.com/security/a-step-by-step-guide-on-encrypting-files-using-truecrypt/
# http://techvj.blogspot.com/2007/03/secure-email-attachments-with-truecrypt.html


#------------------------------------------------


# download & install OSXCrypt, http://www.osxcrypt.org
man ocutil
ocutil
ocutil create -help

kextstat | grep OSXCrypt
ioreg -lw 0 | grep -i osxcrypt


# Example Usage

# Create a 200M volume, FAT formatted, using Seprent-Twofish-AES
ocutil create -verbose -fat -algorithm Serpent-Twofish-AES -size 200M MyCryptedVolume.img

# The same, but using also keyfiles
ocutil create -verbose -fat -keyfiles MyKeyFile1,MyKeyFile2,MyKeyFile3 -algorithm Serpent-Twofish-AES -size 200M MyCryptedVolume.img

# The same, but only using the keyfiles
ocutil create -verbose -fat -nopass -keyfiles MyKeyFile1,MyKeyFile2,MyKeyFile3 -algorithm Serpent-Twofish-AES -size 200M MyCryptedVolume.img

# Create an hidden volume of 100M, FAT formatted, using Serpent-AES, in a previously created volume
ocutil create -verbose -hidden -fat -algorithm Serpent-AES -size 100M MyCryptedVolume.img

# If the outer volume requires keyfiles you'll have something like ...
ocutil create -verbose -hidden -fat -algorithm Serpent-AES -keyfiles MyKeyFile1,MyKeyFile2,MyKeyFile3 -size 100M MyCryptedVolume.img

# If you want to add keyfiles to the hidden volumes to an outer volume with keyfiles, your command will be something like ...
ocutil create -verbose -hidden -fat -algorithm Serpent-AES -keyfiles MyKeyFile1,MyKeyFile2,MyKeyFile3 -size 100M -hidden_keyfiles MyHiddenKeyFile MyCryptedVolume.img

# The same as before but only with keyfiles for the hidden volume
ocutil create -verbose -hidden -fat -algorithm Serpent-AES -keyfiles MyKeyFile1,MyKeyFile2,MyKeyFile3 -size 100M -hidden_nopass -hidden_keyfiles MyHiddenKeyFile MyCryptedVolume.img

# Attaching a volume
ocutil attach -verbose MyCryptedVolume.img

# If the volume requires keyfiles
ocutil attach -verbose -keyfiles MyKeyFile1,MyKeyFile2,MyKeyFile3 MyCryptedVolume.img

# The same as before but only with keyfiles
ocutil attach -verbose -nopass -keyfiles MyKeyFile1,MyKeyFile2,MyKeyFile3 MyCryptedVolume.img

# Attaching an hidden volume
ocutil attach -hidden -verbose MyCryptedVolume.img

# Attaching a volume protecting its hidden volume
ocutil attach -protect_hidden -verbose MyCryptedVolume.img

# Detaching a volume
ocutil detach -verbose MyCryptedVolume.img
#ocutil detach -verbose device-name

# Generating one or more keyfiles
ocutil genkey -verbose output1.key [output2.key ...]

Lectura de archivo secuencial en C

// Ejemplo de lectura de archivo secuencial

#include <stdio.h>

void main()
{
    FILE *ptr;
    char nombre[15],c;
    int ok, edad;

    ptr = fopen("datos.txt", "r");

    do
    {
						/* Obtiene datos del archivo*/
        ok = fscanf(ptr, "%d %s", &edad, nombre);
	   if (ok)
           printf("Edad: %d\n Nombre:%s\n", edad, nombre); /* despliega en pantalla */
	   else
	   printf("*****Error en la lecura");
    }
    while (!feof(ptr));            /* Se repite hasta encontrar EOF (ctrl + z) */

    fclose(ptr);
    printf("pulse una tecla para continuar");
    scanf("%c", &c);
}

task_builder

""" functions for create single tasks from a distance matrix and a cast matrix

 (0 = not present; 1 = positive train; 2 = negative train; 3 = positive test; 4 = negative test).

        PTr NTr                 PTe NTe
       ---------               ---------
  PTr  | 1 | 2 | PTr       PTr | 1 | 2 | PTr
       ---------               ---------
  NTr  | 3 | 4 | NTr       NTr | 3 | 4 | NTr
       ---------               ---------
        PTr NTr                 PTe NTe        
"""

from numpy import *
from scipy import *

def gettaskID(cm, nfam = int(0)):
    '''seleziono le IDs corrispendonti alla colonna (task) nfam'''
    ids1=[]
    ids2=[]
    ids3=[]
    ids4=[]
    for j in range(0,131):
#        print cm[j][nfam]=="1"
#        print "cm[",j,"][0]=",cm[j][nfam]               
        if(cm[j][nfam]==1):
            ids1.extend([j])
        if(cm[j][nfam]==2):
            ids2.extend([j])
        if(cm[j][nfam]==3):
            ids3.extend([j])
        if(cm[j][nfam]==4):
            ids4.extend([j])
    return ids1,ids2,ids3,ids4

def get_labels_old(pos_threshold = 11, lnum = 74):
    labels = []
    for i in range(0,74):
        if(i<=pos_threshold):
            labels.append(1)
            i = i + 1
        else:
            labels.append(0)
    return labels

def get_labels_train(cm, nfam = int(0)):
    labels = []
    ptrain = 0
    ntrain = 0
    ptest = 0
    ntest = 0
    #for j in range(0,131):
    for j in range(0,len(cm)):
        if(cm[j][nfam]==1):
            ptrain = ptrain + 1
        if(cm[j][nfam]==2):
            ntrain = ntrain + 1
        if(cm[j][nfam]==3):
            ptest = ptest + 1
        if(cm[j][nfam]==4):
            ptest = ptest + 1
    for i in range(0,ptrain + ntrain):
        if(i<=ptrain):
            labels.append(1)
            i = i + 1
        else:
            labels.append(0)
    return labels

def get_labels_test(cm, nfam = int(0)):
    labels = []
    ptest = 0
    ntest = 0
    for j in range(0,len(cm)):
        if(cm[j][nfam]==3):
            ptest = ptest + 1
        if(cm[j][nfam]==4):
            ntest = ntest + 1
    for i in range(0,ptest + ntest):
        if(i<=ptest):
            labels.append(1)
            i = i + 1
        else:
            labels.append(0)
    return labels

def train_builder(dm, ids):
    ''' Creo il training set a partire dagli IDs nella cm '''
    train1 = []
    train2 = []
    train3 = []
    train4 = []
    # tr1 ids = (0,0)
    for i in ids[0]:
        for j in ids[0]:
            train1.extend([dm[i][j]])
            #print "dm[",i,"][",j,"]=",dm[i][j]
    atrain1 = array(train1)
    atrain1 = atrain1.reshape((len(ids[0]),len(ids[0])))
    #print atrain1.shape
    # tr2 ids  = (0,1)
    for i in ids[0]:
        for j in ids[1]:
            train2.extend([dm[i][j]])            
            #print "dm[",i,"][",j+1,"]=",dm[i][j]
    atrain2 = array(train2)
    atrain2 = atrain2.reshape((len(ids[0]),len(ids[1])))
    #print atrain2.shape
    # tr3 ids = (1,0)
    for i in ids[1]:
        for j in ids[0]:
            train3.extend([dm[i][j]])
            #print "dm[",i,"][",j+1,"]=",dm[i][j]
    atrain3 = array(train3)
    atrain3 = atrain3.reshape((len(ids[1]),len(ids[0])))
    #print atrain3.shape
    # tr4 ids = (1,1)
    for i in ids[1]:
        for j in ids[1]:
            train4.extend([dm[i][j]])
            #print "dm[",i,"][",j+1,"]=",dm[i][j]
    atrain4 = array(train4)
    atrain4 = atrain4.reshape((len(ids[1]),len(ids[1])))
    #print atrain4.shape  
    # Stacking together different arrays - Questo fa la magia
    atrain12 = hstack((atrain1,atrain2))
    atrain34 = hstack((atrain3,atrain4))
    atrain = vstack((atrain12,atrain34))                  
    return atrain

def test_builder(dm, ids):
    ''' Creo il test set a partire dagli IDs nella cm '''
    test1 = []
    test2 = []
    test3 = []
    test4 = []
    # test1 ids = (0,2)
    for i in ids[0]:
        for j in ids[2]:
            test1.extend([dm[i][j]])
    atest1 = array(test1)
    atest1 = atest1.reshape((len(ids[0]),len(ids[2])))
    #print atest1.shape
    # test2 ids  = (0,3)
    for i in ids[0]:
        for j in ids[3]:
            test2.extend([dm[i][j]])            
    atest2 = array(test2)
    atest2 = atest2.reshape((len(ids[0]),len(ids[3])))
    #print atest2.shape
    # test3 ids = (1,2)
    for i in ids[1]:
        for j in ids[2]:
            test3.extend([dm[i][j]])
    atest3 = array(test3)
    atest3 = atest3.reshape((len(ids[1]),len(ids[2])))
    #print atest3.shape
    # test4 ids = (1,3)
    for i in ids[1]:
        for j in ids[3]:
            test4.extend([dm[i][j]])
    atest4 = array(test4)
    atest4 = atest4.reshape((len(ids[1]),len(ids[3])))
    #print atest4.shape   
    # Stacking together different arrays
    atest12 = hstack((atest1,atest2))
    #print size(atest12)
    atest34 = hstack((atest3,atest4))
    #print size(atest34)
    atest = vstack((atest12,atest34))
    #print size(atest)
#    print atest12.shape
#    print atest34.shape
#    print atest.shape          
                       
    return atest

# ------------------------------------------------------------------------------
''' reading the files in as arrays - 2 way '''

dm_filename = ('../data/3PGK_DNA_BLAST_nolabels.txt')
cm_filename = ("../data/3PGK_30_nolabels.txt")
# 1. Using ScyPy
scipydati = io.array_import.read_array(dm_filename)
# 2. Using array
def read_array(filename):
    f = open(filename,'rb')
    dati = []
    for line in f.readlines():
        numbers = map(int, line.split())
        dati.append(numbers)
    f.close()
    return dati  
# --------------------------------------------------------------
''' Task Creation for task = NFAM'''

NFAM = 0
cm = read_array(cm_filename)
IDs = gettaskID(cm, nfam = NFAM)
dm = read_array(dm_filename)
trainset = train_builder(scipydati, ids=IDs)
testset = test_builder(scipydati, ids=IDs)
trainlabels = get_labels_train(cm, nfam = NFAM)
testlabels = get_labels_test(cm, nfam = NFAM)
#trainset = train_builder(dm, ids=IDs)
#testset = test_builder(dm, ids=IDs)

# --------------------------------------------------------------
''' write the trainset and the testset to a csv file'''
import csv

flag = 0
if (flag==1):    
    # last row contains class labels
    trainsetplus = vstack((trainset, trainlabels))
    testsetplus = vstack((testset, testlabels))
    trainsetplus_tr = transpose(trainsetplus)
    testsetplus_tr = transpose(testsetplus)
    writer = csv.writer(open("trainset_"+str(NFAM)+".csv", "wb"))
    writer.writerows(trainsetplus_tr)
    writer = csv.writer(open("testset_"+str(NFAM)+".csv", "wb"))
    writer.writerows(testsetplus_tr)
else: print"non salvo nulla"

# --------------------------------------------------------------

from svm import *

problem = svm_problem(trainlabels,trainset)
#param_linear_10 = svm_parameter(kernel_type = LINEAR, C = 10, svm_type = C_SVC)
param_rbf_10 = svm_parameter(kernel_type = RBF, C = 10, svm_type = C_SVC)
#m_lin = svm_model(prob, param_linear_10)
m_rbf = svm_model(problem, param_rbf_10)

#from cross_validation import *
#do_cross_validation(trainset, trainlabels, param_rbf_10, 10)
#do_cross_validation(trainset, trainlabels, param_linear_10, 10)

size = len(trainset)
kernels = [LINEAR, POLY, RBF]
kname = ['linear','polynomial','rbf']

param = svm_parameter(C = 10,svm_type = C_SVC)
for k in kernels:
    param.kernel_type = k;
    model = svm_model(problem,param)
    errors = 0
    for i in range(size):
        prediction = model.predict(trainset[i])
        probability = model.predict_probability
        if (trainlabels[i] != prediction):
            errors = errors + 1
    print "##########################################"
    print " kernel %s: error rate = %d / %d" % (kname[param.kernel_type], errors, size)
    print "##########################################"

Scrape torrents on btjunkie

// download all .torrent links on the btjunkie frontpage
//
// more fun with mechanize @
// http://tramchase.com/scrape-myspace-youtube-torrents-for-fun-and-profit

agent = WWW::Mechanize.new
agent.get("http://btjunkie.org/")
links = agent.page.search('.tor_details tr a')
hrefs = links.map { |m| m['href'] }.select { |u| u =~ /\.torrent$/ } # just links ending in .torrent
FileUtils.mkdir_p('btjunkie-torrents') # keep it neat
hrefs.each { |torrent|
  filename = "btjunkie-torrents/#{torrent[0].split('/')[-2]}"
  puts "Saving #{torrent} as #{filename}"
  agent.get(torrent).save_as(filename)
}

Scrape MySpace friend thumbnails

// fetch all img's from a myspace profile's .friendSpace div
// more @ http://tramchase.com/scrape-myspace-youtube-torrents-for-fun-and-profit

agent = WWW::Mechanize.new
agent.get("http://myspace.com/graffitiresearchlab")
links = agent.page.search('.friendSpace img') # found w/ firebug
FileUtils.mkdir_p 'myspace-images' # make the images dir
links.each_with_index { |link, index| 
  url = link['src']
  puts "Saving thumbnail #{url}"
  agent.get(url).save_as("myspace-images/top_friend#{index}_#{File.basename url}")
}

Scrape YouTube thumbnails

// fun with mechanize
// more @ http://tramchase.com/scrape-myspace-youtube-torrents-for-fun-and-profit

agent = WWW::Mechanize.new
url = "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed" # all time
page = agent.get(url)
# parse again w/ Hpcricot for some XML convenience
doc = Hpricot.parse(page.body)
# pp (doc/:entry) # like "search"; cool division overload
images = (doc/'media:thumbnail') # use strings instead of symbols for namespaces
FileUtils.mkdir_p 'youtube-images' # make the images dir
urls = images.map { |i| i[:url] }
urls.each_with_index do |file,index|
  puts "Saving image #{file}"
  agent.get(file).save_as("youtube-images/vid#{index}_#{File.basename file}")
end

Static Pages in Rails without Corresponding Controllers

// See if a file exists on a path provided by a record in your database

def show
	page_url = params[:url].join('/')
	if File.exists?("#{RAILS_ROOT}/app/views/pages/#{page_url}")
		render :template => "static/#{page_url}"
        end
end

Get remote file size, following redirects (PHP)

function get_remote_file_size($url, $readable = true){
   $parsed = parse_url($url);
   $host = $parsed["host"];
   $fp = @fsockopen($host, 80, $errno, $errstr, 20);
   if(!$fp) return false;
   else {
       @fputs($fp, "HEAD $url HTTP/1.1\r\n");
       @fputs($fp, "HOST: $host\r\n");
       @fputs($fp, "Connection: close\r\n\r\n");
       $headers = "";
       while(!@feof($fp))$headers .= @fgets ($fp, 128);
   }
   @fclose ($fp);
   $return = false;
   $arr_headers = explode("\n", $headers);
   foreach($arr_headers as $header) {
			// follow redirect
			$s = 'Location: ';
			if(substr(strtolower ($header), 0, strlen($s)) == strtolower($s)) {
				$url = trim(substr($header, strlen($s)));
				return get_remote_file_size($url, $readable);
			}
			
			// parse for content length
       $s = "Content-Length: ";
       if(substr(strtolower ($header), 0, strlen($s)) == strtolower($s)) {
           $return = trim(substr($header, strlen($s)));
           break;
       }
   }
   if($return && $readable) {
			$size = round($return / 1024, 2);
			$sz = "KB"; // Size In KB
			if ($size > 1024) {
				$size = round($size / 1024, 2);
				$sz = "MB"; // Size in MB
			}
			$return = "$size $sz";
   }
   return $return;
}

concatenate files

The correct syntax for the cat command is:

cat file1 file2 ... [fileN] > file

where file1, file2, fileN are the download images and "file" is the .iso file you are creating.