Shantanu's Blog

Database Consultant

August 28, 2012

 

monitoring mysql error log

The most important aspect of mysql that needs to be monitored is error log file. MySQL will write almost all important errors to this file. Here is a cron that will monitor it every hour and let the DBA know when the file is updated.

02 * * * * tail -1000 `mysqladmin variables | grep log_error | awk '{print $4}'` | grep -e "`date +'\%y\%m\%d \%k' --date='1 hour ago'`" | mail -s "crashed lo from `hostname`"   dba@company.com  > /home/alert_mail_success.txt 2> /home/alert_mail_err.txt

1) Replace "mail -s" with "mail -E -s" so that blank (empty) mails will not be sent.
2) The "-E" option may not work with older mail version. But the following cron should work...

02 * * * * tail -1000 `mysqladmin variables | grep log_error | awk '{print $4}'` | grep -e "`date +'\%y\%m\%d \%k' --date='1 hour ago'`" > myerror.txt; if [[ -s myerror.txt ]];  then cat myerror.txt | mail -s "last hour error log from `hostname`" dba@company.com ; fi > /home/alert_mail_success.txt 2> /home/alert_mail_err.txt

It will not send a mail if the error log extract file (myerror.txt) is empty.


August 24, 2012

 

Online Utilities

Regular Expressions demystified

There are times when using regular expression is the only way to find the text from a given string.
Here is a really useful utility that will explain and at the same time help us to write complex regular expressions.

http://gskinner.com/RegExr/?31u07
_____

SQL formatter

The following utility will help to format a complex SQL query.

http://www.dpriver.com/pp/sqlformat.htm


Labels: ,


August 22, 2012

 

Python tips 9 - SQLite DB

import sqlite3 as sqlite

conn = sqlite.connect(":memory:")
conn.execute("CREATE TABLE A (name integer PRIMARY KEY AUTOINCREMENT, address varchar(100))")
conn.execute("insert into A values (22, 'india')")
conn.execute("insert into A values (23, 'usa')")
a = conn.execute("SELECT * FROM A").fetchall()

for i in a:
    print i[1]

# will print this...   
#india
#usa


# The cursor retains the id of the last row inserted in the lastrowid attribute

import sqlite3
connection = sqlite3.connect(':memory:')
cursor = connection.cursor()
cursor.execute('CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test', 'test'))
print(cursor.lastrowid)

# fetchone() returns the first row from the select statement as a tuple, so fetchone()[0] will return the first (and only) column in the first (and only) row, i.e. the max(id).

cursor = sqlite3.execute('SELECT max(id) FROM table_name')
max_id = cursor.fetchone()[0]
_____


# it is also possible to update a value based on some other column

cursor.execute('SELECT column2 FROM Table ORDER BY column2')
column2 = [row[0] for row in cursor]
for j, c in zip(lst, column2):
    cursor.execute('UPDATE Table SET column = ? WHERE column2 = ?', [j, c])

Labels:


 

Python tips 8 - import module

It is possible to directly import a module and initialize the class.

>>> exec(urllib2.urlopen('http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py').read())
>>> uf = UnionFind()

We can use wget or curl
$ wget http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py

>>> from UnionFind import UnoinFind
>>> uf = UnionFind()

Labels:


August 20, 2012

 

python tips 7 - List comprehension

If you are looking for concise, pythonic and elegant way of writing a loop then list comprehension is the right choice.

## normal loop to print numbers till 10 except 2 and 3
# expected output
# [1, 4, 5, 6, 7, 8, 9, 10]

t = 0
l = []
while t < 10:
    t += 1
    if t == 2 or t == 3: continue
    l.append(t)

## list comprehension # 6 lines in 1
a = [x for x in range(1,10) if x != 2 and x != 3]
## a is now a list and can be used in for x in a:

#  use unpacking in list comprehension
dict((s, v) for (o, s), v in mydict.iteritems() if o is co1)

Labels:


August 19, 2012

 

Python tips 6 - loops

# following has no loop for it is printed only once
def thisLines(n):
    mv = 0
    if n > mv:
        print "testme22"
        n += 1

thisLines(10)

# Using while loop
def printLines(nr):
    myva = 0
    while nr > myva:
        print "testme"
        myva += 1

printLines(10)

# Using recursive function:

def nLines(n):
    if n > 0:
        print "test"
        nLines(n-1)

nLines(10)

Labels:


August 18, 2012

 

python tips 5

'''
save the  URL list in a file and then copy the source code to a text file
'''

import urllib

class mydict():
   def myurllist():
           fp = open('URLS-HERE.txt', "w")
           fp.write('http://google.com/index.html')
           fp.close()
        
   def read_myurllist():
           for line in open('URLS-HERE.txt','r'):
              if line.startswith('http'):
                     fichier = open("other.txt", "w")
                     allhtml = urllib.urlopen(line)
                     fichier.write(allhtml.read())
                     fichier.close()

m = mydict()
m.myurllist
m.read_myurllist

fp1 = open('other.txt', 'r')
for myline in fp1.readlines():
   print myline
fp1.close()

_____


parse_qs is used to Parse a query string. Data are returned as a dictionary.

import urllib2
import urlparse

url = 'http://www.tip.it/runescape/gec/price_graph.php?avg=1&start=1327715574&mainitem=10350&item=10350'
response = urllib2.urlopen(url)
content = response.read()
params = urlparse.parse_qs(content)
print(params['values'])




August 16, 2012

 

python with NumPy

NumPy for windows can be downloaded from...
http://sourceforge.net/projects/numpy/files/NumPy/

## np allows to construct array differently:
import numpy as np
z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')])
np.savetxt('test.txt', z, fmt='%i %s')

August 10, 2012

 

Python tips 4


# Find the ten most common words in abc.txt

def cat(filename):
    f = open(filename, 'rU')
    text = f.read()
    wordlist = text.split()
    for myword in wordlist:
        oldval = d.get(myword, 0)
        d[myword] = oldval + 1

    t = sorted(d.iteritems(), key=lambda x:-x[1])[:3]
    for x in t: print "{0}: {1}".format(*x)

# Better

def cat(filename):
    f = open(filename, 'rU')
    text = f.read()
    wordlist = text.split()
    return collections.Counter(wordlist).most_common(3)

# Best
import re
wordlist = re.findall('\w+', open('abc.txt').read().lower())
collections.Counter(wordlist).most_common(3)

## Counter ##

>>> from collections import Counter

>>> c=Counter({2:2, 3:1, 5:1,9:4})
>>> type(c)

>>> list(c.elements())
[9, 9, 9, 9, 2, 2, 3, 5]


_____

If I need to total the values for each key, I can use the counter method available in collections.

d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
# expected results
# Counter({'c': 7, 'a': 6, 'b': 6})

from collections import Counter
one = sum(map(Counter, d.values()), Counter())
two = sum((Counter(v) for v in d.itervalues()), Counter())
# using loop to count
three = Counter()
for v in d.values():
    three.update(v)

Or it is also possible to use default dictionary method as shown below.
       
from collections import defaultdict
de = defaultdict(int)
for dct in d.values():
    for k,v in dct.items():
        de[k] += v
print(de)



Labels:


 

python tips 3

## list  ##
## A list can contain anything like integer, string, tuple, another list etc.

>>> a = [1,2,'abc']
>>> a
[1, 2, 'abc']


## Variables are only containers or pointers to the real stuff.
## So when a is appended, b will also change. But when a is removed b is not removed because it will still point to the old data.

>>> b = a
>>> a.append(4)
>>> b
[1, 2, 'abc', 4]
>>> del a
>>> a

Traceback (most recent call last):
  File "", line 1, in   a
NameError: name 'a' is not defined

>>> b
[1, 2, 'abc', 4]


## sort  ##

>>> sort
Traceback (most recent call last):
  File "", line 1, in sort
NameError: name 'sort' is not defined

>>> sorted
 built-in function sorted

>>>help sorted
SyntaxError: invalid syntax
>>> help (sorted)
Help on built-in function sorted in module __builtin__:
sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

## sorted is a function that returns the sorted list while a.sort() is a method that will sort data in-place.

>>> a = ['amar', 'akbar', 'anthony']
>>> sorted(a)
['akbar', 'amar', 'anthony']
>>> sorted(a, reverse=True)
['anthony', 'amar', 'akbar']
>>> def Last(s): return s[-1]
>>> sorted(a, key=Last, reverse=True)
['anthony', 'amar', 'akbar']

## reverse sort is possible as well as custom sort can be achived using a function like "Last" in this case

## slicing  ##

>>> b = ':'.join(a)
>>> b
'amar:akbar:anthony'
>>> b.split(':')
['amar', 'akbar', 'anthony']



## tuples  ##
>>> x = (1,2,3)
>>> type(x)
type 'tuple'
>>> a = (1,2,3)
>>> len(a)
3
>>> a[0]
1

## looping tuple values in a list called result
>>> result = []
>>> type (result)
type 'list'
>>> for s in x: result.append(s)
>>> result
[1, 2, 3]

## or simply use the built-in function list to convert a tuple to list

>>> x = (1,2,3)
>>> y = list(x)

>>> type (x)
type 'tuple'
>>> type (y)
type 'str'

## Lists are mutable while tuples and strings are not.
## it means tuple values can not be changed just like list values

>>> x[0] = 9

Traceback (most recent call last):
  File "", line 1, in
    a[0] = 9
TypeError: 'tuple' object does not support item assignment




## dictionary ##

>>> d = {}
>>> d['a'] = 'alpha'
>>> d['o'] = 'omega'
>>> d['g'] = 'gamma'
>>> d
{'a': 'alpha', 'g': 'gamma', 'o': 'omega'}
>>> d['a']
'alpha'
>>> d.get('a')
'alpha'

>>> d['x']
Traceback (most recent call last):
  File "", line 1, in d['x']
KeyError: 'x'

>>> d.get('x')
>>> d.get('x', 'mydefault')
'mydefault'

>>> 'a' in d
True
>>> 'x' in d
False

>>> d.keys()
['a', 'g', 'o']

>>> d.values()
['alpha', 'gamma', 'omega']

>>> d.items()
[('a', 'alpha'), ('g', 'gamma'), ('o', 'omega')]


>>> for k in d: print 'key:', k, '->', d[k]
key: a -> alpha
key: g -> gamma
key: o -> omega

>>> for tuple in d.items(): print tuple
('a', 'alpha')
('g', 'gamma')
('o', 'omega')

>>> for k in sorted(d.keys()): print 'key:', k, '->', d[k]
key: a -> alpha
key: g -> gamma
key: o -> omega



August 09, 2012

 

python tips 2

# first, second and third ranks
rank = range(1,4)
# player names
player = ['amar','akbar','anthony']
# link the ranks with players
result = dict(zip(rank,player))
# find who is third
result[3]
# find what is the rank of amar
[k for k, v in result.iteritems() if  v == 'amar'][0]

# the values can also be assigned to a tuple
(amar, akbar, anthony) = range(1,4)
 
zip can also be used to transpose data
>>> rows = [[1, 1, 2, 3], [4, 5, 6, 7], [1, 2, 5, 7], [6, 9, 8, 5]]

>>> zip(*rows)
[(1, 4, 1, 6), (1, 5, 2, 9), (2, 6, 5, 8), (3, 7, 7, 5)]

Labels:


Archives

June 2001   July 2001   January 2003   May 2003   September 2003   October 2003   December 2003   January 2004   February 2004   March 2004   April 2004   May 2004   June 2004   July 2004   August 2004   September 2004   October 2004   November 2004   December 2004   January 2005   February 2005   March 2005   April 2005   May 2005   June 2005   July 2005   August 2005   September 2005   October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006   January 2007   February 2007   March 2007   April 2007   June 2007   July 2007   August 2007   September 2007   October 2007   November 2007   December 2007   January 2008   February 2008   March 2008   April 2008   July 2008   August 2008   September 2008   October 2008   November 2008   December 2008   January 2009   February 2009   March 2009   April 2009   May 2009   June 2009   July 2009   August 2009   September 2009   October 2009   November 2009   December 2009   January 2010   February 2010   March 2010   April 2010   May 2010   June 2010   July 2010   August 2010   September 2010   October 2010   November 2010   December 2010   January 2011   February 2011   March 2011   April 2011   May 2011   June 2011   July 2011   August 2011   September 2011   October 2011   November 2011   December 2011   January 2012   February 2012   March 2012   April 2012   May 2012   June 2012   July 2012   August 2012   October 2012   November 2012   December 2012   January 2013   February 2013   March 2013   April 2013   May 2013   June 2013   July 2013   September 2013   October 2013   January 2014   March 2014   April 2014   May 2014   July 2014   August 2014   September 2014   October 2014   November 2014   December 2014   January 2015   February 2015   March 2015   April 2015   May 2015   June 2015   July 2015   August 2015   September 2015   January 2016   February 2016   March 2016   April 2016   May 2016   June 2016   July 2016   August 2016   September 2016   October 2016   November 2016   December 2016   January 2017   February 2017   April 2017   May 2017   June 2017   July 2017   August 2017   September 2017   October 2017   November 2017   December 2017   February 2018   March 2018   April 2018   May 2018   June 2018   July 2018   August 2018   September 2018   October 2018   November 2018   December 2018   January 2019   February 2019   March 2019   April 2019   May 2019   July 2019   August 2019   September 2019   October 2019   November 2019   December 2019   January 2020   February 2020   March 2020   April 2020   May 2020   July 2020   August 2020   September 2020   October 2020   December 2020   January 2021   April 2021   May 2021   July 2021   September 2021   March 2022   October 2022   November 2022   March 2023   April 2023   July 2023   September 2023   October 2023   November 2023  

This page is powered by Blogger. Isn't yours?