PythonWise

If it won't be simple, it simply won't be. [source code]

Saturday, November 07, 2009

Find Cell Number Carrier

#!/bin/bash

# Find the carrier for a cell number using whitepages

# Miki Tebeka <miki@mikitebeka.com>

if [ $# -ne 1 ]; then
echo "usage: $(basename $0) NUMBER"
exit 1
fi

# Fake Firefox
agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) "
agent="$agent Gecko/20061204 Firefox/2.0.0.1"

url="http://www.whitepages.com/carrier_lookup?"
url="${url}carrier=other&number_0=${1}&name_1=&number_1=&name_2=&number_2="
url="${url}&name_3=&number_3=&response=1"

curl -A "$agent" -L -s "$url" | \
grep -A1 carrier_result | tail -1 | \
sed -e 's/.*(\(.*\))/\1/' -e 's/^ \+//'

Tuesday, October 27, 2009

EnSalvage

I wrote a little utility to help a fried whose Entourage database got corrupted.

If anybody cares, here it is, you can even download a .app for Mac :)

Friday, October 23, 2009

binary

#!/bin/bash
# Show binary representation of a number

if [ $# -ne 1 ]; then
echo "usage: `basename $0` NUMBER" 1>&2
exit 1
fi

echo "obase=2; $1" | bc -l

Friday, October 09, 2009

strftime

#!/usr/bin/env python
'''Convert seconds since epoch to human readable time format.
Useful in cases where logs dump time information in epoch.

$ echo 1255099899 | strftime
10/09/2009 07:51
$
'''

from time import strftime, localtime
import re

def main(argv=None):
import sys
from optparse import OptionParser

argv = argv or sys.argv

default_format = "%m/%d/%Y %H:%M"
parser = OptionParser("%prog [options] [FILENAME]")
parser.add_option("--format", dest="format",
help="time format [%s]" % default_format, default=default_format)
parser.add_option("--doc", help="show strftime documentation",
dest="doc", action="store_true", default=0)
parser.add_option("--quote", help="quote result (e.g. '10/2/2009')",
dest="quote", default="")

opts, args = parser.parse_args(argv[1:])
if len(args) not in (0, 1):
parser.error("wrong number of arguments") # Will exit

if opts.doc:
import webbrowser
url = "http://docs.python.org/library/time.html#time.strftime"
webbrowser.open(url)
raise SystemExit

infile = args[0] if args else "-"
if infile == "-":
info = sys.stdin
else:
try:
info = open(infile)
except IOError, e:
raise SystemExit("error: can't open %s - %s" % (infile, e))

def callback(match):
t = localtime(float(match.group()))
human = strftime(opts.format, t)
if opts.quote:
human = human.replace(opts.quote, r"\\%s" % opts.quote)
human = opts.quote + human + opts.quote

return human

# We assume 1XXXXXXXXX (2001 +) dates, so we won't convert *everything*
print re.sub("1\d{9}(\.\d+)?", callback, info.read())


if __name__ == "__main__":
main()

Monday, September 28, 2009

Uncomment Your Code

Wednesday, September 16, 2009

process

A combination of pgrep and pkill.

#!/usr/bin/env python
'''Find processes by regexp'''

# Miki Tebeka <miki.tebeka@gmail.com>

import re
from os import popen, getpid, kill
import signal
from sys import platform

def ask_user():
answer = ""
while not answer:
answer = raw_input("kill? [y/n]").strip()
if not answer:
continue
if answer.lower() in ("y", "yes"):
return 1
elif answer.lower() in ("n", "no"):
return 0
else:
print "Please answer yes or no"

def find_signum(signal_name):
if signal_name[:3] == "SIG":
signum = getattr(signal, signal_name, None)
else:
try:
signum = int(signal_name)
except ValueError:
signum = None

return signum

def main(argv=None):
if argv is None:
import sys
argv = sys.argv

from optparse import OptionParser

parser = OptionParser("usage: %prog [options] [REGEX]")
parser.add_option("-k", "--kill", help="kill processes",
dest="kill", action="store_true", default=0)
parser.add_option("-i", "--interactive",
help="interactive killing (ask before each one)",
dest="interactive", action="store_true", default=0)
parser.add_option("-a", "--annotate", help="annotate matching lines",
dest="annotate", action="store_true", default=0)
parser.add_option("-s", help="signal to send", default="SIGTERM",
action="store", dest="signal")
parser.add_option("-9", help="send SIGKILL", dest="signal",
action="store_const", const="SIGKILL")
parser.add_option("-g", "--gvim", help="kill also gvim sessions",
action="store_true", default=0, dest="gvim")

opts, args = parser.parse_args(argv[1:])
if len(args) not in (0, 1):
parser.error("wrong number of arguments") # Will exit

regexp = args[0] if args else "."

try:
is_interesting = re.compile(regexp).search
except re.error:
raise SystemExit("error: bad regular expression - %s" % args[0])

signal = find_signum(opts.signal)
if signal is None:
raise SystemExit("error: bad signal - %s" % opts.signal)

found = 0
first = 1
if platform == "darwin":
cmd = "ps ax"
index = 0
else:
cmd = "ps -eff"
index = 1

for line in popen(cmd):
line = line.rstrip()
# Print header line
if first:
first = 0
print line
continue

if (not opts.annotate) and (not is_interesting(line)):
continue

fields = line.split()
pid = int(fields[index])
if pid == getpid():
continue

# Color lines
if is_interesting(line):
found = 1
if opts.annotate:
print "\033[32m%s\033[0m" % line
else:
print line
elif opts.annotate:
print line

# Kill only intersting lines
if not is_interesting(line):
continue
do_kill = 0
if opts.kill and opts.interactive:
do_kill = ask_user()
elif opts.kill and not opts.gvim:
do_kill = "vim" not in line.lower()
elif opts.kill:
do_kill = 1

if do_kill:
try:
kill(pid, signal)
print "%d killed" % pid
except OSError, e:
print "error: %s" % e
elif opts.kill:
print "not killing %s" % pid

if not found:
error = "error: can't find any process matching `%s'" % args[0]
raise SystemExit(error)

if __name__ == "__main__":
main()

Saturday, September 05, 2009

pyindent

Indent C files according to PEP 7.
(uses indent)

#!/bin/sh

# Indent C files according to http://www.python.org/dev/peps/pep-0007/
# Miki Tebeka <miki.tebeka@gmail.com>

indent -cli4 -npcs -l78 -bad -bap -br -ce -nbc -di1 -psl -i4 -brs -lp -cdw -ut -ts4 $@

Blog Archive

About Me

My Photo
Miki Tebeka
Professional programmer, mainly Python but can handle almost everything.
View my complete profile