Monday, August 24, 2015

Reverse a list in python

Trick source


>>> L = [0,10,20,40]
>>> L[::-1]
[40, 20, 10, 0]

Wednesday, August 19, 2015

Set fontsize in matplotlib when saving in pdf

As matplolib uses a different backend depending the desired output, the results can be different when a figure is shown in the screen or saved as a pdf. Usually, the pdf generated figure has their titles/legends overlapped and with big fonts. The fix for this is first define a figure size when creating the figure and passing a dpi value when saving the figure in pdf:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(9, 9))

# plot your data

fig.savefig('file.pdf', dpi=200)

I've found so far that figsize=(9, 9) and dpi=200 make a good compromise.

Friday, August 14, 2015

Configure Logitech lateral mouse button to save in Sublime text II

Trick source

In the file

   ~/.config/sublime-text-2/Packages/Default/'Default (Linux).sublime-mousemap'

Add the following entry to the JSON data:

   { "button": "button8", "modifiers": [], "press_command": "save" }

The lateral mouse button is button number 8. In order to know what are the current button numbers, use the '''xev''' utility.

How to Move Location of VirtualBox Guest Mini ToolBar

Trick source

Before booting the virtual box machine, go to Display --> General --> Advanced Tab and CHECK the "Show at Top of Screen" checkbox.

Get Filesize in bash

Trick source


$ stat --printf="%s" file.ext

Upgrade GIT

Trick source

To upgrade Git itself to 2.x you can run these commands:

$   sudo apt-get install python-software-properties
$   sudo add-apt-repository ppa:git-core/ppa
$   sudo apt-get update
$   sudo apt-get install git


Next, confirm on the commandline that you are using the newer version:

$ git --version
   git version 2.4.6

Display a Markdown file in the terminal

Trick source

Using pandoc and lynx without creating temporary files:

$ pandoc file.md | lynx -stdin

lynx is installed as the lynx-cur package

Extract images embedded in a PDF

Trick source

You need to install poppler-utils.

Use pdfimages a PDF image extractor tool that saves images from a PDF file to PPM, PBM or JPEG file(s) format.

Usage: pdfimages [options]

Example: Save images in JPEG format


$ pdfimages -j in.pdf /tmp/out

Will save images from PDF file in.pdf in files /tmp/out-000.jpg (or /tmp/out-000.pbm; see below), /tmp/out-001.jpg, etc.

Extracted from pdfimages man page.

-j: Normally, all images are written as PBM (for monochrome images) or PPM for non-monochrome images) files. With this option, images in DCT format are saved as JPEG files. All non-DCT images are saved in PBM/PPM format as usual.

EDIT: Notice that this trick applies to the extraction of raster images!

Encode video in x.264 (mkv) using ffmpeg

Trick source


$ ffmpeg -i input -c:v libx264 -preset slow -crf 22 -c:a copy output.mkv

Note: ffmpeg must be compiled with x264 support. See this link for more info.

Exporting SVG to different formats

Trick source
Use Inkscape for this (from the command line):
  • export to bitmap (png)
    
    $ inkscape -f FILENAME.svg -e FILENAME.png
    
    
    loads FILENAME.svg and exports it to FILENAME.png
    
    $ inkscape -f FILENAME.svg -w WIDTH -h HEIGHT -e FILENAME.png
    
    
    loads FILENAME.svg and exports it to FILENAME.png with width size, WIDTH, and height size, HEIGHT, in pixels
  • export to pdf
    
    $ inkscape -f FILENAME.svg -A FILENAME.pdf
    
    
    loads FILENAME.svg and exports it to FILENAME.pdf
  • export to ps
    
    $ inkscape -f FILENAME.svg -P FILENAME.ps
    
    
    loads FILENAME.svg and exports it to FILENAME.ps
  • export to eps
    
    $ inkscape -f FILENAME.svg -E FILENAME.eps
    
    
    loads FILENAME.svg and exports it to FILENAME.eps

Insert LaTeX equations in Inkscape

Trick source

"Recent versions of Inkscape (since 0.48?) have built-in support for including a LaTeX formula inside a drawing. It is on the menu bar: Extensions->Render->LaTeX Formula. This menu might be hidden if Inkscape cannot find these helper programs: latex, dvips, pstoedit. On Ubuntu, you can install these programs with the command,

$  sudo apt-get install texlive pstoedit

Alternatively, you can use the textext extension. It is similar to the build-in LaTeX support, but has a slightly more polished input interface."

(Re)install / upgrade Flash plugin

Trick source

Some days ago adobe flash complained to launch in my browser (firefox), due to a vulnerability, and asked to be updated, that's the trick in Mint17 (and Ubuntu):

$ sudo add-apt-repository "deb http://archive.canonical.com/ trusty partner"
$ sudo apt-get update
$ sudo apt-get install adobe-flashplugin

Extract a (vector) figure from a pdf

In Linux (Mint 17) a (semiautomatic) trick that worked for me is, first extract the page with the desired vector figure using pdftk:

$ pdftk book.pdf cat 51 output page.pdf

in this case, the page 51 from the file book.pdf is extracted into the file page.pdf
Then using Inkscape, it is possible to open the file page.pdf, select the figure, copy and paste it in a new window, then save it as a new pdf (as a vector image), ready to be included in LaTeX!

Fix for Audacity in Mint17

Trick source

The problem: I can record sound (I can see the waveform) but when I try to play it back there is no sound output or it sounds noise yap-yap-yap and audacity moves through the audio very quickly. If I press play repeatedly eventually the entire GUI freezes. On the command line it gets this error:

    ALSA lib pcm.c:7843:(snd_pcm_recover) underrun occurred

The fix is the same as the fix for the sound issues in Skype. For launching Audacity from the desktop do:

$ sudo sed -i 's/^Exec=.*/Exec=env PULSE_LATENCY_MSEC=30 audacity %U/' /usr/share/applications/audacity.desktop

for launching the program from the command line the hack is make the same than for skype, create a bash script to wrap the PULSE_LATENCY_MSEC variable only for audacity:

$  sudo bash
$  cd /usr/bin # here is audacity
$  cp audacity audacity.bin
$  pico audacity

once pico is opened, write the script:

#!/bin/bash
    
PULSE_LATENCY_MSEC=30
export PULSE_LATENCY_MSEC
/usr/bin/audacity.bin $@

then give it global execution permissions

$ chmod ugo+x audacity

BASH: for Loop File Names With Spaces

Trick source


 #!/bin/bash
 SAVEIFS=$IFS
 IFS=$(echo -en "\n\b")
 for f in *
 do
   echo "$f"
 done
 IFS=$SAVEIFS

Convert text to an image

Trick sour ce


$ echo "My text" | convert -background black -fill white -font Ubuntu-Mono-Bold -pointsize 40 label:@- text.jpg

In order to check the available fonts for ImageMagik:

$ convert -list font

Change default zoom level in Firefox

Trick source

Needed for my 3:4 monitor (portrait mode):
If you want to set the text size/pixel density in firefox different from that of your system's settings like it was handled in prior versions, enter about:config into the firefox address bar (confirm the info message in case it shows up) & search for the preference named layout.css.devPixelsPerPx. double-click it and change its value to 1.0 (or any other zoom factor that fits your purpose; -1.0 is the default value and will adhere to the system settings). In my particular case I needed the browser zoomed at 90%, so the value put is: 0.9

Weird error in MYSQL

Trick source

I got this trying to calculate the standard deviation of a dataset:

mysql> select STDEV_SAMP(precipitation_av) from p_year_averages where lon='-6.25' and lat='35.05';
   ERROR 1548 (HY000): Cannot load from mysql.proc. The table is probably corrupted

Googling a bit, it seems that the fix is simple. In Ubuntu:

$ sudo mysql_upgrade -u root -p

It will ask your system password, then your Mysql password. Then the problem is gone.

Concatenate two videos

Trick source

Concatenation of files with same codecs The concat demuxer was added to ffmpeg 1.1 . Get the lastest STATIC version of ffmpeg from: http://ffmpeg.gusari.org/static/ . Instructions Create a file "mylist.txt" with all the files you want to have concatenated in the following form ( Lines starting with a dash are ignored ) :

 # this is a comment
 file '/path/to/file1'
 file '/path/to/file2'
 file '/path/to/file3'

Note that these can be either relative or absolute paths. Then you can encode your files with:

$ ffmpeg -f concat -i mylist.txt -c copy output

RAR files into a multivolume set

Trick source

To compress a big video file, movie.avi and split it into multiple files, each size up to 12MB,

$  rar a -m5 -v12m myarchive.rar movie.avi

if it is a directory:

$  rar a -m5 -v12m myarchive.rar dir/*

A list of files (myarchive.part1.rar, myarchive.part2.rar, ..) will be created in current directory. You may change the compression quality, -m5 is the best and the slowest, while -m0 do no compression at all (-m3 is default). Use -v4480m in order to get 4Gb chuncks (to put in a whole DVD each one)

Skype fixes for ubuntu 13.04

Trick source
  • Pulse audio not detected: The Skype binary is 32bit and it is linked against a 32bit version of GStreamer, but the 32bit version of the PulseAudio client isn’t installed by default. This is easily fixed by running:
    
      $ sudo apt-get install libpulse0:i386
    
    
    Once done this pulseuadio will be recognized, but the sound will be garbled the fix is
  • Go to /usr/bin
  • rename the skype executabe for skype.bin
  • Create the following script and name it as /usr/bin/skype
    
     #!/bin/bash
     PULSE_LATENCY_MSEC=60 skype.bin
    
    

Replace a String in a file

trick source

Imagine you have a large file ( txt, php, html, anything ) and you want to replace all the words "ugly" with "beautiful" because you just met your old friend Sue again and she/he is coming over for a visit. This is the command:

 $ sed -i 's/ugly/beautiful/g' /home/bruno/old-friends/sue.txt

Well, that command speaks for itself "sed" edits "-i in place ( on the spot ) and replaces the word "ugly with "beautiful" in the file "/home/bruno/old-friends/sue.txt"
DOCX on the spot Write in markdown, convert to docx ... :P
First install pandoc:

$ sudo apt-get install pandoc

Then use it:

$ pandoc -f markdown -t docx fileIn.md -o fileOut.docx

Montage of a series of document scans

Assume that we have 22 scanned docs called giro-n.jpg (portrait). This bash code will join two by two documents in one image (landscape), rescale the image to letter size and rotate 90deg in order to put them back in portrait:

c=1; 
for q in `seq 1 11`; 
  do 
     echo $q;   
     montage giros-${c}.jpg  giros-`echo $c + 1| bc`.jpg \
      -geometry 2544x3508 - | convert - -resize 3508x2544 \
      -rotate 90 join/`printf %02d $q`.jpg ; 
     let c=$c+2; 
  done;

The processed images will be in the join/ directory. Then, in order to create a sinlge pdf with all the images, use this python script:

#!/usr/bin/env python
 
import sys
import os
import glob
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
 
 
if len(sys.argv) < 1:
        print "no args"
        print "usage: this_script outfile.pdf"
        exit
 
 
outpdf=sys.argv[1]
w, h = letter
c = canvas.Canvas(outpdf, pagesize=letter)
 
for filename in sorted(glob.glob("*jpg")):
 s = c.drawImage( filename, 0,0, width=w, height=h, mask=None) 
 print "[", filename,"]"
 c.showPage()
 
c.save()

XFCE under VNC doesn't make tab autocompletion

From http://ubuntuforums.org/archive/index.php/t-1771058.html
"I accidentally discovered a fix for this while trying to solve a different problem. Edit

~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml

find the line

<property name="<Super>Tab" type="string" value="switch_window_key"/>

and change it to

<property name="<Super>Tab" type="empty"/>

reboot or whatever and then tab will work properly! I have no idea why but when using vnc this file seems to override tab's normal behaviour and makes it into a switch window key."

Convert problematic .ps files into pdf

Especially those dynamic pdfs that do not allow to save. So an option is to print the into a .ps. However, those files aren't unable to be reconverted back into pdf (which is a problem is they are going to be printed in Windows). So in Linux the trick to force the conversion into pdf is:

$ gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -dGraphicsAlphaBits=4 -sOutputFile=page_%02d.png -r600 problem_file.ps

this creates png files at 600ppi (don't worry, due to the -r600 the document won't be pixelated). Then, the png are converted into pdfs:

$ convert page_01.png page_01.pdf

do this for each png generated by gs. Finally, assemble everything into a single pdf:

$  pdftk page_01.pdf page_02.pdf page_0n.pdf  cat output fixed_file.pdf

Build a (silent) movie from jpeg images using mencoder


$ mencoder "mf://*.JPG" -mf fps=30 -ovc x264 -vf scale=1980:1080  -o mymovie3.avi

Epson Perfection 610 Xsane bug fix

Trick source

Doing a preview in color mode issued an error. The fix:

$ sudo gedit /etc/sane.d/dll.conf

if the following two lines look like:

 #epson
 epson2

change them to:

 epson
 #epson2

Save, and re-open xsane.

Install Oracle Java 7 on Ubuntu 12.04 x64

Trick source


$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-jdk7-installer

UPDATE for java8/9:

$ sudo apt-get install oracle-java8-installer

Python Executable Zipfiles

Trick source

From the site:
"A new feature that was quietly sneaked into Python 2.6, without the fanfare it deserves, is the ability to distribute Python applications as executable zipfiles. Python has long had support for importing modules and packages from zipfiles - through the oh-so-badly-needed-in-IronPython [1] zipimport. What is new is the ability to make zip archives executable. If you call the Python 2.6+ (or 3.0+) interpreter passing in a zip file instead of a Python file - the interpreter looks inside the zip file for a Python file named __main__.py (at the top-level) and executes it. The zip file can also contain all the (pure-Python only) modules and packages your app depends on. This is a great way of distributing applications as a single file. The nice thing is that the Python interpreter doesn't depend on the extension to recognise zipfiles, instead recognising them automagically. This means that on Windoze you can give these archives a new extension (perhaps '.pyz') and associate them with Python 2.6 - allowing Windows to execute them automatically when you double click on them in explorer. I think, but am not 100% certain, that the zipfile specification is flexible enough that you could also prepend a pound-bang ('#!') interpreter line to make them executable under Mac OS X and Lunix type platforms."

michael$ echo > __main__.py "print 'Hello world'"
michael$ python __main__.py
Hello world
michael$ zip test.zip __main__.py
  adding: __main__.py (stored 0%)
michael$ python test.zip
Hello world

UPDATE: Floris Bruynooghe notes in the comments that you can add a hash-bang line to a zipfile and make it executable:

$ cat > __main__.py
print('hi there')
^D
$ zip test.zip __main__.py
adding: __main__.py (stored 0%)
$ cat > hashbang.txt
#!/usr/bin/env python3.0
^D
$ cat hashbang.txt test.zip > my_exec
$ chmod +x my_exec
$ ./my_exec
hi there
$

Inkscape: make arrowhead of the same color then the line

In some old versions of Inkscape arrowhead did not match its line color. In order to fix this, select the line with the arrowhead, then go to Extensions > Modify Path > Color Markers to Match Stroke and voila!!

Write japanese in LaTeX

Trick source

Install these packages:

$ sudo apt-get install latex-cjk-common
$ sudo apt-get install latex-cjk-japanese

A minimum document:

\documentclass{memoir}
 
\usepackage{CJKutf8}
 
\begin{document}
 
\begin{CJK}{UTF8}{min}未練なく散も桜はさくら哉\end{CJK} \\
\begin{CJK}{UTF8}{maru}未練なく散も桜はさくら哉\end{CJK} \\
\begin{CJK}{UTF8}{goth}未練なく散も桜はさくら哉\end{CJK} \\
without regret \\
they fall and scatter\ldots \\
cherry blossoms
 
\end{document}

The min, maru, and goth selects the font. In order to write furigana (for children and begginers as me ;) ) use the ruby package:

\documentclass{memoir}
 
\usepackage{CJKutf8}
\usepackage[overlap,CJK]{ruby}
 
\begin{document}
 
%% I find the default \rubysep (-0.5ex) too tight, so
%% let's enlarge it a little.
\renewcommand\rubysep{-0.2ex}
 
\begin{CJK}{UTF8}{min}
イスキエルド\ruby{先生}{せんせい}は\ruby{私}{わたし}を\ruby{愛}{あい}して
\end{CJK}
 
\end{document}

Alternatively, xelatex can be used instead.

Send back a MS Excel file from PHP

Trick source
This 'beautiful' mesh of http headers are needed to get IE downloading the file!!!

header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Type: application/vnd.ms-excel");                 //* Decent browsers only need 
header("Content-Disposition: attachment; filename=coupons.xls" ); //* these two headers
header("Content-Transfer-Encoding: binary");      
header("Content-Length: " .  filesize("file.xls") ); 
 
 
readfile("file.xls");

Open webcam using mplayer


$ mplayer -cache 128 -tv driver=v4l2:width=640:height=480 -vo x11 tv://

Dump audio of a video into a .wav file using mplayer


$ mplayer -vo null  -ao pcm:file=audio.wav  video.avi

or

$ mplayer -vo null -vc null -ao pcm:fast  -ao pcm:file=audio.wav  video.avi

Switch rdesktop to fullscreen

To toggle fullscreen mode simply type the following key combination: CTRL-ALT-ENTER

Activate SQLite support in PHP


$ sudo apt-get install php5-sqlite

Convert a video to webm


$ ffmpeg -i CelloWars.mp4 -s 558x314 -aspect 16:9 -vb 500000 Cello.webm

Poor man's way to generate an excel file in PHP

(Trick source)
Just create a regular .PHP file, where you output your data in a nice little html-table. Then place the following snippet in the top of that file (no output can happen before these lines, as they change your headers - so place these all the way at the top):

<?php
header(“Content-type: application/vnd.ms-excel”);
header(“Content-Disposition: attachment; filename=excel.xls”);

...

And it’s just that easy. If you open the page, you’ll see a download-window asking you where to place the file. The headers will tell your computer that it’s an Excel-file, which will parse your html-table (assuming you’ve written it without errors) and display it nicely.

Where is the config file of vinagre?


 ~/.local/share/vinagre/history

Using rsync to make backup


rsync --verbose  --progress --stats --recursive --times \
      --perms --links --delete /path/to/origin /path/to/destination

Skype on Ubuntu 11.04 64Bit webcam fix

This is and old trick that eventually would be useful in newer versions of skype. Problem: webcam doesn't work!! It seems that the problem lies that skype does not load the corresponding 32bit- video for linux 1 libraries. In order to fix the issue: Goto /usr/bin and locate the binary file for skype. Rename it to skype.bin

$ mv skype skype.bin

Create in the same directory a new file called skype and put in it:

#!/bin/bash
LD_PRELOAD=/usr/lib32/libv4l/v4l1compat.so /usr/bin/skype.bin $@

Change the permissions to make it executable:

$ chmod ugo+x /usr/bin/skype

and voilà!

String manipulation in bash


#!/bin/bash

a="MANUEL ARTURO IZQUIERDO"
l=`echo ${#a}-1 | bc`

for q in `seq 0 $l` 
do 
   echo "|'''"${a:$q:1}"'''"
done


get the output:

 |'''M'''
 |'''A'''
 |'''N'''
 |'''U'''
 |'''E'''
 |'''L'''
 |''' '''
 |'''A'''
 |'''R'''
 |'''T'''
 |'''U'''
 |'''R'''
 |'''O'''
 |''' '''
 |'''I'''
 |'''Z'''
 |'''Q'''
 |'''U'''
 |'''I'''
 |'''E'''
 |'''R'''
 |'''D'''
 |'''O'''

The access to the string goes in the form:

 ${varname:index:lenght}

NTFS filesystem creation in linux

(Trick source)

$ mkntfs -L TRASTEOS -Q /dev/sdg1

  • -L: Volume name.
  • -Q: Quick format

Note: the partition must to have the fstype flag set to 7

Scan an image from the (Linux) command line

(Trick source)

$ scanimage  --resolution 300  > scan.ppm 

Imagemagick can be used to convert the output to jpeg:

$ scanimage --resolution 90 | convert - -quality 80% image.jpg

See the scanimage manpage for more info.
Note: the --resolution option is not documented in the manpage!.

Bash: Nasty data reformat

I received a dataset composed by several files with this layout:

 A20C3M1_precip_1930_Europe.ascii
 A20C3M1_precip_1931_Europe.ascii
 A20C3M1_precip_1932_Europe.ascii
 A20C3M1_precip_1933_Europe.ascii
 A20C3M1_precip_1934_Europe.ascii
 A20C3M1_precip_1935_Europe.ascii
 ...

Each file had data like:

  36.761, -15.000,  21.732,  12.170,   7.797,  23.551,  12.186,  19.196,  30.779,  27.348,  32.999,  31.810,  16.109,  17.105
  39.296, -15.000,  84.459,   3.269,   5.787,  19.614,  19.731,  11.071,  25.962,  20.152,  20.350,  19.952,   9.661,  16.531
  41.831, -15.000,  99.225,   0.090,   0.000,   9.166,  18.276,   0.000,   0.000,   0.000,   6.851,  31.107,   3.937,  19.640
  44.366, -15.000,  64.088,   0.000,   0.000,   2.215,   7.657,   0.410,   0.000,   0.000,   6.258,  35.478,   0.388,  15.106
  ...

So I had a year series, a file for each year. Now inside the file I had a pair of coordinates (lat,lon) in the fist two columns denoting a "weather station". Then columns 3 to 14 marked a precipitation value for each month of that year. My mission was to reformat this info in one file for each station, having the values in this layout:

 STATION_[36.761,0.000].dat
 1930  1 3676
 1930  2 0
 1930  3 6439
 1930  4 7340
 1930  5 5179
 1930  6 5577
 1930  7 6001
 1930  8 5937
 1930  9 7331
 1930  10 3211
 1930  11 2632
 1930  12 9107
 1931  1 3676
 1931  2 0
 1931  3 11038
 1931  4 3409
 1931  5 6754
 1931  6 3821
 1931  7 2231
 1931  8 7168
 1931  9 6209
 1931  10 10026
 1931  11 8913
 1931  12 14465
 1932  1 3676
 1932  2 0
 1932  3 9029
 ...

which is the input format for the SPI program. My mission was to use the program with the provided data, so I had to reformat the entire dataset. This bash script does the job (perhaps not very time-efficient, but effective!!)

#!/bin/bash
##########################################################################
## Reformats the precipitation dataset to SPI input format
## Manuel Arturo Izquierdo  (c) 2011
## Run this script inside the directory with the origianl ascii files
##########################################################################


mkdir SPI_INPUT
header=1

# Use A20* for the A20C3M1 dataset
#for dataf in A20*  
# Use HLG* for the HLGM15B dataset
for dataf in HLG*
do
    year=`echo $dataf | cut -d'_' -f4` #use -f4 for HLG* , -f3 for A20*
    year=`echo $year+1700 |bc` #  HLG* only

{ 

    echo "Year: $year"

    while : 
    do 
    read a 
    if test "$a" == ""
    then
       break
    fi
    lon=`echo $a | cut -d',' -f1`
    lat=`echo $a | cut -d',' -f2`
    coord=`echo $lon$lat|cut -d' ' -f1`,`echo $lon$lat|cut -d' ' -f2`
    station='STATION_['$coord'].dat'
    if test "$header" -eq "1"
    then
       echo $station >> SPI_INPUT/$station
    fi
  
    for m in `seq 3 14`
    do
      let month=$m-2 
      aridity=`echo $a | cut -d',' -f$month`
      aridity=`echo "(($aridity*100)+0.5)/1"| bc` #aridity x 100 and integer
      echo "$year  $month $aridity" >> SPI_INPUT/$station
   
    done
  
    done 
} < $dataf

header=`echo $header+1|bc`

done


The script generates a collection of files STATION_[''lat'',''lon''].dat for each station, in the required format. I found the trick to convert from float to int using bc: http://www.alecjacobson.com/weblog/?p=256. et voilà!!

Export data in Excel from Python

(Trick source)

Use the pyExcelerator library found at http://sourceforge.net/projects/pyexcelerator/ . This is a test code:

import pyExcelerator as xl

def save_in_excel(headers,values):
    #Open new workbook
    mydoc=xl.Workbook()
    #Add a worksheet
    mysheet=mydoc.add_sheet("test")
    #write headers
    header_font=xl.Font() #make a font object
    header_font.bold=True
    header_font.underline=True
    #font needs to be style actually
    header_style = xl.XFStyle(); header_style.font = header_font
    for col,value in enumerate(headers):
        mysheet.write(0,col,value,header_style)
    #write values and highlight those that match my criteria
    highlighted_row_font=xl.Font() #no real highlighting available?
    highlighted_row_font.bold=True
    highlighted_row_font.colour_index=2 #2 is red,
    highlighted_row_style = xl.XFStyle(); highlighted_row_style.font = highlighted_row_font
    for row_num,row_values in enumerate(values):
        row_num+=1 #start at row 1
        if row_values[1]=='Manatee':
            for col,value in enumerate(row_values):
                #make Manatee's (sp) red
                mysheet.write(row_num,col,value,highlighted_row_style)
        else:
            for col,value in enumerate(row_values):
                #normal row
                mysheet.write(row_num,col,value)
    #save file
    mydoc.save(r'testpyexel.xlt')

headers=['Date','Name','Localatity']
data=[
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Manatee','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Manatee','San Jose'],
]

save_in_excel(headers,data)

Get number of CPU's in python

(Trick source)

import multiprocessing
multiprocessing.cpu_count()

Import a .csv file into SQLite3

First, a table with the same structure of the .csv file must be created, then this must be done:

$ sqlite3 database.sqlite

Then,

sqlite> .mode csv
sqlite> .import /path/to/csv/file.csv table_name

Alternatively, sqlite-manager can do the job as well.

Python: "sleep" command like the bash's sleep


import time
time.sleep(secs)

The argument may be a floating point number to indicate a more precise sleep time.

Resize an image in ImageMagick without proportions


$ convert SLIDE_-01.ppm -resize 720x486\! pp.png

The \! is important.

Python: Count the number of times a string is present in a file


import string
text = open(fname).read()
print string.count(text, 'the_string')

B/W dither of a color image

See http://www.imagemagick.org/Usage/quantize/#dither_error

convert  logo.png  -monochrome     monochrome.gif

Fix filenames with caracters with an non utf-8 encoding


$ for a in *; do convmv -f latin1 -t utf8 --notest "$a"; done

Clean and compress images of scanned pages

In bash:

 for a in *JPG; 
 do gm convert $a -rotate -90 -colorspace gray PPM:- | gm convert - -threshold $v CBR/${a%.JPG}.png;
 echo $a; 
 done

gm stands for graphicmagick, which is a *faster* clone of Imagemagick $v is a calibration value between 0 and 255 (in Imagemagick it spans between 0 and 65535 ).

Create a Comicbook (cbr)

Compress the images into a .rar file but with a .cbr extension

rar a book_title.cbr *png

Force imagemagick to send the converted img to stdout in a given format


convert IMG_6454.JPG ppm:- > pp.ppm
                     ----- 
                       ^----> that's the trick

IF function in oocalc (aka localc)


    =IF(D174 = D175 ; "*";"")
            ^          ^   ^
         condition   then  else

KDE's trash directory location


 /home/username/.local/share/Trash/files

Convert to grayscale, rotate, and correct luminosity in ImageMagick


convert IMG_6160.JPG -rotate -90 -level 35,60% -colorspace gray pp.jpg

Insert pages from another pdf my my latex doc

from: http://magic.aladdin.cs.cmu.edu/2005/07/02/splitting-and-joining-pdfs-by-pdftk/

even better, use the pdfpages package in tex. as easy as:


\usepackage{pdfpages}
\includepdf[specify pages, mode, how many per page]{file.pdf}


pdflatex foo.tex

PHP: force a confirmation dialog in the browser when downloading a file

Trick source: http://ca.php.net/manual/en/function.header.php Example 1570.

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

   
<?php
    // We'll be outputting a PDF
    header('Content-type: application/pdf');
    
    // It will be called downloaded.pdf
    header('Content-Disposition: attachment; filename="downloaded.pdf"');
    
    // The PDF source is in original.pdf
    readfile('original.pdf');
?>

Imagemagick montage example


montage -title "item_tortero" -label "%f" -geometry 300x250+10+8  *jpg index.jpg

Remove noise of an image (about 70%)


convert  15194.jpg -resize 200% -blur 3  - | convert - -scale 50% filter/15196.jpg

do the same a make the image brighter:

convert  15194.jpg -resize 200% -blur 3 -level 0,55% - | convert - -scale 50% filter/15197.jpg