2015-07-28

PYTHON - List all first-level subdirectories

import os
os.chdir( '/YOUR/PATH/' )
for folder in sorted( os.listdir( os.getcwd() ) ):
    if not os.path.isfile( folder ):
        print folder

PYTHON - Extract string content between parenthesis (without regex)

print YOUR_STRING[ YOUR_STRING.find( '(' ) + 1 : YOUR_STRING.find( ')' ) ]

PYTHON - Short if-else

RESULT = [VALUE_IF_FALSE, VALUE_IF_TRUE][CONDITION]
 
r = [10, 20][0 == 0]

MacOS - How to toggle between windows of the same app

COMMAND-`

PS. To toggle between apps:  COMMAND-TAB

2015-07-27

2015-07-26

PYTHON - How to curl into a file?

(1) Install the pycurl package:
easy_install pycurl


(2) Sample script:

import pycurl
c = pycurl.Curl()
c.setopt(c.USERAGENT, 'Mozilla/5.0 (compatible; pycurl)' )

c.setopt(c.URL, 'http://website.com/page1.html')
with open('target_file_name.html', 'w') as f:
    c.setopt( c.WRITEFUNCTION, f.write )
    c.perform()
f.close()

2015-07-22

MacOS - How to customize your terminal prompt, adding a line after each command

(1) Open or create ~\.bash_profile (a text flat file at the root of your MacOS profile).

(2) Enter this line (cusomize... the dashes can be anything you want... the \n is a carriage return+line feed):

export PS1="----------------\n$"

2015-07-17

MongoDB - Import CSV with field values containing double quotes

You have to escape the double quote.
Do not escape it with a backslash (\").
Instead, escape it with another double quote ("").

MongoDB - How to rename a field

db.COLLECTION_NAME.update( {}, { $rename: {"OLD_FIELD_NAME": "NEW_FIELD_NAME"} }, false, true);

MongoDB - How to import a CSV file

mongoimport --db DATABASE_NAME --collection COLLECTION_NAME --type csv --headerline --file /path/to/file/FILE_NAME.csv

MacOS - Show hidden files and folders

defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Finder

2015-07-15

PYTHON - Randomly choose an list/array element (numeric or text)

import random
print( random.choice( [1,2,3] ) )
print( random.choice( ['a','b','c'] ) )

2015-07-13

PYTHON - Twitter search and results parsing

# 1. Twitter authentication credentials (get yours at dev.twitter.com)
consumerKey = ''
consumerSecret = ''

# 2. Create a twython object (installation command: "sudo easy_install twython")
from twython import Twython
twitter = Twython( consumerKey, consumerSecret )

# 3. Display tweets' text matching a given search term
term = 'chapo'
for status in twitter.search(q=term)["statuses"]:  
    print status["text"]

PYTHON - How to most efficiently concatenate strings

from cStringIO import StringIO
string = StringIO()

string.write( 'First sentence.' )
string.write( 'Second string.' )
string.write( 'Thrid' )

print( string.getvalue() )

PYTHON - How to parse a JSON string

# 1. Original JSON String
text = """{ "count": 2, "record": [ {"lemma":"God"}, {"lemma":"Men"} ] }"""

# 2. Text to JSON object
import json
j = json.loads(text)

# 3. Parse a top-level property
print 'count: ' + str( j['count'] )

# 4. Traverse multiple records
for item in j['record']:
    print( item['lemma'] )

PYTHON - Break a paragraph into a sentences list

import re
text = 'This is. A paragraph with. Three sentences.'
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', text)
for item in sentences:
    print(item)

PYTHON - Getting text from a website

import requests
txt = requests.get("http://lipsum.com/robots.txt").text
print( txt )


2015-07-09

2015-07-08

PYTHON - Display and change current working directory

import os
print( os.getcwd() )
os.chdir( os.path.dirname("C:/folder/subfolder") )

print( os.getcwd() )