├── README.md ├── R_tricks.R ├── application_tricks.note ├── bash_tricks.sh ├── bio_tricks.sh ├── css_tricks.css ├── excel tricks.txt ├── git_tricks.sh ├── gmail tricks.txt ├── idle_tricks.txt ├── illustrator_tricks.txt ├── javascript_tricks.js ├── latex_tricks.tex ├── markdown tricks.markdown ├── microarray_tricks.txt ├── octopress_tricks.markdown ├── python_tricks.py ├── ruby_tricks.rb ├── ruhoh_tricks.txt ├── scope_selectors_trick.txt ├── statistical_tricks.R ├── wiki_tricks.txt └── writing tricks.txt /README.md: -------------------------------------------------------------------------------- 1 | Every code snippet that I have had to look up twice gets added here (R, bash, ruby, python, awk, and other beauties). -------------------------------------------------------------------------------- /application_tricks.note: -------------------------------------------------------------------------------- 1 | ### BetterMarkdown sublime 2 | Asterisks and underscores are autopaired and will wrap selected text 3 | If you start an empty pair and hit backspace, both elements are deleted 4 | If you start an empty pair and hit space, the right element is deleted 5 | backticks are paired 6 | Left bracket pairing is modified to eliminate the selection and leave the cursor at a point where you can insert a [] or () pair for a link 7 | ⌘⌥V will paste the contents of the clipboard as an inline link on selected text 8 | ⌘⌥R will paste the contents of the clipboard as a reference link 9 | ⌘⌥K inserts a standard inline link, ⌘⇧K inserts an inline image 10 | ⌘⌥B and ⌘⌥I are bound to bold and italics (Markdown). 11 | ~ triggers HTML tags (strikethrough) to selected text 12 | Typing "#" when there’s a selection will surround it with "#" to make it a headline. Multiple presses add additional hashes, increasing the level of the header. Once you hit 6 hashes, it will reset to 0 on the next press. The match_header_hashes will determine if the # are mirrored on both sides or just at the beginning of the line. 13 | Typing return at the end of a line that begins with hashmarks will insert closing hashmarks on the headline. They’re not required for Markdown, it’s just aesthetics, and you can change the match_header_hashes option in your settings to disable. 14 | ⌘^1 through ⌘^6 will add the corresponding number of hashmarks for headlines. Works on blank lines and selected text. in tandem with the above headline tools. 15 | ⌘⇧6 will insert a footnote and jump to its definition. If your cursor is in a definition, it will jump back to the marker. 16 | ⌥⇧F will locate footnote markers without definitions and insert the marker for the definition 17 | ⌥⇧G will do the same for missing reference links 18 | 19 | ### iTerm 20 | ⌘⇧⌥ to move a window to a tab 21 | # set up profiles|keys|xterm with numeric keypad 22 | # choose +, option left arrow, send escape sequence, b 23 | # choose +, option right arrow, send escape sequence, f 24 | 25 | ### Quicktime 26 | # playback speed (you don’t even need to hit play) 27 | command + arrows 28 | 29 | ### OSX 30 | # invert colors 31 | ^⌘⌥8 32 | # zoom in 33 | ^ + zoom with trackpad 34 | 35 | # login hooks, run on startup login 36 | sudo defaults write com.apple.loginwindow LoginHook my/app 37 | 38 | ### Chrome 39 | ⌘⌥` - back history 40 | ⌘⌥+ - forward history 41 | 42 | ### Sublime Text 43 | 44 | { 45 | "line_numbers": false, 46 | "gutter": false, 47 | "draw_centered": true, 48 | "wrap_width": 80, 49 | "word_wrap": true, 50 | "scroll_past_end": true 51 | } 52 | 53 | 54 | # select all 55 | cmd+ctrl+g 56 | 57 | # change case camel 58 | To snake_case: "ctrl+alt+c", "ctrl+alt+s" 59 | to camelCase: "ctrl+alt+c", "ctrl+alt+c" 60 | 61 | # change theme (font size sidebar) 62 | /Users/nacho/Library/Application Support/Sublime Text 2/Packages/Theme - Default/Default.sublime-theme 63 | 64 | # close old tabs (tidytabs) 65 | ctrl+alt+w 66 | 67 | # create new file from current path 68 | cmd+alt+n 69 | 70 | # new build 71 | "cmd": ["Rscript", "-e", "library(knitr)"] # use this 72 | "cmd": ["Rscript -e ’library(knitr)’"] # not this 73 | 74 | # open selection in chrome 75 | ^⌥U 76 | 77 | ^Q - toggle record macro 78 | ^⇧Q - run macro 79 | 80 | ⌘F2 - toggle bookmark 81 | F2 - go to bookmark 82 | ⌘⇧F2 - clear bookmarks 83 | 84 | select url + ^⌥u - open url in Chrome 85 | ⌘⌥ arrows - switch tabs 86 | ^+TAB - previous tab on stack 87 | ^2 - Focus split window group 2 88 | ^⇧2 - Move current file to split window group 2 89 | 90 | ⌘⌥ o - toggle overwrite 91 | ⌘⇧ p - choose action. Ex: Package Control 92 | ⌘⇧ h - HTMLpretiffy 93 | F6 - Spell Check 94 | F11 - Show console 95 | ⌘K⌘D - skip while quick adding 96 | ^º console 97 | ddd d 98 | F7 - build tmLanguage from JSON-tmLanguage 99 | ^D - diff with previously saved version of file 100 | 101 | 102 | 103 | ### SFTP 104 | ^⌘ UE - Download Current Folder 105 | ^⌘ UX - Cancel Operation 106 | ^⌘ US - Show Panel 107 | ^⌘ RB - Browse Server 108 | ^⌘ UR - Upload Folder 109 | ^⌘ UF - Upload File 110 | ^⌘ UN - Upload Open Files 111 | ^⌘ UI - Diff with Remote 112 | ^⌘ UY - Sync Local => Remote 113 | ^⌘ UM - Monitor File 114 | ^⌘ UW - Browse Remote 115 | 116 | ### screen 117 | 118 | ### RTM 119 | 120 | ### google cl 121 | google [picasa|blogger|youtube|docs|contacts|calendar|finance] TASK [options] 122 | 123 | google help calendar 124 | google calendar today 125 | google calendar list --query GLM 126 | google calendar list -d tomorrow 127 | google calendar list -d 2012-03-13 128 | 129 | google calendar add "go to class at 2pm" --reminder 5m 130 | 131 | -d DATE, --date=DATE Calendar only - date of the event to add/look for. Can 132 | also specify a range with a comma. Picasa only - sets 133 | the date of the album Finance only - transaction 134 | creation date 135 | 136 | ### voicemail 137 | 1 138 | 2 139 | 3 140 | 4 - replay 141 | 5 142 | 6 143 | 7 - erase 144 | 8 145 | 9 146 | 0 147 | 148 | ### mldonkey 149 | telnet 127.0.0.1 4000 150 | s blah blah 151 | s -format pdf 152 | xs 153 | vr [num] 154 | d [num] 155 | c # connect to more servers -------------------------------------------------------------------------------- /bash_tricks.sh: -------------------------------------------------------------------------------- 1 | # moving directories: mv what_you_are_moving folder_inside_which_you_move_it 2 | rm -rf prueba1 prueba2 # reset 3 | mkdir prueba1 prueba2 4 | touch prueba1/a prueba1/b prueba1/c prueba2/a prueba2/c 5 | 6 | # split the path into its elements 7 | echo $PATH | tr ":" "\n" | sort 8 | # /Users/oliver/.cabal/bin 9 | # /Users/oliver/.rvm/bin 10 | 11 | mv prueba1 prueba2 # ls prueba2 => a c prueba1/ 12 | mv prueba1/* prueba2 # asks if you want to overwrite prueba2/a and prueba2/c 13 | 14 | rm -rf prueba1 prueba2 # reset 15 | mkdir prueba1/dir prueba2/dir # -p by alias (default) 16 | touch prueba1/dir/a prueba1/dir/b prueba1/dir/c prueba2/dir/a prueba2/dir/c 17 | 18 | mv prueba1 prueba2 # ls prueba2/prueba1/dir => a b c 19 | mv prueba1/* prueba2 # asks if you want to overwrite prueba2/dir, it doesn't allow it because prueba2/dir is not empty. 20 | 21 | # pairwise merge skimpdf 22 | skimpdf merge a.pdf b.pdf ab.pdf 23 | 24 | # available cores in cluster 25 | qstat -g c 26 | 27 | # what hw installed hardware 28 | system_profiler 29 | dmidecode # linux 30 | 31 | # xls to txt 32 | xls2csv -q0 -b"--new_sheet--" data_s1.xls > data_s1.txt # -q0 no quotes, watch -g5 number precision 33 | 34 | # copy symlink 35 | cp -R symlink 36 | # update brew 37 | brew update 38 | 39 | # brew upgrade outdated formulas 40 | brew upgrade 41 | 42 | # download concurrently from same server wget (-j is number concurrent downloads) 43 | aria2c -x8 URL 44 | aria2c -s8 URL #also try 45 | 46 | # download and unzip (save as script) 47 | #!/bin/bash 48 | TMPFILE=`tempfile` 49 | PWD=`pwd` 50 | wget "$1" -O $TMPFILE 51 | unzip -d $PWD $TMPFILE 52 | rm $TMPFILE 53 | 54 | # see all characters in text 55 | grep -oE . text.txt | sort -u | tr -d "\n" # '()*+,-./0123456789:;>ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz 56 | 57 | # show non-printing special characters 58 | cat -v # show non-printing, invisible 59 | cat -e # show line ends ($) and non printing 60 | cat -t # show tabs (^I) and non-printing 61 | cat -s # squeeze repeat blank lines into one blank line 62 | cat -n # number lines 63 | cat -b # number non-blank lines 64 | 65 | # number lines in clipboard 66 | pbpaste | cat -n | pbcopy 67 | 68 | # to apply changes in bash profile to current terminal window 69 | source ~/.bash_profile 70 | 71 | # to rename extensions 72 | find /path/to/images -name '*.JPG' -exec bash -c 'mv "$1" "${1/%.JPG/.jpg}"' -- {} \; 73 | 74 | # to use all results from find as a list of argumnts (use "+", otherwise use "\;") 75 | find ../../../Genomes -name "*[^s].fna" -exec ./genoming.pl {} + > output 76 | 77 | # remove a char from a file (in this case, to join lines) 78 | tr -d "\n" < my_file # fastest? 79 | perl -p -e 's/\n//' my_file 80 | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n//g' my_file # slowest 81 | #ex: 82 | tail -n +2 my_file.fna | tr -d "\n" 83 | # otro TR 84 | echo "PACO" | tr "A-Z" "a-z" 85 | 86 | # remove non-printable characters 87 | tr -cd "[:print:]" < file1 # -c means: everything except string 1 (in this case, "[:print:]") 88 | 89 | # Remove diacritical marks from all accented variants of the letter `e': 90 | tr "[=e=]" "e" 91 | 92 | 93 | # show longest repeating sequences in a genome (at least 6 chars long) 94 | tail -n +2 ../../../Genomes/whole/Clostridium\ perfringens.fna | tr -d "\n" | grep -oE (.)\1{5,} | sort -r | head 95 | # even better, It's better to grep a long line than many short lines: 96 | merge_fasta costridium.fna | grep -oE [ACGT]{3,} 97 | 98 | # count number of matches 99 | echo aaaa | grep -o a | wc -l 100 | 101 | # show only matching part grep, makes sense with regexps 102 | grep -E "IFN\w+" -o # IFNAR1, IFNB1... 103 | 104 | # grep options 105 | grep -h # show only match 106 | grep -H # show match and filename (default) 107 | grep -l # show all matching filenames 108 | grep -L # show all non-matching filenames 109 | grep -m NUM # stop grep after NUM matches 110 | 111 | # get the username of every system file 112 | ps aux | cut -d " " -f 1 113 | 114 | # sort by column. -t delimiter -n numeric -k field number 115 | cat output | sort -n -k2 -t: | pretty 116 | 117 | # if sort is too slow, and you just want to calculate row/column frequencies 118 | awk '{count[$1]++} END{for(c in count) print c, count[c]}' calculations/anjan/2hpi_strata.bow > frequencies.txt 119 | 120 | # remove duplicated lines 121 | sort -u 122 | sort | uniq 123 | 124 | # show duplicates 125 | sort | uniq -d 126 | 127 | # remove last line of a file (in place) 128 | sed -i '$ d' fake_data/b_4hpi_QV.qual 129 | 130 | # delete a line in a file containing a string 131 | sed '/delete_this/d' filename.txt 132 | 133 | # change file extension of a group of files 134 | for f in *.fa; do mv "$f" "`basename $f .fa`.fna"; done; 135 | 136 | # remove from basename of multiple files 137 | for i in *.fna 138 | do j=`echo $i | sed 's/hs_alt_HuRef_//g'` 139 | mv "$i" "$j" 140 | done 141 | 142 | # rename spaces to underscores 143 | for f in *.fna ; do mv "$f" $( echo $f | tr ' ' '_' ) ; done 144 | 145 | # find in current directory 146 | find . -iname "*.txt" 147 | find $directory -type f -iname "*.in" # recursive by default 148 | find . -type f -maxdepth 1 -iname "*.txt" 149 | 150 | find . -type f -name \*.map -exec ls -lhtr {} + # execute an action after find (ALWAYS USE echo after -exec so you know what's going to execute) 151 | 152 | # print the 2nd second nth line of a long file efficiently 153 | awk 'NR==2{print;exit}' SRR049672_F3.csfasta 154 | 155 | # grep escape characters 156 | grep "\-1" 157 | grep "\"" 158 | 159 | # grep reverse file (tac reverses order of lines) 160 | tac file | grep "last_ocurrence" 161 | 162 | # find and rename file extension 163 | find /path/ -name "accepted_hits.bam" -exec sh -c 'samtools sort "$1" "${1%.bam}.sorted"' _ {} \; # _ makes sh use absolute paths, $1 is {} 164 | 165 | find . -type f -name "*.so" | while read FNAME; do 166 | mv "$FNAME" "${FNAME%.so}.dylib" # (replace so with dylib) 167 | done 168 | 169 | find calculations/09/ -name "accepted*" -exec sh -c 'echo mv "$1" "${1/accepted_hits/accepted_hits.sorted}"' _ {} \; 170 | 171 | # find and -execdir so the command is run from the subdirectory containing the matched file 172 | find . -name "accepted_hits.sorted.bam" -execdir sh -c 'samtools view $1 | head' _ {} \; # THEY MUST BE SINGLE QUOTES 173 | find /protected/individuals/nacho/cmf/calculations -name "accepted_hits.sorted.bam" -execdir sh -c "samtools view {} | htseq-count --stranded=no -o counts.sam - /protected/individuals/nacho/cmf/raw_data/genome/gencode.v14.annotation.gtf > counts.txt" \; 174 | 175 | # if you want to use $* or $@, you need to pass sh, so that takes up $0 and you don't loose any arguments $1-$n 176 | find path/ -name "counts.txt" -exec sh -c 'head -n1 $@' sh {} + 177 | 178 | # find -exec sh -c details 179 | find /protected/individuals/nacho/cmf/calculations/09 -maxdepth 2 -name "accepted_hits.bam" -exec echo {} \; 180 | find /protected/individuals/nacho/cmf/calculations/09 -maxdepth 2 -name "accepted_hits.bam" -exec sh -c 'echo {}' \; 181 | find /protected/individuals/nacho/cmf/calculations/09 -maxdepth 2 -name "accepted_hits.bam" -exec sh -c "echo {}" \; 182 | find /protected/individuals/nacho/cmf/calculations/09 -maxdepth 2 -name "accepted_hits.bam" -exec sh -c 'echo $1' sh {} \; 183 | find /protected/individuals/nacho/cmf/calculations/09 -maxdepth 2 -name "accepted_hits.bam" -exec sh -c "echo $1" sh {} \; # DOESN'T WORK 184 | find /protected/individuals/nacho/cmf/calculations/09 -maxdepth 2 -name "accepted_hits.bam" -exec sh -c 'echo $1' {} \; # DOESN'T WORK 185 | find /protected/individuals/nacho/cmf/calculations/09 -maxdepth 2 -name "accepted_hits.bam" -exec sh -c "echo $1" {} \; # DOESN'T WORK 186 | 187 | # prepend to a file (with process substitution) 188 | header="T1\tT2\tT3\tI1\tN1\tN2\tN4" 189 | exec 3<> $output_patient1 && awk -v TEXT="$header" 'BEGIN {print TEXT}{print}' $output_patient1 >&3 190 | # or - not tested 191 | cat header.txt <(cat my.txt) 192 | 193 | # direct a single stream of input (ls) to multiple readers (grep & wc) without using temporary files 194 | ls |tee >(grep xxx |wc >xxx.count) >(grep yyy |wc >yyy.count) |grep zzz |wc >zzz.count 195 | 196 | #en vez de mv /a/long/path/foo /a/long/path/bar 197 | mv /a/long/path/{foo,bar} 198 | 199 | #copia seguridad 200 | mv /a/long/path/foo{,.bak} 201 | 202 | # reverse order lines file 203 | tail -r myfile.txt 204 | 205 | #listar 206 | ls -lhtr 207 | ls -lS 208 | -h # human readable sizes 209 | -t # sort by time modified 210 | -r # reverse sort 211 | -S # sort files by size 212 | -F # show types of files 213 | # * executable file 214 | # / directory 215 | # @ symbolic link 216 | # = socket 217 | # % whiteout 218 | # | FIFO 219 | 220 | 221 | # sed return whatever between two regexps (first inclusive) 222 | sed -n '/Q927F2/,/>/p' uniref50.fasta | sed '$d' 223 | 224 | # execute previous command 225 | # Type ! followed by the starting few letters of the command that you would like to re-execute. 226 | sed -n '/Q927F2/,/>/p' uniref50.fasta | sed '$d' 227 | !s 228 | 229 | # use all arguments of previous command 230 | !* 231 | # use last argument of previous command 232 | !$ 233 | # insert previous argument 234 | . 235 | 236 | # columnate!! 237 | column -t my_file 238 | 239 | # join lines of two fields on a common field, cartesian, combine, BOTH FILES MUST BE SORTED 240 | join a b # default is first column of each file, separated by spaces. "a" is one column, "b" is wide info 241 | join <(sort a) <(sort b) # if files are unsorted 242 | join -1 3 -2 2 a b -t ":" 243 | 244 | # join individual XML files 245 | find rn/*.xml -exec tail +3 '{}' \; > rn.xml 246 | # prepend 247 | cat rn.xml | pbcopy && head -n 2 rn/rn00072.xml > rn.xml && pbpaste >> rn.xml 248 | 249 | # hacer comparaciones numéricas 250 | cut -f 1 ecoli_network | awk '$1<10'| wc -l 251 | 252 | # call awk inside awk 253 | awk 'BEGIN{ system("awk '\''BEGIN{ print 1}'\''") }' 254 | 255 | # to number lines 256 | nl myfile 257 | 258 | # pseudo awk in ruby 259 | echo "paco;luis" | ruby -F";" -nae 'puts $F[1]' 260 | 261 | # use bang to call last command from history that starts with those letters. Ex: execute last find command 262 | !f 263 | 264 | # copy elements from previous commands 265 | ls paco luis pedro 266 | ls !:1-3 267 | 268 | # use all arguments 269 | ls !* 270 | 271 | # find and delete 272 | find . -name "temp*" -type f -delete 273 | 274 | # find with regex. Finds: temp.a and temp.b 275 | find -E . -regex ".*temp\.(a|b)" 276 | 277 | # rename 091/EZCD2CUnit091Pane2280B.jpg into 091/D2C_Unit091_Pane2280_B.jpg 278 | for filename in */*.jpg ; do 279 | new_filename=$(echo $filename | sed 's/\(EZC\)\([C2D]*\)\(Unit[[:digit:]]*\)\(Pane[[:digit:]]*\)\(.*\)/\2_\3_\4_\5/g' | sed 's/_A/_Question/' | sed 's/_B/_ZAnswer/') 280 | mv $filename $new_filename 281 | done 282 | 283 | # fix command and edit in editoraslfjalk 284 | fc 285 | 286 | # linga see how many cores per node in linga 287 | qhost 288 | 289 | # clear print line 290 | echo -e '\r\e[K' 291 | 292 | # to download a nature article 293 | ssh nacho@maxwell.cnb.csic.es "wget http://www.nature.com/nature/journal/v475/n7357/pdf/475462a.pdf" 294 | ssh nacho@maxwell.cnb.csic.es "cat 475462a.pdf > 475462a.pdf" 295 | 296 | # convert citable notes into citations 297 | grep -E "^#[^#]" *.note | sed 's/\(.*\)\.note:# \(.*\)/\2\(\1\)/g' > "citable_notes.txt" 298 | 299 | # random number in range 300 | shuf -i 1-100 -n 1 301 | 302 | # for loop range sequence 303 | 304 | for i in $(seq 1 5) 305 | do 306 | echo "Welcome $i times" 307 | done 308 | 309 | # get a substring by range 310 | cut -c 201-220 my_big_string 311 | 312 | # global replace gnu sed (replaces spaces with underscores) # -i edits file in-place 313 | gsed 's/\(Mouse\|Merck\|Human\|Agilent\|Rat\) /\1_/g' gene_info_segex.txt 314 | gsed -i 's/\(Mouse\|Merck\|Human\|Agilent\|Rat\) /\1_/g' gene_info_segex.txt 315 | 316 | # use sed -E -e 's///g' whenever possible to avoid \( ... \) 317 | 318 | # replace tabs using sed (use -i to replace file) 319 | gsed 's/\t/@/g' contig_gene_names2.txt 320 | # rsync local to remote 321 | rsync --verbose --progress --stats --compress --rsh=/usr/bin/ssh \ 322 | --recursive --times --perms --links --delete \ 323 | /Users/nachocab/Code/CNB/mirna_scroll* nacho@maxwell.cnb.csic.es:/home/nacho/mirna_scroll 324 | 325 | # diff two files by line content 326 | a_not_in_b file_a file_b 327 | a_not_in_b file_a file_b -r 328 | # DON'T USE THIS FOR GENE NAMES!! (watch out for partial matches!!! use translate.awk instead) 329 | grep -f small_query_file_with_one_column long_database_file_with_match_column_and_others > in_query_and_in_database.txt 330 | grep -vf small_query_file_with_one_column long_database_file_with_match_column_and_others > in_query_and_not_in_database.txt 331 | 332 | # send a foreground process into background (you get a notification when it's done) 333 | CTRL+Z 334 | bg 1 335 | 336 | # to check how background processes are doing 337 | jobs 338 | 339 | # columnize and paginate (cpag) 340 | column -s";" -t top_day3.csv | less -S 341 | cpag top_day3.csv ";" 342 | 343 | # open stdout in vim 344 | cpag top_day3.csv ";" | vim - 345 | 346 | # sort by column ignoring header in vim 347 | :2,$!sort -k4 348 | 349 | # sort specify column in linux (you probably need the second comma) 350 | sort my_file -k1,1 351 | 352 | # scroll right/left in vim 353 | zH/zL 354 | 140 / 355 | 356 | # make a symbolic link (can't use ../.. paths) 357 | ln -s ORIGINAL_TARGET SYMBOLIC_LINK_NAME 358 | 359 | # remove a non-empty directory 360 | rm -rf DIRECTORY 361 | 362 | # awk split - split in awk: split(input_field, output_array, separator) 363 | split($4,gene_name,"_") 364 | print gene_name[1] 365 | 366 | # print an array in awk 367 | for (gene_name in read_counts) 368 | print gene_name, read_counts[gene_names] 369 | 370 | # include a script 371 | lib_path="/data/home/nacho/lib" 372 | source $lib_path/aux.sh 373 | 374 | # time and execute in background 375 | time sleep 3 & 376 | 377 | # free space (quota in linga) 378 | df 379 | df -h 380 | df -h --direct /protected/individuals/* # show the file, not the mount point 381 | 382 | # used space 383 | du -sh # summarize all subfolders 384 | du -h | sort -h # show all and sort by human-size 385 | du -ah | sort -h # show all and sort by human-size 386 | 387 | 388 | # echo a tab tabs, or new lines 389 | echo -e "\t" 390 | echo "paco\nluis" | wc -l # 1 391 | echo -e "paco\nluis" | wc -l # 2 392 | 393 | # cat show tabs 394 | cat -T file_with_tabs 395 | 396 | # for loop numbers, don't use quotes 397 | for sample in 1 2 5 6 7 8; do ... done 398 | 399 | # check if file or directory exists 400 | if [ -f /tmp/foo.txt ]; then 401 | if [ -d "$DIRECTORY" ]; then 402 | 403 | # append to an array 404 | a=(1 3 56) 405 | a=(${a[@]} 66 77) 406 | echo ${a[@]} 407 | 408 | # kill a process by job number 409 | kill -9 %1 410 | 411 | # shell parameter expansion - variable substitution 412 | ${variable:-word} # If variable is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted. 413 | ${variable:=word} # If variable is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way. 414 | ${variable:?word} # If variable is null or unset, the expansion of word is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted. 415 | ${variable:+word} # If variable is null or unset, nothing is substituted, otherwise the expansion of word is substituted. 416 | 417 | ${variable:offset} 418 | ${variable:offset:length} # Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter starting at the character specified by offset. length and offset are arithmetic expressions (see Shell Arithmetic). This is referred to as Substring Expansion. 419 | 420 | ${!prefix*} 421 | ${!prefix@} # Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When ‘@’ is used and the expansion appears within double quotes, each variable name expands to a separate word. 422 | 423 | ${!name[@]} 424 | ${!name[*]} # If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When ‘@’ is used and the expansion appears within double quotes, each key expands to a separate word. 425 | ${#parameter} # The length in characters of the expanded value of parameter is substituted. If variable is ‘*’ or ‘@’, the value substituted is the number of positional parameters. If variable is an array name subscripted by ‘*’ or ‘@’, the value substituted is the number of elements in the array. 426 | 427 | 428 | # substring removal 429 | a="aacdff" 430 | ${variable#word} # remove from beginning, shortest 431 | echo ${a#*a} # acdff 432 | ${variable##word} # remove from beginning, longest 433 | echo ${a##*a} # cdff 434 | ${variable%word} # remove from end, shortest 435 | echo ${a%f*} # aacdf 436 | ${variable%%word} # remove from end, longest 437 | echo ${a%%f*} # aacd 438 | 439 | ${variable/pattern/string} # Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with ‘#’, it must match at the beginning of the expanded value of parameter. If pattern begins with ‘%’, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If variable is ‘@’ or ‘*’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If variable is an array variable subscripted with ‘@’ or ‘*’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list. 440 | 441 | # case modification 442 | ${PARAMETER^} 443 | ${PARAMETER^^} 444 | ${PARAMETER,} 445 | ${PARAMETER,,} 446 | ${PARAMETER~} 447 | ${PARAMETER~~} # The ^ operator modifies the first character to uppercase, the , operator to lowercase. When using the double-form (^^ and ,,), all characters are converted. 448 | 449 | # case modification in arrays 450 | array=(This is some Text) 451 | echo "${array[@],}" # this is some text 452 | echo "${array[@],,}" # this is some text 453 | echo "${array[@]^}" # This Is Some Text 454 | echo "${array[@]^^}" # THIS IS SOME TEXT 455 | echo "${array[2]^^}" # TEXT 456 | 457 | # find -printf show filename 458 | find path/ -printf "%p\n" # show full path 459 | find path/ -printf "%P\n" # show relative path 460 | 461 | # apple system log 462 | grep backupd /private/var/log/system.log 463 | 464 | # skip header 465 | awk 'NR > 1' 466 | 467 | # get size of a folder 468 | du -hs folder_path 469 | 470 | # copy directory 471 | cp -r lib/ /data/share/pulm/UCLA/Cancer_Progression/edgeR/ 472 | 473 | # change group (don't confuse with chmod -R +x my_folder/) 474 | chgrp -R pulm /data/share/pulm/UCLA/Cancer_Progression/edgeR/ 475 | 476 | # match a field against a regular expression in awk grep, awk regex 477 | awk '$2 !~ /ENSG/ {print $2, $1}' 478 | awk '$2 ~ /ENSG/ {print $2, $1}' 479 | 480 | # convert ensembl to genbank for gsea 481 | cat 4P-IvsN-edgeR.txt | translate ~/Code/Translators/hsa_ensembl_gene_id_to_hsa_genbank_id.csv ";" | awk -F";" -v OFS="\t" '$3 != "" && $2 != "NA"{print $3, $2}' > 4P-IvsN-edgeR-gbk.rnk 482 | 483 | # count empty lines in a file 484 | grep -c ^$ my_file 485 | 486 | # compare two sorted files line by line. Outputs 3 columns by default: unique to file1, unique to file2, intersection file1 and file2 487 | # use --nocheck-order to avoid warnings 488 | # use --output-delimiter=";" 489 | comm file1 file2 490 | comm -23 file1 file2 # lines in file1 but not in file2 (unique to file1) 491 | comm -13 file1 file2 # lines in file2 but not in file1 (unique to file2) 492 | comm -12 file1 file2 # lines in both files (intersection file1 and file2) 493 | 494 | # rename 495 | 496 | # !$ !^ !* 497 | echo foo bar baz 498 | foo bar baz 499 | $ echo bang-dollar: !$ bang-hat: !^ bang-star: !* 500 | echo bang-dollar: baz bang-hat: foo bang-star: foo bar baz 501 | 502 | $ echo foo bar baz 503 | $ echo !:2 504 | echo bar 505 | 506 | # :h :t :r :e 507 | echo Head: !$:h Tail: !$:t 508 | echo Head: /usr/bin Tail: id 509 | Head: /usr/bin Tail: id 510 | 511 | # insert last command 512 | esc+. 513 | 514 | # print last command before using It 515 | !!:p 516 | 517 | # find all places that have perl executables 518 | type -a perl 519 | 520 | # send email from terminal 521 | echo "hola 522 | 523 | --- 524 | Sent from my Unix shell" | mail -s "prueba" "nacho@bu.edu" -f "nachocab@gmail.com" 525 | 526 | # to add a host in ~/.ssh/config (a folder named .ssh in your home folder). Add an entry for each computer you want to connect to, like this: 527 | Host compy 528 | HostName 98.256.211.12 529 | Port 90 530 | User sidney 531 | 532 | ssh compy 533 | 534 | # ls colors linux 535 | ls --color=always 536 | 537 | # show hostname on terminal with color and git status 538 | export PS1=$IBlack$Time12h$Color_Off'$(git branch &>/dev/null;\ 539 | if [ $? -eq 0 ]; then \ 540 | echo "$(echo `git status` | grep "nothing to commit" > /dev/null 2>&1; \ 541 | if [ "$?" -eq "0" ]; then \ 542 | # @4 - Clean repository - nothing to commit 543 | echo "'$Green'"$(__git_ps1 " (%s)"); \ 544 | else \ 545 | # @5 - Changes to working tree 546 | echo "'$IRed'"$(__git_ps1 " {%s}"); \ 547 | fi) '$BRed'\h '$PathShort$Color_Off' \$ "; \ 548 | else \ 549 | # @2 - Prompt when not in GIT repo 550 | echo " '$Red'\h '$PathShort$Color_Off' \$ "; \ 551 | fi)' 552 | 553 | # stop writing password to connect 554 | scp ~/.ssh/id_rsa.pub nacho@rubysky.bumc.bu.edu:~/.ssh/ 555 | ssh nacho@rubysky.bumc.bu.edu 556 | cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys # do this in the server 557 | rm ~/.ssh/id_rsa.pub # erase your local public key, you can create a new one by default, just hit yes and no pwd 558 | 559 | # see known servers hosts 560 | cat ~/.ssh/known_hosts 561 | 562 | # copy file to remote. scp gives you progress 563 | scp ~/.bashrc nacho@decima.bu.edu:~ 564 | scp ~edalign/MergePlusUnusedVOPE39cl.fasta nacho@decima:/fs/spartans3/nacho 565 | scp some_file nacho@decima:/fs/spartans3/nacho 566 | scp ~/Marine\ Genomics/codecheck/EdParaNfilter1.fastq.gz ~/Marine\ Genomics/codecheck/EdParaNfilter2.fastq.gz nacho@blueice.bumc.bu.edu:/home/nacho/storage/cmf/raw_data 567 | 568 | rsync -ave ssh fileToCopy ssh.myhost.net:/some/nonExisting/dirToCopyTO 569 | rsync -ave ssh ~/edalign/MergePlusUnusedVOPE39cl.fasta nacho@decima:/fs/spartans3/nacho/ 570 | rsync -ave ssh ~/Marine\ Genomics/codecheck/ nacho@decima:/fs/spartans3/nacho/raw/ 571 | rsync -ave ssh * nacho@decima:/fs/userB2/nacho/storage/derek/raw/ 572 | 573 | # upload rubysky executable 574 | chmod +x tophat 575 | scp tophat nacho@rubysky.bumc.bu.edu:/protected/individuals/nacho/cmf/src/ # or use cmd+uf in sftp 576 | BOWTIE_INDEXES="/protected/individuals/nacho/cmf/raw_data/genome/bowtie1/";LANE="b_4"; OUT_DIR="/unprotected/projects/lasvchal/moss/fake_calculations/${LANE}_tophat"; /protected/individuals/nacho/cmf/src/tophat --library-type fr-secondstrand --segment-length 25 --no-coverage-search --no-novel-juncs -G "/protected/individuals/nacho/cmf/raw_data/genome/gencode.v14.annotation.gtf" -o "$OUT_DIR" --color --bowtie1 --quals hg19 "/unprotected/projects/lasvchal/moss/fake_data/${LANE}hpi.csfasta" "/unprotected/projects/lasvchal/moss/fake_data/${LANE}hpi_QV.qual" 577 | 578 | 579 | # which shell bash 580 | ps -p $$ 581 | 582 | # which linux 583 | lsb_release -a 584 | uname -a 585 | 586 | # keep a server job running after I log out (only for bash) 587 | ^Z 588 | bg 589 | disown 590 | 591 | nohup command-with-options & 592 | 593 | # screen 594 | screen -S sessionname 595 | run_script 596 | ^-a d # detach 597 | screen -r sessionname # reattach 598 | 599 | ^-a c # create additional 600 | 601 | # unzip .zip file 602 | unzip file # keep original 603 | unzip -d file 604 | 605 | # gunzip COMPRESS into zip in terminal (3 min for a 1GB text file, down to 400MB) 606 | gzip file2 # overwrites original 607 | gzip -c file2 > file2.gz # keep original 608 | find . -type f -name "*.fastq" -exec sh -c "gzip < {} > {}.gz" \; & # convert multiple individually in the background 609 | ls | parallel -j+0 --eta gzip # try parallel 610 | 611 | # unzip DECOMPRESS over terminal 612 | gzip -d file.gz # overwrite the original: -d for decompress 613 | gzip -d -c file.gz > file # keep the original: -d for decompress 614 | tar zxvf allNvT1vsHsCnidprotcsv.tar.gz # --overwrite by default, use -k to keep old files, -x extract files from archive 615 | 616 | tar tvfz file.tar.gz # -t view the file contents without extracting 617 | tar xvfz archive_file.tar.gz /path/to/file # extract a single file 618 | tar xvfz archive_file.tar.gz /path/to/dir/ # extract a single dir 619 | tar xvfz archive_file.tar.gz /path/to/dir1/ /path/to/dir2/ # extract multiple dirs 620 | tar xvf archive_file.tar --wildcards '*.pl' # use regex to specify which files should be extracted 621 | 622 | tar tvfz file.tar.gz -C output_dir # specify a different output directory 623 | 624 | # determine size of gz file (doesn't work over 2GB) 625 | gzip -l compressedfile.gz 626 | 627 | # crappy way to make number human readable 628 | echo 23375001203 | perl -lne 'printf("%.2f MB\n", $_/1024/1024)' 629 | echo 23375001203 | perl -lne 'printf("%.2f GB\n", $_/1024/1024/1024)' 630 | 631 | # zip in a tarball a number of files 632 | tar -cvzf mystuff.tar.gz foo.tex fig1.eps fig2.eps # -c create a new archive, -v verbosely list processed files, -f FILE_NAME -z compress the file (through gzip) 633 | 634 | # growl sticky, use terminal icon, set title, set message 635 | GROWLDATE=`date +"%A, %h %d %Y %H:%m:%S %Z"` 636 | growlnotify -s -a terminal -t "Transfer Complete" -m "$GROWLDATE" 637 | 638 | # remove whitespace in awk 639 | gsub(/^[ \t]+|[ \t]+$/,"") 640 | 641 | # decima kaya1 folders 642 | /fs/userB2/nacho # home 643 | /fs/spartans3/nacho # storage 644 | 645 | # Linga folders (blueice redstar) 646 | /home/nacho # my home 647 | /protected/individuals/nacho # data 648 | 649 | # new login on blueice linga 650 | newgrp lasvchal 651 | qlogin -P lasvchal 652 | 653 | # job management 654 | qhost -j # see which jobs from other users are running on each node 655 | qstat # which jobs are running 656 | qstat -j PID # info about specific job, including scheduling info 657 | qsub job.qsub # submit job 658 | qdel PID # kill job 659 | qdel -u nacho # kill all my jobs 660 | 661 | # find out what groups a user belongs to 662 | id -G -n nacho 663 | projects -lp 664 | 665 | 666 | # run in multithread mode in linga: inside my_script, use the $NSLOTS var. Ex bowtie -p $NSLOTS ... 667 | newgrp lasvchal 668 | qsub -P lasvchal -pe single_node 1-8 src/assemble.qsub 669 | Your job 3170852 ("assemble.sh") has been submitted 670 | 671 | # how many cpus/cores in server 672 | cat /proc/cpuinfo | grep -E "proc|core" 673 | sysctl hw.ncpu # in mac 674 | 675 | # core usage 676 | mpstat -P ALL 677 | mpstat -P ALL 1 678 | 679 | # associative arrays 680 | declare -A array 681 | array[hello]=world 682 | array[goodbye]=lucas 683 | ${array[hello]} # to access 684 | 685 | # to start using an array, you can just define it and assign its elements, or use declare -a 686 | samples_in_patient[1]="1 2 5 6 7 8" 687 | samples_in_patient[1]=(1 2 5 6 7 8) # same thing 688 | samples_in_patient[2]="5 6 7 8" 689 | ${samples_in_patient[@]} # to access all the values 690 | ${samples_in_patient[*]} # to access all the values 691 | 692 | declare -a life_stages=(parasite_1 parasite_2 parasite2planula_1 planula_1 planula2adult_1 adult_1) 693 | 694 | # Aspera Connect 695 | ~/Applications/Aspera\ Connect.app/Contents/Resources/ascp 696 | http://download.asperasoft.com/download/docs/connect/3.0.1/osx/en/html/index.html 697 | 698 | # combine files vertically by colum 699 | paste a b c 700 | 701 | # convert a column into a row, multiline to single lien 702 | cut -f1 paco.csv | xargs # echo by default 703 | echo 1 2 3 4 | xargs -t -n2 mv {} # {} allows to explicitly call each element? 704 | echo 1 2 3 4 | xargs -n2 705 | # 1 2 706 | # 3 4 707 | xargs -t # shows the command 708 | xargs -p # asks for confirmation 709 | 710 | 711 | 712 | # curl 713 | curl -o index.html http://projects.flowingdata.com/life-expectancy/ # explicitly name 714 | curl -O http://projects.flowingdata.com/life-expectancy/index.html # name as remote 715 | 716 | # wget 717 | wget -O - http://www.example.com # send webpage to stdin 718 | wget -P my_folder http://www.example.com # change folder, not filename 719 | wget -O my_folder/my_file_name http://www.example.com # change both, it's like a shell redirect 720 | 721 | # brace expansion 722 | wget http://www.ploscompbiol.org/article/fetchSingleRepresentation.action?uri=info:doi/10.1371/journal.pcbi.1000545.s00{2..6} # download supplementary material 723 | # curl has it integrated 724 | curl -O "http://www.ploscompbiol.org/article/fetchSingleRepresentation.action?uri=info:doi/10.1371/journal.pcbi.1000545.s00[2-6]" 725 | 726 | # download all the URLs from a file 727 | wget -i file_with_urls 728 | 729 | # download entire folder wget 730 | wget -P local_folder -m url_folder # -r -N -l inf --no-remove-listing (m is for mirror) 731 | wget -r -np url_folder # (investigate a way TO AVOID REPLICATING FOLDER STRUCTURE) download all files recursively under the specified path (np: --no-parent), default maximum recursion is 5 732 | 733 | # download and extract tarball 734 | wget -qO - "http://www.tarball.com/tarball.gz" | tar zxvf - 735 | 736 | 737 | # get all pdf and zips from a website 738 | wget --reject html,htm --accept pdf,zip -rl1 url 739 | 740 | # untar a tar.bz2 file to a specific folder 741 | tar -xjf test.tbz -C /tmp/test 742 | 743 | # return true if the variable is unset undefined 744 | if [[ -z "$VAR" ]]; 745 | 746 | # declare function 747 | function_name(){ 748 | local local_var=$1 749 | echo "$local_var" # return first argument 750 | } 751 | 752 | # execute function 753 | function_name "paco" # "paco" 754 | my_var=$(function_name "paco"); echo $my_var # "paco" 755 | 756 | # shift arguments, while saving the first one 757 | input_file=$1; shift 758 | 759 | # with arguments one two three 760 | echo "$@" # 3 761 | echo "$*" # 1 762 | echo $@ # 3 763 | echo $* # 3 764 | 765 | # concat strings 766 | foo="Hello" 767 | foo=$foo" World" 768 | 769 | # CHECK if first file in awk, two file pattern, you need to check for the filename, otherwise FNR == second file if the first file is empty 770 | NR == FNR && FILENAME == ARGV[1] { 771 | query[#{fields}]++; next 772 | } 773 | 774 | # translator pattern 775 | BEGIN{ 776 | while (getline < translator) { 777 | translations[$1] = $2 778 | } 779 | close(translator) 780 | } 781 | 782 | { 783 | $(NF + 1) = translations[$field_to_translate] 784 | print 785 | } 786 | 787 | # output and count lines (use tee to save intermediate files) 788 | cat ns | tee /dev/tty | wc -l 789 | cat ns | tee intermediate_file | wc -l 790 | cat ns | tee /dev/tty intermediate_file | wc -l 791 | 792 | # generate random numbers and reshape output array 793 | jot -r 100 | rs 10 10 # matrix 10x10 794 | 795 | # diff 796 | diff -y --suppress-common-lines filea fileb 797 | 798 | # grep gene info 799 | grep -i "hla-" ~/gene_info/Homo_sapiens.gene_info | cut -f2,3,9 800 | 801 | # awk for loop 802 | for (i=1; i<=10; i++) { 803 | sum += i; # sum = sum + i 804 | } 805 | 806 | # awk concat string 807 | awk 'BEGIN{a=""; a= a "b" 3 "c"; print a}' # don't use a+= "b" 808 | 809 | # mdfind 810 | mdfind -onlyin dir QUERY 811 | mdfind -name matchingFileName QUERY 812 | mdfind -literal QUERY 813 | 814 | # translate 815 | translate(){ wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'; } 816 | 817 | # vi vim shortcuts 818 | ## move 819 | w - go to beginning of next word 820 | e - go to end of next word 821 | b - go back to the beginning of previous word 822 | . - jump back to last edited line. 823 | g; - jump back to last edited position. 824 | f - find forward 825 | F - find backward 826 | ; - repeat last f, F, t or T 827 | , - reverse ; 828 | ## insert 829 | I - insert to the start of current line 830 | A - append at the end of line 831 | o - open a line below 832 | O - open a line above 833 | C - change rest of current line (like ^K) 834 | cc - change the whole line (like a reset) 835 | ## scroll 836 | :43 - go to line 43 837 | ^u - scrolls half a screen up 838 | ^b - scrolls half a screen bottom 839 | 840 | u - undo 841 | ^r - redo 842 | 843 | # time formats 844 | %d Day of the month as a decimal number [01,31]. 845 | %m Month as a decimal number [01,12]. 846 | 847 | %y Year without century as a decimal number [00,99]. 848 | %Y Year with century as a decimal number. 849 | 850 | %A Locale’s full weekday name. 851 | %a Locale’s abbreviated weekday name. 852 | 853 | %H Hour (24-hour clock) as a decimal number [00,23]. 854 | %M Minute as a decimal number [00,59]. 855 | 856 | %b Locale’s abbreviated month name. 857 | %B Locale’s full month name. 858 | 859 | %c Locale’s appropriate date and time representation. 860 | 861 | %f Microsecond as a decimal number [0,999999], zero-padded on the left (1) 862 | %I Hour (12-hour clock) as a decimal number [01,12]. 863 | %j Day of the year as a decimal number [001,366]. 864 | %p Locale’s equivalent of either AM or PM. (2) 865 | %S Second as a decimal number [00,61]. (3) 866 | %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (4) 867 | %w Weekday as a decimal number [0(Sunday),6]. 868 | %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (4) 869 | %x Locale’s appropriate date representation. 870 | %X Locale’s appropriate time representation. 871 | %z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). (5) 872 | %Z Time zone name (empty string if the object is naive). 873 | %% A literal '%' character. 874 | -------------------------------------------------------------------------------- /bio_tricks.sh: -------------------------------------------------------------------------------- 1 | # Bowtie aligns reads to a genome 2 | # Tophat aligns reads to a genome (using bowtie) and then identifies splice junctions between the exons found 3 | # Cufflinks "assembles transcripts, estimates their abundances, and tests for differential expression and regulation in RNA-Seq samples." 4 | 5 | # cuffdiff tries to answer the question if there is a difference in a transcript expression in between two samples (biological, not technical, replicates). 6 | # edgeR and DESeq try to answer if the difference in total expression (total count of a gene including all its isoforms) is significant and not due to biological variability. (useful to see the effects of the treatment: drug, gene knockdown, mutation, different tissue type) 7 | 8 | # awesome way to query gene information given a genbank_id (returns a JSON object) 9 | http://mygene.info/doc 10 | http://mygene.info/query?q=cdk2+AND+species:human 11 | 12 | # query longitudinal_fc, but then you still have to add the header 13 | diff_lines -u -t ~/gene_info/gene_sets/TNF_domain.txt -q virus/lassa/calculations/PBMC/longitudinal_fc_all_by_gene_name_lassa-PBMC-day_3_vs_day_0.csv -f1 -i"," -k0 | awk 'NR>1' > misc/TNF_genes.txt 14 | 15 | # download hg19 905MB 16 | wget http://hgdownload.cse.ucsc.edu/goldenPath/hg19/bigZips/chromFa.tar.gz 17 | gunzip
 chromFa.tar.gz 18 | tar -xvf chromFa.tar 19 | rm -f *random* 20 | rm -f *Un* 21 | rm -f *hap* 22 | cat chr*.fa > hg19.fa 23 | 24 | # download interpro names 25 | wget -O ~/gene_info/misc/interpro_names.txt "ftp://ftp.ebi.ac.uk/pub/databases/interpro/names.dat" 26 | 27 | # download uniprot raw info 28 | wget -O raw_uniprot.txt "http://www.uniprot.org/uniprot/?query=organism%3a9606+keyword%3a1185&force=yes&format=tab&columns=id,reviewed,protein%20names,genes,organism,interpro,go" 29 | 30 | # download uniprot gene symbols 31 | wget -O uniprot_uniprot_id_to_gene_symbol.txt "http://www.uniprot.org/uniprot/?query=taxonomy%3a9606&force=yes&format=tab&columns=id,genes" 32 | awk -v OFS="," '$1 != "" && $2 != "" && NR > 1{print $1, $2}' uniprot_uniprot_id_to_gene_symbol.txt > first_filter_uniprot_id_to_gene_symbol.txt 33 | 34 | # download uniprot genebank_ids 35 | wget -O uniprot_uniprot_id_to_genebank_id.txt "http://www.uniprot.org/uniprot/?query=taxonomy%3a9606&force=yes&format=tab&columns=id,database(GENEID)" 36 | awk -v OFS="," '$1 != "" && $2 != "" && NR > 1{print $1, $2}' uniprot_uniprot_id_to_genebank_id.txt | awk -F";" '{print $1}' > first_filter_uniprot_id_to_genebank_id.txt 37 | 38 | # make translator hsa_genbank_id_to_gene_symbol: Use Homo_sapiens.gene_info instead of hsa_gene_info because we want different genbank_ids to point to the same gene_symbol 39 | awk -v OFS="," '{print $2,$3}' ../Homo_sapiens.gene_info > translator/hsa_genbank_id_to_gene_symbol.txt 40 | 41 | # get all gene symbols with a specific domain 42 | grep IPR006052 raw_uniprot.txt | cut -f1 | pbcopy 43 | 44 | # download uniprot mappings 45 | wget -O uniprot_mappings.gz ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/idmapping/idmapping.dat.gz 46 | awk -v OFS="," '$2=="GeneID"{print $1,$3}' ../raw_uniprot_mapping.txt > ../translator/uniprot_id_to_genbank_id.txt 47 | cat ../raw_uniprot_mapping.txt | awk -v OFS="," '$2=="NCBI_TaxID" && $3=="9606"{print $1}' > hsa_uniprot_ids.txt 48 | 49 | awk -F, -v translator="hsa_uniprot_ids.txt" ' 50 | BEGIN{ 51 | while (getline < translator) { 52 | translations[$1] = $2 53 | } 54 | close(translator) 55 | } 56 | { 57 | if ($1 in translations){ 58 | print 59 | } 60 | } 61 | ' ../translator/uniprot_id_to_genbank_id.txt > ../translator/hsa_uniprot_id_to_genbank_id.txt 62 | 63 | # interesting gene information 64 | String DB 65 | wikigenes 66 | Gene Cards 67 | BioGRID 68 | 69 | # TRANSCRIPTION FACTOR binding sites 70 | http://www.sabiosciences.com/chipqpcrsearch.php?species_id=0&factor=c-Fos&gene=&nfactor=n&ninfo=n&ngene=n&B2=Search 71 | pbpaste | cut -f2 > temp 72 | translate -q temp -r > temp2 73 | gene_info -q temp2 -k gene_symbol 74 | mv temp2 ../gene_sets/AP-1-binding-site_SabioSciences.txt 75 | mv temp2 ../gene_sets/IRF2-binding-site_SabioSciences.txt 76 | mv temp2 ../gene_sets/IRF7-binding-site_SabioSciences.txt 77 | 78 | # tagger 79 | cd connor 80 | cd misc/d3 81 | tagger -q rescued_gene_names.txt > rescued_genes_tags.csv 82 | 83 | # download all viruses from genbank 84 | wget ftp://ftp.ncbi.nih.gov/genomes/Viruses/all.fna.tar.gz 85 | 86 | # download lassa 87 | wget ftp://ftp.ncbi.nih.gov/genomes/Viruses/Lassa_virus_uid14864/NC_004296.faa 88 | wget ftp://ftp.ncbi.nih.gov/genomes/Viruses/Lassa_virus_uid14864/NC_004297.faa 89 | 90 | # download marburg 91 | wget ftp://ftp.ncbi.nih.gov/genomes/Viruses/Lake_Victoria_marburgvirus_uid15199/NC_001608.faa 92 | 93 | # download ebola 94 | wget ftp://ftp.ncbi.nih.gov/genomes/Viruses/Bundibugyo_ebolavirus_uid51245/NC_014373.faa 95 | 96 | # bowtie 97 | bowtie -p $NSLOTS -a --best --strata -v 2 -t --trim3 1 --trim5 1 file_index file.fastq file.bow 98 | file_index # looks in the current folder, the indexes subdirectory of the bowtie executable, then on BOWTIE_INDEXES 99 | -a # report all valid alignments per read. If more than one exists, and using --best 100 | -p $NSLOTS # number of parallel threads 101 | -v 2 # report alignments with at most 2 mm, ignore -e, -l and -n (stratum is the number of mm in the entire alignment) 102 | -n 2 # report alignments with at most 2 mm in their seed of length -l, ignore -v 103 | -t # print wall-clock time required in each phase 104 | --trim3 1 # trim 1 base from low-quality (right) end of each read before aligning 105 | --trim5 1 # trim 1 base from high-quality (left) end of each read before aligning 106 | --best # without best, it reports the first valid alignment. Stratum (number of mm in the seed region) trumps quality: a 1mm alignment with high Phred score is preferred to a 2mm where both positions have low Phred score. 107 | --strata # only show the best stratum (1mm) 108 | -c AATCGTCCGGAT # query a read manually 109 | --supress 1,5,6,7 # don't show specified columns 110 | -k 3 # report up to 3 valid alignments 111 | 112 | # bowtie: -S generate sam file 113 | bowtie -S e_coli reads/e_coli_10000snp.fq ec_snp.sam 114 | 115 | # search existing index s_cerevisiae.ebwt (-c get read from command line instead of file) 116 | bowtie -c s_cerevisiae ATTGTAGTTCGAGTAAGTAATGTGGGTTTG 117 | 118 | # build new index: fasta file, index name 119 | bowtie-build NC_002127.fna e_coli_O157_H7 120 | 121 | # convert sam to bam 122 | samtools view -bS -o ec_snp.bam ec_snp.sam 123 | 124 | # sort bam file 125 | samtools sort ec_snp.bam ec_snp.sorted 126 | 127 | # call variants from sorted bam file 128 | samtools pileup -cv -f genomes/NC_008253.fna ec_snp.sorted.bam 129 | 130 | # change bowtie index 131 | export BOWTIE_INDEXES="new_index_dir/" 132 | 133 | # grep microarrays 134 | grep COX4NB ../../virus/lassa/calculations/PBMC/all_probes_lassa-PBMC-day_3_vs_day_0.txt ../../virus/marburg/calculations/PBMC/all_probes_marburg-PBMC-day_3_vs_day_0.txt 135 | 136 | # translator pattern: query,target. Ex: EN_to_ES_translator.txt 137 | # whale,ballena 138 | # rhinocerous,rinoceronte 139 | -------------------------------------------------------------------------------- /css_tricks.css: -------------------------------------------------------------------------------- 1 | /* coordinates */ 2 | T R B L /* 4 elems */ 3 | T RL B /* 3 elems */ 4 | TB RL /* 2 elems */ 5 | TRBL /* 1 elem */ 6 | 7 | /*center div*/ 8 | margin: 0 auto; 9 | 10 | * /* any element */ 11 | E /* an element of type E */ 12 | E[foo] /* an E element with a "foo" attribute */ 13 | E[foo="bar"] /* an E element whose "foo" attribute value is exactly equal to "bar" */ 14 | E[foo~="bar"] /* an E element whose "foo" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar" */ 15 | E[foo^="bar"] /* an E element whose "foo" attribute value begins exactly with the string "bar" */ 16 | E[foo$="bar"] /* an E element whose "foo" attribute value ends exactly with the string "bar" */ 17 | E[foo*="bar"] /* an E element whose "foo" attribute value contains the substring "bar" */ 18 | E[foo|="en"] /* an E element whose "foo" attribute has a hyphen-separated list of values beginning (from the left) with "en" */ 19 | E[rel="handsome"][title^="Important"] /* you can combine them */ 20 | E:root /* an E element, root of the document */ 21 | E:nth-child(n) /* an E element, the n-th child of its parent */ 22 | E:nth-last-child(n) /* an E element, the n-th child of its parent, counting from the last one */ 23 | E:nth-of-type(n) /* an E element, the n-th sibling of its type */ 24 | E:nth-last-of-type(n) /* an E element, the n-th sibling of its type, counting from the last one */ 25 | E:first-child /* an E element, first child of its parent */ 26 | E:last-child /* an E element, last child of its parent */ 27 | E:first-of-type /* an E element, first sibling of its type */ 28 | E:last-of-type /* an E element, last sibling of its type */ 29 | E:only-child /* an E element, only child of its parent */ 30 | E:only-of-type /* an E element, only sibling of its type */ 31 | E:empty /* an E element that has no children (including text nodes) */ 32 | E:visited /* an E element being the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited) */ 33 | E:focus /* an E element during certain user actions */ 34 | E:target /* an E element being the target of the referring URI */ 35 | E:lang(fr) /* an element of type E in language "fr" (the document language specifies how language is determined) */ 36 | E:disabled /* a user interface element E which is enabled or disabled */ 37 | E:checked /* a user interface element E which is checked (for instance a radio-button or checkbox) */ 38 | E::first-line /* the first formatted line of an E element */ 39 | E::first-letter /* the first formatted letter of an E element */ 40 | E::before /* generated content before an E element */ 41 | E::after /* generated content after an E element */ 42 | E.warning /* an E element whose class is "warning" (the document language specifies how class is determined). */ 43 | E#myid /* an E element with ID equal to "myid". */ 44 | E:not(s) /* an E element that does not match simple selector s */ 45 | E F /* an F element descendant of an E element */ 46 | E > F /* an F element child of an E element */ 47 | E + F /* an F element immediately preceded by an E element */ 48 | E ~ F /* an F element preceded by an E element */ 49 | 50 | 51 | rounded corners { 52 | -moz-border-radius: 5px; 53 | -webkit-border-radius: 5px; 54 | border-radius: 5px; 55 | } 56 | 57 | /* clearfix */ 58 | .group:before, 59 | .group:after { 60 | content: ""; 61 | display: table; 62 | } 63 | .group:after { 64 | clear: both; 65 | } 66 | .group { 67 | zoom: 1; 68 | } 69 | 70 | box shadow { /* x-offset y-offset blur color */ 71 | -moz-box-shadow: inset 4px 4px 8px #222; 72 | -webkit-box-shadow: inset 4px 4px 8px #222; 73 | box-shadow: inset 4px 4px 8px #222; 74 | } 75 | 76 | text shadow { /* x-offset y-offset blur color */ 77 | text-shadow: 4px 4px 8px #222; 78 | } 79 | 80 | img:hover { 81 | -o-transform: scale(1.5); 82 | -moz-transform: scale(1.5); 83 | -webkit-transform: scale(1.5); 84 | transform: scale(1.5); 85 | } 86 | 87 | multiple images { 88 | background: center top url("bg.png") repeat; 89 | background: url("city.png") no-repeat center top, url(bg.png); 90 | } 91 | 92 | off white background{ 93 | background: #f4f4f4 url(../images/background.png); 94 | } 95 | 96 | /* don't set stroke to text or you'll get fuzzy text, set it to auto */ 97 | -------------------------------------------------------------------------------- /excel tricks.txt: -------------------------------------------------------------------------------- 1 | # Excel formats. Each cell has four sections: 2 | positive_zero_and_negative_numbers # 1 section 3 | positive_and_zero_numbers;negative_numbers # 2 sections 4 | positive_numbers;negative_numbers;zero_values;text_values # 4 sections -------------------------------------------------------------------------------- /git_tricks.sh: -------------------------------------------------------------------------------- 1 | # reference 2 | http://gitref.org/index.html 3 | 4 | # undo git add - unadd, remove from index? 5 | git reset 6 | 7 | # create a new repository in github 8 | touch README.md 9 | git init 10 | git add . && git commit -m "It begins." 11 | git create -d "My new thing" # (using hub: creates a new project on GitHub with the name of current directory) 12 | git push -u origin master 13 | 14 | # git remote add origin https://github.com/nachocab/leanback.git 15 | 16 | # push to created repository (origin) 17 | git push -u origin master 18 | 19 | # discard unsaved changes from file(s) and restore an old version: commit first! 20 | git co 82f5 my_old_file my_other_old_file 21 | 22 | # remove a file from git index and the filesystem (use --cached to not remove it) 23 | git rm my_file 24 | git rm -r my_dir/ 25 | 26 | # remove a file from git index: unstage it.(but don't remove it from filesystem) reset staged changes 27 | git rm --cached my_file 28 | 29 | # unstage a file (removes the modification from the index, no the entire file) 30 | git reset my_file 31 | 32 | # discard unstaged changes on a single file 33 | git checkout path/to/file 34 | 35 | # discard all unstaged changes, 36 | git checkout -- . 37 | 38 | # find search text string contents 39 | git grep $(git rev-list --all) 40 | 41 | # revert reset reload, checkout file from previous commit and overwrite current version 42 | git co HEAD main.html 43 | 44 | # rename a file inside git 45 | git mv my_file your_file 46 | 47 | # only stage tracked (known) files 48 | git add -u 49 | 50 | # show contents of last commit as a diff 51 | git show 52 | git show --name-only 53 | 54 | # show contents of a file not as a diff 55 | git show HEAD:file 56 | 57 | # show unstaged contents (what you could still add to the index) compared to the last commit 58 | git diff 59 | # show the names of the files with unstanged changes 60 | git diff --name-only 61 | # show unstanged contents compared to an older commit 62 | git diff HEAD~ # the parent of HEAD 63 | git diff "@{yesterday}" 64 | git whatchanged --since="2 weeks ago" 65 | 66 | # show difference between two commits 67 | git diff 1b6d "master~2" 68 | 69 | # show staged (indexed) contents 70 | git diff --cached 71 | 72 | # show tracked files 73 | git ls-files 74 | 75 | # create a new branch and move to it (one step) 76 | git checkout -b my_new_branch 77 | # create a new branch (name current commit) (two steps) 78 | git branch my_new_branch 79 | # switch to new branch 80 | git co my_new_branch 81 | 82 | # go back three commits (you're at the 4th commit, go back to 1) 83 | # this puts you in an unnamed branch, so you can edit it and name it with git checkout -b dirty_branch 84 | # use case: you need to fix a production bug. 85 | git co HEAD~3 86 | git co master~3 87 | 88 | # go to commit by name (it will switch branches if necessary) 89 | git co :/"fixed that thing" 90 | 91 | # save current work and fix a bug 92 | git commit -a # you're saving the current state fo fix an older commit, you could use a stash 93 | git checkout -b my_fixes 1b6d # fix it 94 | git commit -a -m "Bug fixed" 95 | git checkout master # go back to what you were doing 96 | git merge my_fixes # merge the temporary branch 97 | 98 | # delete a branch 99 | git branch -d my_fixes 100 | 101 | # When you realize you should have created a branch 7 commits ago 102 | git branch -m master part2 # Rename "master" branch to "part2". -m => move, rename 103 | git branch master HEAD~7 # Create new "master", 7 commits upstream. We're still in part2 branch 104 | git checkout HEAD~7 -b master # Create a branch, and switch to it. 105 | 106 | # refer to the second parent (the current branch at the time of the merge is the first parent) 107 | git log HEAD^2 108 | # refer to the first parent 109 | git log HEAD^ 110 | # refer to the second parent of the first parent 111 | git log HEAD^^2 112 | 113 | # List all branches 114 | git branch 115 | 116 | # save current state in a temporary branch and go back to the previous commit 117 | git stash 118 | # go back to the stashed state, you many need to resolve some conflicts 119 | git stash apply 120 | 121 | # change the last commit message 122 | git commit --amend 123 | # add a file to the last commit 124 | git commit --amend -a 125 | 126 | # remove files from previous commit (made a mistake) 127 | git reset --soft HEAD^ 128 | git rm --cached my_file 129 | git commit -c ORIG_HEAD 130 | git commit -C ORIG_HEAD # don't re-edit the commit message 131 | 132 | # delete every commit up to 766f 133 | git reset --hard 766f 134 | 135 | # undo a previous commit without deleting it 136 | git revert 766f 137 | 138 | # web viewer 139 | git instaweb 140 | git instaweb --stop 141 | 142 | # add interactively 143 | git add -p 144 | git add -i 145 | 146 | # see deleted hashes 147 | git reflog 148 | 149 | # go back to older commit 150 | git checkout "@{10 minutes ago}" 151 | git checkout "@{5}" 152 | 153 | # add a remote branch 154 | git remote add origin git@github.com:username/Hello-World.git 155 | git pull origin master 156 | git push -u origin master -------------------------------------------------------------------------------- /gmail tricks.txt: -------------------------------------------------------------------------------- 1 | * then t: select visible unstarred conversations -------------------------------------------------------------------------------- /idle_tricks.txt: -------------------------------------------------------------------------------- 1 | # things to do when you're idle 2 | 3 | file your nails 4 | 5 | add 10 min portuguese vocab 6 | 7 | find a cool bioinfo article 8 | 9 | do a science writing video 10 | 11 | -------------------------------------------------------------------------------- /illustrator_tricks.txt: -------------------------------------------------------------------------------- 1 | # Change keyboard shortcuts 2 | Edit | Keyboard shortcuts 3 | /Users/nacho/Library/Preferences/Adobe Illustrator CS5.1 Settings/en_US/my_illustrator_shortcuts.kys 4 | 5 | # change sRGB to a better color space 6 | /Library/Application Support/Adobe/Color/Settings/Best Workflow CS5.csf 7 | Edit|Color Settings | load | Best Workflow 8 | 9 | # Change keyboard increments 10 | Preferences | General | Keyboard Increments 11 | 12 | # Select objects by clicking on their path, not their fill (you can also do this with Type) 13 | Preferences | Selection & anchor display | object selection by path only 14 | 15 | # Increase layer preview size (this is an illustration level setting) 16 | Layers panel |options | 75 pts 17 | 18 | # Add panels 19 | Window | panel 20 | 21 | # Toggle hide/show panels 22 | TAB 23 | ⇧ + Tab (hide right panels) 24 | 25 | # Toggle between Hide tabs/full screen or super full screen (or press windows at bottom of toolbar) 26 | F 27 | 28 | # Save a panel arrangement (custom workspace) 29 | Essentials | save custom workspace 30 | 31 | # Disable the bounding box (use rotate and scale tools) 32 | View | Show Bounding box 33 | 34 | # Useful shortcuts ⌘⌥⇧^ 35 | ⌘+0 zoom to fit 36 | 37 | # Use pathfinder to cookie-cut your illustrations 38 | 39 | # add downloaded brushes here 40 | /Users/nacho/Library/Application Support/Adobe/Adobe Illustrator CS5.1/en_US/Brushes/ 41 | 42 | # duplicate around a point 43 | Select the object 44 | Select Rotate tool 45 | Alt click on the place where you want the origin to be 46 | choose angle 47 | Copy 48 | Cmd+D or Object|Transform|Transform again 49 | 50 | # transform each 51 | Object |transform |transform each 52 | cmd+shift+alt+d 53 | 54 | # Convert a path into its shape 55 | Object|expand path 56 | 57 | # round corners 58 | Effects | stylize | round corners 59 | object |expand appearance 60 | 61 | # Knife tool to break a path (useful) => 62 | 63 | -------------------------------------------------------------------------------- /javascript_tricks.js: -------------------------------------------------------------------------------- 1 | // coffeescript compile 2 | cake watch 3 | 4 | // coffeescript hash object 5 | math = 6 | root: Math.sqrt 7 | square: square 8 | cube: (x) -> x * square x 9 | 10 | // pop and shift modify arr, clone arr instead by using slice(0) 11 | arr2 = arr.slice(0).pop() 12 | arr2 = arr.slice(0).shift() 13 | 14 | // create an object with the frequencies of each element in an array 15 | t={} 16 | _.chain(arr) 17 | .groupBy (function (p) { return p; }) 18 | .each (function (e, i) { 19 | t[i] = _.size (e); 20 | }); // use .reverse() if you want descending 21 | 22 | // underscore.js flatten(array, [shallow]) 23 | _.flatten([1, [2], [3, [[4]]]]) // [1, 2, 3, 4] 24 | _.flatten([1, [2], [3, [[4]]]], true) // only first level [1, 2, 3, [[4]]] 25 | 26 | // underscore.js without(array, [*values]) 27 | _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); //[2, 3, 4] 28 | 29 | // underscore.js union(*arrays) 30 | _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); //[1, 2, 3, 101, 10] 31 | 32 | // underscore.js intersection(*arrays) 33 | _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]) // [1, 2] 34 | 35 | // underscore.js difference(array, *others) 36 | _.difference([1, 2, 3, 4, 5], [5, 2, 10]); // others can be multiple arrays [1, 3, 4] 37 | 38 | // underscore.js unique or uniq(array, [isSorted], [iterator]) 39 | _.uniq([1, 2, 1, 3, 1, 4]); //[1, 2, 3, 4] 40 | _.uniq([1, 2, 2, 3, 4, 4], true); // faster algorithm 41 | _.uniq([1, 2, 2, 3, 4, 4], function(){}); // If you want to compute unique items based on a transformation, pass an iterator function. 42 | 43 | // underscore.js zip(*arrays) 44 | _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); // [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] 45 | 46 | // underscore.js extend(destination, *sources) combine into an object 47 | _.extend({name : 'moe'}, {age : 50}); // {name : 'moe', age : 50} 48 | 49 | // underscore.js pick(object, *keys) 50 | _.pick({gene_name : 'STAT1', lassa_day_0: 3.2, lassa_day_3: 5.3, cluster:3}, 'gene_name', 'cluster'); // {gene_name : 'STAT1', cluster : 3} 51 | 52 | // underscore.js defaults(object, *defaults) 53 | var iceCream = {flavor : "chocolate"}; 54 | _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"}); //{flavor : "chocolate", sprinkles : "lots"} 55 | 56 | // underscore.js has(object, key) 57 | _.has({a: 1, b: 2, c: 3}, "b"); //true 58 | 59 | // underscore.js all(list, iterator, [context]) Alias: every 60 | _.all([true, 1, null, 'yes'], _.identity); // false 61 | 62 | // underscore.js any(list, [iterator], [context]) Alias: some 63 | _.any([null, 0, 'yes', false]); // true 64 | 65 | // underscore.js include(list, value) Alias: contains, nicer than indexOf 66 | _.include([1, 2, 3], 3); //true 67 | 68 | // underscore.js invoke(list, methodName, [*arguments]) 69 | // Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation. 70 | _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); // [[1, 5, 7], [1, 2, 3]] 71 | 72 | // underscore.js pluck(list, propertyName) 73 | var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; 74 | _.pluck(stooges, 'name'); // ["moe", "larry", "curly"] convenient version of "map" 75 | 76 | // underscore.js sortBy(list, iterator, [context]) 77 | _.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); }); // [5, 4, 6, 3, 1, 2] 78 | 79 | // underscore.js groupBy(list, iterator) 80 | _.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); }); // {1: [1.3], 2: [2.1, 2.4]} 81 | _.groupBy(['lassa_day_3', 'lassa_day_6','ebola_day_3'], function(experiment){ return experiment.split("_")[0]; }); // {ebola: ['ebola_day_3'], lassa: ['lassa_day_3','ebola_day_6']} 82 | _.groupBy(['one', 'two', 'three'], 'length');// iterator can also be a string {3: ["one", "two"], 5: ["three"]} 83 | 84 | // underscore.js first 85 | _([1,2,3]).first(2) //[1,2] 86 | _.first([1,2,3],2) //[1,2] 87 | 88 | // underscore.js chain 89 | var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}]; 90 | var youngest = _.chain(stooges) 91 | .sortBy(function(stooge){ return stooge.age; }) //[{name : 'moe', age : 21}, {name : 'larry', age : 23}, {name : 'curly', age : 25}]; 92 | .map(function(stooge){ return stooge.name + ' is ' + stooge.age; }) // ["moe is 21", "larry is 23", "curly is 25"] 93 | .first() // "moe is 21" 94 | .value(); // return unwrapped objects: "moe is 21" 95 | 96 | // coffeescript ternary 97 | if item == replaceItem then replaceWith else item // item == replaceItem ? replaceWith : item 98 | 99 | // coffeescript there is no elsif 100 | if student.excellentWork 101 | "A+" 102 | else if student.okayStuff 103 | "B" 104 | else 105 | "C" 106 | 107 | // coffeescript loops 108 | my_func(item) for item in array // for(i=0, len=array.length;i < len; i++) { item=array[i]; my_func(item) } 109 | my_func(i+1,item) for item, i in array // for (i=j=0, len=array.length; j < len; i=++j) { item=array[i]; my_func(i+1, item); } 110 | my_func(item) for item in array when item isnt "gene_1" // for (k=0,len=array.length ; k 117 | object.num 118 | objects.filter (object)-> 119 | object.num > 2 120 | objects.select (object)-> 121 | object.num > 2 122 | 123 | 124 | // comprehensions - use it to collect 125 | 126 | countdown = (num for num in [10..7]) // [10,9,8,7] 127 | countdown = (num for num in [10..1] when num > 6) // [10,9,8,7] 128 | even_numbers = (x for x in [0..10] by 2) // [0,2,4,6,8,10] 129 | for num in [10..7] 130 | "the number is #{num}" 131 | 132 | yearsOld = joe: 10, ida: 9, tim: 11 // yearsOld = {joe:10, ida:9, tim:11} 133 | ages = for child, age of yearsOld // "of" iterates over the properties of an object 134 | "#{child} is #{age}" 135 | ages = (age for child, age of yearsOld) // collect the keys. you need the parenthesis 136 | ages = (child.age for child in yearsOld) // do the same with "in" 137 | ages = ([child.age,child.firstName] for child in yearsOld) // collect a subset of properties 138 | 139 | ages = (age for own child, age of yearsOld) // use own to ensure you're not inheriting properties 140 | 141 | buy() while supply > demand // while (supply > demand) { buy() } 142 | sell() until supply > demand // while (!(supply > demand)) { sell() } 143 | num = 99 144 | cancion = while num -= 1 145 | "#{num} bottles of beer in the wall..." 146 | 147 | until // while not 148 | loop // while true 149 | 150 | // array.reverse 151 | [1,2,3].reverse() // [3,2,1] 152 | 153 | // array.shift 154 | [1,2,3].shift() // 1 array is now [2,3] 155 | 156 | // array.sort - Sort the elements of the array. 157 | // array.splice - Add or remove elements from the array. 158 | // array.unshift - Add one or more elements to the front of the array. 159 | 160 | // array.concat - Join the array with other array(s) or value(s). 161 | // array.join - Join all elements of the array into a string. 162 | // array.slice - Extract a section of the array. 163 | // array.indexOf - Find the first occurrence of a value within the array. 164 | // array.lastIndexOf - Find the last occurrence of a value within the array. 165 | 166 | // array.filter - Create a new array with only the elements for which a predicate is true. (check out _.reject) 167 | // array.forEach - Call a function for each element in the array. 168 | // array.every - See if every element in the array satisfies a predicate. 169 | // array.map - Create a new array with the result of a function of every element in the array. 170 | // array.some - See if at least one element in the array satisfies a predicate. 171 | // array.reduce - Apply a function to reduce the array to a single value (from left-to-right). 172 | // array.reduceRight - Apply a function to reduce the array to a single value (from right-to-left) 173 | 174 | // sorting comparators 175 | d3.ascending(4,1) //1 176 | d3.ascending(1,1) //0 177 | d3.ascending(1,4) //-1 178 | d3.descending(1,4) //1 179 | 180 | //d3.min d3.max d3.extent d3.sum 181 | d3.min([1,2,3,-10]) // -10 182 | d3.min([{name:"a",val:3},{name:"b",val:-10}], function(d){ return d.val}) // -10 183 | 184 | // d3.first d3.last 185 | d3.first([{name:"a",val:3},{name:"b",val:-10}], function(d){ return d.val}) // {name:"b",val:-10} 186 | 187 | // d3.map(object) 188 | a = d3.map({name:"STAT1", logFC:3.25, "p value":1e-8, cluster:1, type:"TF"}) 189 | a.keys() // ["name", "logFC", "p value", "cluster", "type"] same as d3.keys({name:"STAT1", logFC:3.25, p_value:1e-8, cluster:1, type:"TF"}) 190 | a.values() // ["STAT1", 3.25, 1e-8, 1, "TF"] 191 | a.has("p value") // true 192 | a.get("p value") 193 | a.set("p value",.5) 194 | a.remove("p value") 195 | a.forEach(function(k, v) { // returns undefined, iteration order is arbitrary 196 | // USEFUL? 197 | }); 198 | 199 | // d3.line.defined 200 | line.defined((d) => d.geneExpression != null) # specific to d3.line, useful to determine which elements are not defined 201 | 202 | // d3.split(array, function) 203 | d3.split([1,3,null,5,undefined,8,9]) // [[1,3],[5],[8,9]] 204 | d3.split([1,3,5,8,9], function(d){ return d == 5}) // [[1,3],[8,9]] 205 | 206 | // d3.nest 207 | genes = [{name:"STAT1", logFC:3.25, p_value:1e-8, cluster:1, type:"TF"}, 208 | {name:"IL10", logFC:4.25, p_value:1e-8, cluster:1, type:"cytokine"}, 209 | {name:"STAT2", logFC:2.25, p_value:1e-8, cluster:2, type:"TF"}, 210 | {name:"STAT3", logFC:2.25, p_value:1e-8, cluster:2, type:"TF"}, 211 | {name:"IL2", logFC:1.25, p_value:1e-8, cluster:2, type:"cytokine"}, 212 | {name:"IL3", logFC:3.25, p_value:1e-8, cluster:3, type:"cytokine"}, 213 | ] 214 | 215 | nested_genes = d3.nest() // you get the original objects accessible by the keys that you specify 216 | .key(function(d) { return d.cluster; }) 217 | .key(function(d) { return d.type; }) 218 | .sortKeys(d3.ascending) // sort by cluster and type ascending (cytokine before TF) 219 | 220 | nested_genes.entries(genes) 221 | // [...,{key:"2", values: [ 222 | // {key:"TF", values: [ 223 | // {name:"STAT2", logFC:2.25, p_value:1e-8, cluster:2, type:"TF"}, 224 | // {name:"STAT3", logFC:2.25, p_value:1e-8, cluster:2, type:"TF"}, 225 | // ]} 226 | //]}] 227 | 228 | nested_genes.rollup(function(d){ // aggregate 229 | return { 230 | mean_expression: d3.mean(d, function(g) {return +g.logFC}) 231 | } 232 | }).entries(genes) 233 | // [...,{key:"2", values: [ 234 | // {key:"TF", values: [ 235 | // mean_expression: 2.25 236 | // ]} 237 | //]}] 238 | 239 | 240 | // d3.zip(arrays, ...) DON'T QUITE GET THIS 241 | d3.zip([[1,3],[3,5,6]]) 242 | 243 | // d3.transpose(matrix) DON'T QUITE GET THIS 244 | 245 | // d3.merge(arrays) 246 | d3.merge([[1,3],[3,5]]) // [1,3,3,5] 247 | 248 | // d3.permute(array,indexes) 249 | arr = ["a", "b", "c"] 250 | d3.permute(arr, [1, 2, 0]) //["b", "c", "a"] 251 | d3.permute(arr, [2, 1]) //["c", "b"] 252 | d3.permute(arr, [2, 1, 2]) //["c", "b", "c"] 253 | 254 | // d3.range(start,stop,step) 255 | d3.range(4) // 0,1,2,3 256 | d3.range(1,4) // 1,2,3 stop is not included 257 | d3.range(1,8,2) // 1,3,5,7 ascending 258 | d3.range(8,1,-2) // 8,6,4,2 descending 259 | d3.range(8,1,2) // [] 260 | d3.range(1,8,-2) // [] 261 | 262 | // append a single element 263 | circles = svg.selectAll("circle") 264 | .data([32, 57, 112, 293]) 265 | .enter().append("circle") 266 | circles.enter().append("circle") // append a single circle 267 | 268 | // update the graph on a dropdown menu change 269 | d3.select("#order").on("change", function() { // 270 | order(this.value); 271 | }); 272 | 273 | function order(value) { 274 | x.domain(orders[value]); // change the ordering of the matrix 275 | 276 | var t = svg.transition().duration(1000); 277 | 278 | t.selectAll(".row") 279 | .delay(function(d, i) { return x(i) * 4; }) 280 | .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; }) //change the position of all rows to the new x scale 281 | .selectAll(".cell") 282 | .delay(function(d) { return x(d.x) * 4; }) 283 | .attr("x", function(d) { return x(d.x); }); // change the position of the cells within each row to the new x scale 284 | 285 | t.selectAll(".column") 286 | .delay(function(d, i) { return x(i) * 4; }) 287 | .attr("transform", function(d, i) { return "translate(" + x(i) + ")rotate(-90)"; }); 288 | } 289 | 290 | // classed 291 | matrix.on("mouseover", mouseover) 292 | function mouseover(target) { 293 | d3.selectAll(".row text").classed("active", function(d, i) { return i == target.y; }); // add the active class to the row text whose target.column was mouseovered 294 | } 295 | 296 | // sort 297 | d3.range(5).map(Math.random).sort(function(a, b) { return d3.ascending(a,b);}) // same as { return a-b;} 298 | d3.range(5).map(Math.random).sort(function(a, b) { return d3.ascending(b,a);}) // same as { return b-a;} 299 | d3.range(n).sort(function(a, b) { return nodes[b].count - nodes[a].count; }) 300 | 301 | order_by_name = d3.range(n).sort(function(a, b) { return d3.ascending(nodes[a].name, nodes[b].name); }) 302 | x = d3.scale.ordinal().rangeBands([0, width]) 303 | x.domain(order_by_name) // sets the default ordering 304 | 305 | // forEach - build a matrix of objects 306 | matrix = []; 307 | arr = [{name: "paco", age: 32}, {name: "luis", age:33}]; 308 | n = arr.length; 309 | arr.forEach(function(object, i) { 310 | object.index = i; 311 | object.count = 0; 312 | 313 | matrix[i] = d3.range(n).map(function(j) { return {x: j, y: i, z: 0}; }); 314 | }); // matrix is [{x: 0, y: 0, z: 0},{x: 0, y: 1, z: 0} 315 | // {x: 1, y: 0, z: 0},{x: 1, y: 1, z: 0}] 316 | // arr is [{name: "paco", age: 32, index:0, count:0}, {name: "luis", age:33, index:1, count:0}]; 317 | 318 | // color the first column/row differently 319 | td = d3.selectAll("tr").selectAll("td") 320 | td.style("color", function(d, i) { return i ? null : "red"; }); // index 0 is falsy, so it's red 321 | td.style("color", function(d,i,j) { return j ? null : "red"}) // color the first cell red 322 | 323 | // convert a number to a char 324 | .text(function(d, i) { return String.fromCharCode(65 + i); }); // A B C D E F ... 325 | 326 | // d3.scale 327 | d3.scale.linear().domain([0, 1]).range([h, 0]) 328 | d3.scale.linear().domain([0, 4]).clamp(true) 329 | 330 | d3.scale.ordinal().rangeBands([0, width]) 331 | d3.scale.ordinal().domain(d3.range(n)).rangeBands([0, w], .2) //.2 is padding in the range [0,1], .5 means the band is equal to the padding width 332 | d3.scale.ordinal().domain(d3.range(m)).rangeBands([0, y0.rangeBand()]) 333 | 334 | d3.scale.category10() 335 | d3.scale.category10().domain(d3.range(10)) 336 | d3.scale.category20c() 337 | 338 | // transform translate - when translating, don't set the x or y attributes, add them to the translation: "translate(20" + (x(i) + 50) +")" 339 | .attr("transform", "translate(20)") // move 20 px to the right 340 | .attr("transform", "translate(-20)") // move 20 px to the left 341 | .attr("transform", "translate(0,10)") // move 10 px down 342 | .attr("transform", "translate(0,-10)") // move 10 px up 343 | .attr("transform", "translate(20,10)") // move 20 px to the right and 10 px down 344 | .attr("transform", "translate(" + margin.left + "," + margin.top + ")") 345 | .attr("transform", "translate(" + x.rangeExtent()[1] + ") rotate(-90)") 346 | .attr("transform", function(d, i) { return "translate(" + y1(i) + ",0)"; }) 347 | .attr("transform", function(d, i) { return "translate(0," + x(i) + ")"; }) 348 | 349 | // d3.select 350 | d3.select("p") 351 | d3.select(e.target) 352 | d3.selectAll("table tr").select("td") // flat selection, select preserves the existing grouping of the previous selection, parent is still body 353 | 354 | // d3.selectAll 355 | d3.selectAll("p") 356 | d3.selectAll(e.target) 357 | d3.selectAll(".a, .b") // selects the union of both classes 358 | d3.selectAll("#outer .inner") // same as d3.select("#outer").selectAll(".inner") 359 | d3.selectAll("td") // flat array of td 360 | d3.selectAll("tr").selectAll("td") // nested selection, selectAll creates a new grouping and returns the grouped array of td by tr AND sets the parent to tr 361 | d3.selectAll("table tr").data(arr).enter().append("td") // ERROR: the parent is body, you can't add a td to body 362 | 363 | // try catch exception 364 | try 365 | { 366 | //Run some code here 367 | } 368 | catch(err) 369 | { 370 | //Handle errors here 371 | } 372 | 373 | // selection.data (when data is assigned to an element, it's stored in __data__, and then DATA NEEDS AN ARRAY OF AN ARRAY) 374 | selection.data() // returns the update selection, the DOM elems that were successfully bound to the data elems. 375 | selection.data(arr) // joins arr with the current selection, by-index (default, to change it, provide a key function) 376 | selection.data(function(d,i) { return i; }) // same as selection.data(arr), except when updating 377 | selection.data(Object) // DON'T USE THIS. the selection already has a data object loaded, which is an array of objects/arrays, Object goes into each element 378 | selection.data(function(d) { return d; }) // USE THIS. d is an element of a previously bound data 379 | selection.data(function(d,i) { return my_array[i]; }) // this is useful when the selection already has data that you don't care about. The length of my_array must match the size of the selection. 380 | selection.data(d3.layout.pie()) // the selection already has a data object loaded, pie() returns the angles for each arc, it's just a function 381 | selection.data(arr, function(d,i) { return d.property; }) // if selection has __data__ (previously bound data), it will do a join with arr 382 | 383 | // selection.datum (it clears any previously bound data (it doesn't compute a join), unlike selection.data) 384 | selection.datum() //returns the bound datum for the first non-null element in the selection. This is generally useful only if you know the selection contains exactly one element. 385 | selection.datum(constant) //same for all elems 386 | selection.datum(function(d,i) {return d}) 387 | // log 10 388 | function log10(val) { 389 | return Math.log(val) / Math.log(10); 390 | } 391 | 392 | // exponent 393 | Math.pow(2,3) // 8 394 | 395 | // create new D3 app 396 | subl models/volcano_model.coffee 397 | subl views/volcano_view.coffee 398 | subl apps/volcano_app.haml apps/volcano_app.coffee 399 | 400 | // VAINILLA ELEMENTS svg: 401 | var svg = d3.select("body") 402 | .append("svg:svg") 403 | .attr("width", 1000) 404 | .attr("height", 1000); 405 | 406 | 407 | var rect = svg.append("rect") 408 | .attr("x",100) 409 | .attr("y",50) 410 | .attr("width", 100) 411 | .attr("height", 100) 412 | .style("fill","lightgrey"); 413 | 414 | var line = svg.append("line") 415 | // .attr("x1",0) 416 | .attr("x2",50) 417 | // .attr("y1",0) 418 | .attr("y2",50) 419 | // .style("stroke-width","2px") 420 | .style("stroke","black"); 421 | 422 | var text = svg.append("text") 423 | .attr("x", 20) 424 | .attr("y", 30) 425 | .attr("text-anchor", "middle") 426 | .attr("dx", ".5em") 427 | // .attr("dy",rect.attr("height")/2) 428 | // .style("stroke","black") 429 | .text("hola paco"); 430 | 431 | // I can't get this to work 432 | var d3_line = d3.svg.line() 433 | .x(function(d) { return x(d.x); }) 434 | .y(function(d) { return y(d.y); }); 435 | var path = svg.selectAll("path") 436 | .data([{x:1,y:2},{x:10,y:11},{x:20,y:22}]) 437 | .enter().append("path") 438 | .attr("d", function(d){ return d3_line(d); }) 439 | 440 | // do this inside the d3.csv(...) loop 441 | var div = d3.select("body").append("div") 442 | .style("position", "absolute") 443 | .style("left", 100 + "px") 444 | .style("width", 100 + "px") 445 | .style("height", 100 + "px") 446 | .style("background", "lightgrey") 447 | // .style("padding", "5px") 448 | // .text("hola"); 449 | 450 | // select elements of an array 451 | a = [1,2,3,4] 452 | a.slice(0) // [1,2,3,4] 453 | a.slice(1) // [2,3,4] 454 | a.slice(2,3) // [3] 455 | 456 | // debug 457 | debugger 458 | 459 | // d3 hover 460 | .on("mouseover", ()-> d3.select(this).style("fill", "#d62728")) 461 | .on("mouseout", ()-> d3.select(this).style("fill", "black")) 462 | 463 | // convert an array of strings into integers (or use parseInt) 464 | a = ['1','20','3'] 465 | for(var i=0; i d.cluster) 602 | .entries(@model.get "genes") 603 | 604 | 605 | // rename using hash 606 | ({PaCo:"paco",Sanchez:"Sánchez"})["Sanchez"] 607 | 608 | //external libraries 609 | %script{:src => "http://code.jquery.com/jquery-1.7.1.min.js"} 610 | %script{:src => "http://documentcloud.github.com/underscore/underscore.js"} 611 | %script{:src => "http://documentcloud.github.com/backbone/backbone.js"} 612 | %script{:src => "http://mbostock.github.com/d3/d3.js"} 613 | %script{:src => "http://twitter.github.com/bootstrap/assets/js/bootstrap-tooltip.js"} 614 | %script{:src => "http://twitter.github.com/bootstrap/assets/js/bootstrap-popover.js"} 615 | 616 | 617 | 618 | 619 | 620 | 621 | // internal libraries 622 | %script{:src => "../../js/jquery.js"} 623 | %script{:src => "../../js/underscore.js"} 624 | %script{:src => "../../js/backbone.js"} 625 | %script{:src => "../../js/d3.js"} 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | // Using class variables 634 | columnNames = getColumnNames(parsed_genes) 635 | 636 | Gene = Backbone.Model.extend 637 | initialize: (attributes)-> 638 | @formatColumns() 639 | @id = @cid 640 | 641 | formatColumns: -> 642 | @attributes[columnName] = +@attributes[columnName] for columnName in @constructor.columnNames # column names (conditions) are numeric 643 | , 644 | columnNames: columnNames # class variable 645 | 646 | Genes = Backbone.Collection.extend 647 | model: Gene 648 | 649 | genes = new Genes(parsed_genes) 650 | 651 | // index array (include) 652 | a = [1,2,4] 653 | a.indexOf(4) // 2 654 | a.indexOf(334) // -1 655 | 656 | // append array push 657 | a = [1,2,4] 658 | a.push(5) // [ 1, 2, 4, 5 ] 659 | 660 | // coffeescript regex with interpolation 661 | ///#{interpolatedVariable}///g 662 | /literalString/g 663 | 664 | // check if substring matches string 665 | long_str.match ///#{myVar}///g 666 | 667 | // absolute value 668 | Math.abs(-1) 669 | 670 | // convert number to string 671 | a += '' 672 | a.toString() 673 | 674 | //clone an array 675 | clone = originalArray.slice(0) 676 | 677 | // quick map, for console 678 | .map(function(x){return x.x}) 679 | 680 | // get the keys of an object 681 | Object.keys(my_obj) 682 | d3.keys(my_obj) 683 | d3.values(my_obj) 684 | d3.entries(my_obj) //[{key:xx,value:yy},{key:xx,value:yy},{key:xx,value:yy},...] 685 | 686 | // count appearance frequency of an element in an array 687 | arr.filter((elem) => 688 | !elem.match(/cluster/) 689 | ).length 690 | 691 | // get the first element of a selection 692 | d3.select("p") 693 | 694 | // get the position of an object with jquery 695 | $("#heatmap .row span:first").offset() 696 | -------------------------------------------------------------------------------- /latex_tricks.tex: -------------------------------------------------------------------------------- 1 | % n choose m 2 | \[ 3 | \cdot{365 \choose 15} 4 | \] 5 | 6 | % big parenthesis or brackets 7 | \[ 8 | \left( X \right) 9 | \] 10 | 11 | % union ∪ 12 | $\cup$ 13 | 14 | % intersection ∩ 15 | $\cap$ 16 | 17 | % limit as N goes to infinity 18 | $\lim_{N \to +\infty}$ 19 | 20 | 21 | % italics 22 | \emph{blah blah} 23 | 24 | % plus or minux 25 | \pm 26 | 27 | % quotation marks quotes 28 | ``blah blah'' 29 | 30 | % space in math mode 31 | \text{ blah blah} 32 | 33 | % listing code 34 | \begin{lstlisting} 35 | 36 | \end{lstlisting} 37 | 38 | % ⟨i⟩ left and right angle brackets 39 | \langle i \rangle 40 | 41 | % asterisk in math mode 42 | $\ast$ 43 | 44 | % sumatorio 45 | $\sum_{i=1}^t$ 46 | 47 | % partial derivative 48 | $\partial$ 49 | 50 | % ô hat circumflex 51 | \hat{o} 52 | 53 | % tilde 54 | \tilde{a} \acute{a} \bar{a} \dot{a} \breve{a} \check{a} \grave{a} \vec{a} \ddot{a} 55 | 56 | % go back to text mode literal verbatim text during math 57 | $\log_2 \frac{2^{-∆Ct}\mbox{ target genes}}{2^{-∆Ct}\mbox{ housekeeping gene}}$ 58 | $\log_2 \frac{2^{-∆Ct}\text{ target genes}}{2^{-∆Ct}\text{ housekeeping gene}}$ 59 | 60 | % literal text, don't interpret, allow all spaces and indentations 61 | \begin{verbatim} 62 | 63 | \end{verbatim} 64 | 65 | % insert image 66 | \begin{figure}[h!] 67 | \centering 68 | \includegraphics[width=1\textwidth]{biogenesis.png} 69 | \caption{miRNA biogenesis} 70 | % \label{fig:biogenesis} 71 | \end{figure} 72 | 73 | % reference figure 74 | Figure~\ref{fig:mds} 75 | 76 | % Figure positioning 77 | h Place the float here, i.e., approximately at the same point it occurs in the source text (however, not exactly at the spot) 78 | t Position at the top of the page. 79 | b Position at the bottom of the page. 80 | p Put on a special page for floats only. 81 | ! Override internal parameters LaTeX uses for determining "good" float positions. 82 | H Places the float at precisely the location in the LaTeX code. Requires the float package,[1] e.g., \usepackage{float}. This is somewhat equivalent to h!. 83 | 84 | % Less than or greater than 85 | < 86 | > 87 | 88 | % Less than or equal to ≤ 89 | \leq 90 | 91 | % comment or annotate an equation 92 | \intertext{$u=S(t); du=S'(t)dt$} 93 | 94 | % matrix 95 | \begin{align*} 96 | begin{pmatrix} 97 | 1 & 0\\ 98 | -1 & 0\\ 99 | 0 & 1 \\ 100 | 0 & -1 \\ 101 | \end{pmatrix} 102 | \end{align*} 103 | % square root cubic 104 | $\sqrt[3]{x+y}$ 105 | 106 | % citations 107 | http://blog.mendeley.com/tipstricks/howto-use-mendeley-to-create-citations-using-latex-and-bibtex/ -------------------------------------------------------------------------------- /markdown tricks.markdown: -------------------------------------------------------------------------------- 1 | 2 | # This is an H1 3 | ## Markdown plus h2 with a custom ID {#id-goes-here} 4 | [Link back to H2](#id-goes-here) 5 | ###### This is an H6 6 | 7 | 8 | 9 | $$\begin{align} \rho_{X,Y} &= \frac{cov(X,Y)}{\sigma_X\sigma_Y} \\ &= \frac{E[(X-\mu_X)(Y-\mu_Y)]}{\sigma_X\sigma_Y} \end{align}$$ 10 | 11 | 12 | A | B | C 13 | --- | --- | --- 14 | 1 | Male | Blue 15 | 2 | Female | Pink 16 | 17 | 18 | 19 | > To be, or not to be, that is the question: 20 | > Whether 'tis nobler in the mind to suffer 21 | > The slings and arrows of outrageous fortune, 22 | 23 | >> nested blockquote 24 | 25 | 26 | * Red 27 | * Green 28 | * Blue 29 | 30 | 31 | 1. Bird 32 | 2. McHale 33 | 3. Parish 34 | 35 | 36 | * * * 37 | *** 38 | --- 39 | 40 | 41 | 42 | 43 | 44 | [header][] 45 | 46 | 47 | This is [an example](http://example.com/ "Title") inline link. 48 | [This link](http://example.net/) has no title attribute. 49 | 50 | [![Rack::Bug](http://img.skitch.com/20091027-xyf4h1yxnefpp7usyddrcmc7dn.png)] 51 | 52 | 53 | This is [an example][id] reference-style link. 54 | This is [an example][id] reference-style link. 55 | [id]: http://daringfireball.net/ 56 | 57 | Visit [Daring Fireball][] for more information. 58 | [Daring Fireball]: http://daringfireball.net/ 59 | 60 | I get 10 times more traffic from [Google] [1] than from 61 | [Yahoo] [2] or [MSN] [3]. 62 | 63 | [1]: http://google.com/ "Google" 64 | [2]: http://search.yahoo.com/ "Yahoo Search" 65 | [3]: http://search.msn.com/ "MSN Search" 66 | 67 | I get 10 times more traffic from [Google][] than from 68 | [Yahoo][] or [MSN][]. 69 | 70 | [google]: http://google.com/ "Google" 71 | [yahoo]: http://search.yahoo.com/ "Yahoo Search" 72 | [msn]: http://search.msn.com/ "MSN Search" 73 | 74 | 75 | ![Alt text](path_url/to/img.jpg) 76 | ![Alt text](path_url/to/img.jpg "Optional title") 77 | 78 | 79 | ![Alt text][id] 80 | [id]: path_url/to/image "Optional title attribute" 81 | 82 | 83 | Smiley face 84 | 85 | 86 | Apple 87 | : Pomaceous fruit of plants of the genus Malus in 88 | the family Rosaceae. 89 | : An american computer company. 90 | 91 | 92 | 93 | *single asterisks* 94 | _single underscores_ 95 | 96 | 97 | **double asterisks** 98 | __double underscores__ 99 | 100 | 101 | `code --version` 102 | 103 | 104 | ```javascript 105 | var s = "JavaScript syntax highlighting"; 106 | alert(s); 107 | ``` 108 | 109 | This line has two spaces at the end (hard for you to see, but trust me!). 110 | So this is a separate line in the *same paragraph*. -------------------------------------------------------------------------------- /microarray_tricks.txt: -------------------------------------------------------------------------------- 1 | # Batch effect => technical source of variation that was added to the samples during handling. 2 | 3 | MDS plot 4 | color by category 5 | color by platform/date 6 | see if the clusters are mixed or not 7 | 8 | Use quantile normalization for Affy 9 | 10 | # mean 11 | X_bar = (1/M)Sum_1^M(X_i) 12 | Y_bar = (1/N)Sum_1^N(Y_i) 13 | 14 | # variance (standard dev squared) (within-group) 15 | (1/M-1)Sum_1^M(X_i - X_bar)^2 (population X, observations X) 16 | (1/N-1)Sum_1^N(Y_i - Y_bar)^2 17 | 18 | # Welch's t-test => the two population variances are assumed to be different and must be estimated separately, used to calculate if two population means are difference 19 | (Y_bar - X_bar)/sqrt(var_y/N + var_X/M) 20 | 21 | (Y_bar - X_bar)=M-value 22 | 23 | The t-test is not good for small sample sizes because we don't have enough data to estimate the variability, and therefore we "underestimate" the denominator (the t-test is not very powerful) 24 | 25 | So, we borrow strength from all the genes to estimate the SD from a specific gene (see empirical bayes). => 26 | 27 | 28 | We look at the variances across arrays for all genes N, we use the distribution of all variances as the prior distribution for each variance. If the sample variance is tiny for a given gene, and we look at all the genes and see that such tiny variances (and therefore, very low p-values) are very rare, we shrink the p-value (we use a prior of inverse chi-square, there is a mathematically convenient formula that tells us how to shrink p-values). 29 | 30 | 31 | #Standard error: the SD of the sampling distribution of a statistic (or also, the estimate of the SD of the population, computed from the current sample) 32 | Ex: the sample mean is the usual estimator of the population mean 33 | diff samples from that population will have different mean values. 34 | 35 | The standard error of the mean (the SE of using the sample mean to estimate the population mean) is the SD of all the possible sample means (of the same size) drawn from the population. 36 | SE is an estimate of how close to the pop. mean your sample mean is likely to be 37 | 38 | The standard error of the regression is the ordinary least squares estimate of the SD of the underlying errors. 39 | 40 | # empirical Bayes 41 | We plot the distribution of the standard errors of each gene 42 | We shrink the small values up toward the mean, and the high values down toward the mean. 43 | 44 | If we see a gene with a very small variance and we see that variances like that are very rare (based on the distribution of all genes) => we shrink it back based on sample size and mean variance. 45 | 46 | # background correction 47 | BC improves accuracy, but it increases variance. We correct for the background taking over the signal at low intensities. 48 | 49 | In practice, many people don't BC, and instead normalize: estimate the bias and remove it. We assume that the cloud of points is around zero: most genes are not differentially expressed. 50 | 51 | # normalize 52 | We estimate the curve (bias) in the MA plot using LOESS. Then we make it straight. 53 | 54 | -------------------------------------------------------------------------------- /octopress_tricks.markdown: -------------------------------------------------------------------------------- 1 | # watch for changes and update site (http://octopress.dev/) 2 | rake watch 3 | 4 | # draft posts path 5 | ~/Documents/Blog/ 6 | 7 | # publish (from ~/Documents/Blog/nachocab.github.com) 8 | rake generate 9 | rake deploy 10 | 11 | # new post 12 | rake new_post['my new post'] 13 | 14 | # Pullquotes 15 | {% pullquote %} 16 | Surround your paragraph with the pull quote tags. Then when you come to 17 | the text you want to pull, {" surround it like this "} and that's all there is to it. 18 | {% endpullquote %} 19 | 20 | # Blockquotes 21 | {% blockquote [author[, source]] [link] [source_link_title] %} 22 | Quote string 23 | {% endblockquote %} 24 | 25 | # Images 26 | add_image peroxidase\ sizes.png 27 | 28 | google picasa post blog /Users/nachocab/Documents/Blog/images/fish.png 29 | google picasa list blog 30 | 31 | # Links 32 | This is an [example link](http://example.com/ "With a Title"). 33 | This is an example link. 34 | 35 | I get 10 times more traffic from [Google][1] than from [Yahoo][2] or [MSN][3]. 36 | 37 | [1]: http://google.com/ "Google" 38 | [2]: http://search.yahoo.com/ "Yahoo Search" 39 | [3]: http://search.msn.com/ "MSN Search" 40 | 41 | I start my morning with a cup of coffee and [The New York Times][NY Times]. 42 | 43 | [ny times]: http://www.nytimes.com/ 44 | 45 | -------------------------------------------------------------------------------- /python_tricks.py: -------------------------------------------------------------------------------- 1 | # debugging 2 | import pdb; pdb.set_trace() 3 | h # help 4 | s # step 5 | n # next 6 | unt # until 7 | r # return 8 | c # continue 9 | j LINE # jump to line number without executing 10 | l # list source code 11 | p EXPR # eval expression 12 | 13 | # python console 14 | python 15 | 16 | # range 17 | range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 18 | 19 | # list comprehensions (inline for) 20 | [i for i in range(10) if i%2 == 0] # [0, 2, 4, 6, 8] 21 | 22 | # sum list (arrays are called lists) 23 | sum([0, 2, 4, 6, 8]) # 20 24 | 25 | # make a copy of a list 26 | a = b = [] # both point to the same list 27 | b = a[:] # b is a copy of list a 28 | 29 | 30 | # print a number with a string 31 | print('The value of x is ' + str(x) + ', and y is ' + str(y)) 32 | 33 | # if else 34 | if "something": 35 | something 36 | else: 37 | something_else 38 | -------------------------------------------------------------------------------- /ruby_tricks.rb: -------------------------------------------------------------------------------- 1 | # sample from an array random 2 | [:foo, :bar].sample # :bar 3 | (1..10).to_a.sample 2 # [3, 10] 4 | 5 | # debugger, don't use ruby-debug 6 | require 'debugger' 7 | debugger 8 | 9 | # sort files by descending modification time 10 | Dir['*.html'].sort_by{ |f| File.mtime(f) }.reverse - 11 | 12 | # get the delete key working on irb: press ctrl+d in terminal preferences|keyboard|forward delete 13 | 14 | # get duplicate elements of an array 15 | questions.select{|e| questions.count(e) > 1 } 16 | 17 | # allow utf8 in script 18 | # encoding: utf-8 19 | 20 | # better irb 21 | pry 22 | 23 | # get user input 24 | gets 25 | answer = gets 26 | 27 | # capture control-c 28 | begin 29 | ... 30 | rescue Interrupt 31 | ... 32 | end 33 | 34 | # check if file exists 35 | File.exist?(path) 36 | 37 | # $: - Array of paths used for looking up external files: [/Users/nacho/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1, /Users/nacho/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/x86_64-darwin11.3.0, /Users/nacho/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby, ...] 38 | $:.unshift File.join(File.dirname(__FILE__), *%w[.. lib]) # prepends "./../lib" to the $: array of paths 39 | # now you can do 40 | require 'ruhoh' # instead of require './../lib/ruhoh', now all the files directly below this folder are accessible, and here you set up all the requirements 41 | 42 | # require - don't need to add the .rb extension 43 | require 'ruhoh/client/client' # instead of 'ruhoh/client/client.rb' 44 | Ruhoh::Client.new # because it's a subfolder 45 | # and then in ruhoh/client/client.rb 46 | class Ruhoh 47 | class Client # could be a module, if you don't need to instantiate 48 | ... 49 | end 50 | end 51 | 52 | # check if a string matches a regex: returns position of first match or nil 53 | "My string" =~ /My/ # 0 54 | "My string" =~ /string/ # 3 55 | "My string" =~ /paco/ # nil 56 | 57 | # check if a string matches a regex: returns a MatchData object 58 | m = "My string".match /xxx/ # nil 59 | m = "My string".match /My/ # m[0]=>"My" m.string=>"My string" m.regexp => /My/ m.begin 0 => 0 60 | m = "My string".match /string/ # m[0]=>"My" m.string=>"My string" m.regexp => /My/ m.begin 0 => 3 61 | m = "My string".match /(\w+)\s(\w+)/ # m[0]=>"My string" m[1]=>"My" m[2]=>"string" m.captures=>["My", "string"] zero-based, you can also use $1 and $2 for the captured elements, m.begin 2 => 3 62 | m = "My string".match /\s(\w+)/ # $1 => "string" m.pre_match => "My" m.post_match => "" 63 | 64 | 65 | # open file write 66 | File.open(local_filename, 'w') {|f| f.write(doc) } 67 | 68 | # read entire file into array 69 | arr = IO.readlines(path) 70 | 71 | # read file line by line 72 | File.open(path) do |file| 73 | file.each do |line| 74 | ... 75 | end 76 | end 77 | 78 | 79 | # format time now 80 | Time.now.ctime # "Sun Jul 22 12:00:43 2012" 81 | Time.now.strftime("%H:%M:%S") # "12:01:52" 82 | 83 | # remove array element 84 | [1,2,3] - [2] 85 | 86 | # remove a substring from a string, sanitize 87 | "paco.fastq".sub(/.fastq$/,'') 88 | str.sub(/[\/]/,"_") # remove forward slash 89 | 90 | # invert hash 91 | class Hash 92 | def inverse # unix gods 93 | i = Hash.new 94 | self.each_pair{ |k,v| 95 | if (v.class == Array) 96 | v.each{ |x| 97 | if i.has_key?(x) 98 | i[x] = [k,i[x]].flatten 99 | else 100 | i[x] = k 101 | end 102 | } 103 | else 104 | if i.has_key?(v) 105 | i[v] = [k,i[v]].flatten 106 | else 107 | i[v] = k 108 | end 109 | end 110 | } 111 | return i 112 | end 113 | end 114 | 115 | # count frequency elements array 116 | arr.inject(Hash.new(0)) {|h,i| h[i] += 1; h } 117 | 118 | # sort hash by value 119 | metrics.sort_by {|key, value| value} # ascending 120 | metrics.sort_by {|key, value| -value} # descending 121 | 122 | # initialize a hash with an array 123 | h = Hash.new {|h,k| h[k] = [] } 124 | h["a"].push(3) 125 | h["a"].push(5) 126 | h["b"].push(6) 127 | # {"a"=>[3, 5], "b"=>[6]} 128 | 129 | # puts to stderr 130 | $stderr.puts 131 | 132 | # exit abort error 133 | abort "MacOS too old, see: https://gist.github.com/1144389" if macos_version < 10.5 134 | 135 | # arguments 136 | ARGV 137 | ARGV[0] # first command 138 | 139 | # current script 140 | $0 141 | 142 | 143 | 144 | # execute command 145 | results = %x[ls] # same as Kernel#` (backticks) 146 | 147 | # get all files of a given type from a directory 148 | Dir.glob(File.join(GENE_SETS_PATH,"*.txt")) 149 | Dir['*.html'] 150 | 151 | # get directory of current file 152 | File.dirname(__FILE__) 153 | File.join(File.dirname(__FILE__), '..', '/') # move up one folder 154 | 155 | # Get filename from path 156 | File.basename($0) 157 | 158 | # remove file extension 159 | File.basename(my_file,File.extname(my_file)) 160 | 161 | # prepend to an array 162 | array.unshift 0 #=> [0, 1, 2, 3, 4] 163 | 164 | # check if element in my array 165 | [1,2,3].include?(2) 166 | 167 | # ruby string interpolate 168 | %{"paco #{pepe}"} 169 | 170 | # map 171 | ["a","b"].map(&:to_sym) 172 | 173 | # class level instance variables 174 | class Polygon 175 | @sides = 8 176 | class << self 177 | attr_accessor :sides 178 | def prueba 179 | puts @options 180 | end 181 | 182 | def run 183 | @options = 3 184 | end 185 | end 186 | end 187 | puts Polygon.sides # => 8 188 | Polygon.run #=> 3 189 | 190 | require 'test_helper' 191 | 192 | class RubyTest < ActiveSupport::TestCase 193 | # Glossary 194 | # 195 | # first-class entities - They can be stored in variables, they are objects, they can be 196 | # created with .new() 197 | # 198 | # Mix a module into a class - Make the module's instance methods available to all 199 | # instances of the class 200 | # 201 | # receiver - Receiver.method(argument) => Receiver is what receives the method message. 202 | context "Ruby" do 203 | should "Parallel assignment" do 204 | # Any assignment expression that has more than one l-value or r-value. 205 | 206 | a = 3 207 | b = [3] 208 | c = [3,4] 209 | assert_equal [3], [*a] 210 | assert_equal [3], [*b] 211 | assert_equal [3,4], [*c] 212 | # One l-value, multiple r-values 213 | x = 1,2,3 214 | assert_equal x, [1,2,3] 215 | 216 | x, = 1,2,3; 217 | assert_equal x, 1 218 | # assert x == 1 219 | 220 | # Multiple l-values, one array r-value 221 | x,y,z = [1,2,3] # same as x,y,z = 1,2,3 222 | assert_equal 1, x 223 | assert_equal 2, y 224 | assert_equal 3, z 225 | 226 | x = [1,2]; assert_equal [1,2], x 227 | x, = [1,2]; assert_equal 1, x 228 | 229 | # different number of l- and r-values 230 | x,y,z = 1,2 231 | assert_equal 1,x 232 | assert_equal 2,y 233 | assert_equal nil,z 234 | 235 | x,y = 1,2,3 # 3 is not assigned 236 | assert_equal 1,x 237 | assert_equal 2,y 238 | 239 | # Parentheses in parallel assignment. The lefthand side can use 240 | # parentheses for subassignment. If two or more l-values are enclosed in 241 | # parentheses, they are initially treated as a single l-value. When the 242 | # corresponding r-value has been determined, the rules of parallel 243 | # assignment are applied recursively. 244 | x,(y,z) = 3,[4,5] 245 | assert_equal 3, x 246 | assert_equal 4, y 247 | assert_equal 5, z 248 | 249 | x,y,z = 3,[4,5] 250 | assert_equal 3, x 251 | assert_equal [4,5], y 252 | assert_equal nil, z 253 | 254 | # Parentheses with hashes 255 | x,(y,z) = 3,{4 => 5} 256 | assert_equal 3,x 257 | assert_equal(({4 => 5}), y) 258 | assert_equal nil, z 259 | 260 | x,(y,z) = 3, *{4 => 5} 261 | assert_equal 3, x 262 | assert_equal 4, y 263 | assert_equal 5, z 264 | 265 | 266 | 267 | 268 | # Return more than one value 269 | def return_two_values 270 | a = 2; b = 3 271 | [a,b] 272 | end 273 | x,y = return_two_values 274 | assert_equal x,2 275 | assert_equal y,3 276 | 277 | 278 | # See the splat operator for more assignments 279 | 280 | end 281 | 282 | should "unless::" do 283 | # Unless means: execute the LEFT unless the RIGHT evaluates to TRUE 284 | # 285 | # falsy values => The right is true, the left executes 286 | a = "not changed"; b = "changed" 287 | 288 | a = b unless false; assert_equal a,"changed" 289 | a = b unless []; assert_equal a,"changed" 290 | a = b unless ""; assert_equal a,"changed" 291 | a = b unless nil; assert_equal a,"changed" 292 | a = b unless {}; assert_equal a,"changed" 293 | 294 | # truthy values => anything else, the left doesn't execute 295 | a = "not changed"; b = "changed" 296 | 297 | a = b unless true; assert_equal a,"not changed" 298 | a = b unless [3]; assert_equal a,"not changed" 299 | end 300 | 301 | should "super:: Chaining" do 302 | # It calls the method in the superclass with the same name, sending it the current 303 | # arguments. (The superclass doesn't have to define it, it could inherit it from an 304 | # ancestor.) 305 | # super => All arguments get passed when calling the method in the superclass 306 | # super() => No arguments get passed when calling the method in the superclass 307 | # super(x,y) => x and y get passed when calling the method in the superclass 308 | 309 | class Point 310 | def initialize(x,y) 311 | @x = x 312 | @y = y 313 | end 314 | end 315 | 316 | class Point3D < Point 317 | def initialize(x,y,z) 318 | super(x,y) # Point3D has access to instance variables @x and @y, so @x, @y = super(x,y) is unnecessary. 319 | @z = z 320 | end 321 | def show 322 | "" << "#{@x} " << "#{@y} " << "#{@z}" 323 | end 324 | end 325 | 326 | p3d = Point3D.new(2,3,4) 327 | assert_equal "2 3 4", p3d.show 328 | 329 | ############ 330 | class Parent 331 | def age 332 | 30 333 | end 334 | end 335 | class Child < Parent 336 | def age 337 | super - 20 338 | end 339 | end 340 | c = Child.new 341 | assert_equal 10, c.age 342 | end 343 | 344 | should "ensure::" do 345 | # Ensure that housekeeping details like closing files, disconnecting DB connections 346 | # and committing transactions get done. Use it whenever you allocate a resource 347 | # (file, DB connection) to ensure proper cleanup occurs. Even if there is an 348 | # exception, the ensure clause gets called. 349 | # 350 | # The ensure clause can replace the running exception with another one, or switch 351 | # the current return value with another one. 352 | def ensure_returns 353 | begin 354 | return 1 355 | ensure 356 | return 2 357 | end 358 | end 359 | assert_equal 2, ensure_returns 360 | end 361 | 362 | should "and::" do 363 | # Using this pattern wee can guarantee that the result we return will be valid, even 364 | # if an unexpected error is raised 365 | def increase_number(number) 366 | number.is_a?(Fixnum) ? number += 1 : (raise ArgumentError) 367 | end 368 | 369 | def increment(number) 370 | begin 371 | return_value = increase_number(number) and return return_value #successful 372 | # If the below executes, something went wrong. 373 | rescue ArgumentError => e 374 | return e.class 375 | end 376 | end 377 | 378 | assert_equal 3, increment(2) 379 | assert_equal(ArgumentError, increment("error"), "It wasn't a number") 380 | end 381 | 382 | should "for...in..." do 383 | @mestres = "" 384 | for mestre in ["bimba", "pastinha", "camisa"] 385 | @mestres << mestre << " " 386 | end 387 | assert_equal "bimba pastinha camisa ", @mestres 388 | end 389 | 390 | should "alias:: " do 391 | def existing; 3; end 392 | alias old_existing existing 393 | assert_equal 3, old_existing 394 | end 395 | 396 | should "configure ruby" do 397 | # gem sources -a http://gems.github.com # add sources 398 | # set HOME=. 399 | # gem install sqlite3-ruby --version 1.2.3 400 | end 401 | 402 | should "case::" do 403 | a = case ['an_array'] 404 | when is_a?(Array) 405 | 'WRONG WAY OF DOING IT' 406 | when Array 407 | 'RIGHT' 408 | when b = ['an option hash'] 409 | b # better than repeating ['an option hash'] 410 | else 411 | 'other' 412 | end 413 | assert_equal 'RIGHT', a 414 | 415 | b = case 'a' 416 | when 'a','b' 417 | 'yes' 418 | end 419 | assert_equal 'yes', b, "You can assign the result of a case structure directly" 420 | 421 | empty = nil 422 | res = case empty 423 | when nil 424 | 3 425 | when blank? 426 | # WRONG: "empty" will never equal "blank?" 427 | else 428 | 4 429 | end 430 | assert_equal 3, res 431 | 432 | arg = "H" 433 | case arg 434 | when Array 435 | when String then arg.downcase! 436 | when :start 437 | when :end then -1 438 | when /[a-z]/ 439 | end 440 | assert_equal "h", arg, "Using case with then" 441 | 442 | case 443 | when 1 == 1 444 | a = 3 445 | end 446 | assert_equal a, 3, "case with no argument" 447 | end 448 | end 449 | 450 | context "Kernel" do 451 | should "method_missing:: obj.method_missing(symbol [, *args] ) => result " do 452 | # symbol is the symbol for the method called, and args are any arguments that were 453 | # passed to it 454 | class Roman 455 | def roman_to_int(str) 456 | case str.to_s 457 | when 'i' then 1 458 | when 'ii' then 2 459 | when 'iii' then 3 460 | end 461 | end 462 | def method_missing(method) 463 | roman_to_int(method) 464 | end 465 | end 466 | 467 | r = Roman.new 468 | assert_equal 3, r.iii 469 | end 470 | end 471 | 472 | context "Operators" do 473 | should "||=::" do 474 | def set_results(results = nil) 475 | results ||= [] 476 | # same thing as: results = results || [] same thing as: results = [] if 477 | # results.nil? 478 | end 479 | assert_equal [], set_results 480 | assert_equal [], set_results(false) 481 | assert_equal [1,2,3], set_results([1,2,3]) 482 | end 483 | 484 | should "*:: The splat operator" do 485 | # Uses Array Expansion Syntax. It lets us group together all remaining parameters 486 | # into a single array variable 487 | 488 | # 1 - ASSIGNMENT: * expands r-value arrays and hashes 489 | pet1, pet2, pet3 = 'duck', *['dog','cat'] 490 | assert_equal 'duck', pet1 491 | assert_equal 'dog', pet2 492 | assert_equal 'cat', pet3 493 | 494 | pet1, pet2, pet3 = 'duck', *{'dog' => 'cat'} 495 | assert_equal 'duck', pet1 496 | assert_equal ['dog','cat'], pet2 497 | assert_equal nil, pet3 498 | 499 | 500 | # 2 - ASSIGNMENT: * on l-values contracts values into arrays 501 | pet1, *other_pets = 'duck','dog','cat' 502 | assert_equal 'duck', pet1 503 | assert_equal ['dog','cat'], other_pets 504 | 505 | 506 | # 3 - convert a non-nested array to hash 507 | vehicles = [ :planes, 21, :cars, 36 ] 508 | vehicles_hash = Hash[*vehicles] 509 | assert_equal({ :planes => 21, :cars => 36 }, vehicles_hash) 510 | # convert a nested array into a hash 511 | vehicles_nested = [[:planes, 21], [:cars, 36]] # same as vehicles_hash.to_a 512 | vehicles_hash_unnested = Hash[*vehicles_nested.flatten] 513 | assert_equal({ :planes => 21, :cars => 36 }, vehicles_hash_unnested) 514 | 515 | assert_equal [:planes, 21, :cars, 36], [*vehicles_nested.flatten] 516 | assert_equal [:planes, 21, :cars, 36], vehicles_nested.flatten #WRONG - produces an error when converting to hash 517 | 518 | # 4 - Convert Hash to array by exploding hash. Not a good idea. Better use to_a 519 | vehicles_array = *{ :planes => 21, :cars => 36 } 520 | assert_same_elements [ [:planes, 21], [:cars, 36] ], vehicles_array 521 | 522 | # 4.1 - special case, with only one element. Convert hash to array. 523 | h = {'paco' => 343} 524 | a = *h 525 | b = h.to_a 526 | assert_equal ['paco',343], a 527 | assert_equal [['paco',343]], b 528 | 529 | h = {'paco' => 343, 'luis' => 454} 530 | a = *h 531 | b = h.to_a 532 | assert_equal [['paco',343],['luis',454]], a 533 | assert_equal a, b 534 | 535 | 536 | # 5 - Use in a case statement - explode array 537 | WILD = %w( lion ñu ) 538 | TAME = %w( cat cow ) 539 | def determine_continent(animal) 540 | case animal 541 | when *WILD then "Africa" 542 | when *TAME then "Europe" 543 | end 544 | end 545 | assert_equal "Africa", determine_continent("ñu") 546 | 547 | # 6 - Array#* operates as Array#join if supplied a string. If give a number, it does 548 | # repetition 549 | array = %w( join this sentence ) 550 | assert_equal "join—this—sentence", ( array * '—') 551 | assert_equal [0,0,0,0,0], [0] * 5 552 | 553 | # 7 - Define methods that take an unlimited number of arguments 554 | def method_with_unlimited_arguments(*args) 555 | true 556 | end 557 | def receives_arguments_and_hash(*args) 558 | options = args.extract_options! 559 | end 560 | def receives_only_hash(*opts) 561 | opts = opts.first.merge(opts.last) # e.g. 562 | end 563 | some_ints = [1,2,3] 564 | assert method_with_unlimited_arguments(2) 565 | assert method_with_unlimited_arguments(some_ints) 566 | assert method_with_unlimited_arguments([1,2,3]) 567 | 568 | # * repeats a string if followed by an integer. 569 | repeated = 'hola' * 2 570 | assert_equal "holahola", repeated 571 | end 572 | 573 | should "!!::Double negation" do 574 | # Used to force an object into an explicit true/false. Usually not necessary 575 | def is_this_true? 576 | @fishy_variable 577 | end 578 | @fishy_variable = nil 579 | assert_false @fishy_variable, "The variable is evaluated as false" 580 | assert_not_equal false, !@fishy_variable, "Even thought it isn't actually " 581 | assert_equal false, !!@fishy_variable, "The double negation coerces it into " 582 | 583 | end 584 | 585 | should "String#<<:: Append altering the left operand (also Array#<< and Set#<<)" do 586 | greeting = "A bananeira" 587 | greeting << " caiu" 588 | assert_equal "A bananeira caiu", greeting 589 | end 590 | 591 | should "%::formatting interpolation" do 592 | assert_equal "9.50", ("%.2f" % 9.5) 593 | 594 | assert_equal "

hello

", ( "<%s>%s" % %w{p hello p} ) 595 | end 596 | 597 | should "<=>::" do 598 | # Fixnum 599 | assert_equal -1, 2 <=> 3 600 | assert_equal 0, 3 <=> 3 601 | assert_equal 1, 3 <=> 2 602 | 603 | # String 604 | assert_equal -1, "abc" <=> "abcd" 605 | assert_equal 0, "abc" <=> "abc" 606 | assert_equal 1, "abcd" <=> "abc" 607 | 608 | # Array 609 | assert_equal -1, [1] <=> [1,2] 610 | assert_equal 0, [1] <=> [1] 611 | assert_equal 1, [1,2] <=> [1] 612 | 613 | end 614 | end 615 | 616 | context "Methods & Classes" do 617 | setup do 618 | class Point 619 | end 620 | 621 | end 622 | should "Singleton Method::" do 623 | # Singleton Method - Method that is defined for only a single object rather than a 624 | # class of objects. 625 | def Point.sum 626 | # sum is a singleton method on an object Point 627 | end 628 | 629 | # The singleton methods of an object are instance methods of its singleton class. 630 | class Iuna 631 | def self.don ; "don"; end 632 | def self.yin ; "yin"; end 633 | 634 | def self.singleton_class 635 | class << self 636 | self 637 | end 638 | end 639 | end 640 | iuna = Iuna.new 641 | assert_contains iuna.class.singleton_class.instance_methods(false), "don" 642 | assert_contains iuna.class.singleton_class.instance_methods(false), "yin" 643 | end 644 | 645 | should "Class methods::" do 646 | # Class methods are singleton methods of an object of Class type 647 | class Iuna 648 | def self.don ; "don"; end 649 | def self.yin ; "yin"; end 650 | end 651 | assert_same_elements ["don","yin"], Iuna.singleton_methods(false) 652 | end 653 | 654 | should "define_method(meth_name, meth_body):: Defines an instance method in the receiver" do 655 | # It expects a Symbol as meth_name and it creates a method with that name, using the 656 | # associated "block" as the method body. Instead of a block, it can also be a Proc 657 | # or a Method object. The block is evaluated using instance_eval. 658 | class A 659 | def create_method(name, &block) 660 | self.class.send(:define_method, name, &block) 661 | end 662 | define_method(:paco) { 3 } 663 | end 664 | 665 | a = A.new 666 | assert_equal 3, a.paco 667 | 668 | a.create_method(:camaron) { 4 } 669 | assert_equal 4, a.camaron 670 | 671 | # you can do the same thing with class_eval 672 | A.class_eval { define_method(:camaron2){ 3 }} 673 | assert_equal 3, a.camaron2 674 | end 675 | 676 | should "Eigenclass:: or singleton class" do 677 | 678 | class << Point # opening the singleton class 679 | def class_method1 680 | # instance method of the eigenclass, and also class method of Point. 681 | end 682 | def class_method2 683 | end 684 | end 685 | 686 | # Alternative Syntax: If you open the eigenclass of a class object within the 687 | # definition of a class itself, you can use self instead of the name of the class 688 | class Point 689 | # instance methods go here 690 | class << self # opening the singleton class 691 | # class methods go here as instance methods of the eigenclass 692 | def class_method3 693 | 694 | end 695 | end 696 | end 697 | end 698 | 699 | should "method visibility public:: private:: protected::" do 700 | # methods are normally public (except the initialize method, which is private). 701 | 702 | # private methods are implicitely invoked on self, and may not be explicitly invoked 703 | # on an object. 704 | 705 | # public, private and protected only apply to methods. Instance & class variables 706 | # are encapsulated and thus, behave as private (the only way to make an instance 707 | # variable accessible from outside a class is defining an accessor method). 708 | # Constants behave as public (there is no way of making them unaccessible to outside 709 | # use). 710 | 711 | 712 | # A protected method is like a private method (it can only be invoked from within 713 | # the implementation of a class or its subclasses) but it may be explicitely invoked 714 | # on any instance of the class. 715 | # 716 | class Esquiva 717 | def patada(esq) esq.esquivar end 718 | 719 | protected 720 | def esquivar() "esquivando" end 721 | 722 | end 723 | esq1 = Esquiva.new 724 | esq2 = Esquiva.new 725 | 726 | assert_equal "esquivando", esq1.patada(esq2), "Calling protected method" 727 | assert_raise NoMethodError do 728 | esq1.esquivar # esquivar is protected 729 | end 730 | # def safe_send(receiver, method, message) # regular send bypasses visibility rules 731 | # eval "receiver.#{method}" # receiver.method 732 | # rescue => e 733 | # puts "#{message}: #{e}" # This is my message: NoMethodError 734 | # end 735 | # 736 | # visibility = ARGV.shift || "public" 737 | # 738 | # 739 | end 740 | 741 | should "Subclassing <:: or inheritance" do 742 | # Used to extend a class with the methods in another class. When we define a class, 743 | # we may specify that it extends—or inherits from—another class, known as the 744 | # superclass. 745 | # 746 | # class Gem < Ruby #=> Gem is a subclass of Ruby. Ruby is the superclass of Gem 747 | # If you do not specify a superclass, the class implicitly extends Object. 748 | 749 | # < is a boolean operator 750 | assert String < Comparable, "String inherits from Comparable" 751 | 752 | assert_false String < Integer, "String doesn't inherit from Integer" 753 | end 754 | 755 | 756 | end 757 | 758 | context "Module" do 759 | # Modules are classes that can't be instantiated or subclassed. They can be used as 760 | # namespaces (to group related methods or constants) and as mixins (to include 761 | # instance methods in classes). 762 | setup do 763 | module InstanceMethods 764 | def an_instance_method; self.class ;end 765 | end 766 | module ClassMethods 767 | def a_class_method; self ;end 768 | end 769 | end 770 | should "include:: and extend:: can only be called on A MODULE " do 771 | # include: Adds module methods as INSTANCE METHODS. 772 | # 773 | # extend: Adds all module methods ONLY TO THE INSTANCE it's called on. 774 | # 775 | # If you want to access a method defined inside a class 776 | 777 | 778 | class MyClass 779 | include InstanceMethods 780 | extend ClassMethods # ClassMethods == SingletonMethods 781 | # If extend is called inside the class, it adds module methods as CLASS METHODS 782 | # (because adding instance methods to its eigenclass makes them class methods). 783 | end 784 | 785 | my_class_instance = MyClass.new 786 | assert_equal MyClass, my_class_instance.an_instance_method, "Instance methods are now available" 787 | assert_equal MyClass, MyClass.a_class_method, "Class methods are now available" 788 | 789 | # Using extend outside the class definition, adds the methods as singleton methods 790 | # (meaning, only to that instance of the class). 791 | obj_instance = Object.new 792 | obj_instance.extend InstanceMethods # Other object instances won't have access to "an_instance_method" 793 | assert_equal Object, obj_instance.an_instance_method, "Instance methods are now available" 794 | end 795 | 796 | should "include:: and extend:: simplified" do 797 | module InstanceMethodsWithExtend 798 | # Called everytime a module is included. Same thing with extended. base is also 799 | # known as klass 800 | def self.included(base) 801 | base.extend(ClassMethods) 802 | end 803 | end 804 | class MyClass 805 | include InstanceMethodsWithExtend 806 | end 807 | 808 | my_class_instance = MyClass.new 809 | assert_equal MyClass, my_class_instance.an_instance_method, "Instance methods are now available" 810 | assert_equal MyClass, MyClass.a_class_method, "Class methods are now available" 811 | end 812 | 813 | should "require::" do 814 | # Loads an external file. Ruby finds these files by searching in the LOAD_PATH. You 815 | # may need to include after requiring (if they contain modules). 816 | 817 | # If a file is in the lib directory, you require it directly by name. require 818 | # 'easter' # lib/easter.rb 819 | # 820 | # If it's in a subdirectory of lib, you need to specify it. 821 | # require 'shipping/airmail' # lib/shipping/airmail.rb 822 | end 823 | 824 | should "const_get:: mod.const_get(sym) => obj" do 825 | # Returns the value of the named constant in mod. 826 | assert_equal 3, Math.const_get(:PI).round 827 | 828 | # Leave the lefthandside empty to look for a global constant 829 | assert ::ARGV, "global constant" 830 | end 831 | 832 | should "class << self::" do 833 | class Capoeira 834 | def an_instance_method;end 835 | 836 | class << self 837 | def a_class_method;end 838 | end 839 | 840 | def self.another_class_method;end 841 | end 842 | assert_same_elements %w( a_class_method another_class_method), Capoeira.public_methods - Capoeira.superclass.public_methods 843 | 844 | end 845 | 846 | end 847 | 848 | context "Literals" do 849 | should "String literals" do 850 | # There are four matching delimiters: [], {}, (), <>. Any other delimiter used has 851 | # to be repeated: !!,||, "", '', //,++,**,:: etc. 852 | 853 | # No interpolation: '' or %q 854 | assert_equal "paco", 'paco' 855 | assert_equal "paco", %q[paco] 856 | assert_equal "paco", %q{paco} 857 | assert_equal "paco", %q(paco) 858 | assert_equal "pao", %qo>, "Because they are paired, matching delimiters can be nested" 859 | assert_equal "pa{c}o", %q/pa{c}o/ 860 | assert_equal "pa_co", %q_pa\_co_ 861 | 862 | # Interpolation "", %Q or just % 863 | assert_equal "4", "#{2*2}" 864 | assert_equal "4", %Q+#{2*2}+ 865 | assert_equal "4", %|#{2*2}| 866 | 867 | # Here documents 868 | multiline_no_dash = < SyntaxError use this instead: my_block = lambda{ |x| 905 | # x*x } my_block.call 906 | end 907 | 908 | should "Blocks: yield::" do 909 | # IF YOU SEE A "yield", it means that the function that has it will recieve a 910 | # block at runtime. 911 | def pass_number_as_block_argument(number) 912 | yield number # "number" becomes the argument of the block. number is yielded to the block 913 | end 914 | 915 | assert pass_number_as_block_argument(4) { |x| x > 3 } 916 | assert_false pass_number_as_block_argument(2) { |x| x > 3 } 917 | 918 | class IsTwo 919 | def is_two?(num) 920 | num == 2 921 | end 922 | end 923 | 924 | def foo 925 | yield IsTwo.new 926 | end 927 | 928 | assert_false foo { |bar| bar.is_two? 3 } 929 | assert foo { |bar| bar.is_two? 2 } 930 | 931 | #[1,2,3].select 932 | # def select 933 | # ary = [] 934 | # each do |item| 935 | # if yield(item) 936 | # ary << item 937 | # end 938 | # end 939 | # ary 940 | # end 941 | 942 | Array.class_eval do 943 | def select_words1 944 | if block_given? 945 | self.select { |word, frequency| yield(word, frequency) }.collect { |word, frequency| word } 946 | end 947 | end 948 | def select_words2(&block) 949 | if block 950 | self.select(&block).collect { |word, frequency| word } 951 | end 952 | end 953 | end 954 | assert_equal ["a"], [["a",2],["b",1]].select_words1 { |word, freq| freq == 2 } 955 | assert_equal ["a"], [["a",2],["b",1]].select_words2 { |word, freq| freq == 2 } 956 | end 957 | 958 | should "a block refers to outer variables, not inner" do 959 | def execute_the_block_three_times_with_local_variable 960 | my_var = 100 #var in the context from which it is called 961 | yield 962 | yield 963 | yield 964 | end 965 | my_var = 5 #var in the same context as the block 966 | execute_the_block_three_times_with_local_variable { my_var += 1 } 967 | assert_equal 8, my_var 968 | end 969 | 970 | should "&:: creates procs implicitely. It converts Blocks into Procs and viceversa" do 971 | def convert_block_to_proc(&block)# The unary ampersand operator 972 | block #now it's a proc 973 | end 974 | 975 | external_proc = convert_block_to_proc { |x| x > 3 } 976 | 977 | assert external_proc.call(4), "the block returns true" 978 | assert_false external_proc.call(1), "the block returns false" 979 | 980 | # any? expects a block and we're sending it a proc 981 | assert_raise ArgumentError do 982 | [1,4,7].any? external_proc 983 | end 984 | 985 | assert [1,4,7].any?(&external_proc), "We turn the proc back into a block" 986 | end 987 | 988 | should "Proc:: use call(). proc { |...| block } => a_proc. Also, call proc with Proc#[]::" do 989 | # Procs have block-like behavior, they are objects. Greatest feature => Procs can 990 | # be saved in variables. 991 | def convert_block_to_proc_using_ampersand(&block) 992 | block 993 | end 994 | def convert_block_to_proc_using_proc_new(&block) 995 | Proc.new(&block) 996 | end 997 | proc_with_ampersand = convert_block_to_proc_using_ampersand { "&" } 998 | proc_with_proc_new = convert_block_to_proc_using_proc_new { "Proc.new()" } 999 | assert_equal "&", proc_with_ampersand.call 1000 | assert_equal "Proc.new()", proc_with_proc_new.call 1001 | 1002 | # Alternative way to call Proc#[] 1003 | my_proc = lambda{ |x| x * 2 } 1004 | assert_equal 6, my_proc.call(3) 1005 | assert_equal 6, my_proc[3] 1006 | end 1007 | 1008 | should "not passsing variables to blocks" do 1009 | assert_equal [:a,:b], {:a => 3, :b => 5}.collect { |letter, _| letter } 1010 | end 1011 | 1012 | should "Proc:: Pass a Proc as an argument" do 1013 | # Calling a proc is like yielding to a block 1014 | Array.class_eval do 1015 | def iterate!(code) # note, no &. A Proc is just a regular parameter 1016 | self.each_with_index do |n,i| 1017 | self[i] = code.call(n) 1018 | end 1019 | end 1020 | end 1021 | square = Proc.new do |n| 1022 | n**2 1023 | end 1024 | assert_equal [1,4,9,16], [1,2,3,4].iterate!(square) 1025 | end 1026 | 1027 | should "defined?:: checks if a variable is defined" do 1028 | assert_false defined?(d), "d is not defined" 1029 | end 1030 | 1031 | should "block_given?:: checks to see if a block has been sent as an argument" do 1032 | def did_you_pass_me_a_block?() 1033 | block_given? ? yield : "No block" 1034 | end 1035 | 1036 | assert_equal "No block", did_you_pass_me_a_block? 1037 | assert_equal "Yes, I did", did_you_pass_me_a_block? { 'Yes, I did' } 1038 | proc = Proc.new { 'Kind of. I passed you a proc' } 1039 | assert_equal "Kind of. I passed you a proc", did_you_pass_me_a_block?(&proc) 1040 | end 1041 | 1042 | should "to_proc::" do 1043 | # If you send something that isn't a Proc to the & unary op. It will try to 1044 | # convert it into a proc by using its to_proc method, and then convert it into a 1045 | # block 1046 | 1047 | end 1048 | 1049 | should "Lambda:: lambda { |...| block } => a_proc | proc { ... } is a synonym" do 1050 | # Lambdas have method-like behavior, but they are instances of class Proc. Calling 1051 | # a lambda is like invoking a method. 1052 | 1053 | saved_proc_with_error = Proc.new { return 3 } 1054 | 1055 | # Can't call a proc that returns a value 1056 | assert_raise LocalJumpError do 1057 | saved_proc_with_error.call 1058 | end 1059 | 1060 | # either remove the return, or use a lambda 1061 | saved_proc = Proc.new { 3 } # remove the return 1062 | assert_equal 3, saved_proc.call 1063 | 1064 | saved_lambda = lambda { return 3 } # Using a lambda 1065 | assert_equal 3, saved_lambda.call 1066 | end 1067 | 1068 | should "Lambda and Proc differences" do 1069 | # 1) Lambdas don't check the number of parameters passed when called. Procs do. 1070 | checks_params = lambda { |one, two, three| "#{one} #{two} #{three.class}" } 1071 | assert_raise ArgumentError do 1072 | checks_params.call(1,2) 1073 | end 1074 | 1075 | does_not_check_params = Proc.new { |one, two, three| "#{one} #{two} #{three.class}" } 1076 | assert_equal "1 2 NilClass", does_not_check_params.call(1,2) 1077 | 1078 | # 2) Lambdas have diminutive returns. A Proc will stop a method and return the 1079 | # value provided, lambdas will return their value to the method and let the method 1080 | # continue on. 1081 | def proc_return 1082 | Proc.new { return "Proc.new"}.call #stop here 1083 | return "proc_return method finished" 1084 | end 1085 | def lambda_return 1086 | lambda { return "lambda"}.call 1087 | return "lambda_return method finished" #stop here 1088 | end 1089 | 1090 | assert_equal "Proc.new", proc_return # Procs are code snippets, not methods. 1091 | assert_equal "lambda_return method finished", lambda_return 1092 | # lambdas are methods: they check the number of arguments and don't override the 1093 | # calling method's return 1094 | end 1095 | 1096 | should "block-arguments::" do 1097 | # #block-arguments are like regular arguments. They get assigned when the lambda 1098 | # is called 1099 | methods = %w( upcase! chop! ) 1100 | var = "hola" 1101 | block = lambda { |responder| methods.each { |method| responder.send(method) } } 1102 | block.call(var) # var becomes "responder" block-argument. 1103 | assert_equal "HOL", var 1104 | end 1105 | 1106 | should "Method::" do 1107 | # Useful if you want to pass a method as a block. It's like a lambda but without 1108 | # being anonymous 1109 | Array.class_eval do 1110 | def iterate!(code) # note, no &. A Proc is just a regular parameter 1111 | self.each_with_index do |n,i| 1112 | self[i] = code.call(n) 1113 | end 1114 | end 1115 | end 1116 | 1117 | def square(n) 1118 | n**2 1119 | end 1120 | assert_equal [1,4,9,16], [1,2,3,4].iterate!(method(:square)) 1121 | 1122 | end 1123 | 1124 | end 1125 | 1126 | context "Iterators" do 1127 | should "Array.map:: also called Enum.collect::" do 1128 | # Wraps the elements generated inside the block into an Array. 1129 | 1130 | assert_equal [1,4,9], [1,2,3].collect { |x| x*x }, "Array" 1131 | assert_equal [2,4,6], (1..3).collect { |x| x*2 }, "Range" 1132 | assert_equal [2,3,4], [1,2,3].collect(&:succ) # calls .method(:succ) 1133 | 1134 | assert_equal [[2],[2],[2]], [1,2,3].collect { |x| [2] }, "Array" 1135 | # DO NOT CONFUSE WITH each:: "each" returns the original array, "collect" returns 1136 | # the resulting array 1137 | assert_equal [1,4,9], [1,2,3].collect { |x| x*x }, "Array" 1138 | assert_equal [1,2,3], [1,2,3].each { |x| x*x }, "Array" 1139 | 1140 | # Convert an array into a hash 1141 | hash = {} 1142 | ['a','b','c','a','b'].collect {|letter| hash[letter] ? hash[letter] += 1 : hash[letter] = 1 } 1143 | hash #you can assign the hash directly to collect because in this case it will return 1's and 2's 1144 | assert_same_elements( {'a' => 2, 'b' => 2, 'c' => 1}, hash ) 1145 | 1146 | nested_array = [[1,:a],[2, :b],[3, :c]] 1147 | ret = nested_array.collect { |number, letter| 1148 | true 1149 | } 1150 | assert ret 1151 | 1152 | #repeated numbers 1153 | assert_equal [1,2,1,1,2], [1,2,1,1,2].select{ |x| x }.collect{ |x| x } 1154 | 1155 | end 1156 | 1157 | should "inject::" do 1158 | # Invokes the associated block with two arguments. The first argument is an 1159 | # accumulator convert previous iterations. The second is the next element. The 1160 | # return value becomes the first block-argument for the next iteration (except for 1161 | # the last iteration). The initial value of the accumulator is either the arg to 1162 | # inject, or the first element of the enumerable object. 1163 | data = [2,5,3,4] 1164 | sum = data.inject { |sum, current_value| sum + current_value} 1165 | assert_equal 2 + 5 + 3 + 4, sum 1166 | 1167 | multiply = data.inject(1) { |accum, current_value| accum * current_value } 1168 | assert_equal 1 * 2 * 5 * 3 * 4, multiply 1169 | 1170 | maximum = data.inject { |max, current_value| max > current_value ? max : current_value} 1171 | assert_equal 5, maximum 1172 | 1173 | # injecting an empty hash converts a nested array into a hash. It's better to use 1174 | # hash_with_splat, but if it's nested with two or more leves it might give errors, 1175 | # then you might want to use flatten(1). 1176 | nested_array = [ [1,2],[3,4],[5,6] ] 1177 | new_hash = nested_array.inject({}) do |hash, (key, value)| # hash,(key,value) = {},[1,2] 1178 | hash[key] = value 1179 | hash 1180 | end 1181 | hash_with_splat = Hash[*nested_array.flatten] 1182 | assert_same_elements(({5 => 6, 1 => 2, 3 => 4}),new_hash) 1183 | assert_same_elements(({5 => 6, 1 => 2, 3 => 4}), hash_with_splat ) 1184 | 1185 | # inject an array 1186 | nested_hash ={%w( à ä á) => 'a', %w( é è ê ë) => 'e'} 1187 | convert, to = nested_hash.inject(['','']) do |array,(key,value)| # array,(key,value) = ['',''], *{['à','ä','á'] => 'a'} 1188 | array[0] << key * '' 1189 | array[1] << value * key.size 1190 | array 1191 | end 1192 | assert_equal 'àäáéèêë',convert 1193 | assert_equal 'aaaeeee',to 1194 | 1195 | end 1196 | 1197 | should "each::" do 1198 | hash = { :hola => 'oi', :adios => 'adeus'} 1199 | joined_hash = "" 1200 | hash.each { |key,value| joined_hash += (key.to_s + value)} # key, value = [key, value] parallel assignment 1201 | assert_equal "holaoiadiosadeus".length, joined_hash.length 1202 | 1203 | # When using Hash.each with two block-parameters, it's the same as using 1204 | # Hash.each_pair. 1205 | end 1206 | 1207 | should "next::" do 1208 | # While inside a loop, you can always skip an element 1209 | add = 0 1210 | [1,nil,"djd",3,4].each do |number| 1211 | next unless number.kind_of?(Fixnum) #Skip if not a number 1212 | add += number 1213 | end 1214 | assert_equal 8, add 1215 | end 1216 | 1217 | 1218 | end 1219 | 1220 | context "String:" do 1221 | should "concatenate: <<::" do 1222 | # #It's better to append than to build new ones 1223 | str = '' 1224 | a = 'Nava' 1225 | b = 'laga' 1226 | c = 'mella' 1227 | assert_equal 'Navalagamella', str << a << b << c, "Better, they already existed" 1228 | str = '' 1229 | assert_equal 'Navalagamella', str << "#{a}" << "#{b}" << "#{c}", "Less efficient, creates new strings" 1230 | str = '' 1231 | assert_equal 'Navalagamella', str.concat(a + b + c) 1232 | end 1233 | 1234 | should "match:: String#[]" do 1235 | # Alternative to using mach. It returns the portion of the string that matches the 1236 | # regex. 1237 | assert_equal "ac", "paco"[/ac/] 1238 | assert_equal "f", "asdf"[/d(.)/, 1] 1239 | end 1240 | 1241 | should "scan::" do 1242 | # collects all of the regular expression's matches against the string into an array. 1243 | # If the pattern has groups, each element of the array is itself an array of 1244 | # captured text. 1245 | assert_equal ["a", "d"], "asdf".scan(/[a-e]/) 1246 | 1247 | assert_equal [["ruby"], ["regex"]], "hello ruby; hello regex".scan(/hello (\w+)/) 1248 | assert_equal ["ruby", "regex"], [["ruby"], ["regex"]].flatten 1249 | end 1250 | 1251 | should "split:: I want to break up a string everytime a delimiter appears" do 1252 | # str.split(pattern=$;, [limit]) => array $; is the delimiter 1253 | str = "Hola Paco. Cuanto tiempo. Ole." 1254 | 1255 | # Split at every period 1256 | assert_equal ["Hola Paco", " Cuanto tiempo", " Ole"], str.split(".") 1257 | assert_equal ["Hola Paco", " Cuanto tiempo", " Ole"], str.split(/\./) 1258 | 1259 | # Split at every period, removing the whitespace 1260 | assert_equal ["Hola Paco", "Cuanto tiempo", "Ole"], str.split(/\.\s*/) 1261 | 1262 | # Split at every period, removing the whitespace and returning the delimiter 1263 | assert_equal ["Hola Paco", ".", "Cuanto tiempo", ".", "Ole", "."], str.split(/(\.)\s*/) 1264 | 1265 | 1266 | # Split at every period, removing the whitespace and returning one of the delimiters 1267 | str = "¡Hola Paco! ¿Como andas? Ole…" 1268 | assert_equal ["¡Hola Paco", "!", "¿Como andas", "?", "Ole", "…"], str.split(/(\.|\?|\!|\…)\s*/) 1269 | 1270 | 1271 | end 1272 | 1273 | should "strip::" do 1274 | # #remove leading and trailing whitespace 1275 | assert_equal "hola cuñao", " hola cuñao ".strip 1276 | end 1277 | end 1278 | 1279 | context "Enumerable" do 1280 | # Enumerable is a mixin that allows traversal, searching and sorting methods. The 1281 | # requirements are that the class that mixes it in must have a method "each()", and in 1282 | # some cases also the operator <=> (for max, min, sort) 1283 | # 1284 | # Classes that implement each: Array, Hash, Range, String 1285 | should "each::" do 1286 | # (5..10).each 1287 | end 1288 | 1289 | should "any?:: enum.any? [{|obj| block } ] => true or false; ^::" do 1290 | # Passes each element of the collection to the given block and it returns TRUE if at 1291 | # least ONE of the collection members is not false or nil. It expects a block. If no 1292 | # block is passed any? returns TRUE if at least one element is not nil 1293 | assert %w( ant bear cat ).any? {|word| word.length >= 3} 1294 | 1295 | def received_arguments?(*args) 1296 | args.any? 1297 | end 1298 | assert received_arguments?(1,2,"hola") 1299 | assert_false received_arguments? 1300 | 1301 | assert %w( ant bear cat ).any? ^ nil # ^ is xor: TRUE ^ FALSE => TRUE 1302 | assert [].any? ^ "block" # FALSE ^ TRUE => TRUE 1303 | assert_false %w( ant bear cat ).any? ^ "block" # TRUE ^ TRUE => FALSE 1304 | assert_false false ^ false # FALSE ^ FALSE => FALSE 1305 | 1306 | end 1307 | 1308 | should "collect:: or map::" do 1309 | assert_equal [2,3,4], [1,2,3].collect { |x| x.succ }, "Array" 1310 | assert_equal [2,3,4], (1..3).collect { |x| x.succ }, "Range" 1311 | assert_equal ["ABC DEF"], "abc def".collect { |x| x.upcase }, "String" 1312 | # Not useful with Hash. Use inject instead 1313 | end 1314 | 1315 | should "detect::" do 1316 | # Returns the first in enum for which block is not false. If no object matches, 1317 | # calls ifnone and returns its result when it is specified, or returns nil 1318 | 1319 | is_nil = (1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } 1320 | is_35 = (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } 1321 | assert_equal nil, is_nil 1322 | assert_equal 35, is_35 1323 | end 1324 | 1325 | should "sort_by::" do 1326 | # Sorts enum using a set of keys generated by mapping the values in enum through the 1327 | # given block. Not very efficient. 1328 | # 1329 | # Ascending order by default 1330 | assert_equal %w( fig pear apple ), %w{ apple pear fig }.sort_by {|word| word.length} 1331 | 1332 | # Descending order 1333 | assert_equal %w( apple pear fig ), %w{ apple pear fig }.sort_by {|word| -word.length} 1334 | 1335 | end 1336 | 1337 | should "enum_for:: AKA to_enum::" do 1338 | # Create a new enumerator instance. You can choose between each_slice, each_cons and 1339 | # each_with_index. 1340 | # Useful when you want to chain an enumerator with .collect or .map 1341 | assert_equal %w( x0 y1 z2 ), 1342 | %w( x y z).enum_for(:each_with_index).map {|letter, index| letter + index.to_s } 1343 | assert_raise LocalJumpError do 1344 | %w( x y z).each_with_index.map {|letter, index| letter + index.to_s } 1345 | end 1346 | 1347 | end 1348 | 1349 | # process array elements in groups of 4 1350 | (1..100).to_a.each_slice(4) {|e| p e} 1351 | 1352 | should "each_slice::" do 1353 | # Processes the array by pairs, triplets, etc 1354 | assert_equal [2,5], [1,1,2,3].enum_for(:each_slice,2).map {|first, second| first + second} 1355 | end 1356 | 1357 | should "each_cons::" do 1358 | # Processes the array by pairs, triplets, etc OF CONSECUTIVE NUMBERS. 1359 | assert_equal [2,3,5], [1,1,2,3].enum_for(:each_cons,2).map {|first, second| first + second} 1360 | end 1361 | 1362 | end 1363 | 1364 | context "Range" do 1365 | should "include?:: Check if an item belongs to a range or an array" do 1366 | assert((1..100).include?(79)) 1367 | assert([1,50,79,100].include?(79)) 1368 | end 1369 | end 1370 | 1371 | context "Set" do 1372 | # A set is a collection of values without duplicates. The elements have no order. A 1373 | # hash is a set of k/v pairs. 1374 | 1375 | should "to_set:: Creating Any Enumerable can be converted to a Set" do 1376 | assert_equal Set[5,1,2,3,4], (1..5).to_set 1377 | assert_equal Set[1,2,5], [1,2,5].to_set 1378 | assert_equal Set[1,2,5], Set.new([1,2,5]) 1379 | assert_equal Set[2,3,4], Set.new([1,2,3]) { |x| x+1 } 1380 | end 1381 | 1382 | should "&:: ^:: |:: -:: <<:: Set Operations" do 1383 | primes = Set[2,3,5,7] 1384 | odds = Set[1,3,5,7,9] 1385 | 1386 | assert_equal Set[5,7,3], primes & odds, "Intersection" 1387 | assert_equal Set[5,7,3,1,2,9], primes | odds, "Union" 1388 | assert_equal Set[2], primes - odds, "Difference" 1389 | assert_equal Set[1,2,9], primes ^ odds, "Mutual Exclusion: (a|b) - (a&b) " 1390 | 1391 | assert_equal Set[2,3,5,7,11], primes << 11, "Add item" 1392 | end 1393 | end 1394 | 1395 | context "Object" do 1396 | 1397 | should "returning::" do 1398 | def boo 1399 | a = [] 1400 | a << 1 1401 | a << 2 1402 | a 1403 | end 1404 | def ole 1405 | returning a = [] do 1406 | a << 1 1407 | a << 2 1408 | end 1409 | end 1410 | def ole2 1411 | returning [] do |a| 1412 | a << 1 1413 | a << 2 1414 | end 1415 | end 1416 | def ole3 1417 | returning [] do |a| 1418 | [1,2].each { |i| a << i } 1419 | end 1420 | end 1421 | 1422 | assert_equal [1,2], boo 1423 | assert_equal [1,2], ole 1424 | assert_equal [1,2], ole2 1425 | assert_equal [1,2], ole3 1426 | end 1427 | 1428 | should "clone::" do 1429 | # This duplication doesn't happen with numbers 1430 | # (I think it's only classes and methods) 1431 | 1432 | arr1 = [1,2,3] 1433 | arr2 = arr1 1434 | arr2.pop 1435 | assert_equal [1,2], arr1 1436 | assert_equal [1,2], arr2 1437 | 1438 | arr1 = [1,2,3] 1439 | arr2 = arr1.clone 1440 | arr2.pop 1441 | assert_equal [1,2,3], arr1 1442 | assert_equal [1,2], arr2 1443 | end 1444 | 1445 | should "blank?::" do 1446 | # object is blank if it’s false, empty, or a whitespace string. This simplifies: 1447 | # (a.nil? || a.empty?) to: if a.blank? 1448 | assert ''.blank? 1449 | assert ' '.blank? 1450 | assert "".blank? 1451 | assert " ".blank? 1452 | assert [].blank? 1453 | assert nil.blank? 1454 | assert(({}).blank?) 1455 | assert Hash[].blank? 1456 | end 1457 | 1458 | should "==::, equal?:: and eql?::" do 1459 | class A; end 1460 | a = A.new; b = A.new 1461 | 1462 | # == same object (usually overriden in descendant classes) 1463 | assert 1 == 1.0 1464 | assert [] == [] 1465 | assert "" == "" 1466 | assert_false a == b 1467 | 1468 | # eql? same value 1469 | assert_false 1.eql? 1.0 1470 | assert [].eql? [] 1471 | assert "".eql? "" 1472 | assert_false a.eql? b # == is synonymous with eql? for Object instances. 1473 | 1474 | # equal? same object (should never be overriden in descendant classes) 1475 | assert_false 1.equal? 1.0 1476 | assert_false [].equal? [] 1477 | assert_false "".equal? "" 1478 | assert_false a.equal? b 1479 | 1480 | assert a.equal? a 1481 | end 1482 | 1483 | should "respond_to?:: obj.respond_to?(symbol, include_private=false) => true or false" do 1484 | # Returns true if obj responds to the given method. 1485 | assert_false 3.respond_to?(:upcase) 1486 | assert "hola".respond_to?(:upcase) 1487 | 1488 | class A; def a; "a"; end ;end 1489 | class B; def b; "b"; end ;end 1490 | as_and_bs = [A.new , A.new, B.new, A.new, B.new ] 1491 | result = as_and_bs.collect { |elem| elem.a if elem.respond_to?(:a) }.compact 1492 | assert_equal ["a","a","a"], result 1493 | 1494 | result_without_compact = as_and_bs.collect { |elem| elem.a if elem.respond_to?(:a) } 1495 | assert_equal ["a","a",nil,"a",nil], result_without_compact 1496 | end 1497 | 1498 | should "send:: obj.send(symbol [, args...]) => obj" do 1499 | # Invokes the method identified by symbol, passing it any arguments specified. 1500 | assert_equal 4, 3.send(:succ) 1501 | 1502 | # Send bypasses method visibility constraints, it can invoke private and protected methods. 1503 | class A 1504 | def private_abada; 3; end 1505 | private :private_abada 1506 | end 1507 | a = A.new 1508 | assert_raise NoMethodError do 1509 | a.private_abada 1510 | end 1511 | assert_equal 3, a.send(:private_abada), "Bypassing visibility rules" 1512 | end 1513 | 1514 | should "with_options::" do 1515 | # provides a way to factor out redundant options on multiple method calls. 1516 | # 1517 | # #same as: map.default "", :action => 'index', :controller => 'post' 1518 | ActionController::Routing::Routes.draw do |map| 1519 | map.with_options(:controller => 'post') do |post| 1520 | post.default "", :action => 'index' 1521 | end 1522 | end 1523 | 1524 | assert_equal 'index', ActionController::Routing::Routes.recognize_path("/")[:action] 1525 | end 1526 | end 1527 | 1528 | context "rake actions" do 1529 | should "generate a controller" do 1530 | # ruby script/generate haml_controller Posts open debit credit close 1531 | 1532 | "" # ruby script/generate haml_controller 'admin/credit_cards' suspend late_fee 1533 | end 1534 | should "generate a migration" do 1535 | # ruby script/generate migration CreatePost ruby script/generate migration 1536 | # AddTitleBodyToPost title:string body:text published:boolean 1537 | end 1538 | should "generate a model" do 1539 | # ruby script/generate model Account ruby script/generate model post title:string 1540 | # body:text published:boolean 1541 | end 1542 | should "generate a scaffold" do 1543 | # ruby script/generate scaffold post title:string body:text published:boolean 1544 | end 1545 | should "destroy something generated" do 1546 | # ruby script/destroy controller Posts ruby script/destroy migration CreatePost 1547 | # 1548 | # ruby script/destroy model Account 1549 | end 1550 | end 1551 | 1552 | context "Symbols" do 1553 | # Symbols are inmutable strings, which means they can't be change, they must be 1554 | # overwritten. 1555 | should "convert symbols to strings and viceversa" do 1556 | assert_equal "hola", :hola.to_s 1557 | assert_equal :hola, "hola".intern 1558 | assert_equal :hola, "hola".to_sym 1559 | assert_equal :"hola guey", %s[hola guey] 1560 | end 1561 | 1562 | should "Symbols should not change" do 1563 | assert_equal "berimbau e atabaque", "berimbau" << " e atabaque" 1564 | assert_raise NoMethodError do 1565 | :berimbau << :" e atabaque" # Can't append a symbol 1566 | end 1567 | end 1568 | 1569 | should "Symbols are more memory efficient than strings" do 1570 | assert_not_equal "hola".object_id, "hola".object_id, "Two objects in memory" 1571 | assert_equal :hola.object_id, :hola.object_id 1572 | end 1573 | 1574 | should "Always use simbols if you can" do 1575 | assert 5.respond_to?("to_f"), "Ruby is casting it to a symbol, why waste memory?" 1576 | assert 5.respond_to?(:to_f), "Better" 1577 | end 1578 | end 1579 | 1580 | context "Numeric" do 1581 | # "Numeric" 1582 | # "Integer" "Float" 1583 | # "Fixnum" "Bignum" 1584 | # 1585 | should "You can separate thousands with underscores" do 1586 | assert_equal 1_000_000, 1000000 1587 | end 1588 | 1589 | should "Float#round::" do 1590 | assert_equal 3, Math::PI.round 1591 | assert_equal 3.1, Math::PI.round(1) 1592 | assert_equal 3.14, Math::PI.round(2) 1593 | assert_equal 3.142, Math::PI.round(3) 1594 | end 1595 | 1596 | should "step::" do 1597 | # num.step(limit, step ) {|i| block } => num 1598 | # creates a seq of numbers starting at num, incremented by step until limit 1599 | # on each call to the block 1600 | a = "" 1601 | 1.step(10,2) { |i| a << i.to_s } 1602 | assert_equal "13579", a 1603 | end 1604 | end 1605 | 1606 | context "Reflections & Bindings" do 1607 | setup do 1608 | class Demo 1609 | def initialize(n) 1610 | @secret = n 1611 | end 1612 | def get_binding 1613 | return binding() 1614 | end 1615 | end 1616 | end 1617 | should "eval::" do 1618 | # eval evaluates a ruby string 1619 | assert_equal 7, eval("3 + 4") 1620 | 1621 | eval "def multiply(x,y); x*y; end" 1622 | assert_equal 28, multiply(7,4) 1623 | end 1624 | should "eval can receive a binding to set the context" do 1625 | # Bindings store the execution context at some particular place in the code. 1626 | demo = Demo.new(99) 1627 | assert_equal 99, eval("@secret", demo.get_binding) 1628 | end 1629 | should "eval can receive a proc to set the context" do 1630 | # greeter = Proc.new { |greetings| greetings.map { |greeting| "#{greeting} #{name}"}} 1631 | # eval( "name = 'pastinha'", greeter) 1632 | # assert_equal ['oi pastinha', 'aloha pastinha'], greeter.call(['oi', 'aloha']) 1633 | end 1634 | 1635 | should "instance_eval:: " do 1636 | # Evaluates a string or block within the context of the receiver (obj). This is 1637 | # done by setting the variable self within the string or block to obj, giving the 1638 | # code access to obj's instance variables. 1639 | # 1640 | # In the version of instance_eval that takes a String, the optional second and third 1641 | # parameters supply a filename and starting line number for compilation errors. 1642 | 1643 | class Klass 1644 | def initialize 1645 | @secret = 99 1646 | end 1647 | end 1648 | k = Klass.new 1649 | assert_equal 99, k.instance_eval { @secret } 1650 | assert_equal 99, k.instance_eval("@secret") 1651 | assert_raise NoMethodError do 1652 | k.secret #there is no accessor for that variable 1653 | end 1654 | end 1655 | 1656 | should "instance_eval:: use it to define singleton methods on instances and class methods on Classes" do 1657 | a = String.new 1658 | a.instance_eval { 1659 | def my_name(name) 1660 | "My name is #{name}" 1661 | end 1662 | } 1663 | assert_equal "My name is Nacho", a.my_name('Nacho') # my_name is a singleton method 1664 | assert_raise NoMethodError do 1665 | "paco".my_name('Nacho') 1666 | end 1667 | 1668 | Fixnum.instance_eval "def zero; 0; end" 1669 | assert_equal 0, Fixnum.zero # zero is a class method 1670 | end 1671 | 1672 | should "class_eval:: AKA module_eval:: use it to define instance methods" do 1673 | # include?:: 1674 | # mod.class_eval(string [, filename [, lineno]]) => obj filename and lineno set 1675 | # the text for error messages Evaluates a string or block in the context of the 1676 | # receiver 1677 | assert_equal 1, Demo.class_eval{ @@x = 1 } 1678 | assert_equal 1, Demo.class_eval{ @@x } 1679 | 1680 | Fixnum.class_eval { def number; self; end } 1681 | assert_equal 5, 5.number # number is an instance method of class Fixnum 1682 | 1683 | # You can dinamically use private methods 1684 | module M; end 1685 | assert_raise NoMethodError do 1686 | String.include M # include is a private method 1687 | end 1688 | assert_nothing_raised do 1689 | String.class_eval { include M } 1690 | end 1691 | assert String.include?(M) 1692 | end 1693 | end 1694 | 1695 | context "Introspection" do 1696 | should "is_a?:: kind_of?:: ===:: know its type" do 1697 | assert 5.is_a?(Integer) 1698 | assert 5.kind_of?(Integer) 1699 | assert Integer === 5 1700 | 1701 | assert_false 5 === Integer 1702 | end 1703 | 1704 | should "check whether a module includes another" do 1705 | module M1 ; end 1706 | module M2 ; include M1 ; end 1707 | assert M2.include?(M1) 1708 | end 1709 | 1710 | should "An object or class should know its public and private methods" do 1711 | assert 5.respond_to?(:"+"), "Public" 1712 | assert Fixnum.respond_to?(:include, true), "Private" 1713 | 1714 | assert_false Fixnum.respond_to?(:include), "Private" 1715 | end 1716 | 1717 | should "A class should know its ancestors::" do 1718 | assert_contains Fixnum.ancestors, Integer 1719 | end 1720 | 1721 | should "A class should know what modules has included" do 1722 | assert_contains Fixnum.included_modules, Kernel 1723 | end 1724 | 1725 | should "An object should find all its methods" do 1726 | assert_contains 5.methods, "+" 1727 | end 1728 | 1729 | should "A class should know its public, private and singleton methods" do 1730 | assert_contains String.public_instance_methods, "upcase!" 1731 | assert String.public_method_defined?(:upcase!) 1732 | 1733 | assert_contains String.private_instance_methods, "initialize" 1734 | assert_contains String.singleton_methods, "method_added" 1735 | end 1736 | 1737 | should "An object should know its instance variables, public, private methods" do 1738 | d = Date.new 1739 | assert_contains d.instance_variables, "@of" 1740 | assert d.instance_variable_defined?(:@of) 1741 | 1742 | assert_equal 0, d.instance_variable_get(:@of) #remember to send text, not the variable 1743 | 1744 | assert_contains d.public_methods, "between?" 1745 | assert_does_not_contain d.public_methods(false), "between?", "Exclude inherited methods" 1746 | assert_contains d.private_methods, "lambda" 1747 | assert_equal [], d.singleton_methods 1748 | end 1749 | 1750 | end 1751 | 1752 | end 1753 | 1754 | 1755 | 1756 | class ViewsTest < ActionView::TestCase 1757 | context "Helpers" do 1758 | should "content_for::" do 1759 | # Calling content_for stores a block of markup in an identifier for later use. You 1760 | # can make subsequent calls to the stored content in other templates or the layout 1761 | # by passing the identifier as an argument to yield. 1762 | content_for :name do 1763 | 3 1764 | end 1765 | assert_equal "3", @content_for_name 1766 | end 1767 | 1768 | should "javascript_include_tag(*sources)::" do 1769 | # Returns an HTML script tag for each of the sources provided. You can pass 1-the 1770 | # filename (w or w/o ext), 2-the full path (relative to your document root). You can 1771 | # modify the html attrs of the SCRIPT tag by passing a hash as the last argument. 1772 | 1773 | assert_dom_equal('', 1774 | javascript_include_tag("xmlhr"), "No extension") 1775 | end 1776 | 1777 | should "content_tag::content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)" do 1778 | # Returns an HTML block tag of type name surrounding the content. Instead of passing 1779 | # the content as an argument, you can also use a block in which case, you pass your 1780 | # options as the second parameter 1781 | html = content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong") 1782 | assert_equal '

Hello world!

', html 1783 | 1784 | 1785 | active_item = true 1786 | html = content_tag(:div, "Hello World", :class => ("active" if active_item )) 1787 | assert_equal '
Hello World
', html 1788 | 1789 | 1790 | # Using a block - notice collect:: is not the same as each:: - Cannot convert String into Array 1791 | # Use the content tag as a block 1792 | html = content_tag :div do 1793 | ['a','b','c'].collect { |letter| content_tag(:scan, letter) } 1794 | end 1795 | assert_equal '
abc
', html 1796 | 1797 | # Concatenate two content_tag blocks - use parentheses 1798 | html = content_tag(:div) + 1799 | (content_tag :div do 1800 | ['a','b','c'].collect { |letter| content_tag(:scan, letter) } 1801 | end) 1802 | assert_equal '
abc
', html 1803 | end 1804 | 1805 | should "capture::(&block)" do 1806 | # When a Passes a variable to be evaluated as the argument for the block defined in 1807 | # the template. 1808 | # def render_join(collection, join_string, &block) 1809 | # output = collection.collect do |item| 1810 | # capture(item, &block) 1811 | # end.join(join_string) 1812 | # concat(output) 1813 | # end 1814 | # <%render_join(@items,'
') do |item|%> 1815 | #

Item title: <%= item.title %>

1816 | # <% end %> 1817 | end 1818 | 1819 | should "concat::" do 1820 | # Outputs text in the view, concat "hello" is the equivalent of <%= "hello" %>. The 1821 | # block binding is deprecated. Whatever you pass to output_buffer will get rendered. 1822 | 1823 | self.output_buffer = "" 1824 | assert_equal "hola", concat('hola') 1825 | assert_equal "hola", output_buffer 1826 | 1827 | def rounded_block(&block) 1828 | concat( 1829 | content_tag(:div) do 1830 | content_tag(:p) + content_tag(:scan) { capture(&block) } + content_tag(:em) 1831 | end 1832 | ) 1833 | end 1834 | end 1835 | end 1836 | end 1837 | 1838 | 1839 | # 1840 | #\action_controller 1841 | # |-base.rb 1842 | # module ActionController 1843 | # class Base 1844 | # def url_for(options = {}) 1845 | # \routing 1846 | # |-builder.rb 1847 | # module ActionController 1848 | # module Routing --> used as a namespace to define a bunch of classes. Never: 'include Routing' 1849 | # class Routebuilder 1850 | # def segment_for(string) 1851 | # 1852 | #module AC 1853 | # module Routing 1854 | # module Optimisation 1855 | # def generate_optimisation_block(route,kind) 1856 | # class Optimiser 1857 | # class PositionalArguments < Optimiser 1858 | # class PositionalArgumentsWithAdditionalParams < PositionalArguments 1859 | # OPTIMISERS = [PositionalArguments, PositionalArgumentsWithAdditionalParams] 1860 | -------------------------------------------------------------------------------- /ruhoh_tricks.txt: -------------------------------------------------------------------------------- 1 | # TODO: 2 | add an .ico 3 | upload knitr_reports to your github 4 | style website 5 | style code blocks, syntax and wrap lines 6 | 7 | # install ruhoh 8 | gem install ruhoh 9 | 10 | # create a github repository called nachocab.ruhoh.com 11 | settings|service hooks|add the webhook http://post.ruhoh.com 12 | 13 | # Map to nachocab.ruhoh.com 14 | go to http://post.ruhoh.com 15 | use nachocab/jos to log in to NameCheap.com, click on nachocab.ruhoh.com | All host records | 50.116.20.239 | Save Changes 16 | 17 | # clone the ruhoh git repo and push your own copy to your repo 18 | git clone git://github.com/ruhoh/blog.git nachocab.ruhoh.com 19 | cd nachocab.ruhoh.com 20 | git remote set-url origin git@github.com:nachocab/nachocab.ruhoh.com.git 21 | git push origin master 22 | 23 | # run local server that autodetects changes. 24 | rackup -p 9292 25 | 26 | # View blog 27 | http://localhost:9292/ 28 | http://localhost:9292/dash # dashboard, lists all pages 29 | 30 | # Update blog. Every commit you push to your GitHub master will trigger an update on your ruhoh.com blog. 31 | # make some change, save, test locally: http://localhost:9292/ 32 | git add . 33 | git ci -m "Changed something" 34 | git push 35 | 36 | # Create a new post (sets the date) 37 | ruhoh post # draft: posts/untitled-post.md 38 | ruhoh post "The Next Big Thing" # the-next-big-thing.md 39 | 40 | # Rename drafts (untitled posts) after you specify the post title in YAML 41 | ruhoh titleize # Renamed posts/untitled-post.md to: posts/my-title-post.md 42 | 43 | # folder structure 44 | +-main/ 45 | |-log.txt # logs 46 | |-config.yml # global config 47 | |-dash.html 48 | |-site.yml 49 | +-compiled/ 50 | +-themes/ 51 | +-twitter/ # name of theme 52 | +-javascripts/ 53 | +-layouts/ 54 | |-default.html # main page 55 | |-page.html # individual pages 56 | |-post.html # individual posts 57 | +-widgets/ 58 | +-media/ 59 | | +-my-media-file.png # 60 | +-partials/ 61 | +-plugins/ 62 | +-posts/ 63 | | +- 64 | +-pages/ 65 | |-about.md 66 | +-projects/ 67 | |-android.md 68 | 69 | 70 | # code highlighting is done using google prettify, you can change the theme in themes/twitter/theme.yml 71 | 72 | # post/draft options 73 | --- 74 | date : '2012-04-12' 75 | categories : # or use multilevel categories "code/android/games", or multiple categories ["code","games"] or in yaml format 76 | - code 77 | tags : 78 | - javascript 79 | - tutorial 80 | title: My post 81 | permalink: '/blog/:month/:year:/:title' 82 | 83 | layout : 'super-post' # custom layout on a per-post basis, default is 'post' (post.html) 84 | type : draft # if a draft 85 | --- 86 | 87 | 88 | # Create a new page stub 89 | ruhoh pages about.md # pages/about.md 90 | ruhoh pages projects/android.md # # pages/projects/android.md 91 | ruhoh pages projects/android --ext .html # # pages/projects/android.html 92 | ruhoh pages projects/android # pages/projects/android/index.md 93 | 94 | # page options 95 | permalink: 'pretty' 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | # Create a layout 105 | ruhoh layout leanback 106 | 107 | # Compile to static website. 108 | ruhoh compile 109 | 110 | # Create a new draft. Post title is optional. Drafts are viewed as posts in development mode 111 | ruhoh draft 112 | 113 | # List all drafts. 114 | ruhoh drafts 115 | 116 | # config.ru 117 | require 'rack' 118 | require 'ruhoh' 119 | run Ruhoh::Program.preview(:env => 'production') # use development to see drafts as posts 120 | 121 | # global settings config.yml 122 | theme : 'theme-name' 123 | production_url : 'http://nachocab.ruhoh.com' 124 | pages: 125 | permalink: 'pretty' # using index.html 126 | posts : 127 | exclude: ['~$', '^_posts\/crappy_posts\/'] # regex 128 | layout : 'super-post' 129 | summary_lines : 30 130 | latest : 10 131 | permalink : '/:categories/:title' # :year, :month, :day, :title, :filename (not including path), :categories (first category), :i_month (month from the filename), :i_day (day from the filename) 132 | pages: 133 | exclude: ['~$', '^crappy_pages\/'] # regex 134 | layout: 'custom-layout' 135 | 136 | # Templates (Mustache) 137 | {{function_name}} # escaped variable 138 | {{{function_name}}} # unescaped variable 139 | 140 | # page object. 141 | page.id 142 | page.url # url/permalink: <a href="{{page.url}}">{{page.title}}</a> 143 | page.title # <h1>{{ page.title }}</h1> 144 | page.date 145 | page.layout 146 | page.sub_layout 147 | page.master_layout 148 | 149 | # Any data added to a page's YAML meta-data is available to the page object 150 | --- 151 | title: Oh Happy Day 152 | icon : sun # page.icon 153 | days : # page.days 154 | - monday 155 | - tuesday 156 | --- 157 | 158 | # site object contains info from site.yml (ex: navigational lists) and everything from config.yml in site.config 159 | --- 160 | author: 161 | name: Nacho Caballero # <li>Author: {{ site.author.name }}</li> 162 | email: nachocab@gmail.com 163 | 164 | navigation: 165 | - index.md 166 | - about.md 167 | - projects/startup.html 168 | - contact.md 169 | --- 170 | 171 | # urls 172 | urls.theme_stylesheets 173 | urls.theme_javascripts # <link href="{{ urls.theme_stylesheets }}/bootstrap/css/bootstrap.min.css" rel="stylesheet"> 174 | urls.theme_media 175 | urls.media 176 | 177 | 178 | # Mustache sections render blocks of text one or more times, depending on the value of the key in the current context. If key is false => never displayed, if true => displayed once, if list => displayed once per item. 179 | { 180 | "person": true, 181 | } 182 | {{#person}} # begin person section 183 | Show person 184 | {{/person}} # end person section 185 | 186 | { 187 | "repo": [ 188 | { "name": "resque" }, 189 | { "name": "hub" }, 190 | { "name": "rip" }, 191 | ] 192 | } 193 | {{#repo}} 194 | <b>{{name}}</b> # <b>resque</b> <b>hub</b> <b>rip</b> 195 | {{/repo}} 196 | 197 | {{# posts }} # also, you can use {{# posts_latest}}, {{{summary}}}, {{# categories}}, {{# tags}} 198 | <li><a href="{{url}}">{{title}}</a></li> 199 | {{/ posts }} 200 | 201 | # inverted sections (!) 202 | {{^repo}} 203 | No repos :( 204 | {{/repo}} 205 | 206 | {{# is_active_page }} 207 | <li class="active"><a href="{{ url }}" class="active">{{ title }}</a></li> 208 | {{/ is_active_page }} 209 | {{^ is_active_page }} 210 | <li><a href="{{ url }}">{{ title }}</a></li> 211 | {{/ is_active_page }} 212 | 213 | 214 | # comment 215 | {{! ignore me }} 216 | 217 | # partial 218 | {{> next_more}} 219 | 220 | # contextual helpers 221 | {{# site.navigation?to_pages }} # site.yml navigation: expand to page object 222 | <li><a href="{{url}}">{{title}}</a></li> 223 | {{/ site.navigation?to_pages }} 224 | 225 | {{# db.posts.categories.ruby.posts?to_posts }} # expand to post object 226 | <li><a href="{{url}}">{{title}}</a></li> 227 | {{/ db.posts.categories.ruby.posts?to_posts }} 228 | 229 | {{# page?next }} 230 | Newer: <a href="{{ url }}">{{ title }}</a></li> 231 | {{/ page?next }} 232 | 233 | {{# page.categories?to_categories }} 234 | <li><a href="{{url}}">{{name}} <span>{{count}}</span></a></li> 235 | {{/ page.categories?to_categories }} 236 | 237 | 238 | # show help 239 | ruhoh help 240 | 241 | # List all posts. 242 | ruhoh posts 243 | 244 | # List all pages. 245 | ruhoh pages 246 | 247 | # List the full payload hash as given to the templater. It shows what is available to your templates 248 | ruhoh payload 249 | ruhoh payload | subl 250 | 251 | # Create a new layout for the currently active theme. 252 | ruhoh layout <name> 253 | 254 | # Create a new theme scaffold. 255 | ruhoh theme <name> 256 | 257 | # create a new blog (using scaffold) 258 | ruhoh new myblog -------------------------------------------------------------------------------- /scope_selectors_trick.txt: -------------------------------------------------------------------------------- 1 | comment — for comments. 2 | line — line comments, we specialize further so that the type of comment start character(s) can be extracted from the scope. 3 | double-slash — // comment 4 | double-dash — -- comment 5 | number-sign — # comment 6 | percentage — % comment 7 | character — other types of line comments. 8 | block — multi-line comments like /* … */ and <!-- … -->. 9 | documentation — embedded documentation. 10 | 11 | 12 | constant — various forms of constants. 13 | numeric — those which represent numbers, e.g. 42, 1.3f, 0x4AB1U. 14 | character — those which represent characters, e.g. <, \e, \031. 15 | escape — escape sequences like \e would be constant.character.escape. 16 | language — constants (generally) provided by the language which are “special” like true, false, nil, YES, NO, etc. 17 | other — other constants, e.g. colors in CSS. 18 | 19 | 20 | entity — an entity refers to a larger part of the document, for example a chapter, class, function, or tag. We do not scope the entire entity as entity.* (we use meta.* for that). But we do use entity.* for the “placeholders” in the larger entity, e.g. if the entity is a chapter, we would use entity.name.section for the chapter title. 21 | name — we are naming the larger entity. 22 | function — the name of a function. 23 | type — the name of a type declaration or class. 24 | tag — a tag name. 25 | section — the name is the name of a section/heading. 26 | other — other entities. 27 | inherited-class — the superclass/baseclass name. 28 | attribute-name — the name of an attribute (mainly in tags). 29 | 30 | 31 | invalid — stuff which is “invalid”. 32 | illegal — illegal, e.g. an ampersand or lower-than character in HTML (which is not part of an entity/tag). 33 | deprecated — for deprecated stuff e.g. using an API function which is deprecated or using styling with strict HTML. 34 | 35 | keyword — keywords (when these do not fall into the other groups). 36 | control — mainly related to flow control like continue, while, return, etc. 37 | operator — operators can either be textual (e.g. or) or be characters. 38 | other — other keywords. 39 | 40 | markup — this is for markup languages and generally applies to larger subsets of the text. 41 | underline — underlined text. 42 | link — this is for links, as a convenience this is derived from markup.underline so that if there is no theme rule which specifically targets markup.underline.link then it will inherit the underline style. 43 | bold — bold text (text which is strong and similar should preferably be derived from this name). 44 | heading — a section header. Optionally provide the heading level as the next element, for example markup.heading.2.html for <h2>…</h2> in HTML. 45 | italic — italic text (text which is emphasized and similar should preferably be derived from this name). 46 | list — list items. 47 | numbered — numbered list items. 48 | unnumbered — unnumbered list items. 49 | quote — quoted (sometimes block quoted) text. 50 | raw — text which is verbatim, e.g. code listings. Normally spell checking is disabled for markup.raw. 51 | other — other markup constructs. 52 | 53 | 54 | meta — the meta scope is generally used to markup larger parts of the document. For example the entire line which declares a function would be meta.function and the subsets would be storage.type, entity.name.function, variable.parameter etc. and only the latter would be styled. Sometimes the meta part of the scope will be used only to limit the more general element that is styled, most of the time meta scopes are however used in scope selectors for activation of bundle items. For example in Objective-C there is a meta scope for the interface declaration of a class and the implementation, allowing the same tab-triggers to expand differently, depending on context. 55 | 56 | storage — things relating to “storage”. 57 | type — the type of something, class, function, int, var, etc. 58 | modifier — a storage modifier like static, final, abstract, etc. 59 | 60 | 61 | string — strings. 62 | quoted — quoted strings. 63 | single — single quoted strings: 'foo'. 64 | double — double quoted strings: "foo". 65 | triple — triple quoted strings: """Python""". 66 | other — other types of quoting: $'shell', %s{...}. 67 | unquoted — for things like here-docs and here-strings. 68 | interpolated — strings which are “evaluated”: `date`, $(pwd). 69 | regexp — regular expressions: /(\w+)/. 70 | other — other types of strings (should rarely be used). 71 | 72 | support — things provided by a framework or library should be below support. 73 | function — functions provided by the framework/library. For example NSLog in Objective-C is support.function. 74 | class — when the framework/library provides classes. 75 | type — types provided by the framework/library, this is probably only used for languages derived from C, which has typedef (and struct). Most other languages would introduce new types as classes. 76 | constant — constants (magic values) provided by the framework/library. 77 | variable — variables provided by the framework/library. For example NSApp in AppKit. 78 | other — the above should be exhaustive, but for everything else use support.other. 79 | 80 | 81 | variable — variables. Not all languages allow easy identification (and thus markup) of these. 82 | parameter — when the variable is declared as the parameter. 83 | language — reserved language variables like this, super, self, etc. 84 | other — other variables, like $some_variables. -------------------------------------------------------------------------------- /statistical_tricks.R: -------------------------------------------------------------------------------- 1 | # boxplot: box-and-whisker plot, the data is broken up into quartiles: the box contains the middle 50% of the Ct values for each gene, the black bar is the median, the whiskers represent the top and bottom 25% of the observations. Circles represent outliers. 2 | 3 | # standard error (of the sample mean): THINK ACCURACY - THE SD OF THE sample mean (x_bar), it describes the accuracy of the sample mean as an estimate of the population mean. an estimate of how close is my sample mean to the population mean (should decrease by increasing sample size): standard error of the mean (i.e., of using the sample mean as a method of estimating the population mean) is the standard deviation of those sample means over all possible samples (of a given size) drawn from the population. 4 | The sample mean has 95% prob of being within 2 se of the pop mean 5 | # standard deviation (of the sample): THINK VARIABILITY - DESCRIBES THE SPREAD OF VALUES IN THE SAMPLE: how much do the individuals within the sample differ from the sample mean (unaffected by sample size) => it varies from sample to sample but stays the same on average when the sample size increases 6 | A new value has 95% prob of being within 2 sds of the sample mean 7 | 8 | # The following four quantities have an intimate relationship: Given any three, we can determine the fourth: sample size, effect size, 9 | # significance level: = P(Type I error) = probability of finding an effect that is not there 10 | # power: = 1 - P(Type II error) = probability of finding an effect that is there 11 | 12 | # marginal distribution of the statistics: the individual distribution of each statistic 13 | 14 | # residual variance: unexplained variation, it's used to calculate the standard error of the estimate => sum of square differences between the y-value of each ordered pair in the regression line and each corresponding predicted y-value 15 | 16 | # hyperparameter: parameter of a prior distribution (as opposed to a parameter of the model for the system being studied) 17 | 18 | # statistic: a function of the (observed) data => therefore, also a random variable (X denotes a random variable corresponding to the observed data) 19 | 20 | # estimator: a statistic used to infer the value of an unkown parameter in a statistical model. Ex: Parameter is a, estimator is â. If data is symbolized by random var X, the estimator is symbolized as a fn of that rand var â(X) 21 | # An estimator is judged by looking at its properties: unbiasedness, mean square error (MSE), consistency, asymptotic distribution... 22 | 23 | # error of an estimator: e(x) = â(x) - a => the error depends both on the estimator (â) and on the sample data (x) 24 | 25 | # error (of a sample): difference between the sample and the true function value (unobservable, based on the population). 26 | # residual (of a sample): difference between the sample and the estimated function value (based on the sample). 27 | 28 | # error vs residual => statistical error: diff between the height of each man in a random sample of n people and the (unobservable) population mean => the of errors is almost surely not zero => they are independent 29 | # residual: diff between the height of each man and the sample mean => which means that the sum of residuals within a random sample is 0 => residuals are not independent 30 | 31 | # z-score: measured in number of standard deviations above or below the mean => standardized statistical errors (based on population) => z = (x-MEAN)/SD 32 | # t-statistic: ratio of the departure of an estimated parameter from its notional value and its SE 33 | 34 | # expected value of the estimator: E(â(X)) 35 | 36 | # mean squared error: expected value of the squared errors => probability-weighted average over all samples of the squared errors => MSE(â) = E[(â(X)-a)^2] => how far on average are the collection of estimates from the parameter being estimated? 37 | # MSE(â) = var(â) + (B(â))^2, if unbiased => MSE(â) == var(â) 38 | 39 | # standard error of an estimator (â): sqrt(var(â)) == sd(â) => an estimate of the sd of â (an estimator of the parameter a) 40 | 41 | # sampling deviation: d(x) = â(x) - E(â(X)) 42 | 43 | # variance: expected value of the squared sampling deviations => var(â) = E[(â-E(â))^2] => how far on average are the collection of estimates from the expected value of the estimates? 44 | 45 | # difference between MSE and variance => bull's eye: parameter, throwing arrows: estimator, arrows: estimates of the estimator => high variance means the arrows are dispersed, low variance means the arrows are clustered. High MSE means the average distance between the arrows and the bull's eye is high, low MSE means the average distance between the arrows and the bull's eye is low. You can have high variance, low MSE arrows, and viceversa. 46 | 47 | # bias (of an estimator): B(â) = E(â) - a = E(â-a) => difference between the average of the collection of estimates and the parameter, also == expected value of the error. High bias means the average position of the arrows is off-target, they may be dispersed (high variance) or clustered (low variance) 48 | 49 | # unbiased: an estimator is unbiased iff B(â) = E(â-a) = 0 (you can't have a biased estimate, only biased estimators; the error of a single estimate is not the same as the bias an estimator: you can have an estimate with high error from an unbiased estimator) 50 | 51 | # estimate: a realization of an estimator, which is a statistic, and therefore a random variable 52 | 53 | # robust estimator: estimator that is resistant to errors in the results, produced from outliers and other small departures from model assumptions (usually, normality). Ex: median is a robust measure (estimator) of central tendency, the mean is not; the mean absolute deviation (MAD) and IQR are robust measure of statistical dispersion, the sd and range are not. 54 | 55 | # TPR: sensitivity (hit rate, recall) => TPR = TP/P = TP/(TP+FN) 56 | # SPC: specificity (TNR) = TN/N = TN/(FP+TN) = 1-FPR 57 | # FPR: (false alarm rate, fall-out) => FPR = FP/N = FP/(FP+TN) 58 | 59 | # ACC: accuracy = (TP + TN)/all 60 | # PPV: precision (positive predicted value) = TP/(TP+FP) 61 | 62 | # FDR: false discovery rate = FP/(FP+TP) 63 | # NPV: negative predicted value = TN/(TN+FN) 64 | 65 | 66 | 67 | 68 | # sleep dataset 69 | sleep.wide <- data.frame(ID=1:10, group1=sleep$extra[1:10], group2=sleep$extra[11:20]) 70 | 71 | # Student t-test assumes equal variances - test whether two samples are drawn from populations with different means 72 | t.test(extra ~ group, sleep, var.equal=TRUE) # long format 73 | t.test(sleep.wide$group1, sleep.wide$group2, var.equal=TRUE) # t = -1.8608, df = 18, p-value = 0.07919 74 | 75 | # Welch t-test doesn't assume equal variances - test whether two samples are drawn from populations with different means. How significant is the difference between two groups of observations? 76 | t.test(extra ~ group, sleep) 77 | t.test(sleep.wide$group1, sleep.wide$group2) # t = -1.8608, df = 17.776, p-value = 0.07939 78 | 79 | # Paired-sample t-test - For observations before and after a treatment, or of two matched subjects with different treatments. 80 | t.test(extra ~ group, sleep, paired=TRUE) 81 | t.test(sleep.wide$group1, sleep.wide$group2, paired=TRUE) # t = -4.0621, df = 9, p-value = 0.002833 82 | 83 | # Paired-sample t-test is the same as testing whether the difference between each pair of observations has a population mean of 0. 84 | t.test(sleep.wide$group1 - sleep.wide$group2, mu=0, var.equal=TRUE) # t = -4.0621, df = 9, p-value = 0.002833 85 | 86 | # One sample t-test - Comparing a group against an expecteed population mean 87 | t.test(sleep$extra, mu=0) # t = 3.413, df = 19, p-value = 0.002918 88 | 89 | # linear regression 90 | lm(output~input) -------------------------------------------------------------------------------- /wiki_tricks.txt: -------------------------------------------------------------------------------- 1 | # look for help 2 | Help:whatever 3 | 4 | # italic (2) 5 | ''italic'' 6 | 7 | # bold (3) 8 | '''bold''' 9 | 10 | # bold and italic (5) 11 | '''''bold and italic''''' 12 | 13 | # External link 14 | [[Name of page]] 15 | [[Name of page|Text to display]] 16 | [[apple]]s # links to Apple, but shows "apples" as link 17 | [[Life]]long # links to Life, but shows "lifelong" as link 18 | 19 | # Internal link 20 | [[#Heading name]] 21 | [[#Heading name|A name]] 22 | 23 | # Image 24 | [[File:Wiki.png|thumb|alt=text|This is the caption]] 25 | [[File:Wiki.png|thumb|60px|alt=text|Caption]] # add size 26 | 27 | 28 | # Templates 29 | {{example}} # This is an example of a template. For help with templates, see Help:Template. 30 | {{smallcaps|This Text}} # THIS TEXT 31 | {{convert|29|km|mi}} # 29 kilometres (18 mi) 32 | {{fact}} # citation needed 33 | 34 | {{Use dmy dates|date=July 2012}} 35 | 36 | # About template 37 | {{About|the hemorrhagic fever-causing Lassa virus|the rabiform virus|Lyssavirus}} # This article is about the hemorrhagic fever-causing Lassa virus. For the rabiform virus, see Lyssavirus. 38 | 39 | {{Taxobox 40 | | name = ''Lassa virus'' 41 | | image = Lassa virus.JPG 42 | | image_width = 200 px 43 | | image_caption = [[Transmission electron microscopy|TEM]] [[micrograph]] of ''Lassa virus'' [[Virion#Structure|virions]]. 44 | | virus_group = v 45 | | familia = ''[[Arenavirus|Arenaviridae]]'' 46 | | genus = ''[[Arenavirus]]'' 47 | | species = '''''Lassa virus''''' 48 | }} 49 | 50 | {{Infobox disease 51 | | Name = Lassa Fever 52 | | Image = 53 | | Caption = 54 | | ICD10 = {{ICD10|A|96|2|a|90}} 55 | | ICD9 = {{ICD9|078.8}} 56 | | ICDO = 57 | | OMIM = 58 | | DiseasesDB = 7272 59 | | MedlinePlus = 60 | | eMedicineSubj = 61 | | eMedicineTopic = 62 | | MeshID = D007835 63 | }} 64 | 65 | {{redir|AIDS virus|the computer virus|AIDS (computer virus)}} 66 | 67 | {{pp-semi|small=yes}} 68 | 69 | # Redirect 70 | #REDIRECT [[Target page]] # place at start of first line 71 | #REDIRECT [[Target page#anchorName]] # redirect to section 72 | 73 | # Section headings (level 1 is for page titles, don't use) 74 | ==Level 2== # section heading 75 | ===Level 3=== # subsection 76 | ====Level 4==== 77 | =====Level 5===== 78 | ======Level 6====== 79 | 80 | # Nonindexed headers: for defined terms 81 | ; Header name 82 | 83 | # bulleted list 84 | * One 85 | * Two 86 | ** Two point one 87 | * Three 88 | 89 | # numbered list 90 | # One 91 | # Two 92 | ## Two point one 93 | # Three 94 | 95 | # indenting text 96 | no indent (normal) 97 | :first indent 98 | ::second indent 99 | :::third indent 100 | 101 | # Footnote references 102 | Hello,<ref>Encyclopædia Britannica</ref> World.<ref>http://www.w3.org/</ref> # Hello,[1] World.[2] 103 | 104 | == References == 105 | {{Reflist}} # ^ Encyclopædia Britannica 106 | # ^ http://www.w3.org/ 107 | 108 | {{Reflist|2}} # 2 columns 109 | 110 | # cite journal 111 | <ref>{{cite journal |author=Frame JD, Baldwin JM, Gocke DJ, Troup JM |title=Lassa fever, a new virus disease of man from West Africa. I. Clinical description and pathological findings |journal=Am. J. Trop. Med. Hyg. |volume=19 |issue=4 |pages=670–6 |date=1 July 1970|pmid=4246571 |url=http://www.ajtmh.org/cgi/content/abstract/19/4/670 }}</ref> 112 | 113 | # Named references 114 | <ref name=Ogbu_2007>{{cite journal |author=Ogbu O, Ajuluchukwu E, Uneke CJ |title=Lassa fever in West African sub-region: an overview |journal=Journal of vector borne diseases |volume=44 |issue=1 |pages=1–11 |year=2007 |pmid=17378212 |doi=}}</ref> 115 | 116 | <ref name=Ogbu_2007 /> # then you can use it again 117 | 118 | # Cite doi 119 | <ref name=Example2006>{{Cite doi|10.1146/annurev.earth.33.092203.122621|noedit}}</ref> 120 | <ref name=Example2006/> # use again 121 | 122 | # cite web 123 | {{cite web |url= |title= |last= |first= |author= |authorlink= |last2= |first2= |author2= |authorlink2= |date= |month= |year= |work= |publisher= |location= |page= |pages= |at= |language= |trans_title= |type= |format= |arxiv= |asin= |bibcode= |doi= |doibroken= |isbn= |issn= |jfm= |jstor= |lccn= |mr= |oclc= |ol= |osti= |pmc = |pmid= |rfc= |ssrn= |zbl= |id= |archiveurl= |archivedate= |deadurl= |accessdate= |quote= |ref= |separator= |postscript=}} 124 | 125 | {{cite web |url = http://www.example.org/ |title = My Favorite Things, Part II |author = Doe, John |date = 30 April 2005 |work = Encyclopedia of Things |accessdate = 6 July 2005 }} 126 | 127 | # horizontal line 128 | ---- 129 | 130 | # Table of contents: the page must have at least four headings, 131 | __TOC__ # force it to appear at location, otherwise it appears in front of the first header 132 | __NOTOC__ # no table of contents 133 | 134 | # blockquote 135 | <blockquote>blah blah</blockquote> 136 | 137 | 138 | -------------------------------------------------------------------------------- /writing tricks.txt: -------------------------------------------------------------------------------- 1 | # Dash – 2 | # emphasis, if you use parenthesis it indicates the info is not importatnt 3 | The drugs did more than prevent new fat accumulation. They also triggered overweight mice to shed significant amounts of fat–up to half their body weight 4 | # definition, especially long definitions 5 | To establish that the marrow cells–also called adult stem cells or endothelial precursor cells–can colonize the eye, Friedlander and his colleagues first transplanted stem cells from an adult mouse into the eyes of newborn mice 6 | 7 | # common words as verbs 8 | # line: 9 | Ependyma is the thin epithelial membrane lining the ventricular system of the brain and the spinal cord. 10 | 11 | Hickman and colleagues 12 | relay, confronted, endowed, mounted, initiates? termed, usher in, galvanize==(shock with an electric current, spur, espabilar) 13 | 14 | Q? Q? Q? A long list to be sure, but longer still as each answer raises its own set of questions. 15 | 16 | 17 | # instead of ... => use ... 18 | getting ready => readying herself 19 | see => spot 20 | 21 | # good verbs 22 | relay 23 | brew 24 | stem 25 | 26 | underscore 27 | 28 | cast (doubt) 29 | 30 | halt 31 | break 32 | disrupt 33 | disturb 34 | disable 35 | 36 | employ 37 | 38 | produce 39 | generate 40 | translate --------------------------------------------------------------------------------