An interesting bit of math

http://plus.maths.org/content/os/issue26/features/sautoy/index

Every time you use your credit card on the internet to buy a ticket to see Real Madrid play, your account is kept secret from hackers thanks to the power of prime numbers. Prime numbers have become the locks that preserve the secrets that are racing through the electronic shopping mall.

Each e-business chooses two big primes, p and q, which they keep secret. The product of these primes, N=pxq, is made public. A calculation using N encrypts your credit card, but the only way to undo the calculation and decrypt the secret message is to know the secret primes p and q. Cracking codes is the same as cracking the public number N into its prime building blocks. It’s a bit like a chemist who wants to know the atoms inside a compound. Although chemists have solved their problem, mathematicians lack any fast way to do this prime-number spectroscopy – to the relief of internet cryptographers.

Fun ASCII text decoration from the 90s

I couldn’t resist posting these because they’re great for drawing attention to stuff on internal wiki pages and documentation. Shamelessly ripped from http://www.xatworld.com/nicks/decorarnickxat.html

╚»★«╝ ( EMO NICK) ╚»★«╝
¨¨¨™¤¦¤™¨¨¨~*§*®§* ( YOUR XAT NICK HERE ) *§®*§*~¨¨¨™¤¦¤™¨¨¨
©~®§][©] ( YOUR XAT NICK HERE ) [©][§®~©
®~©~®][§] ( YOUR XAT NICK HERE ) [§][®~©~®
§®*§[•.*.•]™ ( YOUR XAT NICK HERE ) ™[•.*.•]§®*§
}{®~©}{*§*}{¤¦¤} ( YOUR XAT NICK HERE ) {*§*}{¤¦¤}{®~©}{
°¨¨¨™¤¦¤™¨¨¨° ( YOUR XAT NICK HERE ) °¨¨¨™¤¦¤™¨¨¨°
O~°’¨¤¦¤¨’°~O** ( YOUR XAT NICK HERE ) **O~°’¨¤¦¤¨’°~O
™©~®}- ( YOUR XAT NICK HERE ) -{©~®™
™`~*.*~`¤-_ ( YOUR XAT NICK HERE ) _-¤`~*.*~`™
™`•.¸¸.•¤¦¤`••._.• ] ( YOUR XAT NICK HERE ) [ `•.¸¸.•¤¦¤`••._.•`™
°¨¨¨™`•.•`¤¦¤ ( YOUR XAT NICK HERE ) ¤¦¤`•.•` ™¨¨¨°
¨'*•~-.¸¸,.-~* ] ( YOUR XAT NICK HERE ) [ ¨'*•~-.¸¸,.-~*'
o°°o°°o°*~.] ( YOUR XAT NICK HERE ) [.~* °o°°o°°o
(¯`•._.•[ ( YOUR XAT NICK HERE ) ]•._.•´¯)
×÷•.•´¯`•)» ( YOUR XAT NICK HERE ) «(•´¯`•.•÷×
,.-~*’¨¯¨’*•~-.¸-(_ ( YOUR XAT NICK HERE ) _)-,.-~*’¨¯¨’*•~-.¸
O?°’¨ ( YOUR XAT NICK HERE ) ¨’°?O
- – –^[ ( YOUR XAT NICK HERE ) ]^– – -
••.•´¯`•.•• ( YOUR XAT NICK HERE ) ••.•´¯`•.••
`•.¸¸.•´´¯`••._.• ( YOUR XAT NICK HERE ) `•.¸¸.•´´¯`••._.•
(¯`•._) ( YOUR XAT NICK HERE ) (¯`•._)
¯¨’*•~-.¸¸,.-~*’ ( YOUR XAT NICK HERE ) ¯¨’*•~-.¸¸,.-~*’
O?°’¨ ( YOUR XAT NICK HERE ) ¨’°?O
×?°”?`”°?× ( YOUR XAT NICK HERE ) ×?°”?`”°?×
¨°o.O ( YOUR XAT NICK HERE ) O.o°
(¯`·._.·[ ( YOUR XAT NICK HERE ) ]·._.·´¯)
¨°o.O ( YOUR XAT NICK HERE ) O.o°
×÷·.·´¯`·)» ( YOUR XAT NICK HERE ) «(·´¯`·.·÷×
· ··^v´¯`×) ( YOUR XAT NICK HERE ) (×´¯`v^·· ·
,.-~*’¨¯¨’*·~-.¸-(_ ( YOUR XAT NICK HERE ) _)-,.-~*’¨¯¨’*·~-.¸
- – –^[ ( YOUR XAT NICK HERE ) ] ^– – -
•·.·´¯`·.·• ( YOUR XAT NICK HERE ) •·.·´¯`·.·•
`·.¸¸.·´´¯`··._.· ( YOUR XAT NICK HERE ) `·.¸¸.·´´¯`··._.·
(¯`·._) ( YOUR XAT NICK HERE ) (¯`·._)
¯¨’*·~-.¸¸,.-~*’ ( YOUR XAT NICK HERE ) ¯¨’*·~-.¸¸,.-~*’
Oº°‘¨ ( YOUR XAT NICK HERE ) ¨‘°ºO
׺°”˜`”°º× ( YOUR XAT NICK HERE ) ׺°”˜`”°º×
.·´¯`·-> ( YOUR XAT NICK HERE ) <-·´¯`·.
<((((º><.·´¯`·. ( YOUR XAT NICK HERE ) ¸.·´¯`·.¸><((((º>
- -¤–^] ( YOUR XAT NICK HERE ) [^--¤- -
~²ºº²~ ( YOUR XAT NICK HERE ) ~²ºº³~
._|.<(+_+)>.|_. ( YOUR XAT NICK HERE ) ._|.<(+_+)>.|_.
..|..<(+_ ( YOUR XAT NICK HERE ) _+>..|..
-·=»‡«=·- ( YOUR XAT NICK HERE ) -·=»‡«=·-
•°o.O ( YOUR XAT NICK HERE ) O.o°•
––––•(-• ( YOUR XAT NICK HERE ) •-)•––––
(¯`•¸·´¯) ( YOUR XAT NICK HERE ) (¯`·¸•´¯)
··¤(`×[¤ ( YOUR XAT NICK HERE ) ¤]×´)¤··
—(•·÷[ ( YOUR XAT NICK HERE ) ]÷·•)—
·ï¡÷¡ï· ( YOUR XAT NICK HERE ) ·ï¡÷¡ï·
·!¦[· ( YOUR XAT NICK HERE ) ·]¦!·
°º¤ø,¸¸,ø¤º°`°º¤ø,¸ ( YOUR XAT NICK HERE ) °º¤ø,¸¸,ø¤º°`°º¤ø,¸
»-(¯`v´¯)-» ( YOUR XAT NICK HERE ) »-(¯`v´¯)-»
°l||l° ( YOUR XAT NICK HERE ) °l||l°
•°¤*(¯`°(F)( ( YOUR XAT NICK HERE ) )(F)°´¯)*¤°•
—¤÷(`[¤* ( YOUR XAT NICK HERE ) *¤]´)÷¤—
¸.´)(`·[ ( YOUR XAT NICK HERE ) ]·´)(` .¸
·÷±‡± ( YOUR XAT NICK HERE ) ±‡±÷
+*¨^¨*+ ( YOUR XAT NICK HERE ) +*¨^¨*+

`diff` the contents of two URLs

I needed a quick little tool to see if a page hosted on a CDN updated and how long the update took, so I wrote a small bash script that accepts input in the form of the first and second arguments it is called with.

Usage (This would diff example.com against example.net every 60 seconds)

while true; do bash diffurl.sh http://example.com http://example.net; sleep 60; done

In another terminal, you’d probably want to `tail -f diffurl.sh` to follow the results.

Script source:

#!/bin/bash
THEDATE=$(date +%y%m%d%H%M%S)
fn1="1-${THEDATE}.tmp"
fn2="2-${THEDATE}.tmp"
wget -O "$fn1" "$1"
wget -O "$fn2" "$2"
echo >> diffurl.log
echo "---- $(date) ----" >> diffurl.log
diff "$fn1" "$fn2" 2>&1 >> diffurl.log

Calculate data transferred in Apache / Litespeed web server

The module we use to monitor Apache bandwidth at work isn’t compatible with Litespeed web server (lsws), so I made a small script to just check for blatant abuse.

#!/bin/bash

mylogs=$(grep CustomLog /etc/httpd/conf.d/vhost_* |grep transfer | awk '{print $3}' |cut -d / -f 3 |sort |uniq)

for x in $mylogs; do
    echo
    echo "---- $x ----"
    for y in $(ls /home/$x/var/*/logs/transfer.log); do
        domain=$(echo $y | cut -d / -f 5)
        since=$(head -1 $y | awk '{print $4}')
        todo=$(awk '{sum+=$10} END {print sum/1048576}' $y)
        out=$(echo $todo |awk '{printf("%5.0f\n",$0)}')

        # optional, if enabled it only prints domains with more than 3000 MB since log creation
        #if [ $out -gt 3000 ]; then
            echo -e "$out MB \t $domain \t \t since $since]"
        #fi
    done
done

Should be pretty straightforward besides the mildly advanced ‘awk’ usage (
(“mildly advanced” because I guess “basic” usage would mean only using awk to print a particular column, which would be better done with bash’s ‘read’ built-in)

Python SQLite Logging Handler

I would think that someone would have already implemented a SQLite back-end for logging stuff in Python using the built-in ‘logging’ module, but I couldn’t find anything, so I just made one. Not implemented yet, but planned: logging to different tables based on logger name or possibly something else.

Here is sqlitehandler.py:

import logging
import sqlite3
import time

class SQLiteHandler(logging.Handler): # Inherit from logging.Handler
    def __init__(self, filename):
        global db
        # run the regular Handler __init__
        logging.Handler.__init__(self)
        # Our custom argument
        db = sqlite3.connect(filename) # might need to use self.filename
        db.execute("CREATE TABLE IF NOT EXISTS debug(date text, loggername text, srclineno integer, func text, level text, msg text)")
        db.commit()

    def emit(self, record):
        # record.message is the log message
        thisdate = time.time()
        print record.getMessage()
        db.execute('INSERT INTO debug(date, loggername, srclineno, func, level, msg) VALUES(?,?,?,?,?,?)', (thisdate, record.name, record.lineno, record.funcName, record.levelname, record.msg))
        db.commit()

And here is a sample implementation with some other stuff from my bitcoin trading bot:

import urllib2
import json
import logging
import logging.handlers
import sqlitehandler
from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('bitbot.conf')

# ---- INIT ----
def getRate():
    result = json.load(urllib2.urlopen(parser.get('mtgox', 'ApiTickerUrl')))
    return result['ticker']['buy']

print parser._sections['mtgox']
print getRate()

# ---- MAIN ----
# Create a logging object (after configuring logging)
logger = logging.getLogger('someLoggerNameLikeDebugOrWhatever')

# optionally, we could define a logger like so:
#myHandler = sqlitehandler.SQLiteHandler('debugLog.sqlite')

# set the lowest level of event to log.  If undefined, defaults to logging.WARNING
# valid levels: 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'
logger.setLevel(logging.DEBUG)

# Add our custom logging handler to logger
# The arg we're passing is the name of the SQLite database file to use
logger.addHandler(sqlitehandler.SQLiteHandler('debugLog.sqlite'))

# test out the different log levels
logger.debug('Test 1')
logger.info('Test 2')
logger.warning('Test 3')
logger.error('Test 4')
logger.critical('Test 5')

Lastly, here is bitbot.conf which you’ll need to run the without modification:

[mtgox]
email: [email protected]
pass: somepassword
ApiTickerUrl: https://mtgox.com/code/data/ticker.php
ApiGetFundsUrl: https://mtgox.com/code/getFunds.php
ApiSellUrl: https://mtgox.com/code/sellBTC.php

Have fun, and check out bitbot for how I’m actually using this in a project. I’ll try to update this post when I improve this handler to do more cool stuff, but I might forget.

Clicky Kitty:
Clicky Kitty!

Quickly change file extensions in Bash

This is something that I didn’t learn until I had been using bash for a few years, but it’s insanely useful.

Let’s say you have a file called ‘default.conf’ that you want to rename because you’re [whatever];

mv default.conf{,.backup}

Now default.conf is named default.conf.backup. You can remove things, too:

mv default.conf.backup{.backup,}

Now it’s default.conf again.

This is called Brace Expansion

Page 5 of 16« First...34567...10...Last »