code:
filename = None

def SaveFile(filename):
    global filename
    if filename == None:
        chooser = gtk.FileChooserDialog("Save File...", None,
                                    gtk.FILE_CHOOSER_ACTION_SAVE,
                                    (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                     gtk.STOCK_SAVE, gtk.RESPONSE_OK))
        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            filename = chooser.get_filename()
            chooser.destroy()
            wbuffer = textview.get_buffer()
            text = wbuffer.get_text(wbuffer.get_start_iter(), wbuffer.get_end_iter())
            openfile = open(filename,"w")
            openfile.write(text)
            openfile.close()
            print filename, "this is the first part"
            return filename
        else:
            chooser.destroy()
    elif filename != None:
        wbuffer = textview.get_buffer()
        text = wbuffer.get_text(wbuffer.get_start_iter(), wbuffer.get_end_iter())
        openfile = open(filename,"w")
        openfile.write(text)
        openfile.close()
        print filename, "made it this far"
        return filename
    else:
        chooser.destroy()
        return filename

rawDescription: python gtk save gtksourceview

description: Python gtk save gtksourceview


code:
for x in iter(foo, 0):
    print x

rawDescription: "Iterate" a function's return values

description: "Iterate" a function's return values


code: a = np.arange(12); a.resize(3, 4); print a

rawDescription: Reshaping Arrays in Numpy with variables


code:
print "fred\xbf"
print r"fred\xbf"

rawDescription: How do I tell Python not to interpret backslashes in strings?

description: Tell Python not to interpret backslashes in strings


code:
import argparse
parser = argparse.ArgumentParser(
        description='this is the description',
        epilog="This is the epilog",
        argument_default=argparse.SUPPRESS
        )

parser.add_argument('-v', '--verbose', help='verbose', action='store_true', default=False)

root_group = parser.add_mutually_exclusive_group()

group_list = root_group.add_mutually_exclusive_group()
group_list.add_argument('-m', help='list only modules', action='store_const', dest='list', const='modules', default='all')
group_list.add_argument('-p', help='list only ports', action='store_const', dest='list', const='ports', default='all')
group_list.add_argument('--list', help='list only module or ports', choices=['modules','ports'], metavar='<modules/ports>', default='all')

group_simulate = root_group.add_mutually_exclusive_group()
group_simulate.add_argument('-M', help='simulate module down', nargs=1, metavar='module_name', dest='simulate')
group_simulate.add_argument('-P', help='simulate FC port down', nargs=1, metavar='fc_port_name', dest='simulate')
group_simulate.add_argument('-I', help='simulate iSCSI port down', nargs=1, metavar='iSCSI_port_name', dest='simulate')
group_simulate.add_argument('--simulate', help='simulate module or port down', nargs=1, dest='simulate')

args = parser.parse_args()

print args

rawDescription: Python dependencies between groups using argparse


code:
from scrapy.spider import Spider
from scrapy.selector import Selector

class wildberries(Spider):
    name = "wildberries"
    allowed_domains = ['wildberries.ru']
    start_urls      = ['http://www.wildberries.ru/']

    def parse(self, response):
        selector = Selector(response)
        print "Hello World", response.url
        maincats = selector.xpath('//div[@class="topmenu"]/ul[@class="green_menu"]/li/a/@href').extract()
        print maincats

rawDescription: Scrapy start_urls are not parsed

description: Scrapy start_urls are not parsed


code:
for name, nums in get_entries( infile ):
    print name, nums

rawDescription: Python: Build a dictionary from a file's contents


code:
import csv
reader = csv.reader(open('test.csv'))

result = {row[0]:[i for i in row[1:] if i] for row in reader if row and row[0]}
print result

rawDescription: Reading csv file in Python and create a dictionary


code:
reader.next() # advances to second line
for row in reader: # loops over remaining lines
    while i < 10: # loops over i
        print row # prints current row - this would be the second row in the first forloop iteration... 10 times, because you loop over i.
        i=i+1 # increments i, so the next rows, i is already >=10, your while-loop only affects the second line.

rawDescription: CSV reader repeatedly reading 1 line

description: CSV reader repeatedly reading 1 line


rawDescription: How to create structured array out of unstructured HTML using python

description: Create structured array out of unstructured HTML using python


code:
from bs4 import BeautifulSoup

html = """

<title>CATe - hj1612</title>

<input name="keyt" type="hidden" value="a3dvl"/>
<input type="submit" value="View"/>
or

<input type="reset" value="Reset"/>

"""

soup = BeautifulSoup(html)

print soup.find(name="input", attrs={'name': 'keyt'})

rawDescription: Parsing html using Beautiful Soup in python


code:
x0 = (2200, 12)
bounds = [(2000,3500),(10,50)]
print minimize(f, x0, method='SLSQP', bounds=bounds)

rawDescription: Use optimize.minimize from scipy with 2 variables and interpolated function


code:
year = 2012
print year + 1

rawDescription: How to Print next year from current year in Python


code:
for c in gen_oriented_cycles('abcd'):
    print c

rawDescription: Most efficient way to list all oriented cycles given n elements in Python


code:
#234567891123456789212345678931234567894123456789512345678961234567897123456789

# core
import inspect
import pickle
import datetime

# 3rd party
import gnupg

def depickle():
    """ pull and depickle our signed data """
    f = open('pickle.txt', 'r')
    signed_data = pickle.load(f)
    f.close()
    return signed_data

# depickle our signed data
signed_data = depickle()
# inspect the object
for key, value in inspect.getmembers(signed_data):
    print key

rawDescription: python gnupg timestamp

description: Python gnupg timestamp


code:
new_lis = sorted(sc_percentage, key = lambda x : x[1], reverse = True)[:10]
for item in new_lis:
   print item

rawDescription: Sort the top ten results

description: Sort the top ten results


code:
from bs4 import BeautifulSoup

data = """

text1 desc1 text2

desc2

desc3text3

text4des4

text5

"""
soup = BeautifulSoup(data)
for p in soup('p', class_='abc'):
    if len(p.contents) == 1 and p.contents[0].name == 'a':
        print p

rawDescription: Beautiful Soup: Remove Tags that only contain href


code:
from collections import Counter
from itertools import chain

dicts = [
    {1: 'url1', 3: 'url2', 7: 'url3', 5: 'url4'},
    {1: 'url1', 7: 'url3'},
    {5: 'url4', 10: 'url5'},
]

result = Counter(chain.from_iterable(dicts))

print dict(result)

rawDescription: How to count number of repeated keys in several dictionaries?

description: Count number of repeated keys in several dictionaries


code:
class MyD(object):
    def __init__(self, val):
        self.val = val

    def __get__(self, obj, objtype):
        return self.val

    def __set__(self, obj, val):
        self.val = val

class C(object):
    a = MyD(42)
    def __init__(self):
        self.d = MyD(42)

    def __getattribute__(self, name):
        attr = super(C, self).__getattribute__(name)
        if hasattr(attr, '__get__'):
            return attr.__get__(self, C)
        return attr

c = C()
print c.d
print c.a

rawDescription: Can a python descriptor be used to instantiate an attribute in the __init__ of another class?


code:
class myApp(App):
    def build(self):
        self.load_kv("kivy.3.kv")
        tb = ThemeBackground()
        print "value =",tb.myslider.value # <---- value here
        print "min =",tb.myslider.min # <--- min here
        return tb

rawDescription: Apps in Kivy: get values in kv file

description: Apps in Kivy: get values in kv file


rawDescription: Django Query using .order_by() and .latest()


code:
for j in range(num):
    print "*" * (num-i)

rawDescription: I am new to python programming and I have an assignment in which I have to print a certain pattern of stars using a function


code:
print len(set(re.findall('\w+', dataString.lower()))) # Number of unique words
print len(re.findall('\w+', dataString.lower())) # Total number of words

rawDescription: I want to create a program that can analyze downloaded text file in python


code:
import os

os.chdir('/home/Desktop/songs')
letter = {d : [child
                  for child in os.listdir('./' + d)
                  if os.path.isdir('./' + d)
              ]
              for d in os.listdir('.')
              if os.path.isdir(d)
         }
print letter

rawDescription: Python search folder and make a Dictionary


code:
#!/usr/bin/python

import functools
import timeit

class Revision:
  # a revision is something like a textfile.
  # the search() method will search the textfile
  # and return the lines which match the given pattern.
  # for demonstration purposes this class is simplified
  # to return predefined results
  def __init__(self, results):
    self.results = results
  def search(self, pattern):
    return self.results

class AbstractSearcher:
  def __init__(self, revisions):
    self.revisions = revisions
  def search_for_first_occurence(self, pattern):
    keys = sorted(self.revisions.iterkeys())
    return self.collect_one_occurence(keys, pattern)
  def search_for_last_occurence(self, pattern):
    keys = sorted(self.revisions.iterkeys(), reverse = True)
    return self.collect_one_occurence(keys, pattern)
  def search_for_any_occurence(self, pattern):
    keys = self.revisions.iterkeys()
    return self.collect_one_occurence(keys, pattern)
  def search_for_all_occurences(self, pattern):
    keys = self.revisions.iterkeys()
    return self.collect_all_occurences(keys, pattern)

class SearcherYield(AbstractSearcher):

  def search_revisions(self, keys, pattern):
    # create generator which yields the results one by one
    for key in keys:
      rev = self.revisions[key]
      result = rev.search(pattern)
      if result:
        yield result

  def collect_one_occurence(self, keys, pattern):
    # take the first result and then abandon the generator
    for result in self.search_revisions(keys, pattern):
      return result
    return []

  def collect_all_occurences(self, keys, pattern):
    # collect all results from generator
    results = []
    for result in self.search_revisions(keys, pattern):
      results.extend(result)
    return results

class SearcherCondition(AbstractSearcher):

  def search_revisions(self, keys, pattern, just_one):
    # collect either all results from all revisions
    # or break the loop after first result found
    results = []
    for key in keys:
      rev = self.revisions[key]
      result = rev.search(pattern)
      if result:
        results.extend(result)
        if just_one:
          break
    return results

  def collect_one_occurence(self, keys, pattern):
    return self.search_revisions(keys, pattern, just_one = True)

  def collect_all_occurences(self, keys, pattern):
    return self.search_revisions(keys, pattern, just_one = False)

def benchmark(revcount, timeitcount):

  lastrev = {}
  for i in range(revcount):
    lastrev[i] = Revision([])
  lastrev[revcount] = Revision([1])

  allrevs = {}
  for i in range(revcount):
    allrevs[i] = Revision([1])

  last_yield = SearcherYield(lastrev)
  last_cond = SearcherCondition(lastrev)
  all_yield = SearcherYield(allrevs)
  all_cond = SearcherCondition(allrevs)

  lfy = functools.partial(last_yield.search_for_first_occurence, 'foo')
  lfc = functools.partial(last_cond.search_for_first_occurence, 'foo')
  lay = functools.partial(last_yield.search_for_all_occurences, 'foo')
  lac = functools.partial(last_cond.search_for_all_occurences, 'foo')
  aay = functools.partial(all_yield.search_for_all_occurences, 'foo')
  aac = functools.partial(all_cond.search_for_all_occurences, 'foo')

  print 'benchmark with revcount: %d timeitcount: %d' % (revcount, timeitcount)
  print 'last, first, yield:', timeit.timeit(lfy, number = timeitcount)
  print 'last, first,  cond:', timeit.timeit(lfc, number = timeitcount)
  print 'last,   all, yield:', timeit.timeit(lay, number = timeitcount)
  print 'last,   all,  cond:', timeit.timeit(lac, number = timeitcount)
  print ' all,   all, yield:', timeit.timeit(aay, number = timeitcount)
  print ' all,   all,  cond:', timeit.timeit(aac, number = timeitcount)

def main():
  timeitcount = 1000
  benchmark(1000, timeitcount)
  benchmark(2000, timeitcount)
  benchmark(10000, timeitcount)

if __name__ == '__main__':
  main()

rawDescription: Abuse yield to avoid condition in loop

description: Abuse yield to avoid condition in loop


code:
file = open('data.pkl', 'rb')

image = pickle.load(pkl_file)
print image
file.close()

rawDescription: pickling a python image object

description: Pickling a python image object


code:
class Socket(QTcpSocket):
    def __init__(self):
        QTcpSocket.__init__(self)
        self.stateChanged.connect(self.handleStateChanged)

    def handleStateChanged(self, state):
        print state

rawDescription: Q_ENUMS in PyQt4

description: Q_ENUMS in PyQt4


code:
for x in range(1, 11):
    print x

rawDescription: Can someone explain what all the codes mean? PYTHON


code:
my_record = SeqIO.read('my_file.gbk', 'gb')
print "DBXREFS: ", my_record.dbxrefs
print "ANNOTATIONS: ", my_record.annotations.keys()
print "FEATURES: ", my_record.features

rawDescription: How to create genbank flat file

description: Create genbank flat file


code:
lines = [
    "0 @F8@ FAM",
    "1 FAMC @F5@",
    "1 FAMS @F5@"
]

for line in lines:
    if re.search(r'\bFAM\b', line):
        var = line
        print var

rawDescription: Searching for a unique word in a string

description: Searching for a unique word in a string


code:
CSV = ""
for k,v in d.items():
    line = "{},{}\n".format(k, ",".join(v))
    CSV+=line
print CSV

rawDescription: Reading/Writing out a dictionary to csv file in python


code:
import traceback
import sys

def format_exception(e):
    exception_list = traceback.format_stack()
    exception_list = exception_list[:-2]
    exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
    exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))

    exception_str = "Traceback (most recent call last):\n"
    exception_str += "".join(exception_list)
    # Removing the last \n
    exception_str = exception_str[:-1]

    return exception_str

def main1():
    main2()

def main2():
    try:
        main3()
    except Exception as e:
        print "Printing only the traceback above the current stack frame"
        print "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
        print
        print "Printing the full traceback as if we had not caught it here..."
        print format_exception(e)

def main3():
    raise Exception()

if __name__ == '__main__':
    main1()

rawDescription: How to get a complete exception stack trace in Python

description: Get a complete exception stack trace in Python


code:
import re
p = re.compile(ur'\b\d+e\+\d+\b')
test_str = u"6[Sup. 1e+02]"
re.findall(p, test_str)

rawDescription: regex findall to retrieve a substring based on start and end character

description: Regex findall to retrieve a substring based on start and end character


code:
total = sum(l) + sum(l2)
print total

rawDescription: How to store a list of numbers generated as output in Python?

description: Store a list of numbers generated as output in Python


code:
"""
multi_joinablequeue.py
"""
from multiprocessing import Process, JoinableQueue
import time

def reader(queue):
    while True:
        msg = queue.get()         # Read from the queue and do nothing
        queue.task_done()

def writer(count, queue):
    for ii in xrange(0, count):
        queue.put(ii)             # Write 'count' numbers into the queue

if __name__=='__main__':
    for count in [10**4, 10**5, 10**6]:
        queue = JoinableQueue()   # reader() reads from queue
                                  # writer() writes to queue
        reader_p = Process(target=reader, args=((queue),))
        reader_p.daemon = True
        reader_p.start()     # Launch the reader process

        _start = time.time()
        writer(count, queue) # Send a lot of stuff to reader()
        queue.join()         # Wait for the reader to finish
        print "Sending %s numbers to JoinableQueue() took %s seconds" % (count,
            (time.time() - _start))

rawDescription: Python multiprocessing - Pipe vs Queue

description: Python multiprocessing - Pipe vs Queue


code:
word = 'COMPUTER'
SUM = 0
for char in word:
    value = ord(char)
    SUM += value

print SUM

rawDescription: Adding ASCII Values together. Jython/Python


code:
import inspect

print inspect.stack()

rawDescription: Generate graph of the imports

description: Generate graph of the imports


code:
print label.place_forget.__doc__
print label.grid_forget.__doc__
print label.pack_forget.__doc__

rawDescription: How to temporarily remove ( not delete and replace ) Tkinter widget without using just .place?

description: Temporarily remove ( not delete and replace ) Tkinter widget without using just .place


code:
if '/website-builder' in link['href']:
    print link['href']

rawDescription: how do you get links with certain words using beautifulsoup

description: Get links with certain words using beautifulsoup


code:
X = np.arange(-5,5).reshape(5,2)
T,p = polynomial_features_with_cross_terms(X, order=3)
print X
print p
print T

rawDescription: Scipy fitting polynomial model to some data


code:
text = """

    <title>This tag includes 'name', so it should be retrieved</title>

This is also a tag to be retrieved

Generic h2 tag

"""

import lxml.html
doc = lxml.html.fromstring(text)
print doc.xpath('//*[contains(text(), $stuff)]/parent::*/'
    'following-sibling::*[1]/*[@class=$stuff]/text()', stuff='name')

rawDescription: How to retrieve a HTML tag based on a regular expression

description: Retrieve a HTML tag based on a regular expression


rawDescription: Python: Which is faster: matching lists or matching dictionaries?


rawDescription: How to conduct complex operations using sympy?

description: Conduct complex operations using sympy


rawDescription: Rendering Text Calendar

description: Rendering Text Calendar


code:
theList = range(10000)

n = 11
print '---------------------', n
print sumPair(theList, n),
print timeit.timeit('sumPair(theList, n)', 'from __main__ import sumPair, theList, n', number = 100)

print sumPair2(theList, n),
print timeit.timeit('sumPair2(theList, n)', 'from __main__ import sumPair2, theList, n', number = 100)

print sumPair_gnibbler(theList, n),
print timeit.timeit('sumPair_gnibbler(theList, n)', 'from __main__ import sumPair_gnibbler, theList, n', number = 100)

n = 3000
print '---------------------', n
print sumPair(theList, n),
print timeit.timeit('sumPair(theList, n)', 'from __main__ import sumPair, theList, n', number = 100)

print sumPair2(theList, n),
print timeit.timeit('sumPair2(theList, n)', 'from __main__ import sumPair2, theList, n', number = 100)

print sumPair_gnibbler(theList, n),
print timeit.timeit('sumPair_gnibbler(theList, n)', 'from __main__ import sumPair_gnibbler, theList, n', number = 100)

n = 30000
print '---------------------', n
print sumPair(theList, n),
print timeit.timeit('sumPair(theList, n)', 'from __main__ import sumPair, theList, n', number = 100)

print sumPair2(theList, n),
print timeit.timeit('sumPair2(theList, n)', 'from __main__ import sumPair2, theList, n', number = 100)

print sumPair_gnibbler(theList, n),
print timeit.timeit('sumPair_gnibbler(theList, n)', 'from __main__ import sumPair_gnibbler, theList, n', number = 100)

rawDescription: One loop? python

description: One loop? python


code:
for start, end in year_boundaries(date(2012, 11, 12), date(2014, 5, 15)):
    print start, '-', end

rawDescription: Python date seperating a multiple year date span to single year spans


rawDescription: 2D Numpy array to HTML table?

description: 2D Numpy array to HTML table


code: print 'Hello world! The answer is, as always, {}'.format(42)

rawDescription: Pythonic way of converting integers to string


code:
def initialize():
    session = c_uint32()
    status = c_int32()
    _libtest.initialize(byref(session), byref(status))
    return session.value, status.value

if __name__ == '__main__':
    session, status = initialize()
    print 'session:', session
    print 'status:', status

rawDescription: Use ctypes with typedef

description: Use ctypes with typedef


code:
your_list = []
with open('your_file.txt') as fobj:
    for line in fobj:
        your_list.append(line.strip().split('/'))

for sublist in your_list:
    print sublist

rawDescription: How to use a loop to print out data from a list

description: Use a loop to print out data from a list


code:
# Vectorize takes a Python function and converts it into a Numpy
# vector function that operates on arrays
np_len = np.vectorize(lambda x: len(x))

np_len(t)
# gives array([[3, 3, 5], [4, 4, 3]])

idx = np_len(t).argmin(0) # get the index along the 0th axis
# gives array([0, 0, 1])

result = t
for i in idx[1:]:
    result = result[i]
print result
# gives "two", the string with the smallest length

rawDescription: Arrays of strings into numpy.amax

description: Arrays of strings into numpy.amax


code:
hex_string = "0x0000040800000000"
number = int(hex_string, 16)    # Convert to an integer
mask_39_to_32 = 0xFF00000000    # Suitable mask to extract the bits with

print "As hex: 0x%X" % number
print
print "Bits 39-32:                         xxxxxxxx"
print " As binary: {:0>64s}".format(bin(number)[2:])
print "      Mask: {:0>64s}".format(bin(mask_39_to_32)[2:])
print "AND result: {:0>64s}".format(bin(number & mask_39_to_32)[2:])
print "   Shifted: {:0>64s}".format(bin((number & mask_39_to_32) >> 32)[2:])
print " As an int: {:d}".format((number & mask_39_to_32) >> 32)

rawDescription: Parsing out bit offsets from a hex number in Python


code:
class Revision(models.Model):
    # Model junk...

    @classmethod
    def send_email(cls, sender, instance, created, **kwargs):
        if created:
            print "DO STUFF"

signals.post_save.connect(Revision.send_email, sender=Revision)

rawDescription: How can I have a Django signal call a model method?

description: Have a Django signal call a model method


code:
x=np.random.randint(0,3,size=100)
y=np.random.randint(0,100,size=100)
d=np.vstack([x,y]).T
print d[:5,:]

rawDescription: Composite a numpy array/matrix based on column values and variables?


code:
f1 = 25.4
f2 = f1

for i in xrange(1, 11):
    f2 /= 10.0          # to cm
    f2 *= (1.0 / 2.54)  # to in
    f2 *= 25.4          # back to mm
    print 'after %2d loops there are %2d doubles between them' % (i, dulpdiff(f1, f2))

rawDescription: floating point equality in Python and in general

description: Floating point equality in Python and in general


code:
next(x for x in range(10) if x == 7)  #This is a silly way to write 7 ...
next(x for x in range(10) if x == 11)
next((x for x in range(10) if x == 7), None)
print next((x for x in range(10) if x == 11), None)

rawDescription: Return the first item in a list matching a condition


code:
import pandas as pd

df = pd.read_csv("color.csv")
df_gen = df.copy().groupby("Color")

dfs = [] # Container for dataframes.

for key, value in df_gen:
    value["ROLL_CORR"] = pd.rolling_corr(value["Value1"],value["Value2"], 3)
    print value
    dfs.append(value)

df_final = pd.concat(dfs)
print df_final

rawDescription: Calculate rolling correlation with pandas


code:
def clean_cut(st, end):
    st += ' ' #In case end > len(st)
    return st[:st[:end + 1].rfind(' ')]
for i in ( 15, 16, 17,30,35):
    cutdown = clean_cut( sample , i )
    print "%s | %s" % ( i , cutdown )

rawDescription: How to optimize matching a substring of n length, but only whole words?

description: Optimize matching a substring of n length, but only whole words


code:
import re

p = re.compile(r'http://download\d+\.mysite\.com/\w+/\w+/upload\.rar')

table = [
    'http://download2142.mysite.com/d0kz4p5p3uog/api60w0g1o1jil1/upload.rar',
    'http://download2142.mysite.com/d0kz4p5p3uog/api60w0g1o1jil1/upload.raw',
    'http://download123.mysite.com/456/789/upload.rar',
    'http://downloadabc.mysite.com/def/ghi/upload.rar',
    'http://download1234.mysite.com/def/ghi/upload.rar',
    'http://download1234.mysite.org/def/ghi/upload.rar',
]

for s in table:
    m = p.match(s)
    print s, m is not None

rawDescription: How can I match regular expression for this url?

description: Match regular expression for this url


code:
def get_field_value(soup, field):
    return soup.find(text='%s:' % field).parent.find_next_sibling('td').get_text(strip=True)

print get_field_value(soup, 'Religion')
print get_field_value(soup, 'Nationality')
print get_field_value(soup, 'Birthplace')

rawDescription: BeautifulSoup Python script no longer working for mining a simple field


code:
# Get a set of unique first elements for each list
set1 = set([n[0] for n in mark1])
set2 = set([n[0] for n in mark2])

# Items in mark1 but not mark2
if set1.difference(set2):
  print 'some marks are not the same - no match found'

# Items in mark2 but not mark1
if set2.difference(set1):
  print 'some marks are not the same - no match found'

rawDescription: Python: data unmatched in csv output

description: Python: data unmatched in csv output


code:
def German():
    import random
    a_q = {'Berlin':'What is east capital city for German?',
           'Bonn':'What is west capital city for German?',
           'Michael Schumacher':'What is a famous formula one driver?',
           'Albert Einstein':'He was one of the smartest one.',
           'The Berlin Wall':'What was the wall called that separated the country?',
           'Boris Becker':'He was a good tennis player he won two wimbildom titles?',
           '2006':'What year was the FIFA World Cup held in Germany?',
           '3':'How many world cups does Germany have?',
           'Yodeling':'What is one of the tradition in German?',
           '9 months':'How long does Zugspitze winter last for?'}

    q = [x for x in random.sample(a_q, len(a_q))] #create list of questions
    i=0 #start counter

    while i < len(q):                 #iterate through every question

        correctanswer = a_q[q[i]]     #define the correct answer
        print 'Question: ', correctanswer
        c=random.sample(a_q, 3)
        while c.count(q[i]) != 1:
            c=random.sample(a_q, 3)   #get the answer pool
        key1, key2, key3 = c
        print '\nA. %s \nB. %s \nC. %s' % (key1, key2, key3)
        A, B, C = a_q[key1], a_q[key2], a_q[key3]
        answer = raw_input('What is the right answer? ')

        while answer not in 'ABCD':   #check for invalid inputs
             print "That is not a valid selection.\n"
             answer = raw_input('What is the right answer? ')

        if answer == 'A' and A  == correctanswer:
            print "That's correct!"
        elif answer == 'B' and B == correctanswer:
            print "That's correct!"
        elif answer == 'C' and C == correctanswer:
            print "That's correct!"
        else:
            print "I'm sorry, that is incorrect"
        i+=1

German()

rawDescription: Delete a string in a dictionary after it's shown


code:
data = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Violet']
first = data[0]
while data:
    a, b = data[0], data[-1]
    data = data[1:-1]
    print '{} -> {}'.format(a, b)
    print '{} -> {}'.format(b, data[0] if data else first)

rawDescription: Matching list items to items at the other end of the same list?


code:
import operator

def diff(s1, s2, match=operator.eq, neutral="*", subst=2):
    """s1, s2: the two strings or lists to match
    match: function to determine whether two elements match up
    neutral: 'neutral' element for padding
    subst: substitution costs
    """
    s1, s2 = neutral + s1, neutral + s2

    # calculate edit distance / sequence match with DP
    A = [[0] * len(s2) for i in range(len(s1))]
    for i in range(len(s1)):
        for k in range(len(s2)):
            if min(i, k) == 0:
                A[i][k] = max(i, k)
            else:
                diag = 0 if match(s1[i], s2[k]) else subst
                A[i][k] = min(A[i-1][k-1] + diag,
                              A[i  ][k-1] + 1,
                              A[i-1][k  ] + 1)

    # reconstruct path
    path, i, k = [], len(s1)-1, len(s2)-1
    while i or k:
        if A[i][k] == A[i-1][k] + 1:
            path, i = [-1] + path, i-1
        elif A[i][k] == A[i][k-1] + 1:
            path, k = [1] + path, k-1
        else:
            path, i, k = [0] + path, i-1, k-1

    return A[len(s1)-1][len(s2)-1], path

def print_match(list1, list2, path):
    i1, i2 = iter(list1), iter(list2)
    for p in path:
        if p == -1: print "DEL %20r"      %  next(i1)
        if p ==  0: print "EQ  %20r %20r" % (next(i1), next(i2))
        if p == +1: print "INS %41r"      %            next(i2)

# with strings
word1, word2 = "INTENTION", "EXECUTION"
x, path = diff(word1, word2)
print_match(word1, word2, path)

# with your lists of lists
list1 = [[['B', 10], 1], [['C', 15], 1], [['F', 30], 1]]
list2 = [[['G', 20], 2], [['D', 25], 1]]
x, path = diff(list1, list2, match=lambda x, y: x[1] == y[1], neutral=[[None, -1]])
print_match(list1, list2, path)

rawDescription: Two list comparison in Python

description: Two list comparison in Python


code:
import os.path

def loo(x):
    return [[el for el in x if el!=x[i]] for i in range(len(x))]

def p(subjects, directory):
    l = loo(subjects)
    for group in l:
        for subj in group:
            print os.path.join(directory, subj)
        print

p(['S1','S2','S3','S4','S5'], 'c:\\')

rawDescription: Leaving one item out in a python list and print paths


code:
import getpass
import sys
import telnetlib

HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("ls\n")
tn.write("exit\n")

print tn.read_all()

rawDescription: Python socket works as a telnet connection and requires double read


code:
s1 = set([1,2,3])  # You can add things incrementally with "s1.add(value)"
s2 = set([2,3,4])

shared_items = s1.intersection(s2)
print shared_items

rawDescription: Script to compare a string in two different files


code: print "x:", x

rawDescription: Python Beginner. Is this Python code as efficient as it could be?


code:
with open('/tmp/example.txt') as f:
  lines_in = f.readlines()

inside_block = False
lines_out = []

for line in lines_in:
  if line.startswith('• '):
    if not inside_block:
      lines_out.append('
\n')
      inside_block = True
    lines_out.append('
{}
\n'.format(line.strip().replace('• ','')))
  else:
    if inside_block:
      lines_out.append('
\n')
      inside_block = False
    lines_out.append(line)

print ''.join(lines_in)
print '-'*78
print ''.join(lines_out)

rawDescription: Regex: Capture a group of lines with the same beginnings?


code:
mystring = 'abccd'
m = re.match(r'.*(\w)\1', mystring)
print m.group(1)  # 'c'

rawDescription: How to look for consecutive repeats in regex?

description: Look for consecutive repeats in regex


code:
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
data = urllib2.urlopen(req, timeout=6).read()
print data

rawDescription: Python urllib2 request error

description: Python urllib2 request error


code:
cache = {}
def main():
    print "recursive method"
    print "time taken",

rawDescription: why this recursive backtracking function slower than the non-recursive one for calcuating minimum number of coins for change in python?

description: Why this recursive backtracking function slower than the non-recursive one for calcuating minimum number of coins for change in python


code:
resp,data = mail.uid('FETCH', '1:*' , '(RFC822)')
messages = [data[i][1].strip() for i in xrange(0, len(data), 2)]
for msg in messages:
    msg_str = email.message_from_string(msg)
    print msg_str.get('Date')

rawDescription: getting emails from gmail via python

description: Getting emails from gmail via python


code:
months = df['date']
print pd.date_range(months.iloc[0], months.iloc[3], freq='M')
DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31'], dtype='datetime64[ns]', freq='M')

rawDescription: Create monthly pandas DatetimeIndex

description: Create monthly pandas DatetimeIndex


code:
inventory = {
    'item1': {'id': 1, 'template': None, 'height': 80, 'width': 120, 'length': 75, 'weight': 100},
    'item2': {'id': 2, 'template': None, 'height': 30, 'width': 40,  'length': 20, 'weight': 20},
    'item3': {'id': 3, 'template': None, 'height': 80, 'width': 100, 'length': 96, 'weight': 150},
    'item4': {'id': 4, 'template': None, 'height': 30, 'width': 40,  'length': 60, 'weight': 75},
    'item5': {'id': 5, 'template': None, 'height': 80, 'width': 100, 'length': 36, 'weight': 33}
}

import itertools as itools

def print_inventory():
    print 'inventory:'
    for key in sorted(inventory.iterkeys()):
        print '  {}: {}'.format(key, inventory[key])

print "-- BEFORE --"
print_inventory()

THRESHOLD = 2
ALLKEYS = ['template', 'height', 'width', 'length', 'weight']
EXCLUDEDKEYS = ['template', 'length', 'weight']
INCLUDEDKEYS = [key for key in ALLKEYS if key not in EXCLUDEDKEYS]

# determines which keys make up a template
sortby = lambda item, keys=INCLUDEDKEYS: tuple(item[key] for key in keys)

templates = {}
templateID = 0
sortedinventory = sorted(inventory.itervalues(), key=sortby)
for templatetuple, similariter in itools.groupby(sortedinventory, sortby):
    similaritems = list(similariter)
    if len(similaritems) >= THRESHOLD:
        # create and assign a template
        templateID += 1
        templates[templateID] = templatetuple # tuple of values of INCLUDEDKEYS
        for item in similaritems:
            item['template'] = templateID
print
print "-- AFTER --"
print_inventory()
print
print 'templates:', templates
print

rawDescription: Python dictionaries, find similarities

description: Python dictionaries, find similarities


code:
for c in '123':
    print repr(c)

rawDescription: Sum a csv column in python

description: Sum a csv column in python


code:
from sqlalchemy import *
from sqlalchemy.orm import *

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(64))

    comments = relationship("Comment",
                        secondary="user_comment",
                        lazy="dynamic", viewonly=True)

    def __init__(self, name, **kw):
        super(User, self).__init__(**kw)
        self.name = name

class UserComment(Base):
    __tablename__ = 'user_comment'
    user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    comment_id = Column(Integer, ForeignKey('comment.id'), primary_key=True)

    user = relationship(User,
                backref=backref("user_comments",
                                cascade="all, delete-orphan")
            )

    comment = relationship("Comment")

    def __init__(self, comment=None, user=None):
        self.user = user
        self.comment = comment

class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True)
    comment = Column('comment', String(64))
    date = Column(DateTime)

    def __init__(self, comment):
        self.comment = comment

    def __repr__(self):
        return 'Comment(%s)' % repr(self.comment)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

s = Session(e)

s.add_all([
    User(name='u1', user_comments=[
        UserComment(comment=Comment(comment='c1')),
        UserComment(comment=Comment(comment='c2')),
        UserComment(comment=Comment(comment='c3')),
    ])
])
s.commit()

u1 = s.query(User).first()
print u1.comments.order_by(Comment.date.desc()).all()

rawDescription: sqlalchemy association_proxy pagination

description: Sqlalchemy association_proxy pagination


code: def meth(self): print self.__class__

rawDescription: How can I get the name of a child class?

description: Get the name of a child class


code:
#!usr/bin/env python

import random
import collections

# Candidates:
candidates = ['John', 'Max', 'Philip', 'Eric', 'Jane']

def simul_ballots(num_voters):
   """
   Returns the (random) ballots of num_voters voters.
   """

   ballots = []

   choice = candidates[:]

   for _ in range(num_voters):
      random.shuffle(choice)
      ballots.append(choice[:])  # Copy

   return ballots

def get_counts(ballots):
   """
   Returns the number of votes for each candidate placed first in the
   ballots.

   Candidates present in the ballots but found in any first ballot
   places are given a count of zero.
   """

   counts = dict()
   for ballot in ballots:
      vote = ballot[0]
      if vote in counts:
         counts[vote] += 1
      else:
         counts[vote] = 1

   # Python 2.7+ replacement for the above code:
   # counts = collections.Counter(ballot[0] for ballot in ballots)

   candidates = set()
   for ballot in ballots:
      candidates.update(ballot)

   for not_represented in set(candidates)-set(counts):
      counts[not_represented] = 0

   return counts

def get_winners(ballots):
   """
   Returns the winners in the given ballots (lists of candidates), or
   [] if there is no winner.

   A winner is a candidate with 50 % or more of the votes, or a
   candidate with as many votes as all the other candidates.
   """

   counts = get_counts(ballots)

   max_count = max(counts.values())
   num_counts = sum(counts.values())

   potential_winners = [candidate for (candidate, count) in counts.items()
                        if count == max_count]

   if max_count >= num_counts/2. or len(potential_winners) == len(counts):
      return potential_winners
   else:
      return []

def get_losers(ballots):
   """
   Returns the loser(s) of the ballots, i.e. the candidate(s) with the
   fewest voters.

   Returns [] if all candidates have the same number of votes.
   """

   counts = get_counts(ballots)

   min_count = min(counts.values())

   potential_losers = [candidate for (candidate, count) in counts.items()
                       if count == min_count]

   if len(potential_losers) == len(counts):
      return []
   else:
      return potential_losers

def remove_candidate(ballots, candidate):
   """
   Removes the given candidate from the ballots.
   """
   for ballot in ballots:
      ballot.remove(candidate)

if __name__ == '__main__':

   ballots = simul_ballots(20)

   while True:

      print "* Votes:"
      for ballot in ballots:
         print '-', ballot
      print "=> Counts:", get_counts(ballots)

      winners = get_winners(ballots)
      if winners:
         break

      # The losers are removed:
      losers = get_losers(ballots)
      print '=> Losers:', losers
      for loser in losers:
         remove_candidate(ballots, loser)

   print "Winners: ", winners

rawDescription: List sorting/modify problem

description: List sorting/modify problem


code:
import re

soupObj = [u'$(function(){SEAT.PG.initDialog(".generate-popup-3030",[{msez:"3030",c:"#333",o:0.5,f:false,html:SEAT.PG.getImgPopHtml}]);SEAT.PG.mappaInterattiva({longitude:13.37489,latitude:42.36009,sito:"pgol",zoomLevel:"1",lng:1,mirino:"http://img.pgol.it/pgol/img/mk_pallino.png",allowFoto:true,mapType:null,streetView:false,dr:false,addMobile:false,ums:"sorellenurzia"});var a=SEAT.commenti({__2011_commento_click_stella:"Clicca su una stella per dare il tuo voto",__2011_commento_da_evitare:"Da evitare",__2011_commento_di_meglio:"C\'\xe8 di meglio",__2011_commento_non_male:"Non male",__2011_commento_mi_piace:"Mi piace",__2011_commento_consigliato:"Consigliato",__2011_commento_scrivi:"Scrivi una recensione per condividere la tua esperienza con gli altri utenti",__2011_commento_breve:"Scrivi almeno 120 caratteri per dare informazioni utili e complete a chi legger\xe0 la recensione.",__2011_commento_manca_voto:"Ti sei dimenticato di dare un voto",__2011_commento_servizio_non_disponibile:"Il servizio al momento non \xe8 disponibile",__2011_commento_segnala:"Segnala la recensione",__2011_commento_segnala_msg1:"Ritieni che questa recensione sia offensiva o inappropriata a PagineGialle.it?",__2011_commento_segnala_msg2:"La nostra redazione si occuper\xe0 di controllarne il contenuto e, se necessario, di rimuoverlo dal sito",__2011_conferma:"conferma",__2011_annulla:"annulla",__2011_ha_scritto_il:"ha scritto il",__2011_pubblica:"pubblica",__2011_commento_modifica_recensione:"Modifica recensione",__2011_conferma_notifica:"Aggiornamento via email attivo",__2012_commenti_relatedopec:"Conosci anche queste attivit\xe0?",__2011_elimina_notifica:"Aggiornamento via email non attivo"});a.enableAbuse();a.enableRating()});']

m = re.search('longitude:([-+]?\d+.\d+),latitude:([-+]?\d+.\d)', soupObj[0])
if m:
  longitude = m.group(1)
  latitude = m.group(2)
  print "longitude=%s, latitude=%s" % (longitude, latitude)
else:
  print "Failed to match longitude, latitude."

rawDescription: Extracting lat/long from a BeautifulSoup object in python


code:
import re
sample = '''\
My text \\b the best \\b
but i cant do this \\a task because
this is fu** regex? And other text
'''
sample = re.sub(r'\\b(.*?)\\b', r'
\1
', sample)
sample = re.sub(r'\\a(\s*\w+)', r'\1', sample)
sample
print sample

rawDescription: Python: replace some tags to html tags in string


code:
class Backpack:
    def __init__(self):
        self.inside = []
    def add(self, toadd):
        self.inside.append(toadd)
    def addmany(self, listtoadd):
        self.inside += listtoadd
    def __str__(self):
        return ', '.join(str(i) for i in self.inside)

pack = Backpack()
pack.add('thing')
pack.add('other thing')
pack.add('another thing')
print 'Your backpack contains:', pack

rawDescription: Good way to concatenate str to list?

description: Good way to concatenate str to list


code:
def main():
    while(True):
        try:
            x=int(input('Enter the number of rows: '))
            y=int(input('Enter the number of cols: '))
            matrix = create_matrix(x, y)
            for row in matrix:
                print row
            break
        except ValueError:
            print "Just give integers please. Try again."

rawDescription: Populating a matrix with random numbers and computing sums of those numbers


code:
def flatten(*arr):
    for a in arr:
        if isinstance(a, (list, tuple)):
            for sub in flatten(*a):
                yield sub
        else:
             yield a

print list(flatten(['hi there','how are you'],'well there','what?',[1, 23423,33]))

rawDescription: Recursive call in python seems not to descend


rawDescription: Python: Bytes to string with accented characters


code:
di={re.compile(r'a'): 'ay in there', re.compile('b'): 'bees in there'}
for s in ('say', 'what', 'you', 'mean', 'bag'):
    print s, [di[k] for k in di if k.search(s)]

rawDescription: Dictionary key in python are RegExp

description: Dictionary key in python are RegExp


code: print unicode('a')

rawDescription: Suppress the u'prefix indicating unicode' in python strings


code:
#!python2.7
import io
import sys
f=io.BytesIO()

def foo():
    print 'hello, world!'

save,sys.stdout = sys.stdout,f
foo()
sys.stdout = save
f.seek(0)
print f.read()

rawDescription: Access the printed output of a function call


code:
def readNames():
    nameList = []
    while True: #infinite loop
        addList = raw_input("Please enter a name: ")
        if addList == 'finish':
            return nameList
        nameList.append(addList)

# store the result, then print it
names = readNames()
print names

rawDescription: Loop will not break

description: Loop will not break


code:
import scapy
tcpdump = sniff(count=5,filter="host 64.233.167.99",prn=lambda x:x.summary())
print tcpdump

rawDescription: tcpdump to only print urls

description: Tcpdump to only print urls


code:
server = None
configurebot()
print server

rawDescription: reading config from file

description: Reading config from file


code:
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()

rawDescription: How can I join a list into a string (caveat)?

description: Join a list into a string (caveat)


code:
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        print_time(self.name, self.counter, 5)
        print "Exiting " + self.name

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

print "Exiting Main Thread"

rawDescription: Multiplethreading pauses the second thread


code:
#!/usr/bin/env python
print "Content-type: text/html"
print
print "Test Page"

rawDescription: Python not interpreted on apache

description: Python not interpreted on apache


code:
import threading

some_rlock = threading.RLock()

with some_rlock:
    print "some_rlock is locked while this executes"

rawDescription: Live plot using PyQtGraph is drawing even with the device disconnected


code:
import os
from multiprocessing import *

class ImageData(object):
    def __init__(self, a, b):
        pass

    def shepard_interpolation(self, queue, seeds=10):
        self.pid = os.getpid()
        print self.pid, "queue put"
        queue.put(self)

if __name__ == '__main__':
    q = Queue()
    processes = [ Process(
      target=ImageData.shepard_interpolation, args=(ImageData(50, 50), q))
        for _ in range(10) ]
    for process in processes:
        process.start()
    results = []
    for process in processes:  # just to have the correct amount of results
        results.append(q.get())
    print '---------Out--------'
    for process in processes:
        process.join()
    print [ result.pid for result in results ]

rawDescription: Multiprocessing in Python - Concurrence

description: Multiprocessing in Python - Concurrence


code:
import os

def cls_changer(name, parents, attrs):
    model_name = os.path.basename(__file__).split('.')[0]
    return type(model_name+name, parents, attrs)

class A(object):
    __metaclass__ = cls_changer
    pass

print A.__name__

rawDescription: Is it possible to change the name of a class (type) with a python decorator?


code:
import pandas
import random
import collections

md = collections.defaultdict(dict)
md['p'][1] = random.random()
md['p'][2] = random.random()
md['q'][2] = random.random()
md['q'][1] = random.random()
md['r'][1] = random.random()
md['r'][2] = random.random()

df = pandas.DataFrame(md)
df.index.name = 'request_id'

print df

rawDescription: Pandas Dataframe: Reduce Diagonal Sub-Frame to Single Row or How to Fill a Dataframe Piece by Piece


code:
class SocketServerListen(QObject):
    def __init__(self):
        QObject.__init__(self)
        host = "127.0.0.1"
        port = 22001
        QgsMessageLog.logMessage("Initializing server")
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind((host, port))
        self.socket.listen(5)

    def run(self):
        while True:
            try:
                QgsMessageLog.logMessage("Waiting for connection")
                conn, address = self.socket.accept()

                QgsMessageLog.logMessage("Connected to client")

                #receive header and message
                time.sleep(1)
                lengthMessage = conn.recv(4)
                message = conn.recv(int(lengthMessage))
                QgsMessageLog.logMessage("Message:" + message)

                conn.close()

            except socket.error, msg:
                print "Socket error! %s" % msg
                break

    def kill(self):
        self.killed = True
    finished = pyqtSignal(object)
    error = pyqtSignal(Exception,basestring)
    progress = pyqtSignal(float)

rawDescription: Socket server not responding when in thread


rawDescription: Python, how to sort dictionary by keys, when keys are floating point numbers in scientific format?


code:
lines = open("txtfile.txt").readlines()
results = {}
last_part = {}
for line in lines:
    if line.strip() == "":
        continue
    elif line.startswith(tuple("shorts: longs: mosts: count: avglen:".split())):
        n, _, v = line.partition(":")
        results[n.strip()] = v.strip()
    else:
        n, v = line.split(" ")
        last_part[n.strip()] = v.strip()
results['last_part'] = last_part
print results

rawDescription: How to delete unwanted quotation marks in dictionary

description: Delete unwanted quotation marks in dictionary


code:
if any(n[0] == date_new for n in unformatted_returns):
    print "found date"
    rate_of_return_calc(date, date_new)
else:
    print "date {0} not found".format(date_new)
    day_accumulater(d, m, y, date_new, date)

rawDescription: Python: for each tuple in list, check if string in tuple


code:
lines = ['Putting a value ...',
         'Getting value with only row key ...',
         'Getting value with only row key and family...',
         'Getting value with only row key and family and qualifier...',
         'Getting value with row key which is not put...']

for line in lines:
  print '%-59s' % line,
  # ...
  print 'OK'

rawDescription: pretty printing in python

description: Pretty printing in python


code:
for i in permute2(s):
     print i

rawDescription: Python permutations of both sequence and subsequences


code:
import signal, sys, time

def handler(num, _):
    print 'got:', sigmap.get(num, '<other>')
    if num == signal.SIGINT:
        sys.exit(1)
    return 1

signames = ['SIGINT','SIGHUP','SIGQUIT','SIGUSR1']
sigmap = dict((getattr(signal, k), k) for k in signames)
for name in signames:
    signal.signal(getattr(signal, name), handler)
while 1:
    time.sleep(1)

rawDescription: Python: Built-in Keyboard Signal/Interrupts


code:
import Tkinter

def main():
    print 'main'
    t.mainloop()
    print 'end main'

t = Tkinter.Tk()
b = Tkinter.Button(t, command = main)
b.pack()
t.mainloop()

rawDescription: Tkinter nested mainloop

description: Tkinter nested mainloop


code:
def get_blocks(values):
    mi, ma = 0, 0
    result = []
    temp = []
    for v in sorted(values):
        if not temp:
            mi = ma = v
            temp.append(v)
        else:
            if abs(v - mi) < 7 and abs(v - ma) < 7:
                temp.append(v)
                if v < mi:
                    mi = v
                elif v > ma:
                    ma = v
            else:
                if len(temp) > 1:
                    result.append(temp)
                mi = ma = v
                temp = [v]
    return result

a = [87, 84, 86, 89, 90, 2014, 1000, 1002, 997, 999]
print get_blocks(a)

rawDescription: Find numbers in Python list which are within a certain distance of each other


code: print '\n'.join('\\'.join([ s if i >= p else ' '*len(s) for i, s in enumerate(x) ]) for p, x in eachWithPrefix(x.split('\\') for x in v))

rawDescription: How to group strings with similar beginnings in a sorted list?

description: Group strings with similar beginnings in a sorted list


code: ROOT_URLCONF = `myproject.urls`

rawDescription: How do I successfully pass a function reference to Django’s reverse() function?

description: Successfully pass a function reference to Django’s reverse() function


code:
def rot13(entry):
    for each_word in entry: # Starts with h
        print each_word
        # Prints h
        return each_word
        # Returns the letter h. Breaks.

rawDescription: Very basic Q regarding for Loops in Python


code:
import hello

a1 = hello.A(1,2)
a2 = hello.A(3,4)
ret = hello.get_a(a1, a2)
print "size:", len(ret)
print "values:"
for x in ret:
  print x.a, x.b

rawDescription: expose C++ function to python

description: Expose C++ function to python


code:
import re
data = "asdsaq2323-asds"
if re.compile("^[a-zA-Z0-9*]+$").match(data):
    print "match"
else:
    print "no match"

rawDescription: Python: Data validation using regular expression


code:
from scipy import sparse
import numpy as np

arr_csc = sparse.csc_matrix([[0, 1, 0],
                            [3, 4, 0]])

result = []

all_rows = np.arange(arr_csc.shape[0])

for i in xrange(len(arr_csc.indptr) - 1):
    start = arr_csc.indptr[i]
    end = arr_csc.indptr[i+1]

    result.append(np.setdiff1d(all_rows, arr_csc.indices[start : end]))

print result

rawDescription: Finding the row indices of zero elements in csc_matrix


code:
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Foo(object):
    pass

class MyWidget(QWidget):
    mysignal = pyqtSignal(int, list)

    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)
        self.hlayout = QHBoxLayout()
        self.setLayout(self.hlayout)
        self.b = QPushButton("Emit your signal!", self)
        self.hlayout.addWidget(self.b)
        self.b.clicked.connect(self.clickHandler)
        self.mysignal.connect(self.mySignalHandler)

    def clickHandler(self):
        self.mysignal.emit(5, ["a", Foo(), 6])

    def mySignalHandler(self, n, l):
        print n
        print l

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(app.exec_())

rawDescription: Define pyqt4 signals with a list as argument


code:
import numpy as np

x = np.array([[1,1,2,2],
              [1,1,2,2],
              [3,3,4,4],
              [3,3,4,4]])

for val in np.unique(x):
    rows, cols = np.where(x == val)
    rowstart, rowstop = np.min(rows), np.max(rows)
    colstart, colstop = np.min(cols), np.max(cols)
    print val, (rowstart, colstart), (rowstop, colstop)

rawDescription: How to select all locations of unique elements in numpy 2d array with bounding box around them?

description: Select all locations of unique elements in numpy 2d array with bounding box around them


code:
for j in keyws:
    match = re.match(r"noi(\w+)k|fnoi(\w+)v(\w+)|noi(\w+)v(\w+)",j)
    if match:
        results = match.group(1) or match.group(2) or match.group(4)
        print "Results :", results

rawDescription: Regular expression match a or b pattern

description: Regular expression match a or b pattern


code:
con = cx_Oracle.connect(user="myuser", password="mypass", dsn=dsnStr)
print con.version
con.close()

rawDescription: cx_Oracle doesn't connect when using SID instead of service name on connection string

description: Cx_Oracle doesn't connect when using SID instead of service name on connection string


code:
for item in list(zip(soup.find_all("dd")[0::3],soup.find_all("dd")[2::3])):
    date, salary = item
    print ', '.join([date.string, salary.string])

rawDescription: Using BeautifulSoup to extract specific dl and dd list elements


code:
class counter:
    count = 0
    def __init__(self):
        self.__class__.count += 1

print 'counter.count BEFORE ==',counter.count  # The result is 0
NewCounter1 = counter()
print '\nNewCounter1.__dict__ ==',NewCounter1.__dict__  # The result is {}
print 'NewCounter1.count    ==',NewCounter1.count # The result is 1
print 'counter.count AFTER  ==',counter.count  # The result is 1

rawDescription: What in the world is the attribute "__class__" in python


code:
def print_both(file, *args):
    temp = sys.stdout #assign console output to a variable
    print ' '.join([arg for arg in args])
    sys.stdout = file
    print ' '.join([arg for arg in args])
    sys.stdout = temp #set stdout back to console output

rawDescription: Python output on both console and file

description: Python output on both console and file


code:
usernames = set(os.listdir('/path/to/directory/with/usernames/'))
from collections import Counter

f = open('/path/to/6 million')
name_counts = Counter(line.split()[1] for line in f if line in usenames)
print name_counts.most_common()

rawDescription: Comparing 40 million lines in a file with 6 million list items in Python


code:
class Foo(object):
    def __init__(self):
        self.j = None
    def __iter__(self):
        for i in range(10):
            self.j = 10 - i
            yield i

my_generator = Foo()

for k in my_generator:
    print 'j is',my_generator.j
    print 'k is',k

rawDescription: Add a member variable / method to a Python generator?


code:
chunker = Chunker(3)
for s in "abcd", "efgh":
    for chunk in chunker(s):
        print ''.join(chunk)

if chunker.chunk: # is there anything left?
    print ''.join(chunker.chunk)

rawDescription: Iteration over list slices

description: Iteration over list slices


code:
import re

s = '''Aug 23, 2011 10:31:35 AM This is the start of the text.
      This is more Text.
This is another line
This is another line
      This is more.
Aug 23, 2011 10:41:00 AM This is the next in the series.
This is another line
      This is more Text.
This is another line
      This is another line
      This is more.
Aug 24, 2011 10:41:00 AM This is the next in the series.
This is another line
      This is more Text.
This is another line
      This is another line
      This is more. '''

months = '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'
ch = '%s \d\d?, \d{4} \d\d:\d\d:\d\d (?:AM|am|PM|pm)' % months

regx = re.compile('%s.*?(?=%s|\Z)' % (ch,ch), re.DOTALL)

for x in regx.findall(s):
    print repr(x)
    print

rawDescription: Return all lines following a matched date and time up, but not including the next date and time?


code:
from itertools import product

# don't shadow the built-in name `dict`
d = {'key1': ['str0','str1','str2','strn'], 'key2': ['apples','bananas','mangos'], 'key3': ['spam','eggs','more spam']}

# dicts aren't sorted, but you seem to want key1 -> key2 -> key3 order, so
# let's get a sorted copy of the keys
keys = sorted(d.keys())
# and then get the values in the same order
values = [d[key] for key in keys]

# perform the Cartesian product
# product(*values) means product(values[0], values[1], values[2], ...)
results = product(*values)

# each `result` is something like ('str0', 'apples', 'spam')
for result in results:
    # pair up each entry in `result` with its corresponding key
    # So, zip(('key1', 'key2', 'key3'), ('str0', 'apples', 'spam'))
    # yields (('key1', 'str0'), ('key2', 'apples'), ('key3', 'spam'))
    # schematically speaking, anyway
    for key, thing in zip(keys, result):
        print key + '.' + thing,
    print

rawDescription: creating n nested loops from a dictionary of lists

description: Creating n nested loops from a dictionary of lists


code:
import re

regx = re.compile('at\\b')

ch = 'the fat cat was impressed by all the rats gathering at one corner of the great room'

print ch
print
print regx.sub('ATU',ch)

rawDescription: string suffix replacement in python

description: String suffix replacement in python


code:
print "\n"
f = "{:>22}" * (len(cities) + 1)
print f.format("", *cities)
for c in cities:
    print
    print f.format(c, *[resultDict.get((c, e))[0] for e in cities])
    print f.format("[GC]", *[resultDict.get((c, e))[1] for e in cities])

rawDescription: Printing list to table

description: Printing list to table


code:
import os
import binascii
import mmap

header = binascii.unhexlify("000100a0")
footer = binascii.unhexlify("0000000000")
sample = binascii.unhexlify("ABCD"
                "000100a0AAAAAA000000000000"
                "ABCDABCD"
                "000100a0BBBBBB000000000000"
                "ABCD")

# Create the sample file:
with open("sample.data", "wb") as f:
    f.write(sample)

# sample done. Now we have a REAL binary data in sample.data

with open('sample.data', 'rb') as f:
    print "Data: %s" % binascii.hexlify(f.read())
    mm = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
    current_offset = 0
    header_index = mm.find(header, current_offset)
    footer_index = mm.find(footer, current_offset + len(header))
    if header_index >= 0 and footer_index > header_index:
        print "Found header at %s and footer at %s"\
              % (header_index, footer_index)
        mm.seek(header_index + len(header))
        body = mm.read(footer_index - mm.tell())
        while body is not None:
            print "body: %s" % binascii.hexlify(body)
            current_offset = mm.tell()
            header_index = mm.find(header, current_offset + len(footer))
            footer_index = mm.find(footer, current_offset + len(footer) + len(header))
            if header_index >= 0 and footer_index > header_index:
                print "Found header at %s and footer at %s"\
                    % (header_index, footer_index)
                mm.seek(header_index + len(header))
                body = mm.read(footer_index - mm.tell())
            else:
                body = None

rawDescription: Taking a hex file and extracting data

description: Taking a hex file and extracting data


code:
c = 'Message'
@decorator_factory(c)
def msg_printer():
    print var

msg_printer()
'var' in globals()

rawDescription: How to inject variable into scope with a decorator in python

description: Inject variable into scope with a decorator in python


code:
from bs4 import BeautifulSoup

data = '<spotter num="0187" report_at="2014-03-15 20:10:25" lat="49.8696518" lng="-80.0973129" callsign="wxman132" active="1" public="" gps="0" phone="" email="addu@nnu.nne" first="" last=""/>'
soup = BeautifulSoup(data)

spotter = soup.spotter
print spotter['lat'], spotter['lng']

rawDescription: Python parse XML variables from a single tag


code:
pos = 0
for line in open(filename):
    for i in xrange(len(line)):
        if line[i:i+len(substring)] == substring:
           print 'Found @ %d!' % (pos + i)
    pos += len(line) + 2 # 1 if on Linux

rawDescription: Open file into array, search for string and return value


code:
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
    data={'track': 'requests'}, auth=('username', 'password'),
    stream=True)

for line in r.iter_lines():
    if line: # filter out keep-alive new lines
        print json.loads(line)

rawDescription: The Requests streaming example does not work in my environment


code:
class MyMatrix(np.matrix):
    def __new__(cls):
        # note that we have to send cls to super's __new__, even though we gave it to super already.
        # I think this is because __new__ is technically a staticmethod even though it should be a classmethod
        return super(MyMatrix, cls).__new__(cls, "1 2; 3 4")

mat = MyMatrix()

print mat
# outputs [[1 2] [3 4]]

rawDescription: Numpy Matrix class: Default constructor attributes for inherited class


code:
import pickle
import marshal
import types

class Foo():
    def __init__(self, fun):
        self.fun = fun

    def call_fun(self, arg):
        self.fun(arg)

    def save(self, f):
        saved = self.fun
        self.fun = marshal.dumps(self.fun.func_code)
        pickle.dump(self, f)
        self.fun = saved

    @staticmethod
    def load(f):
        foo = pickle.load(f)
        foo.fun = types.FunctionType(marshal.loads(foo.fun), globals())
        return foo

def sample_function(arg):
    arg.effect(4)

class Arg():
    def effect(self, value):
        print "ok: " + str(value)

rawDescription: Problematic function pickling

description: Problematic function pickling


code:
url = "http://www.brothersoft.com/d.php?soft_id=159403&url=http%3A%2F%2Ffiles.brothersoft.com%2Fmp3_audio%2Fmidi_tools%2FSynthFontSetup.exe&name=SynthFont"
print url.replace("&" + url.split('&')[-1],"")

rawDescription: How to split and remove unwanted string in url?

description: Split and remove unwanted string in url


code:
data = [
    ['A','a','1'],
    ['B','b','2'],
    ['C','c','3'],
    ['D','d','4']
]

# Desired output:
#
#   A B C D
# a 1
# b   2
# c     3
# d       4

# Check data consists of colname, rowname, value triples
assert all([3 == len(row) for row in data])
# Convert all data to strings
data = [ [str(c) for c in r] for r in data]
# Check all data is one character wide
assert all([1 == len(s) for s in r for r in data])

#============================================================================
# Verbose version
#============================================================================
col_names, row_names, values = zip(*data) # Transpose

header_line = '  ' + ' '.join(col_names)
row_lines = []
for idx, (row_name, value) in enumerate(zip(row_names,values)):
    # Use '  '*n to get 2n consecutive spaces.
    row_line = row_name + ' ' + '  '*idx + value
    row_lines.append(row_line)

print header_line
for r in row_lines:
    print (r)

rawDescription: Formatting output as table

description: Formatting output as table


code: print result['a']

rawDescription: How do I turn a list of tuples into a dictionary while keeping redundant values?

description: Turn a list of tuples into a dictionary while keeping redundant values


code:
class A(object):

   def __init__(self, value):
       self.value = value

   def __add__(self, other):
       return A(self.value + other.value)

a = A(1)
b = A(2)
c = a + b
print c.value  # 3

rawDescription: How to add 2 objects of a class by overide __add__ method?

description: Add 2 objects of a class by overide __add__ method


code:
import re
tags_starting_with_level = soup.findAll(re.compile('^level'))
for tag in tags_starting_with_level: print tag.name
# level1
# level2

rawDescription: Editing XML as a dictionary in python?

description: Editing XML as a dictionary in python


code: print "Center Colour (swapped)", cimg[i[1], i[0]]

rawDescription: OpenCV pixel colours all the same

description: OpenCV pixel colours all the same


rawDescription: How can I filter a YAML dataset with an attribute value?

description: Filter a YAML dataset with an attribute value


code:
reservation = conn.get_all_instances()[0]
# Yeah I don't know why they have these stupid reservation objects either...
instance = reservation.instances[0]
print instance.tags
# prints a dictionary of the tags {'Name': 'Given name'}

rawDescription: boto aws pulling down list of instances

description: Boto aws pulling down list of instances


code:
import urllib2  # the lib that handles the url stuff

data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
    print line

rawDescription: In Python, given a URL to a text file, what is the simplest way to read the contents of the text file?


code:
s = 'hello there'
word1, word2 = s.split()
print word1
print word2

rawDescription: How can I separate two separated words in a variable?

description: Separate two separated words in a variable


code: print df[1].diff().mod(100).sum()

rawDescription: Sum of precipitation per Timeframe in pandas DataFrame


code:
for b in range(6):
    for a in range(b+1, 7):
        print "a:", a, "b:", b

rawDescription: How to do a loop inside of a loop in python

description: Do a loop inside of a loop in python


rawDescription: Interpolate values in a 2D Python numerical dictionary


code:
strs = "log:A 22 log:B 44 log:C 74 log:D 24 log:B 10"
from collections import defaultdict
dic = defaultdict(int)
it = iter(strs.split())
for k in it:
    dic[k] += int(next(it))

for k,v in sorted(dic.items(), key = lambda x: x[1], reverse = True):
    print k,v

rawDescription: python matching list items

description: Python matching list items


code:
questions = ['Question 1', 'Question 2', 'Question 3'] #You can add as many questions as you like
random.shuffle(questions)  #Mixes the items in "questions" into a random order
print questions[0]
print questions[1]
print questions[2]

rawDescription: how to randomize order of questions in a quiz in python?

description: Randomize order of questions in a quiz in python


code: print "%s, %i" % k

rawDescription: How to remove quotes and brackets in tuple in python

description: Remove quotes and brackets in tuple in python


code:
import lxml.etree
tree = lxml.etree.parse('1.xml')
for child in tree.findall('./Parent/Child'):
    print '{} has {}'.format(child.getparent().get('name'), child.get('name'))

rawDescription: Parse XML with ElementTree

description: Parse XML with ElementTree


code:
print zip( a[0], b[0] )
print zip( a[1], b[1] )

rawDescription: concise and fast zip operation on lists of lists in Python?

description: Concise and fast zip operation on lists of lists in Python


code:
import sys
import subprocess
import threading

cmd = "/path/to/utility -x arg1 -y arg2"

class Command(threading.Thread):
    def __init__(self, cmd):
        super(Command, self).__init__()
        self.cmd = cmd
        self.process = None
        self.returncode = None
        self.jobid = None

    def run(self):
        print "Starting job..."
        self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE, shell=True)
        out, err = self.process.communicate()
        self.jobid = out.split()[10]

    def alive(self):
        if self.process.poll():
            return True
        else:
            return False

    def getJobID(self):
        return self.jobid

job = Command(cmd)
job.start()

if job.alive():
   print "Job is still alive."
else:
   print "Job is not alive."

sys.exit(0)

rawDescription: Best Approach to Threading/Spawning Multiple OS Commands and Getting Output at Various Points


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
df.insert(0, 'lookup_key', np.random.randint(0, 5, 10))
print df
lkup_dict = {i: np.random.randint(0, 5) for i in range(5)}
print lkup_dict

rawDescription: Apply Across Dynamic Number of Columns

description: Apply Across Dynamic Number of Columns


rawDescription: have a .exe run in the background and type things into that through python

description: Have a .exe run in the background and type things into that through python


code:
import msvcrt

print "Please enter a value"
char = msvcrt.getch()
print char

rawDescription: How to accept input without the need to press enter Python 3

description: Accept input without the need to press enter Python 3


code:
a = {
    'test1462477941.log': {'end_diff': 537,
                           'file_epoch': 1462477941,
                           'start_diff': -33},
    'test1462478161.log': {'end_diff': 317,
                           'file_epoch': 1462478161,
                           'start_diff': 284},
    'test1462478346.log': {'end_diff': 132,
                           'file_epoch': 1462478346,
                           'start_diff': 99},
}

only_positive_start_diff = filter(lambda x: x[1]['start_diff'] > 0, a.items())
min_start_diff = min(only_positive_start_diff, key=lambda x: x[1]['start_diff'])

print min_start_diff[0]  # Min log file

rawDescription: How do I find the top level KEY of the lowest positive VALUE from a particular SUBKEY?

description: Find the top level KEY of the lowest positive VALUE from a particular SUBKEY


code:
def recurse( x ):
  for k, v in x.items():
    if isinstance( v , dict ):
      recurse( v )
    else:
      print "key: {}, val: {}".format(k, v)

rawDescription: How to loop over a dictionary with more than 3 sublevels of dictionaries inside it

description: Loop over a dictionary with more than 3 sublevels of dictionaries inside it


code:
import numpy as np
a = np.random.randn(100, 2)
b = np.random.randn(200, 2)

d1 = euclidean_distances(a, b)
d2 = distance_matrix(a, b, p=2)
print d1.shape  # yields (100, 200), one distance for each possible couple
print d2.shape

rawDescription: Vectorize over only one axis in a 2D array with numpy vectorize


code:
class C(object):
    _scaling_method = None

    def same(self, u):
        return u

    def double(self, u):
        return u * 2

    scale = same

    @property
    def scaling_method(self):
        return self._scaling_method

    @scaling_method.setter
    def scaling_method(self, value):
        if value.lower() == "double":
            self.__class__._scaling_method = "double"
            self.__class__.scale = self.double
        elif value.lower() == "same":
            self.__class___.scaling_method = "same"
            self.__class__.scale = self.same
        else:
            print "Unknown scaling method."

rawDescription: Changing dynamically one method of a class


code:
def astropymethod2(img, hduid=1):
    # from http://astropy.readthedocs.org/en/latest/wcs/
    hdu = fits.open(img)
    w = WCS(hdu[hduid].header)
    lon, lat = w.wcs_pix2world(100., 100., 1)
    print lon, lat

rawDescription: Find physical coordinates of a pixel in a fits file with python


code:
ia, ib = np.where(np.less.outer(df_a.a, df_b.c))
print pd.concat((df_a.take(ia).reset_index(drop=True),
                 df_b.take(ib).reset_index(drop=True)), axis=1)

rawDescription: how to perform an inner or outer join of DataFrames with Pandas on non-simplistic criterion

description: Perform an inner or outer join of DataFrames with Pandas on non-simplistic criterion


code:
import sys

def get_locals(func):
    def wrap(*args, **kw):
        sys.settrace(tracefunc)
        try:
            res = func(*args, **kw)
        finally:
            sys.settrace(None)
        return res

    def tracefunc(frame, event, arg):
        if event == "return":
            if frame.f_code is func.func_code:
                wrap.last_res = frame.f_locals
        return tracefunc

    return wrap

@get_locals
def foo(x,y):
    z = x + y
    return z

def bar(x, y):
    z = x - y
    return z

a = 1
b = 2
c = foo(a, b)
d = bar(a, b)

print foo.last_res

rawDescription: Keep function namespace alive for debugging in IPython


code:
class Foo:
  pass # dummy class

x = Foo()

Foo.bar = lambda self: 42

print x.bar()

rawDescription: Can you monkey patch methods on core types in python?

description: Monkey patch methods on core types in python


code:
from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

rawDescription: Printing colors in python terminal

description: Printing colors in python terminal


code: print '\n'.join(sorted(list(set(map((lambda line: re.sub(r'lo(.*)$', r'\1', line)), s.split('\n'))))))

rawDescription: Converting a sed regular expression to python code


code: print Users[0]

rawDescription: Removing characters from a tuple

description: Removing characters from a tuple


code:
# When you query the data back it returns instances of your class:

for user in s.query(User):
    print type(user), user.name, user.password

rawDescription: Is it possible to store Python class objects in SQLite?


code:
import re
txt = "[something name=\"Paul\" other=\"1/1/1\"][something name=\"James\" other=\"4/3/5\"][something name=\"Victor\" other=\"7/2/6\"][something name=\"Jane\" other=\"4/3/6\"]"
for name in re.findall('name\=\\"(.*?)\\\"', txt):
    print name

rawDescription: Python 2.7 print strings

description: Python 2.7 print strings


code:
import ast

members = []
with open('file.py', 'r') as f:
    src = f.read()

tree = ast.parse(src)

for child in tree.body:
    if isinstance(child, ast.Assign):
        for target in child.targets:
            members.append(target.id)

print members
# ['b1', 'a0', 'a1']

rawDescription: Get ordered list of attributes of a Python module


code:
import re

string = ('Houston, TX ' +
         '(San Francisco, CA) ' +
         'South & West (Houston, TX) ' +
         '(South & West (Houston, TX))')

matches = re.findall("([\w\s]+),\s(\w+)", string)
for match in matches:
    print 'City: ' + match[0] + ', State: ' + match[1]

rawDescription: Regex to separate City and State from input string


code:
import sys
print "X"

rawDescription: How can I change the prompt displayed by Sphinx when documenting interactive sessions?

description: Change the prompt displayed by Sphinx when documenting interactive sessions


code:
import operator

def compress(sequence):
    """Packs source sequence into sub-sequences and finds the longest"""
    if not sequence: return []
    max_length = 0
    max_item = None
    cur_length = 0
    cur_item = sequence[0]
    compressed = []
    for item in sequence:
        if item == cur_item:
            cur_length += 1
        else:
            compressed.append((cur_item, cur_length))
            if cur_length >= max_length:
                max_length, max_item = cur_length, cur_item
            cur_item, cur_length = item, 1
    # Forgot to handle the last sequence
    compressed.append((cur_item, cur_length))
    if cur_length >= max_length:
        max_length, max_item = cur_length, cur_item
    # End of fixes
    return compressed, max_length, max_item

if __name__ == '__main__':
    sequence = [1,1,1,1,2,2,3,3,6,6,6,6,6,6,6,6,4,4,4,4,4,3,3,7,7,7,1,1]
    compressed, max_length, max_item = compress(sequence)

    print 'original:', sequence
    print 'compressed:', compressed
    print 'max_length:', max_length, 'max_item:', max_item
    print 'uncompressed:', [[item] * length for item, length in compressed] # This is for example only

    pre_result = [[max_item if length * 2 <= max_length else item] * length for item, length in compressed]
    print 'uncompressed with replace:', pre_result
    result = reduce(operator.add, pre_result) # Join all sequences into one list again
    print 'result:', result

rawDescription: python lists manipulation group by count

description: Python lists manipulation group by count


rawDescription: How can you output a varying argument in Python?

description: Output a varying argument in Python


code:
from a import method
import inspect

code = inspect.getsource(method)
local_var = 2
method()
print code
exec code
method()

rawDescription: Forcing imported method to use local variables


code:
for entry in dat['accounts']['data']:
    print entry['name']

rawDescription: parsing json data using request function in python.... i am unable to access the objects

description: Parsing json data using request function in python.... i am unable to access the objects


code:
for factorization in generate_all_factorizations([2, 2, 5]):
    print factorization
print "----"
for factorization in generate_all_factorizations([2, 3, 5, 7]):
    print factorization

rawDescription: Algorithm to find ALL factorizations of an integer


code:
def grouper(n, iterable):
    args = [iter(iterable)] * n
    return zip(*args)

t = (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)
print grouper(4, t)

rawDescription: Spliting a long tuple into smaller tuples


code:
from socket import socket

class PolySocket(object):
    def __init__(self, *p):
        print "PolySocket init"
        self._sock = socket(*p)

    def __getattr__(self, name):
        return getattr(self._sock, name)

    def sendall(self, *p):
        print "PolySocket sendall"
        return self._sock.sendall(*p)

    def send(self, *p):
        print "PolySocket send"
        return self._sock.send(*p)

    def connect(self, *p):
        print "connecting..."
        self._sock.connect(*p)
        print "connected"

HOST = "stackoverflow.com"
PORT = 80
readbuffer = ""

s = PolySocket()
s.connect((HOST, PORT))
s.send("a")
s.sendall("a")

rawDescription: Can't overload python socket.send

description: Can't overload python socket.send


code:
from itertools import groupby

data = ['a','a','x','c','e','e','f','f','f']
for k, g in groupby(data):
    if len(list(g)) > 1:
        print k

rawDescription: Conditional loop in python

description: Conditional loop in python


code:
import re

#Reading from file and updating values
fhand = open('a.txt', 'r')
tmp_list=[]
for line in fhand:
  #Split line using ','
    words = line.split(',')
  #Remove non-numeric chars from 34th string using regex
    words[3] = re.sub(r'\D', "", words[3])
  #Update the 3rd string
    # If the 3rd field is blank go to the next line
    if len(words[3]) < 1 :
        #Removed continue it from here we need to reconstruct the original line and write it to file
        print "Field empty.Continue..."
    elif len(words[3]) >= 1 and len(words[3]) < 5 :
       #format won't add leading zeros. zfill(5) will add required number of leading zeros depending on the length of word[3].
        words[3]=words[3].zfill(5)

    #After updating 3rd value in words list, again creating a line out of it.
    tmp_str = ",".join(words)
    tmp_list.append(tmp_str)
fhand.close()

#Writing to same file
whand = open("a.txt",'w')
for val in tmp_list:
    whand.write(val)
whand.close()

rawDescription: Printing to a file via Python

description: Printing to a file via Python


code:
from docutils.core import publish_doctree
import xml.etree.ElementTree as etree

source = """Some help text

:param x: some parameter
:type x: and it's type

:return: Some text
:rtype: Return type

Some trailing text. I have no idea if the above is valid Sphinx
documentation!
"""

doctree = publish_doctree(source).asdom()

# Convert to etree.ElementTree since this is easier to work with than
# xml.minidom
doctree = etree.fromstring(doctree.toxml())

# Get all field lists in the document.
field_lists = doctree.findall('field_list')

fields = [f for field_list in field_lists \
    for f in field_list.findall('field')]

field_names = [name.text for field in fields \
    for name in field.findall('field_name')]

field_text = [etree.tostring(element) for field in fields \
    for element in field.findall('field_body')]

print zip(field_names, field_text)

rawDescription: Parse sphinx like documentation

description: Parse sphinx like documentation


code:
import time
import threading

class CoolThing(object):

    def __init__(self):
        self.thread = None

    def run_in_background(self, callback, period=0.5):
        wait_count = 0
        while True:
            if self.thread:
                if self.thread[1].running or wait_count>10:
                    raise RuntimeError()
                time.sleep(0.5)
                wait_count += 1
            else:
                break

        def worker():
            t0 = time.time()
            worker.running = True
            while worker.running:
                if time.time()-t0>2:
                    callback()
                    t0 = time.time()
                time.sleep(period)
            worker.callback()

        worker.callback = self.dispose
        self.thread = (threading.Thread(target=worker), worker)
        self.thread[0].start()

    def stop_background(self, join=False):
        if not self.thread:
            raise RuntimeError
        self.thread[1].running = False
        if join:
            self.thread[0].join()
        self.stopping = True

    def dispose(self):
        self.thread = None
        self.stopping

def my_callback():
    print "Beep"

if __name__=="__main__":
    cool_thing = CoolThing()
    cool_thing.run_in_background(my_callback, 0.5)
    time.sleep(10)
    cool_thing.stop_background()
    # Immediatley restart process
    cool_thing.run_in_background(my_callback, 0.5)
    time.sleep(10)
    cool_thing.stop_background()
    print cool_thing.thread
    time.sleep(3)
    print cool_thing.thread

rawDescription: What to do with thread being about to terminate?


code:
print "DATABASE\names.txt" # interpreted as two lines
print r"DATABASE\names.txt"

rawDescription: IO ERROR(ERRNO 20) while Accessing a file inside a folder in python


rawDescription: Control a print format when printing a list in Python


code:
from random import randrange
import datetime

def random_date(start,l):
   current = start
   while l >= 0:
      curr = current + datetime.timedelta(minutes=randrange(60))
      yield curr
      l-=1

startDate = datetime.datetime(2013, 9, 20,13,00)

for x in random_date(startDate,10):
  print x.strftime("%d/%m/%y %H:%M")

rawDescription: Create random time stamp list in python

description: Create random time stamp list in python


code:
import codecs
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
trainfile = 'train.txt'
testfile = 'test.txt'
word_vectorizer = CountVectorizer(analyzer='word')
trainset = word_vectorizer.fit_transform(codecs.open(trainfile,'r','utf8'))
tags = ['CHICKEN POX','HEPATITIS A','HEPATITIS B','Human papillomavirus','MENINGITIS']
mnb = MultinomialNB()
mnb.fit(trainset, tags)
codecs.open(testfile,'r','utf8')
testset = word_vectorizer.transform(codecs.open(testfile,'r','utf8'))
results = mnb.predict(testset)
print results

rawDescription: Implementing Naive Bayes for Twitter data


code:
from collections import defaultdict

a = [('N', '7289'),
     #...
     ('G', '2')]

groups = defaultdict(list)
for tupl in a:
    key, value = tupl[0], float(tupl[1])
    groups[key].append(value)

for key, values in groups.iteritems():
    print key, max(values), min(values)

rawDescription: How to find max and min number from a file in python

description: Find max and min number from a file in python


code:
from cv2 import *
import numpy as np

# Initialize a and b numpy arrays with coordinates and weights
a = np.zeros((5,2))

for i in range(0,5):
    a[i][1] = i+1

a[0][0] = 1
a[1][0] = 1
a[2][0] = 0
a[3][0] = 0
a[4][0] = 1

b = np.zeros(4,2)

for i in range(0,4):
    b[i][1] = i+1

b[0][0] = 0
b[1][0] = 1
b[2][0] = 0
b[3][0] = 1

# Convert from numpy array to CV_32FC1 Mat
a64 = cv.fromarray(a)
a32 = cv.CreateMat(a64.rows, a64.cols, cv.CV_32FC1)
cv.Convert(a64, a32)

b64 = cv.fromarray(b)
b32 = cv.CreateMat(b64.rows, b64.cols, cv.CV_32FC1)
cv.Convert(b64, b32)

# Calculate Earth Mover's
print cv.CalcEMD2(a32,b32,cv.CV_DIST_L2)

# Wait for key
cv.WaitKey(0)

rawDescription: How to compute "EMD" for 2 numpy arrays i.e "histogram" using opencv?

description: Compute "EMD" for 2 numpy arrays i.e "histogram" using opencv


code:
import requests
r = requests.post('http://money.rediff.com/indices/bse/bsesmallcap',
              data={'currentPageNo': 3, 'RowPerPage': 100})
print r.text

rawDescription: How to webscrape this website

description: Webscrape this website


rawDescription: efficient algorithmic method to concatenate rows of an array into a 1-D array

description: Efficient algorithmic method to concatenate rows of an array into a 1-D array


code:
class MyClass(object):
    def __new__(cls_self, *args, **kwargs):
        print "I am {} called with {} and {}".format(cls_self, args, kwargs)
        return None

myobj = MyClass(1,2,3,a=4,b=5,c=6)
print myobj # == None

rawDescription: Why is my metaclass not behaving as expected


code:
import BaseHTTPServer
import CGIHTTPServer
import cgitb;
cgitb.enable() ## This line enables CGI error reporting

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
PORT = 8000
server_address = ("", PORT)
handler.cgi_directories = ["/cgi-bin"]

httpd = server(server_address, handler)
print 'Server running on 127.0.0.1:8000...'
httpd.serve_forever()

rawDescription: cgi file .py not exexuting; file gets displayed instead

description: Cgi file .py not exexuting; file gets displayed instead


code:
from email.message import Message
from email.header import Header
msg = Message()
msg['Subject'] = Header('主題', 'utf-8')
print msg.as_string()

rawDescription: Encoding mail subject (SMTP) in Python with non-ASCII characters


code:
for item in soup.find_all(text=lambda x: 'something new' in x):
    print item

rawDescription: get specific text such as "Something new" using BeautifulSoup Python

description: Get specific text such as "Something new" using BeautifulSoup Python


code:
from itertools import groupby

for letter, rows in groupby(cur, key=lambda r: r[0][0]):
    print ' '.join([r[0] for r in rows])

rawDescription: SQLite Python printing in rows?

description: SQLite Python printing in rows


rawDescription: How to get hex string from signed integer

description: Get hex string from signed integer


code:
from cmd import Cmd

class PipelineExample(Cmd):

    def do_greet(self, person):
        if person:
            greeting = "hello, " + person
        else:
            greeting = 'hello'
        self.output = greeting

    def do_echo(self, text):
        self.output = text

    def do_pipe(self, args):
        buffer = None
        for arg in args:
            s = arg
            if buffer:
                # This command just adds the output of a previous command as the last argument
                s += ' ' + buffer
            self.onecmd(s)
            buffer = self.output

    def postcmd(self, stop, line):
        if hasattr(self, 'output') and self.output:
            print self.output
            self.output = None
        return stop

    def parseline(self, line):
        if '|' in line:
            return 'pipe', line.split('|'), line
        return Cmd.parseline(self, line)

    def do_EOF(self, line):
        return True

if __name__ == '__main__':
    PipelineExample().cmdloop()

rawDescription: implement a unix pipe with python cmd module?

description: Implement a unix pipe with python cmd module


code:
data = "abcdefghijklmnopqrstuvwxyz"
print data[:20].ljust(20, "0")        # abcdefghijklmnopqrst

data = "abcd"
print data[:20].ljust(20, "0")        # abcd0000000000000000

rawDescription: python if a list is over 20 characters shorten it to 20 if it is less than 20 characters, add 0s to make it 20

description: Python if a list is over 20 characters shorten it to 20 if it is less than 20 characters, add 0s to make it 20


code:
class meh():
    def __init__(self):
        self.cat = 'dinosaur'
        self.number = 1
    # some example methods - don't actually do this
    # this is not a good use of a method
    # or object-oriented programming in general

    def add_number(self, i):
        self.number+=i

j = meh()
print j.__dict__
{'number': 1, 'cat': 'dinosaur'}

rawDescription: how to parse Flickr using flickrapi in python

description: Parse Flickr using flickrapi in python


code:
class callcounted(object):
    """Decorator to determine number of calls for a method"""

    def __init__(self,method):
        self.method=method
        self.counter=0

    def __call__(self,*args,**kwargs):
        self.counter+=1
        return self.method(*args,**kwargs)

import logging
logging.error=callcounted(logging.error)
logging.error('one')
logging.error('two')
print logging.error.counter

rawDescription: How many times was logging.error() called?


rawDescription: Regex not working in python script

description: Regex not working in python script


code:
import xlrd

book = xlrd.open_workbook('myfile.xls')

print book.nsheets
print book.sheet_names()

sh = book.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols

rawDescription: Very basic Python to Excel how to

description: Very basic Python to Excel how to


code:
import itertools
g = product(lambda: itertools.permutations(xrange(100)),
            lambda: itertools.permutations(xrange(100)))
print next(g)
print sum(1 for _ in g)

rawDescription: Cartesian product of large iterators (itertools)


code:
import re
p = re.compile("(%s)" % "|".join(words))
for word in text:
    print p.sub(r"<tag>\1</tag>", word)

rawDescription: How to find words from list of words in another list

description: Find words from list of words in another list


code: pattern_split = re.compile(ur"\W+", re.UNICODE)

rawDescription: python re.compile and split with ÆØÅ charcters

description: Python re.compile and split with ÆØÅ charcters


code:
from bs4 import BeautifulSoup
import requests

url = 'http://www.vivotek.com/faq/'
query = 'appnote'

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36'}

session = requests.Session()
response = session.get(url, headers=headers)

soup = BeautifulSoup(response.content)

post_data = {'__EVENTTARGET':'',
             '__EVENTARGUMENT':'',
             '__LASTFOCUS':'',
             '__VIEWSTATE': soup.find('input', id='__VIEWSTATE')['value'],
             '__VIEWSTATEGENERATOR': soup.find('input', id='__VIEWSTATEGENERATOR')['value'],
             '__VIEWSTATEENCRYPTED': '',
             '__PREVIOUSPAGE': soup.find('input', id='__PREVIOUSPAGE')['value'],
             '__EVENTVALIDATION': soup.find('input', id='__EVENTVALIDATION')['value'],

             'ctl00$HeaderUc1$LanguageDDLUc1$ddlLanguage': 'en',
             'ctl00$ContentPlaceHolder1$CategoryDDLUc1$DropDownList1': '-1',
             'ctl00$ContentPlaceHolder1$ProductDDLUc1$DropDownList1': '-1',
             'ctl00$ContentPlaceHolder1$Content': query,
             'ctl00$ContentPlaceHolder1$Search': 'Search'
            }

response = session.post(url, data=post_data, headers=headers)

soup = BeautifulSoup(response.content)
for item in soup.select('a#ArticleShowLink'):
    print item.text.strip()

rawDescription: POST URL Encoded vs Line-based text data via Python Requests


code:
gen = RampUp()
gen.calc = simple
gen.target = 20
for _ in xrange(100):
    # that's the value you pass to your motor controller
    print next(gen)

rawDescription: Ramping Joystick values over time

description: Ramping Joystick values over time


code:
d='banttnay'
from itertools import *
def unique_everseen(iterable, key=None):
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

for x in unique_everseen(d):
    print x,d.count(x)

rawDescription: How can i count and not repeat the same letter in python

description: Count and not repeat the same letter in python


code:
import gc

class A(object): pass
class B(A): pass

def which_list(self):
    lists_referring_to_me = []
    for obj in gc.get_referrers(self):
        if isinstance(obj, list):
            lists_referring_to_me.append(obj)

    return lists_referring_to_me

a = A()
b = B()
foo = [a, 52, b]
bar = ['spam', b]

print which_list(a)
print which_list(b)

rawDescription: Finding what list a class instance is in, in Python


code:
if ( curre < final ):
    # print midP
    print "t: " + array[midP][TAPE_NUMBER] + ", d: " + desiderata
    binarySearch( array, desiderata, midP + 1, iMax )

rawDescription: Python function returns None (all trivial solutions checked and they do not work)


code:
#!/usr/bin/env python
inputFile = open('CMakeLists.txt', 'r')

version = None
savedBefore = ""
savedAfter = ""

for line in inputFile:
    if "_PATCH " in line:
        print "inside: ", line
        version = line
    elif version is None:
        savedBefore += line
    else:
        savedAfter += line

inputFile.close()

inputFile = open('CMakeLists.txt', 'w')

x = version.split('"')
print "x: ", x

a = x[0]
b = int(x[1]) + 1
c = x[2]

new_version = str(a) + '"' + str(b) + '"' + str(c)
print "new_version: ", new_version

inputFile.write(savedBefore)
inputFile.write(str(new_version))
inputFile.write(savedAfter)

inputFile.close()

rawDescription: replacing a string in a text file

description: Replacing a string in a text file


code:
import socket
import threading
import sys
host = ''
port = 50000

class client(threading.Thread):
    def __init__(self, conn):
        super(client, self).__init__()
        self.conn = conn
        self.data = ""

    def run(self):
        while True:
            self.data = self.data + self.conn.recv(1024)
            if self.data.endswith(u"\r\n"):
                print self.data
                self.data = ""

    def send_msg(self,msg):
        self.conn.send(msg)

    def close(self):
        self.conn.close()

class connectionThread(threading.Thread):
    def __init__(self, host, port):
        super(connectionThread, self).__init__()
        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.s.bind((host,port))
            self.s.listen(5)
        except socket.error:
            print 'Failed to create socket'
            sys.exit()
        self.clients = []

    def run(self):
        while True:
            conn, address = self.s.accept()
            c = client(conn)
            c.start()
            c.send_msg(u"\r\n")
            self.clients.append(c)
            print '[+] Client connected: {0}'.format(address[0])

def main():
    get_conns = connectionThread(host, port)
    get_conns.start()
    while True:
        try:
            response = raw_input()
            for c in get_conns.clients:
                c.send_msg(response + u"\r\n")
        except KeyboardInterrupt:
            sys.exit()

if __name__ == '__main__':
    main()

rawDescription: Python Socket Listening

description: Python Socket Listening


rawDescription: Django QuerySet values_list returning unknown characters


code:
query = QSqlQuery("SELECT COUNT(*) FROM your_table")
query.next()
print query.value(0).toString()  # print the number of records
print model.rowCount()  # print 0 as the model has not been populated yet

rawDescription: PyQt4: Display progress bar while qtsql table is being loaded