code:
import json
f = sc.textFile('/path/to/file')
d = lines.map(lambda line: json.loads(line))

rawDescription: Loading JSON dataset into Spark, then use filter, map, etc


code:
dct = {'label1':'value1' , 'label2':'value2'}
for labels in dct:
    print('label - ' + labels)
    print('value - ' + dct[labels])

rawDescription: Sets with conditions in python

description: Sets with conditions in python


code: (max(a[0] for a in list), max(a[1] for a in list))

rawDescription: Fastest way to find the greatest 1st and 2nd items of a list of tuples simultaneously in python


code:
import wx

class Frame(wx.Frame):
  def __init__(self, parent, id, title, img_path):
    wx.Frame.__init__(self, parent, id, title,
                      style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)

    image = wx.StaticBitmap(self, wx.ID_ANY)
    image.SetBitmap(wx.Bitmap(img_path))

    sizer = wx.BoxSizer()
    sizer.Add(image)
    self.SetSizerAndFit(sizer)

    self.Show(True)

app = wx.App()
frame = Frame(None, wx.ID_ANY, 'Image', '/path/to/file.png')
app.MainLoop()

rawDescription: Sizing a frame to an image in WxPython

description: Sizing a frame to an image in WxPython


code:
def mathNum(v, w, x, y, z):
    total = v + w
    altTotal1 = v + x
    altTotal2 = w + y
    ans = total * (altTotal1 + altTotal2)
    return ans

def main():
    v, w, x, y, z = getNum()
    print("Your first number is: ", v)
    print("Your second number is: ", w)
    print("Your third number is: ", x)
    print("Your fourth number is: ", y)
    print("Your fifth number is: ", z)

    ans = mathNum(v, w, x, y, z)
    print("Your answer to the random problem is: ", ans)

rawDescription: I am trying to not get a variable to ask for input a second time in Python 3.4


code:
def parse_model(self, response):
    sel = Selector(response)
    models = sel.xpath("//li[@class='class_12']")
    for model in models:

        item = SiteUtem(response.meta["item"])
        url2 = model.xpath('a/@href')[0].extract()
        item ['model'] = model.xpath("a/text()")[0].extract()
        item ['model_link'] = url2

        yield item

rawDescription: Scrapy nested page crawling

description: Scrapy nested page crawling


code:
import sympy
alpha1, r1_x, r1_y = sympy.var("alpha1 r1_x r1_y")
B1 = sympy.exp(-alpha1 * (r1_x**2 + r1_y**2))
B1.integrate(r1_x)
B1.expand(alpha1)
B1.expand(alpha1).integrate(r1_x)

rawDescription: Symbolic Integration in Python using Sympy


code:
from os.path import dirname
ROOT = dirname(__file__)

rawDescription: Defining path to module's configuration files


code:
from collections import defaultdict
d = defaultdict(list)
d["hello"].append(1)
d["hello"].append(2)
dict(d)

rawDescription: Append to a nested list or dict in Python


code:
import xlwt as xl

doc = xl.Workbook() #Create document
#Add a worksheet
sheet = doc.add_sheet("Some Sheet")
for i in range(100):
    #Write 2 columns
    sheet.write(i, 0, i+1)
    sheet.write(i, 1, i*2)
    #Write result (SUM for example)
    sheet.write(i, 2, xl.Formula("SUM(A%d:B%d)" % (i+1, i+1)))
doc.save("my_table.xls")

rawDescription: How to insert values of a whole column in python using xlwt

description: Insert values of a whole column in python using xlwt


code:
import q; q(foo)

# use @q to trace a function's arguments and return value
@q
def bar():
   ...

# to start an interactive console at any point in your code:
q.d()

rawDescription: log a variable name and value

description: Log a variable name and value


code:
from math import floor, ceil
import profile

amino_weight = {
    'A':  71.038,
    'C': 103.009,
    'D': 115.027,
    'E': 129.043,
    'F': 147.068,
    'G':  57.021,
    'H': 137.059,
    'I': 113.084,
    'K': 128.095,
    'L': 113.084,   # you omitted leutine?
    'M': 131.040,
    'N': 114.043,
    'P':  97.053,
    'Q': 128.059,   # you omitted glutamine?
    'R': 156.101,
    'S':  87.032,
    'T': 101.048,
    'V':  99.068,
    'W': 186.079,
    'Y': 163.063
}

def get_float(prompt):
    while True:
        try:
            return float(raw_input(prompt))
        except ValueError:
            pass

# This is where the fun happens!
def get_mass_combos(aminos, pos, lo, hi, cutoff):
    this = aminos[pos]         # use a pointer into the string, to avoid copying 8 million partial strings around
    wt = amino_weight[this]
    kmax = int(floor(hi / wt))
    npos = pos - 1
    if npos:                   # more aminos to consider recursively
        for k in xrange(0, kmax + 1):
            mass    = k * wt
            nlo     = lo - mass
            nhi     = hi - mass
            ncutoff = cutoff - mass
            if nlo <= 0. and nhi >= 0.:
                # we found a winner!
                yield {this: k}
            elif ncutoff < 0.:
                # no further solution is possible
                break
            else:
                # recurse
                for cc in get_mass_combos(aminos, npos, nlo, nhi, ncutoff):
                    if k > 0: cc[this] = k
                    yield cc
    else:                      # last amino - it's this or nothing
        kmin = int(ceil(lo / wt))
        for k in xrange(kmin, kmax+1):
            yield {this: k}

def to_string(combo):
    keys = sorted(combo)
    return ''.join(k*combo[k] for k in keys)

def total_mass(combo):
    return sum(amino_weight[a]*n for a,n in combo.items())

def fact(n):
    num = 1
    for i in xrange(2, n+1):
        num *= i
    return num

def permutations(combo):
    num = 0
    div = 1
    for v in combo.values():
        num += v
        div *= fact(v)
    return fact(num) / div

def find_combos(lo, hi):
    total = 0
    bases = []
    aminos = ''.join(sorted(amino_weight, key = lambda x: amino_weight[x]))
    for combo in get_mass_combos(aminos, len(aminos)-1, lo, hi, hi - amino_weight[aminos[0]]):
        base = to_string(combo)
        bases.append(base)
        mass = total_mass(combo)
        cc = permutations(combo)
        total += cc
        print("{} (mass {}, {} permutations)".format(base, mass, cc))
    print('Total: {} bases, {} permutations'.format(len(bases), total))

def main():
    lo = get_float('Bottom of target mass range? ')
    hi = get_float('Top of target mass range? ')

    prof = profile.Profile()
    prof.run('find_combos({}, {})'.format(lo, hi))
    prof.print_stats()

if __name__=="__main__":
    main()

rawDescription: Algorithm optimization to find possible aminoacid sequences with total mass m


code:
s = 'hello\n'
raw = r'hello\n'
s
raw
print(s)
print(raw)

rawDescription: Does Python3 still need raw string in regular expression?


code:
import random

computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)

print(
    """
    Welcome Player to the fabulous number guessing game.
    Please allow me to show you my incredible deduction skills
    """)

question = None
lower = 0 # initial lower guess
higher = 101  # initial higher guess
while question != ("yes"):
    question = input("Has the player picked a number? ")
    question = question.lower()
    if question == "yes":
        print("\nI will now guess your number!!!\n")
        while player_number == None:
            computer_tries += 1
            print(computer_guess, "\n")
            confirmation = input("Is this the correct number? ")
            confirmation = confirmation.lower()
            if confirmation == "yes":
                player_number = computer_guess
                if computer_tries < 2:
                    print("I did it! I guessed your number was", computer_guess,
                           "and it only \ntook me", computer_tries,
                           "try to get it right!")
                else:
                    print("I did it! I guessed your number was", computer_guess,
                           "and it only \ntook me", computer_tries,
                           "tries to get it right!")
            else:
                higher_lower = None
                while higher_lower not in ("higher", "lower"):
                    higher_lower = input("Is my guess higher or lower"
                                + " than your number? ")
                    higher_lower = higher_lower.lower()
                    if higher_lower == "higher":
                        higher = computer_guess
                        computer_guess = random.randint(lower+1, higher-1)
                    elif higher_lower == "lower":
                        lower = computer_guess
                        computer_guess = random.randint(lower+1, higher-1)
                    else:
                        print("Please choose either higher or lower.")
                    print("DEBUG: number must be " + str(lower) + " < x < " + str(higher))

input("\n\nPress the enter key to exit")

rawDescription: Python 3.1 number guessing game higher or lower loop


code:
import os
import glob
source_pattern = 'c:/texts/*.txt'
output_directory = 'c:/texts/tokenized'

# Iterate over files matching source_pattern
for input_file in glob.glob(source_pattern):

    # build the output filename
    base,ext = os.path.splitext(os.path.basename(input_file))
    output_file = os.path.join(output_directory,base + '_tokenized' + ext)

    with open(input_file) as in_file, open(output_file,'w') as out_file:
        for line in in_file:
            out_file.write(','.join(line.split()) + '\n')

rawDescription: How to output in different directory?

description: Output in different directory


rawDescription: Downloading files from remote location using google openid authentication


code:
import os, requests
from cookielib import LWPCookieJar

def login():
    global s
    s = requests.Session()
    if os.path.exists('cookiejar'):
        print('Cookies exist! Fast login.\r'),
        global csrf
        with open('cookiejar') as f:
            s.cookies = requests.utils.cookiejar_from_dict(pickle.load(f))
        csrf = s.cookies['csrftoken']
        print('csrf: {0}').format(csrf) # Debug information
    else:
        print('Cookies do not exist. Slow login.\r'),
        s.get('http://www.example.com/') # to get csrf
        csrf = s.cookies['csrftoken']
        data= dict(csrftoken=csrf, username="user", password="pass")
        s.post('https://www.example.com/login/', data=data, headers=headers)
        with open('cookiejar', 'w') as f:
            pickle.dump(requests.utils.dict_from_cookiejar(s.cookies), f)

rawDescription: Struggling to retrieve csrf token from a cookiejar object


code:
q1 = Q()
if conditionA:
    q1 |= Q(income__gte=5000)
if conditionB:
    q1 |= Q(income=0)

User.objects.filter(q1)

rawDescription: Dynamically setting OR filter values in Django queryset


code:
def effectively_readable(path):
    import os, stat

    uid = os.getuid()
    euid = os.geteuid()
    gid = os.getgid()
    egid = os.getegid()

    # This is probably true most of the time, so just let os.access()
    # handle it.  Avoids potential bugs in the rest of this function.
    if uid == euid and gid == egid:
        return os.access(path, os.R_OK)

    st = os.stat(path)

    # This may be wrong depending on the semantics of your OS.
    # i.e. if the file is -------r--, does the owner have access or not?
    if st.st_uid == euid:
        return st.st_mode & stat.S_IRUSR != 0

    # See comment for UID check above.
    groups = os.getgroups()
    if st.st_gid == egid or st.st_gid in groups:
        return st.st_mode & stat.S_IRGRP != 0

    return st.st_mode & stat.S_IROTH != 0

rawDescription: Python equivalent of Perl file test readable (-r), writeable (-w) and executable (-x) operators


code: os.system('cleartool co -nc ' + pathname)

rawDescription: Using python to check out a file (cleartool)


code:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.TAG_NAME, "myaccount")))

rawDescription: Using Angular JS(Protractor) with Selenium in Python


rawDescription: Dividing a string in python

description: Dividing a string in python


code:
df
g = df.groupby(0)
g[1].nunique()

rawDescription: python count number of unique elements in csv column

description: Python count number of unique elements in csv column


code:
def add_numbers(a):
    total = 0
    i = 0
    while a[i] < 10 and i < len(a):
        total = total + a[i]
        i = i + 1
    return total        # return  should be outside the loop

rawDescription: Python Help please - creating basic functions (Ver 2.7)


code:
from django.contrib.contenttypes.models import ContentType
ct = ContentType.objects.get(model='user')
ct_class = ct.model_class()
ct_instance = ct_class()
ct_instance.username = 'hellow'
ct_instance.save()

rawDescription: django content types - how to get model class of content type to create a instance?

description: Django content types - how to get model class of content type to create a instance


code:
import xml.etree.ElementTree as ET
path = 'in.xml'
tree = ET.parse(path)
root = tree.getroot()
prev = None

def elements_equal(e1, e2):
    if type(e1) != type(e2):
        return False
    if e1.tag != e1.tag: return False
    if e1.text != e2.text: return False
    if e1.tail != e2.tail: return False
    if e1.attrib != e2.attrib: return False
    if len(e1) != len(e2): return False
    return all([elements_equal(c1, c2) for c1, c2 in zip(e1, e2)])

for page in root:                     # iterate over pages
    elems_to_remove = []
    for elem in page:
        if elements_equal(elem, prev):
            print("found duplicate: %s" % elem.text)   # equal function works well
            elems_to_remove.append(elem)
            continue
        prev = elem
    for elem_to_remove in elems_to_remove:
        page.remove(elem_to_remove)
tree.write("out.xml")

rawDescription: Check and remove duplicated children tags in XML


code: ' | '.join(new_line.split(','))

rawDescription: Writerows from python list - how can I remove brackets and apostrophes


code:
import Tkinter as TK

class smartstopkiosk_tk(TK.Tk):
    def __init__(self, parent):
        TK.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()
        #self.parent.title("Smartstop Kiosk")
        software = ('Microsoft', 'Abode', 'SAP', 'Lotus  Notes', 'Jive','Cisco', 'Chrome')
        hardware = ("Computer",  "Charger", " USB Headset", "Keyboard", "Mouse", "Webcam")
        microsoft = ("Outlook", "Lync", "Word", "Excel", "PowerPoint", "Visio", "Project", "Publisher")
        adobe = ("Adobe Reader", "Java", "Flash", "Adobe Pro")
        cisco = ('IP Communicator', '')
        wireless = ("MYLOW",  "Corporate", "Visitor", "MYLTW")
        printers  = ("2N", "2S", "3N", "3S", "4N",  "4S",  "5N", "5S")
        mobile =  ("Blackberry", "iPhone","iPad")
        AD  = ("Unlock", "Reset")
        LocalTemplate = ('User Assistance with Software', 'User Assistance with Hardware', 'Mobile Device Support', 'Software Installation Request', 'Hardware Request', 'Wireless Connection', 'Password Reset/Username Unlocked',
    'Add Printer')
        def getchoice2():
            print
            # use same method to find out which of the second list is chosen, and carry on.

        def getchoice():
            seltext = ''
            INDEX = Listbox1.curselection()
            if INDEX == ('0',) or INDEX == ('4',):
                seltext = software
            if INDEX == ('1',) or INDEX == ('5',):
                seltext = hardware
            if INDEX == ('2',):
                seltext = mobile
            if INDEX == ('3',):
                seltext = wireless
            if INDEX == ('6',):
                seltext = AD
            if INDEX == ('7',):
                seltext = printers
            selectchoice.config(command = getchoice2)
            for x in seltext:
                Listbox2.insert(TK.END, x)

        #creates font types
        font = ('Times New Roman', 14, 'bold')
        font2 = ('Times New Roman',12, 'bold')
        #Creates Instructions for Users
        stepOne = TK.LabelFrame(self, text=" 1. User Information: ", font = font2)
        stepOne.grid(row=0, columnspan=7, sticky='w', padx=5, pady=5, ipadx=5,   ipady=5)
        stepTwo = TK.LabelFrame(self, text="2. Select Program or Hardware Problems", font = font2)
        stepTwo.grid(row=3, columnspan=7, sticky='w', padx=5, pady=5, ipadx=5, ipady=5)
        stepThree = TK.LabelFrame(self, text="Please Enter the Problem or Your Request:", font = font2)
        stepThree.grid(row=6, columnspan=7, sticky='w', padx=5, pady=5, ipadx=5, ipady=5)
        #Creates Label for Users
        Label1 = TK.Label(stepOne, text = "First Name", font = font)
        Label1.grid(column = 2, row = 0, sticky = 'w', padx = (10, 10))
        Label2 = TK.Label(stepOne, text = "Last Name", font = font)
        Label2.grid(column = 4, row = 0, sticky = 'w', padx = (10, 10))
        Label3 = TK.Label(stepOne, text = "Mylan UserName", font = font)
        Label3.grid(column = 6, row = 0, sticky = 'w', padx = (10, 10))
        #Creates Entry Box for User input
        self.entry = TK.Entry(stepOne, width = 30)
        self.entry.grid(column = 2, row = 1,padx = (10, 10))
        entry2 = TK.Entry(stepOne, width = 30)
        entry2.grid(column = 4, row = 1,padx = (10, 10))
        entry3 = TK.Entry(stepOne, width = 30)
        entry3.grid(column = 6, row = 1, columnspan = 2, padx = (10, 10))
        #Creates User Input Box
        Usertext = TK.Text(stepThree, height = 10, width = 110, font = font)
        Usertext.grid(column = 2, row = 15, padx = (10, 10))
        #Creates List Boxes
        Listbox1 = TK.Listbox(stepTwo, selectmode = 'SINGLE', height = 10, width = 35, font   = font)
        Listbox1.grid(column = 2, row = 1, padx = (10, 10))
        for i in LocalTemplate:
            Listbox1.insert(TK.END, i)
        Listbox2 = TK.Listbox(stepTwo, selectmode = 'SINGLE', height = 10, width = 35, font = font)
        Listbox2.grid(column = 4, row = 1, padx = (10, 10))
        Listbox3 = TK.Listbox(stepTwo, selectmode = 'SINGLE', height = 10, width = 35, font = font)
        Listbox3.grid(column = 6, row = 1, padx = (10, 10))
        #Creates Buttons
        selectchoice = TK.Button(self, text = 'select my choice', font = font2, command = getchoice)
        selectchoice.grid(row = 5, column = 1, sticky = 'we', padx = (10, 10))
        Submit = TK.Button(self, text = 'Submit', font = font2)
        Submit.grid(column = 3, row = 10, sticky = 'we', padx = (10, 10))
        Startover = TK.Button(self, text = 'Cancel', font = font2)
        Startover.grid(column = 4, row = 10, sticky = 'we', padx = (10, 10))

def main():
    app = smartstopkiosk_tk(None)
    app.geometry("1300x768")
    app.mainloop()

if __name__ == "__main__":
    main()

rawDescription: How does one take a listbox selection and depending on that selection a second list box is created?

description: Take a listbox selection and depending on that selection a second list box is created


code:
import csv

#turn csv files into a list of lists
with open('train.csv','rU') as csvfile:
     reader = csv.reader(csvfile)
     csv_data = list(reader)

# Create two lists to handle the patients
# And two more lists to collect the 'sum' of the columns
# The one that needs to hold the sum 'must' have 0 so we
# can work with them more easily
iList = []
iList_sum = [0,0,0,0,0,0,0,0,0,0,0,0,0]

hList = []
hList_sum = [0,0,0,0,0,0,0,0,0,0,0,0,0]

# Only use one loop to make the process mega faster
for row in csv_data:
    # If row 13 is greater than 0, then place them as unhealthy
    if (row and int(row[13]) > 0):
        # This appends the whole 'line'/'row' for storing :)
        # That's what you want (instead of saving only one cell at a time)
        iList.append(row)

    # If it failed the initial condition (greater than 0), then row 13
    # is either less than or equal to 0. That's simply the logical outcome
    else:
        hList.append(row)

# Use these to verify the data and make sure we collected the right thing
# print iList
# [['67', '1', '4', '160', '286', '0', '2', '108', '1', '1.5', '2', '3', '3', '2'], ['67', '1', '4', '120', '229', '0', '2', '129', '1', '2.6', '2', '2', '7', '1']]
# print hList
# [['63', '1', '1', '145', '233', '1', '2', '150', '0', '2.3', '3', '0', '6', '0'], ['37', '1', '3', '130', '250', '0', '0', '187', '0', '3.5', '3', '0', '3', '0']]

# We can use list comprehension, but since this is a beginner task, let's go with basics:

# Loop through all the 'rows' of the ill patient
for ill_data in iList:

    # Loop through the data within each row, and sum them up
    for i in range(0,len(ill_data) - 1):
        iList_sum[i] += float(ill_data[i])

# Now repeat the process for healthy patient
# Loop through all the 'rows' of the healthy patient
for healthy_data in hList:

    # Loop through the data within each row, and sum them up
    for i in range(0,len(healthy_data) - 1):
        hList_sum[i] += float(ill_data[i])

# Using list comprehension, I basically go through each number
# In ill list (sum of all columns), and divide it by the lenght of iList that
# I found from the csv file. So, if there are 22 ill patients, then len(iList) will
# be 22. You can see that the whole thing is wrapped in brackets, so it would show
# as a python list

ill_avg = [ ill / len(iList) for ill in iList_sum]
hlt_avg = [ hlt / len(hList) for hlt in hList_sum]

# Do whatever....

rawDescription: CSV Python column/line averages

description: CSV Python column/line averages


code:
import random as rn

class Piece():

    def __init__(self):
        #vals = [top, right, bottom, left]
        self.vals = [rn.randint(10,99) for _ in range(4)]
        self.n = 4

    def rotate_left(self):
        self.vals = [self.vals[i-self.n+1] for i in range(self.n)]

    def rotate_right(self):
        self.vals = [self.vals[i-1] for i in range(self.n)]

    def get_vals(self):
        return self.vals

rawDescription: How can i print this in python using rows and cols?

description: Print this in python using rows and cols


code:
file = open("demo.txt","r")
text = file.read()

def find(info,text):
    match = re.findall(info + "+\w+\d+",text)
    if match:
        print(match)
    else:
        print("Not found!")

# This is how you call the function
find("whatever info is supposed to be",text)

rawDescription: python Regular expression

description: Python Regular expression


code:
import pylab as plt
import numpy as np

Z=np.array((range(1,30),range(31,60),range(61,90))).transpose()

X,Y=np.meshgrid(range(Z.shape[0]+1),range(Z.shape[1]+1))
im = plt.pcolormesh(X,Y,Z.transpose(), cmap='hot')
plt.colorbar(im, orientation='horizontal')
plt.show()

rawDescription: Plotting a 2D array with matplotlib.imshow


code:
a, b, c = 1, 2, 3
txt  = "[a,b,c]"
lst = eval(txt)
lst
type(lst)

rawDescription: Removing String from a list

description: Removing String from a list


code:
from bokeh.models.glyphs import  Text

text_glyph = Text(x="x", y="y", x_offset=10, text="foo")
text_renderer = plot.add_glyph(data_source, text_glyph)

rawDescription: Python Bokeh Stacked Bar Chart - How to display data label inside bars?


code:
import numpy as np
import matplotlib.pyplot as pp
val = 0. # this is the value where you want the data to appear on the y-axis.
ar = np.arange(10) # just as an example array
pp.plot(ar, np.zeros_like(ar) + val, 'x')
pp.show()

rawDescription: How to plot 1-d data at given y-value with pylab

description: Plot 1-d data at given y-value with pylab


code:
combo = gtk.combo_box_new_text()
combo.append_text('hello')
combo.append_text('world')
combo.set_active(0)

box = builder.get_object('some-box')
box.pack_start(combo, False, False)

rawDescription: How do I add items to a gtk.ComboBox created through glade at runtime?

description: Add items to a gtk.ComboBox created through glade at runtime


code:
class Widget(QtGui.QWidget):
    def __init__(self):
        super(Widget, self).__init__()
        self.resize(600,400)

        layout = QtGui.QVBoxLayout(self)
        self.table = QtGui.QTableWidget(20,10)
        self.vBar = self.table.verticalScrollBar()
        self._vBar_lastVal = self.vBar.value()

        layout.addWidget(self.table)

        self.vBar.valueChanged.connect(self.scrollbarChanged)

    def scrollbarChanged(self, val):
        bar = self.vBar
        minVal, maxVal = bar.minimum(), bar.maximum()
        avg = (minVal+maxVal)/2
        rowCount = self.table.rowCount()

        # scrolling down
        if val > self._vBar_lastVal and val >= avg:
            self.table.insertRow(rowCount)

        # scrolling up
        elif val < self._vBar_lastVal:
            lastRow = rowCount-1
            empty = True
            for col in xrange(self.table.columnCount()):
                item = self.table.item(lastRow, col)
                if item and item.text():
                    empty=False
                    break
            if empty:
                self.table.removeRow(lastRow)

        self._vBar_lastVal = val

rawDescription: Qt and PyQt tablewidget growing row count


code:
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,8))
ax1 = fig.add_axes([.25,.5,.5,.25])
ax2 = fig.add_axes([.25,.25,.5,.25])

ax1.set_xticklabels([])

# Important to render initial ytick labels
fig.show()
fig.canvas.draw()

# Remove the last ytick label
labels = [tick.get_text() for tick in ax2.get_yticklabels()]
ax2.set_yticklabels(labels[:-1])

# Refresh the canvas to reflect the change
fig.canvas.draw()

rawDescription: How to delete axis label for just one tick in matplotlib

description: Delete axis label for just one tick in matplotlib


code:
def funct(obj):
        import copy
        print('entro')
        return str(copy.deepcopy(obj))
class metacl(type):
        def __new__(meta,classname,supers,classdict):
                classdict['__xxx__'] = funct
                return type.__new__(meta,classname,supers,classdict)
class list(list,metaclass=metacl): pass

rawDescription: How to redefine the = in python?

description: Redefine the = in python


code:
def versioncmp(current, required):
    current = [int(i) for i in current.split('.')]
    required = [int(i) for i in required.split('.')]
    return current >= required

rawDescription: Comparing versions with Fabric

description: Comparing versions with Fabric


code:
import sys, json, time
import logging, datetime
import os

def saveCurrentTime(time):
    currentTimeFile = open(currentTimeFileName, 'w')
    currentTimeFile.write(str(timer))
    currentTimeFile.close()
    return

def checkActiveStatus():
    if os.path.exists(timerStopFileName):
        return 0
    else:
        return 1

now = datetime.datetime.now()
script_dir = os.path.dirname(__file__)

LOG_FILENAME = 'python/log/' + now.strftime("%Y-%m-%d") + '.log' #server config
#LOG_FILENAME = 'log/' + now.strftime("%Y-%m-%d") + '.log' #local test
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
logging.info(now.strftime("%H:%M:%S") + ' New Timer has been started')

timer = None
matchId = None
active = 1
currentTimeFileName = None
timerStopFileName = None
#timerStatusFileName = None

storageRelativePath = '/../../app/storage/timer/'
#storagePath = os.path.join(script_dir, storageRelativePath)
storagePath = script_dir + storageRelativePath

# active = getTimerStatus(matchId)

try:
    data = json.loads(sys.argv[1])
except:
    logging.exception('Can not retrieve arguments. Script will be terminated.')
    print("ERROR")
    sys.exit(1)

timer = data[0]
matchId = data[1]
logging.info(now.strftime("%H:%M:%S") + ' Created Timer [time: ' + str(timer) + ', match: ' + str(matchId) + ']')

currentTimeFileName = storagePath + str(matchId) + "timer"
timerStopFileName = storagePath + str(matchId) + "stop"
#timerStatusFileName = storagePath + str(matchId) + "status"

while timer and active:
    timer -= 1
    saveCurrentTime(timer)
    active = checkActiveStatus()
    time.sleep(1)

if active:
    print("Time out [ID:" + str(matchId) +"]")
    #call web service
else:
    if os.path.isfile(timerStopFileName):
        os.remove(timerStopFileName)
    elif os.path.isdir(timerStopFileName):
        os.rmdir(timerStopFileName)
    print("Timer has stopped, current value " + str(timer))
    #call web service

rawDescription: Launch and control a script written in Python in PHP application


code:
import csv

with open('text.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    rows = [[value.strip() for value in row] for row in reader]

    average_age_list = [float(row[0]) for row in rows]
    print ('average age: ' + str(sum(average_age_list) / float(len(average_age_list))))

    average_chol_list = [float(row[3]) for row in rows]
    print ('average chol: ' + str(sum(average_chol_list) / float(len(average_chol_list))))

    bp_list = [float(row[4]) for row in rows]
    print ('average age: ' + str(sum(bp_list) / float(len(bp_list))))

rawDescription: calculate multiple average from text python

description: Calculate multiple average from text python


code: # -*- coding: utf8 -*-

rawDescription: Unsupported characters in input

description: Unsupported characters in input


code:
df
del df.index.name
df

rawDescription: Remove index name in pandas

description: Remove index name in pandas


code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Path") #Path to your chrome profile
w = webdriver.Chrome(executable_path="C:\\Users\\chromedriver.exe", chrome_options=options)

rawDescription: How to load default profile in chrome using Python Selenium Webdriver?

description: Load default profile in chrome using Python Selenium Webdriver


code:
import daemon
import time

def do_something():
    while True:
        with open("/tmp/current_time.txt", "w") as f:
            f.write("The time is now " + time.ctime())
        time.sleep(5)

def run():
    with daemon.DaemonContext():
        do_something()

if __name__ == "__main__":
    run()

rawDescription: How can I write a non-stop crawler with python and run it on a server?

description: Write a non-stop crawler with python and run it on a server


code:
def get_queryset(self, *args, **kwargs):
    """
    Checks if currentuser = true is in the URL and filters this it.
    """
    queryset = super(FilterMixin, self).get_queryset(*args, **kwargs)

    currentuser = self.request.QUERY_PARAMS.get('currentuser')
    project = self.request.QUERY_PARAMS.get('project')

    if currentuser == "true":
        queryset = queryset.filter(user=self.request.user)

    if project:
        queryset = queryset.filter(project=project)

    return queryset

rawDescription: How to chain filters together using Django Rest Framework filters

description: Chain filters together using Django Rest Framework filters


code:
from scipy.ndimage import median_filter

filtered_array = median_filter(random_array, size=3)

rawDescription: How do I find and remove white specks from an image using SciPy/NumPy?

description: Find and remove white specks from an image using SciPy/NumPy


code:
def least_significant_digit_power(num_string):
    if '.' in num_string:
        # There's a decimal point. Figure out how many digits are to the right
        # of the decimal point and negate that.
        return -len(num_string.partition('.')[2])
    else:
        # No decimal point. Count trailing zeros.
        return len(num_string) - len(num_string.rstrip('0'))

rawDescription: In Python how to find the least significant digit


code:
import bisect

def closest(haystack, needle):
    if len(haystack) == 0: return None, None

    index = bisect.bisect_left(haystack, needle)
    if index == 0:
        return None, haystack[0]
    if index == len(haystack):
        return haystack[index], None
    if haystack[index] == needle:
        return haystack[index], haystack[index]
    return haystack[index-1], haystack[index]

rawDescription: Finding "closest" strings in a Python list (alphabetically)


code:
import pickle
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

_mimeType = 'application/x-standarditemmodeldatalist'

class Model(QStandardItemModel):
    def dropMimeData(
            self, data, action, row, column, parent):
        # Access parent before calling super implementation, because it may mutate parent
        dest_str = 'parent {}'.format(parent.data(Qt.DisplayRole)) if \
            parent.isValid() else 'root'

        ret_val = super().dropMimeData(data, action, row, column, parent)
        if action != Qt.MoveAction or not data.hasFormat(_mimeType):
            return ret_val

        item_data = pickle.loads(data.data(_mimeType))[0]
        print('Moving {} to {}'.format(item_data, dest_str))
        return True

    # Override in order to add custom MIME data
    def mimeData(self, indexes):
        mimeData = super().mimeData(indexes)
        data = [index.data(Qt.DisplayRole) for index in indexes]
        mimeData.setData(_mimeType, pickle.dumps(data))

        return mimeData

    # Override in order to announce our custom MIME type
    def mimeTypes(self):
        return super().mimeTypes() + [_mimeType]

def _create_item(text):
    item = QStandardItem(text)
    flags = Qt.ItemIsDragEnabled | Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsDropEnabled
    item.setFlags(flags)
    return item

model = Model()
model.appendRow([_create_item('Item 1')])
model.appendRow([_create_item('Item 2')])

app = QApplication([])
view = QTreeView()
view.setDragDropMode(view.InternalMove)
view.setModel(model)
view.show()
app.exec_()

rawDescription: How to detect that an item in a QStandardItemModel is dropped onto another?

description: Detect that an item in a QStandardItemModel is dropped onto another


code:
def includeme(config):
    from .models.user import User

    settings = config.get_settings()
    dbsession_factory = get_dbsession_factory(settings)
    config.add_request_method(
        lambda request: dbsession_factory(),
        'dbsession',
        reify=True)
    config.add_request_method(
        lambda request: User.get_by_username(
            request.dbsession,
            request.authenticated_userid),
        'user',
        reify=True)

def get_dbsession_factory(settings):
    engine = engine_from_config(settings, 'sqlalchemy.')
    dbsession_factory = sessionmaker()
    register(dbsession_factory)
    dbsession_factory.configure(bind=engine)
    return dbsession_factory

rawDescription: Get username information from a cookie in Pyramid (Python)


code:
from django.utils.translation import get_language
get_language()

rawDescription: Django 1.3 get_absolute_url and localeurl


code:
form_data = self.read(cr, uid, ids, ['start_date','end_date'], context=context)[0]

sql = """
    select
        i.date_invoice,
        i.number,
        (select name from res_partner where id=i.partner_id) as partner,
        i.currency_id,
        (select name from res_currency where id=i.currency_id) as currency,
        COALESCE((select description from account_tax where name=t.name), '') as description,
        t.amount,
        t.base,
        COALESCE((t.amount+t.base),0) as total
from
    account_invoice i, account_invoice_tax t
where
    t.invoice_id = i.id and
    i.state = 'open' and
    i.type = 'out_invoice' and
    i.date_invoice >= '%s'
    and i.date_invoice <= '%s'
order by t.name
"""%(form_data['start_date'],form_data['end_date'])

cr.execute(sql)
data = cr.dictfetchall()

rawDescription: Restrict To Return None Value from the SQL Query


code:
cmd = 'UPDATE SQLDATABASE SET ' + field + ' = %s WHERE file_name'\
      ' = %s AND slides_name = %s;'
cur.execute(cmd, (temp_list[y],filename,temp_list[0]))

rawDescription: Trouble passing in variable for column name in mySQLDB for python


code:
#!/usr/bin/python

import re, sys

pat_incomplete = re.compile(r'\\\s*$')
pat_indented = re.compile(r'^\t')

try:
    _, fname_in, fname_out = sys.argv
except ValueError:
    print("Usage: python line_joiner.py <input_filename> <output_filename>")
    sys.exit(1)

with open(fname_in) as in_f, open(fname_out, "w") as out_f:
    lines = iter(in_f)
    try:
        line = next(lines)
        s = pat_incomplete.sub('', line)
    except StopIteration:
        print("Input file did not contain any data")
        sys.exit(2)

    for line in lines:
        line = pat_incomplete.sub('', line)
        if pat_indented.match(line):
            s += pat_indented.sub('',line)
        else:
            out_f.write(s)
            s = line
    out_f.write(s)

rawDescription: Remove certain return characters from tab-separated values file


code:
def onListView1ListItemSelected(self, event):
    obj     = event.GetEventObject()
    index   = event.GetIndex()
    columns = obj.GetColumnCount()
    data    = []

    for i in range(columns):
        item = obj.GetItem(index, i)
        data.append(item.GetText())

    print(data)

rawDescription: How do you get the list data from a wxpyton gui click event?

description: Get the list data from a wxpyton gui click event


code:
import json
string = 'This sentence has some "quotes" in it\n'
json.dumps(string) #gives you '"This sentence has some \\"quotes\\" in it\\n"'

rawDescription: Replace all quotes in a string with escaped quotes?


code: [x > y for x, y in a]

rawDescription: Most "pythonic" way to check ordering of sub lists of a list?


code:
strrs="LIFE IS FULL"
strrs.split()

rawDescription: How to convert a string into a list in python

description: Convert a string into a list in python


code:
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    slug = db.Column(db.String(200), nullable=False)

    def __init__(self, name):
        self.name = name
        self.slug = slugify(name)

rawDescription: Automatically setting the value of a field based on another with SQLAlchemy


code:
q = session.query(Person)
q = q.filter(Person.building == g.current_building)
q = q.filter(~Person.groups.any())

rawDescription: Query to check if size of collection is 0 or empty in SQLAlchemy?


code:
def isPrime (n):                       ## we define a function
    primeList = [2, 3]                 ## 2 is the only even prime number
    i = 4
    while 3<i<n:                       # i is assigned to numbers 3 to n
        if i%2 == 1:                   # if odd do the following
            if i%3 != 0:
                primeList.append(i)    # add  to prime list
            else:
                i%2 == False

        i = i + 1                 # since i%2 == 0 we restart loop
    return primeList

rawDescription: Python Prime number wont return

description: Python Prime number wont return


code:
set(amino).isdisjoint(set(sequence))   # True if the sets have nothing in common
set(amino).intersection(set(sequence)) # a set of common elements

rawDescription: Checking presence of all elements of one iterable in the other without using loop in python


code:
lsta = ['a','b','c']
lstb = ['1','2','3','4']
lstc = ['x','y']
from itertools import product
["".join(t) for t in product(lsta, lstb, lstc)]

rawDescription: What's the fastest way to make string combinations out of lists in python?


code:
import mechanize

br = mechanize.Browser()
br.open("http://internal.aamaadmiparty.org/Directory/Format.aspx?master=blank")
br.select_form(nr=0)

br.form['ctl00$MainContent$txtname'] = 'Test Name'
# fill out other fields

req = br.submit()

rawDescription: Using Mechanize (Python) to fill form

description: Using Mechanize (Python) to fill form


code:
filename = input("Enter a filename: ")

try:
    # Access filename as a variable
    open(filename + ".txt", "w")
    print("Succesfully opened", filename,".txt")

# Catch the specific exception
except IOError:
    print("File cannot be found.")

rawDescription: Open a file with a variable

description: Open a file with a variable


code:
# identify the columns we want to aggregate by; this could
# equivalently be defined as list(df.columns[0:3])
group_cols = ['tracking_id', 'gene_id', 'gene_short_name']
# identify the columns which we want to average; this could
# equivalently be defined as list(df.columns[4:])
metric_cols = ['FPKM-1', 'FPKM-2']

# create a new DataFrame with a MultiIndex consisting of the group_cols
# and a column for the mean of each column in metric_cols
aggs = df.groupby(group_cols)[metric_cols].mean()
# remove the metric_cols from df because we are going to replace them
# with the means in aggs
df.drop(metric_cols, axis=1, inplace=True)
# dedupe to leave only one row with each combination of group_cols
# in df
df.drop_duplicates(subset=group_cols, keep='last', inplace=True)
# add the mean columns from aggs into df
df = df.merge(right=aggs, right_index=True, left_on=group_cols, how='right')

rawDescription: groupby and calculate mean but keeping all columns

description: Groupby and calculate mean but keeping all columns


code:
from subprocess import Popen, PIPE

p = Popen("/path/to/env.sh", stdin=PIPE)   # set environment, start new shell
p.communicate("python something.py\nexit") # pass commands to the opened shell

rawDescription: Using Python to open a shell environment, run a command and exit environment


rawDescription: Group array into array of tuples - odd length


code:
#!/usr/bin/env python3

tweet = "Some Tweet including Asimov #Example"

with open("so_textfile_reading.txt", "r") as infile:
    # be aware you are not using a standard minus (HYPHEN-MINUS)
    # in your file to separate the entries, but dashes (EN-DASH)
    entries = [line.strip().split(" – ") for line in infile]
    for author, book, link in entries:
        if (author in tweet) or (book in tweet):
            # Create reply here
            print(link)

rawDescription: Iterate over a text file having hyphenated three different fields on each line and return third field to a query matching the first two?


code:
import os
import msvcrt
import _winapi

CREATE_NEW                  = 1
CREATE_ALWAYS               = 2
OPEN_EXISTING               = 3
OPEN_ALWAYS                 = 4
TRUNCATE_EXISTING           = 5
FILE_SHARE_READ             = 0x00000001
FILE_SHARE_WRITE            = 0x00000002
FILE_SHARE_DELETE           = 0x00000004
FILE_SHARE_VALID_FLAGS      = 0x00000007
FILE_ATTRIBUTE_READONLY     = 0x00000001
FILE_ATTRIBUTE_NORMAL       = 0x00000080
FILE_ATTRIBUTE_TEMPORARY    = 0x00000100
FILE_FLAG_DELETE_ON_CLOSE   = 0x04000000
FILE_FLAG_SEQUENTIAL_SCAN   = 0x08000000
FILE_FLAG_RANDOM_ACCESS     = 0x10000000
GENERIC_READ                = 0x80000000
GENERIC_WRITE               = 0x40000000
DELETE                      = 0x00010000
NULL                        = 0

_ACCESS_MASK = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
_ACCESS_MAP  = {os.O_RDONLY : GENERIC_READ,
                os.O_WRONLY : GENERIC_WRITE,
                os.O_RDWR   : GENERIC_READ | GENERIC_WRITE}

_CREATE_MASK = os.O_CREAT | os.O_EXCL | os.O_TRUNC
_CREATE_MAP  = {0                                   : OPEN_EXISTING,
                os.O_EXCL                           : OPEN_EXISTING,
                os.O_CREAT                          : OPEN_ALWAYS,
                os.O_CREAT | os.O_EXCL              : CREATE_NEW,
                os.O_CREAT | os.O_TRUNC | os.O_EXCL : CREATE_NEW,
                os.O_TRUNC                          : TRUNCATE_EXISTING,
                os.O_TRUNC | os.O_EXCL              : TRUNCATE_EXISTING,
                os.O_CREAT | os.O_TRUNC             : CREATE_ALWAYS}

def os_open(file, flags, mode=0o777,
            *, share_flags=FILE_SHARE_VALID_FLAGS):
    '''
    Replacement for os.open() allowing moving or unlinking before closing
    '''
    if not isinstance(flags, int) and mode >= 0:
        raise ValueError('bad flags: %r' % flags)

    if not isinstance(mode, int) and mode >= 0:
        raise ValueError('bad mode: %r' % mode)

    if share_flags & ~FILE_SHARE_VALID_FLAGS:
        raise ValueError('bad share_flags: %r' % share_flags)

    access_flags = _ACCESS_MAP[flags & _ACCESS_MASK]
    create_flags = _CREATE_MAP[flags & _CREATE_MASK]
    attrib_flags = FILE_ATTRIBUTE_NORMAL

    if flags & os.O_CREAT and mode & ~0o444 == 0:
        attrib_flags = FILE_ATTRIBUTE_READONLY

    if flags & os.O_TEMPORARY:
        share_flags |= FILE_SHARE_DELETE
        attrib_flags |= FILE_FLAG_DELETE_ON_CLOSE
        access_flags |= DELETE

    if flags & os.O_SHORT_LIVED:
        attrib_flags |= FILE_ATTRIBUTE_TEMPORARY

    if flags & os.O_SEQUENTIAL:
        attrib_flags |= FILE_FLAG_SEQUENTIAL_SCAN

    if flags & os.O_RANDOM:
        attrib_flags |= FILE_FLAG_RANDOM_ACCESS

    h = _winapi.CreateFile(file, access_flags, share_flags, NULL,
                           create_flags, attrib_flags, NULL)
    return msvcrt.open_osfhandle(h, flags | os.O_NOINHERIT)

rawDescription: What share mode is used when files are opened using open()


code:
from ast import literal_eval
lis = [u'[7,6,5,4,3, 1]', u'[4, 5, 6]']
map(literal_eval, lis)
[literal_eval(x) for x in lis]

rawDescription: Convert list of unicode list in list

description: Convert list of unicode list in list


code:
numbers = input("Enter numbers seperated by spaces:-") # i.e. '1 2 3 3 2 2 2 1 3 4 5 3'
my_list = list(map(int, numbers.strip().split(' ')))
count = {}
for x in set(my_list):
    count[x] = my_list.count(x)

for key, value in count.items():
    if value == 1:
        print('{} occurs one time'.format(key))
    else:
        print('{} occurs {} times'.format(key, value))

rawDescription: Counting occurences of number in a list separated by spaces using dictionaries


code:
class MovieSerializer(serializers.ModelSerializer):
    trailer = serializers.SerializerMethodField()

    class Meta:
        model = Movie
        fields = ('trailer',)

    def get_trailer(self, obj):
        trailers = []

        for trailer in obj.trailer_set.all():
            trailers.append(trailer.trailerurl)

        return trailers

rawDescription: django restful-framework display format

description: Django restful-framework display format


code:
from celery import Celery
app = Celery(...)

process_order = app.signature('your-other-project.tasks.process_order')
result = process_order.delay(order_id)  # standard calling api works
print(result.get())

rawDescription: How can i use celery with different code base in API and workers

description: Use celery with different code base in API and workers


code:
import sys
sys.path.insert(0,"/home/optimi/bzffourn/ZIB/python_scripts/pyMathProg/picos")
import picos.constraint

rawDescription: Specify the developement version of a python module


rawDescription: round() in Python doesn't seem to be rounding properly

description: Round() in Python doesn't seem to be rounding properly


code:
class Test(object):
    test = {}

class Test2(Test):
    pass

id(Test.test)
id(Test2.test)
Test.test.update({1:2})
Test2.test
Test2.test = {}
id(Test2.test)
Test.test
Test2.test
del Test2.test
Test2.test

rawDescription: Updating a dict attrib from an extended class updates the base class. Why?


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''

This is a column

More columns heh

''')
soup.find_all(class_='column')
import bs4
bs4.__version__

rawDescription: beautifulsoup find_all() class shortcut doesn't work

description: Beautifulsoup find_all() class shortcut doesn't work


code:
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
import datetime

# number slices of pie
num = 10

# generate some labels
dates = [datetime.datetime(2014,1,1) + datetime.timedelta(days=np.random.randint(1,20)) for i in range(num)]
labels = [d.strftime('%d-%m-%Y') for d in dates]

# generate some values
values = np.random.randint(2,10, num)

# force half of them to be zero
mask = np.random.choice(num, num // 2, replace=False)
values[mask] = 0

# pick some colors
colors = plt.cm.Blues(np.linspace(0,1,num))

fig, ax = plt.subplots(figsize=(9.0, 6.10), subplot_kw={'aspect': 1})
wedges, labels, pcts = ax.pie(values, colors=colors, labels=labels, autopct='%1.1f%%')

# find duplicate labels and the amount of duplicates
c = Counter([l.get_position() for l in labels])
dups = {key: val for key, val in c.items() if val > 1}

# degrees of spacing between duplicate labels
offset = np.deg2rad(3.)

# loop over any duplicate 'position'
for pos, n in dups.items():

    # select all labels with that position
    dup_labels = [l for l in labels if l.get_position() == pos]

    # calculate the angle with respect to the center of the pie
    theta = np.arctan2(pos[1], pos[0])

    # get the offsets
    offsets = np.linspace(-(n-1) * offset, (n-1) * offset, n)

    # loop over the duplicate labels
    for l, off in zip(dup_labels, offsets):

        lbl_radius = 1.3

        # calculate the new label positions
        newx = lbl_radius * np.cos(theta + off)
        newy = lbl_radius * np.sin(theta + off)

        l.set_position((newx, newy))

        # rotate the label
        rot = np.rad2deg(theta + off)

        # adjust the rotation so its
        # never upside-down
        if rot > 90:
            rot += 180
        elif rot < -90:
            rot += 180

        # rotate and highlight the adjusted labels
        l.set_rotation(rot)
        l.set_ha('center')
        l.set_color('#aa0000')

rawDescription: Pie chart labels are overlapping for same values.


rawDescription: Pandas: How to check whether the first "n" elements of a string contain a substring?


code:
@blueprint.route("/interview/", methods=['GET'])
@blueprint.route("/interview/<int:question_id>", methods=['POST'])
def interview(question_id=None):
    ...
    question=Question.query.get(question_id)
    ...

rawDescription: flask-sqlalchemy stores unintended variables into database

description: Flask-sqlalchemy stores unintended variables into database


code:
self.shutdown_item.connect("activate",self.shutdown)
self.shutdown_item.connect("activate",self.sensitiveshutdown)

def sensitiveshutdown(self, widget):
    self.shutdown_item.set_sensitive(False)
    gobject.timeout_add(5000, self.reviveShutDown)

def reviveShutDown(self):
    self.shutdown_item.set_sensitive(True)
    return False

rawDescription: How can I first set a MenuItem sensitive and then insensitive again? Python GTK

description: First set a MenuItem sensitive and then insensitive again? Python GTK


code:
def run_commands(func, path):
    return subprocess.call(HDFS + func + path, shell = True)

rawDescription: how to store return value and NOT command call status using python script?

description: Store return value and NOT command call status using python script


rawDescription: Convert Pandas dataframe to Sparse Numpy Matrix directly


code:
import argparse
import os
import tempfile
import shutil
import atexit

class readable_dir(argparse.Action):
    def __call__(self,parser, namespace, values, option_string=None):
        prospective_dir=values
        if not os.path.isdir(prospective_dir):
            raise argparse.ArgumentTypeError("readable_dir:{0} is not a valid path".format(prospective_dir))
        if os.access(prospective_dir, os.R_OK):
            setattr(namespace,self.dest,prospective_dir)
        else:
            raise argparse.ArgumentTypeError("readable_dir:{0} is not a readable dir".format(prospective_dir))

ldir = tempfile.mkdtemp()
atexit.register(lambda dir=ldir: shutil.rmtree(ldir))

parser = argparse.ArgumentParser(description='test', fromfile_prefix_chars="@")
parser.add_argument('-l', '--launch_directory', action=readable_dir, default=ldir)
args = parser.parse_args()
print (args)

rawDescription: directory path types with argparse

description: Directory path types with argparse


code:
from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = "My hello app",
    ext_modules = cythonize("src/*.pyx",
                            compiler_directives={'profile': True})
)

rawDescription: Enable Cython profiling for whole program?


code:
def meets_sensorname_criteria(sensorname):
    max_len = 10
    restricted_chars = ('@', '!', '?')
    return (len(sensorname) < max_len
            and not any((char in sensorname) for char in restricted_chars))

def change_sensor_name():
    new_sensorname = tkSimpleDialog.askstring("Sensorname", "Please input the new sensorname")
    while not meets_sensorname_criteria(new_sensorname):
        # Some warning alert here to explain expected input might be good
        new_sensorname = tkSimpleDialog.askstring("Sensorname", "Please input the new sensorname")

rawDescription: python 27 input string using tkSimpleDialog

description: Python 27 input string using tkSimpleDialog


rawDescription: How do you create a date range spanning multiple days with only some intra-day values in pandas?

description: Create a date range spanning multiple days with only some intra-day values in pandas


code:
def input_max3():
    return max(int(input()) for i in range(3))

rawDescription: Python Function that returns greatest integer


code:
class UserForm(ModelForm):
    first_name = forms.CharField(label='Vorname')
    # ...

    class Meta:
        model = User
        fields = ["first_name", "last_name", "username", "email", "password"]

rawDescription: django user model - override labels in model form

description: Django user model - override labels in model form


code:
df
df.index
df.index.names
df.groupby(level=['ch', 'time']).mean()

rawDescription: How to apply condition on level of pandas.multiindex?

description: Apply condition on level of pandas.multiindex


code:
df = pd.DataFrame(np.random.randint(0, 10, (5,5)), columns=["Col{}".format(i) for i in range(1,6)])
df
col_names = ["Col1", "Col5"]
df[col_names]
df["Total"] = df[col_names].sum(axis=1)
df

rawDescription: How to sum up values in specific columns

description: Sum up values in specific columns


rawDescription: How can I get a column from a 2D python array?

description: Get a column from a 2D python array


code:
dr = pd.date_range('2014', periods=5)
hours = pd.Index(np.arange(5))
pd.DatetimeIndex(dr.values + hours.values * pd.offsets.Hour(1).nanos)

rawDescription: How to combine dates and hours column into one index column in a pandas series?

description: Combine dates and hours column into one index column in a pandas series


code:
while i < len(phipsi):
    if phipsi[i][0]>a and phipsi[i][0]<b:
        if phipsi[i][1]>c and phipsi[i][1]<d:
            print ('the couple [%+.2f, %+.2f] has his angles in helix' % (phipsi[i][0], phipsi[i][1]))
    else:
        print ('the couple [%+.2f, %+.2f] does not have his angles in helix' % (phipsi[i][0], phipsi[i][1]))
    i=i+1

rawDescription: Have a sentence printed in Python without ' or ", using the print function


code:
# Had to do this stuff in a try-finally, since some testing
# went a little wrong.....
try:
    # Set the following two lines to your creds and server
    M = imaplib2.IMAP4_SSL("imap.gmail.com")
    M.login(USER, PASSWORD)
    # We need to get out of the AUTH state, so we just select
    # the INBOX.
    M.select("INBOX")
    numUnseen = getUnseen()
    sendPushNotification(numUnseen)

    #print M.status("INBOX", '(UNSEEN)')
    # Start the Idler thread
    idler = Idler(M)
    idler.start()

    # Sleep forever, one minute at a time
    while True:
        time.sleep(60)

finally:
    # Clean up.
    idler.stop()
    idler.join()
    M.close()
    # This is important!
    M.logout()

rawDescription: Changes to a Gmail notification script

description: Changes to a Gmail notification script


code: import import_my_lib

rawDescription: Python: Best way to add to sys.path relative to the current running script


code:
def move (l, from_, to = 2):
    return l.insert (to, l.pop (from_) )

rawDescription: How to move an item in a list two units down

description: Move an item in a list two units down


code:
import Image
# get an image that is greyscale with alpha
i = Image.open('hsvwheel.png').convert('LA')
# get the two bands
L,A = i.split()
# a fully saturated band
S, = Image.new('L', i.size, 255).split()
# re-combine the bands
# this keeps tha alpha channel in the new image
i2 = Image.merge('RGBA', (S,L,L,A))
# save
i2.save('test.png')

rawDescription: PIL Converting an image's hue, then saving out in Python


code:
fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f")
fulldate = fulldate + datetime.timedelta(milliseconds=500)

rawDescription: How can I add N milliseconds to a datetime in Python

description: Add N milliseconds to a datetime in Python


code:
from UserList import UserList

class Alist(UserList):
    def __init__(self, iterable, copy=True):
        if copy:
            super(Alist, self).__init__(iterable)

        else:
            self.data = iterable

    def plot_me(self):
        pass

rawDescription: using __class__ to change python class, Heap Error

description: Using __class__ to change python class, Heap Error


code:
from scrapy.http import Request

class YourSpider(BaseSpider):
    # ...spider init details...
    def parse(self, response):
        # ...process item...
        yield item
        yield Request(response.url, callback=self.parse)

rawDescription: How to scrape the same url in loop with Scrapy

description: Scrape the same url in loop with Scrapy


rawDescription: Extracting row from matrix in Python and use that row as a color in Matplotlib


code:
access_token = facebook.get_app_access_token(APP_ID, APP_SECRET)
graph = facebook.GraphAPI(access_token)
request = graph.get_object("%s_%s" % (request_id, recipient_id))
inviter_id = request["from"]["id"]

rawDescription: Facebook API: How to get the inviterID through requestID?


code:
class Heater(object):
    def __init__(self, agent):
        self.agent = agent
    # define other methods for interaction with Heater application
    # in which you can access agent methods like self.agent.a_method(...)

rawDescription: Python double inheritance

description: Python double inheritance


code:
from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^dashboard/', login_required(TemplateView.as_view(template_name="dashboard.html"))),
)

rawDescription: "No module named simple" login_required depreciated


code:
def copy_with_prog(src, dest, callback = None):
    while True:
        # copy loop stuff
        if callback:
            callback(pos, total)

prog = ProgressBar(...)
copy_with_prog(src, dest, lambda pos, total: prog.update(pos, total))

rawDescription: How to copy a file in Python with a progress bar?

description: Copy a file in Python with a progress bar


code:
import xml.dom.minidom
s = "<example>4 < 5</example>"
x = xml.dom.minidom.parseString(s)
x.firstChild.firstChild.toxml()

rawDescription: Python: Stopping miniDOM from expanding escape sequences


code:
[logger_submodule]
level = INFO
handlers = submodulelog
qualname = myapp.lib.submodule
propagate=0

rawDescription: Python logging hijack sub-module logs to another file (Pylons)


rawDescription: how to compare strftime values

description: Compare strftime values


code:
x1 = float(raw_input("x1: "))
y1 = float(raw_input("y1: "))
x2 = float(raw_input("x2: "))
y2 = float(raw_input("y2: "))

rawDescription: How do I do simple user input in python?

description: Do simple user input in python


code:
try:
    answer = raw_input('Control-C to exit, <ENTER> to play again: ')
    if len(answer) > 0:
        raise(ValueError('Unexpected input'))
    else:
        continue
except (KeyboardInterrupt, ValueError):
    sys.exit(0)

rawDescription: How to capture the enter key in Python without Tkinter

description: Capture the enter key in Python without Tkinter


rawDescription: dot product of two 1D vectors in numpy

description: Dot product of two 1D vectors in numpy


code:
multiple = df.groupby(["dateuse", "station"])["variable1"].transform(len) > 1
must_be_isolated = df["variable1"] == "yyy"
df[~(multiple & must_be_isolated)]

rawDescription: Python Pandas check if a value occurs more then once in the same day


code:
import sys
from PIL import Image, ImageDraw

class Region():
    def __init__(self, x, y):
        self._pixels = [(x, y)]
        self._min_x = x
        self._max_x = x
        self._min_y = y
        self._max_y = y

    def add(self, x, y):
        self._pixels.append((x, y))
        self._min_x = min(self._min_x, x)
        self._max_x = max(self._max_x, x)
        self._min_y = min(self._min_y, y)
        self._max_y = max(self._max_y, y)

    def box(self):
        return [(self._min_x, self._min_y), (self._max_x, self._max_y)]

def find_regions(im):
    width, height  = im.size
    regions = {}
    pixel_region = [[0 for y in range(height)] for x in range(width)]
    equivalences = {}
    n_regions = 0
    #first pass. find regions.
    for x in xrange(width):
        for y in xrange(height):
            #look for a black pixel
            if im.getpixel((x, y)) == (0, 0, 0, 255): #BLACK
                # get the region number from north or west
                # or create new region
                region_n = pixel_region[x-1][y] if x > 0 else 0
                region_w = pixel_region[x][y-1] if y > 0 else 0

                max_region = max(region_n, region_w)

                if max_region > 0:
                    #a neighbour already has a region
                    #new region is the smallest > 0
                    new_region = min(filter(lambda i: i > 0, (region_n, region_w)))
                    #update equivalences
                    if max_region > new_region:
                        if max_region in equivalences:
                            equivalences[max_region].add(new_region)
                        else:
                            equivalences[max_region] = set((new_region, ))
                else:
                    n_regions += 1
                    new_region = n_regions

                pixel_region[x][y] = new_region

    #Scan image again, assigning all equivalent regions the same region value.
    for x in xrange(width):
        for y in xrange(height):
                r = pixel_region[x][y]
                if r > 0:
                    while r in equivalences:
                        r = min(equivalences[r])

                    if not r in regions:
                        regions[r] = Region(x, y)
                    else:
                        regions[r].add(x, y)

    return list(regions.itervalues())

def main():
    im = Image.open(r"c:\users\personal\py\ocr\test.png")
    regions = find_regions(im)
    draw = ImageDraw.Draw(im)
    for r in regions:
        draw.rectangle(r.box(), outline=(255, 0, 0))
    del draw
    #im.show()
    output = file("output.png", "wb")
    im.save(output)
    output.close()

if __name__ == "__main__":
    main()

rawDescription: My own OCR-program in Python

description: My own OCR-program in Python


code:
class System:
    def signUp(self, user_name):
        user = User(user_name)
        user.comment = Comment()
        user.tag = Tag()
        ...

rawDescription: Creating Multiple objects once user sign-up (Social Network using OOP)


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        for column in range(columns):
            for row in range(rows):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                if row % 2:
                    item.setFlags(QtCore.Qt.ItemIsUserCheckable |
                                  QtCore.Qt.ItemIsEnabled)
                    item.setCheckState(QtCore.Qt.Unchecked)
                self.table.setItem(row, column, item)
        self.table.itemClicked.connect(self.handleItemClicked)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self._list = []

    def handleItemClicked(self, item):
        if item.checkState() == QtCore.Qt.Checked:
            print('"%s" Checked' % item.text())
            self._list.append(item.row())
            print(self._list)
        else:
            print('"%s" Clicked' % item.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(6, 3)
    window.resize(350, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt : Checkbox in QTableWidget

description: PyQt : Checkbox in QTableWidget


code:
import sys

class VirtualModule(object):
    def __init__(self, name):
        self.__name__ = name.rsplit('.', 1)[-1]
        self.__package__ = name
        self.__loader__ = None

    def __getattr__(self, name):
        if name is valid:
            # Return dynamic classes here
            return VirtualClass(name)

        raise AttributeError(name)

virtual_module_name = 'myproject.myfactory.virtualmodule'
sys.modules[virtual_module_name] = VirtualModule(virtual_module_name)

rawDescription: Can I build an automatic class-factory that works on import?

description: Build an automatic class-factory that works on import


code: return bool(the_str)

rawDescription: How to evaluate string as boolean in return statement?

description: Evaluate string as boolean in return statement


code:
import zmq

if __name__=='__main__':
    context = zmq.Context()
    socket = context.socket(zmq.ROUTER)       # Changed
    socket.setsockopt(zmq.IDENTITY, "R1")
    socket.connect("tcp://127.0.0.1:6660")
    while True:
        print("Wating for request...")

        me = socket.recv()       # New
        empty = socket.recv()    # New
        toAddr = socket.recv()
        empty = socket.recv()
        req = socket.recv()
        print("%s received!" % str(req))

        socket.send(me, zmq.SNDMORE)       # New
        socket.send(empty, zmq.SNDMORE)    # New
        socket.send(toAddr, zmq.SNDMORE)
        socket.send(empty, zmq.SNDMORE)
        socket.send("Reply to %s" % str(req))

rawDescription: ZeroMQ ROUTER socket can not send message to REP socket


code:
import ast

with open(filename) as f:
    tree = ast.parse(f.read())
    sum(isinstance(exp, ast.FunctionDef) for exp in tree.body)

rawDescription: Good way to count number of functions of a python file, given path


code: plt.title('Effect of RARa overexpression on Cyp26A1 dose-response curve',fontsize=15, y=1.5) # Change y value accordinly

rawDescription: How to remove top value of y-axis only from Python's Matplotlib figure?

description: Remove top value of y-axis only from Python's Matplotlib figure


code:
def resview(request):
    if request.method == "POST":
        upload_resume = request.FILES['upload_resume']
        file_header = request.POST.get('resume_header')
        fname = request.POST.get('fname')

        if upload_resume and file_header:
            details, _ = resmodel.objects.get_or_create(user=request.user, fname=fname)
            if not details.file1:
                details.file1 = upload_resume
                details.file_header1 = file_header
            elif not details.file2:
                details.file2 = upload_resume
                details.file_header2 = file_header
            elif not details.file3:
                details.file3 = upload_resume
                details.file_header3 = file_header
            elif not details.file4:
                details.file4 = upload_resume
                details.file_header4 = file_header
            details.save()

        return HttpResponseRedirect('/profile/save/success/')
    else:
        return render_to_response('resume.html')

rawDescription: django condition for adding multiple files

description: Django condition for adding multiple files


rawDescription: List comprehension for flatteing values from dicts from list


code:
import pandas as pd
import numpy as np
d = {'A' : pd.Series([1, 0, 2, 9],),
     'B' : pd.Series([0, float("nan"), float("nan"), float("nan")])}

df = pd.DataFrame(d)
for i in range(1,len(df.A)):
    df.B[i] = df.B[0] + np.sum(df.A[:i])
df

rawDescription: Python Pandas: How to make a column row dependent on it's previous rows, possibly with a function?


rawDescription: Calculate an incremental mean using python pandas


code: next(s for s in list_of_string if s)

rawDescription: Get first non-empty string from a list in python


code:
import ast
astr="{'key1':'value1','key2':'value2'}"
ast.literal_eval(astr)

rawDescription: parsing string to a dict

description: Parsing string to a dict


code:
from num2words import num2words
num2words(1e25)
num2words(10000000000000000000000000)

rawDescription: Verbally format a number in Python

description: Verbally format a number in Python


code:
limit = int(input("enter upper limit for perfect number search: "))

n = 1

while n <= limit:

    sum = 0
    divisor = 1
    while divisor < n:
        if not n % divisor:
            sum += divisor
        divisor = divisor + 1
    if sum == n:
        print(n, "is a perfect number")
    n = n + 1

rawDescription: Python Perfect Numbers

description: Python Perfect Numbers


code:
import sys
import tempfile
import subprocess

def example(output):
    r""" Do something ...

    >>> output = example('Processing file ...')
    >>> print output # doctest:+ELLIPSIS
    'Processing file ...'

    Check how many file was processed.
    >>> [line.startswith('Processing file')
    ... for line in output.splitlines()].count(True)
    1

    """
    cmd = "print '%s'" % (output, )
    with tempfile.TemporaryFile() as output:
        subprocess.check_call([sys.executable, '-c', cmd], stdout=output)
        output.seek(0)
        res = output.read()

    return res

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: How can I check with doctest that a program produced certain output?

description: Check with doctest that a program produced certain output


code:
def toInt(arr, idx):
    res = 0
    for i in xrange(4):
      res |= (arr[idx*4 + i] << 8*i)
    return res

'%08x' % toInt(char_array, 0)
'%08x' % toInt(char_array, 1)

rawDescription: Typecasting or accessing char array to integer array in Python


code:
import operator
ops = {'<=': operator.le, '>=': operator.ge}

In [3]: ops['>='](2, 1)
Out[3]: True

rawDescription: Python perform operation in string

description: Python perform operation in string


code:
my_regex = re.compile("<this is where the magic (doesn't)? happen(s)?>")

@pytest.mark.parametrize('test_str', [
    "an easy test that I'm sure will pass",
    "a few things that may trip me up",
    "a really pathological, contrived example",
    "something from the real world?",
])
def test_my_regex(test_str):
     assert my_regex.match(test_str) is not None

rawDescription: Testing regexes in Python using py.test

description: Testing regexes in Python using py.test


code:
import itertools
a = [[1,2,3],[4,5,6],[7,8,9,10]]
list(itertools.product(*a))

rawDescription: All combinations of a list of lists

description: All combinations of a list of lists


code:
from collections import Counter

with open ('input.txt') as f:
    for idx, line in enumerate(f):
        if line != '\n':
            counter = Counter(line.lower())
            counter.subtract('aardvark')
            if min(counter.values()) >= 0:
                print('Aardvark on line %d' % (idx + 1))

rawDescription: Checking if letters in a line can make up a word


code:
import xlrd
import xlwt
from xlutils.copy import copy
import os.path
rb = xlrd.open_workbook('my_workbook.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0)
wb = copy(rb)
sheet = wb.get_sheet(0)
sheet.write(5,2,"string")
wb.save('my_workbook.xls')

rawDescription: AttributeError: 'Sheet' object has no attribute 'write'


code:
from os import path
from glob import glob
pd.to_datetime([path.getmtime(fn) for fn in glob("*.*")], unit="s")

rawDescription: Write date modified to file name .csv or to column in .csv file


code:
#!/usr/bin/env python3

import click

@click.group()
def cli():
    pass

@cli.command('import')
def my_import_func():
    click.echo("Importing")

if __name__ == '__main__':
    cli()

rawDescription: How can I define a function called "import" in Python?

description: Define a function called "import" in Python


code:
import ast
s = u"[u'38', u'36', u'34', u'32']"
[ item.encode('ascii') for item in ast.literal_eval(s) ]

rawDescription: Unicode - String - list Manipulation

description: Unicode - String - list Manipulation


rawDescription: Efficiently construct Pandas DataFrame from large list of tuples/rows


code: large_string = re.sub('\[year\](.*?)\[fullname\]', str(year) + '\g<1>' + name, large_string)

rawDescription: Python multiple regex matching in a single statement


code:
import cgi
escaped = cgi.escape(unescaped)

rawDescription: Converting to and from '<' and '>' automatically with Python


code:
import wx

class TransparentAwareFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.transparency = 255

    def SetTransparent(self, value):
        self.transparency = value
        wx.Frame.SetTransparent(self, value)

    def GetTransparent(self):
        return self.transparency

class MainWindow(TransparentAwareFrame):
    def __init__(self, *args, **kwargs):
        TransparentAwareFrame.__init__(self, *args, **kwargs)
        self.button = wx.Button(self, label="Click me!")
        self.Show()
        self.button.Bind(wx.EVT_BUTTON, self.onButton)

    def onButton(self, e):
        self.SetTransparent(self.GetTransparent() - 20)

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Getting a Windows Transparency wxPython

description: Getting a Windows Transparency wxPython


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import itertools

fig, ax = plt.subplots()
button = Button(ax, 'Click me!')

colors = itertools.cycle(['red', 'green', 'blue'])

def change_color(event):
    button.color = next(colors)
    # If you want the button's color to change as soon as it's clicked, you'll
    # need to set the hovercolor, as well, as the mouse is still over it
    button.hovercolor = button.color
    fig.canvas.draw()

button.on_clicked(change_color)

plt.show()

rawDescription: Change matplotlib Button color when pressed


code:
import email.utils
map(email.utils.parseaddr, email_list)

rawDescription: In Python, identify parts of an e-mail address


code:
import cloud
import cPickle as pickle

# to write
cloud.bucket.putf(pickle.dumps(P), 'p.csv')

# to read
obj = pickle.loads(cloud.bucket.getf('p.csv').read())

rawDescription: How to output a Numpy array to a file object for Picloud

description: Output a Numpy array to a file object for Picloud


code:
edge_list = []
delete_these = []
for point, edges in edges_per_point.items():
    edge_list.append(edges.pop(0))
    if edges:
        edges_per_point[point] = edges
    else:
        delete_these.append(point)

for point in delete_these:
    del edges_per_point[point]

rawDescription: Removing item from dictionary of lists

description: Removing item from dictionary of lists


code:
import math
epsilon = 0.1**5
(math.fabs((0.1 * 0.1) - 0.01) < epsilon)

rawDescription: odds with floating computations

description: Odds with floating computations


code:
frame.set_index(['date', 'mat', 'strike'])
df.capvol.unstack('mat')

rawDescription: Duplicate entries for index in pandas pivot function


code:
text = "Studies have shown that...[^title=Fish consumption and incidence of stroke: a meta-analysis of cohort studies]... Another experiment demonstrated that... [^title=The second title]"
re.findall(r"\[\^title=(.*?)\]", text)

rawDescription: Regular expression to return all characters between two strings


code:
import networkx as nx
data=[[1, 5, 6], [2, 3, 5, 6], [2, 5], [7]]
G = nx.DiGraph()
for path in data:
    G.add_nodes_from(path)
    G.add_path(path)
ts=nx.topological_sort(G)
print(ts)
# [7, 2, 3, 1, 5, 6]

rawDescription: Python topological sort using lists indicating edges


code:
from xmlrpclib import dumps, loads
s = '\x3a\x0d\x0a'
e = dumps((s,)) # Just a tuple
e
loads(e)

rawDescription: Allowing any ASCII character transmitted in string with xmlrpc


code:
display_list = []

with open('closeparams.txt') as data_file:
   for line in data_file:
      display_list.append(line.strip().split(';'))

print(display_list[0][3]) # [i][j]

rawDescription: python csv text file to array[i,j]

description: Python csv text file to array[i,j]


code: [filter(lambda x: x != '', y) for y in a]

rawDescription: python remove several identical list elements by value

description: Python remove several identical list elements by value


code:
from sys import stdout

from twisted.web.xmlrpc import Proxy
from twisted.internet import reactor
from twisted.python.log import startLogging

startLogging(stdout)

p = Proxy('http://localhost:8080/RPC2')
class QuietQueryFactory(p.queryFactory):
    noisy = False

p.queryFactory = QuietQueryFactory
p.callRemote('echo', 'foo')

reactor.run()

rawDescription: Twisted: how to silence certain log messages?


code:
class Country:
    def __init__(self, population, literacy, firms, area, populationDensity):
        (self.population, self.literacy, self.firms, self.area, self.populationDensity) = (population, literacy, firms, area, populationDensity)

rawDescription: Can one make Python constructors more concise?


rawDescription: python regex simple help - dealing with parentheses

description: Python regex simple help - dealing with parentheses


code:
result = dbsession.query(Shares.price, \
                            func.sum(Shares.quantity).label("Total sold")) \
                            .filter(Shares.company== 'Google') \
                            .group_by(Shares.price).all()

rawDescription: Using alias() for 'select as' in SQLAlchemy


code:
class Throw(object): pass
throw = Throw() # easy sentinel hack
def next(iterator, default=throw):
  """next(iterator[, default])

  Return the next item from the iterator. If default is given
  and the iterator is exhausted, it is returned instead of
  raising StopIteration.
  """
  try:
    iternext = iterator.next.__call__
    # this way an AttributeError while executing next() isn't hidden
    # (2.6 does this too)
  except AttributeError:
    raise TypeError("%s object is not an iterator" % type(iterator).__name__)
  try:
    return iternext()
  except StopIteration:
    if default is throw:
      raise
    return default

rawDescription: def next() for Python pre-2.6? (instead of object.next method)

description: Def next() for Python pre-2.6? (instead of object.next method)


code:
# Can be used to add default HTML code (e.g. default header section with CSS).
htmlTemplate = """
<html>
<head>
<link rel="stylesheet" type="text/css" charset="utf-8" media="screen" href="http://paste.ubuntu.com/static/pastebin.css">
</head>
<body>
%s
</body>
</html>
"""

rawDescription: Markdown preview Python-based plugin for gedit


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox

# make figure + Axes
fig, ax = plt.subplots()

# make initial bounding box
bbox0 = Bbox.from_bounds(0, 0, 1, 1)
# use the `ax.transData` transform to tell the bounding box we have given
# it position + size in data.  If you want to specify in Axes fraction
# use ax.transAxes
bbox = TransformedBbox(bbox0, ax.transData)
# make image Artist
bbox_image = BboxImage(bbox,
                       cmap=plt.get_cmap('winter'),
                       norm=None,
                       origin=None,
                       **kwargs
                       )
# shove in some data
a = np.arange(256).reshape(1, 256)/256.

bbox_image.set_data(a)
# add the Artist to the Axes
ax.add_artist(bbox_image)
# set limits
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

# loop over new positions
for j in range(50):
    x = j % 10
    y = j // 10
    # make a new bounding box
    bbox0 = Bbox.from_bounds(x, y, 1, 1)
    bbox = TransformedBbox(bbox0, ax.transData)
    bbox_image.bbox = bbox
    # re-draw the plot
    plt.draw()
    # pause so the gui can catch up
    plt.pause(.1)

rawDescription: manipulating and animating an image on a matplotlib plot

description: Manipulating and animating an image on a matplotlib plot


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib.ticker import FormatStrFormatter, MultipleLocator

yearvec = [2002, 2003, 2004, 2005]
plt.close('all')
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlim3d(0, 250)
ax.set_ylim3d(0, 250)
ax.set_zlim3d(yearvec[0], yearvec[-1])

majorLocator   = MultipleLocator(1)
ax.zaxis.set_major_locator(majorLocator)
zFormatter = FormatStrFormatter('%d')
ax.zaxis.set_major_formatter(zFormatter)

rawDescription: Eliminating scientific notation on vertical axis of 3d plot (Python)


code:
SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
"H2SO4".translate(SUB)

rawDescription: Printing subscript in python

description: Printing subscript in python


code:
prev = [None]

s = [prev.__setitem__(0, val) or val
     for item in list
     for val in [something(item, prev[0])]]

rawDescription: Access prior element in a list comprehension


code:
import os
import shutil
import zipfile

my_dir = r"D:\Download"
my_zip = r"D:\Download\my_file.zip"

with zipfile.ZipFile(my_zip) as zip_file:
    for member in zip_file.namelist():
        filename = os.path.basename(member)
        # skip directories
        if not filename:
            continue

        # copy file (taken from zipfile's extract)
        source = zip_file.open(member)
        target = file(os.path.join(my_dir, filename), "wb")
        with source, target:
            shutil.copyfileobj(source, target)

rawDescription: Extract files from zip without keeping the structure using python ZipFile?


code: name = 'm\_out'

rawDescription: matplotlib: override underscore in string when using LaTeX in text box

description: Matplotlib: override underscore in string when using LaTeX in text box


code:
s, l, m
d = dict(zip(l, m))
d  #dict is better then using two list i think
[d.get(i, j) for i, j in enumerate(s)]

rawDescription: How to replace values in a list at indexed positions?

description: Replace values in a list at indexed positions


code:
def my_fun(iterable):
    iterable = iter(iterable)
    # Do whatever.

rawDescription: How to check if an iterable can be traversed again?

description: Check if an iterable can be traversed again


code:
class RestHandler(object):
    # "default" exception handling in the super class
    def handle_exception(self, e):
        logger.error('Default error handling caught a "%s"' % e)

class RestRegisterHandler(RestHandler):
    # "specific" exception handling in the child class
    def handle_exception(self, e):
        # Just an idea, you can implement this in different ways
        WRITE_ERROR             = (InvalidRequest, InvalidToken, DuplicateKeyError)
        WRITE_ERROR_WITH_LOGGER = (Exception,)
        RAISE_VALIDATION_ERROR  = (ModelValidationError,)

        if e in WRITE_ERROR:
            self.write_error(404, str(e))
        elif e in WRITE_ERROR_WITH_LOGGER:
            logger.error(e)
            self.write_error(404, str(e))
        elif e in RAISE_VALIDATION_ERROR:
            logger.error("Unknown Validation error: '{0}'".format(e))
            raise utils.errors.ValidationError(400, error_messages=e.messages)
        else:
            # if couldn't be handled here, fallback to the default implementation
            super(RestHandler, self).handle_exception(e)

    @gen.coroutine
    def post(self):
        self.raw_data = None
        try:
            yield self.validate_user()
            self.raw_data = json_decode(self.request.body)
            logger.debug(self.raw_data)
            model_object = self.model(self.raw_data)
            model_object.validate()
            logger.debug("Inseting to database")
            yield model_object.insert(self.db)

        except Exception as e:
            self.handle_exception(e)

        else:
            logger.debug("db saved")
            self.write("Registered succesfully")
            return

rawDescription: exception handler as a function

description: Exception handler as a function


code:
lists = [['m','r','b','l'],
         ['m','b','l'],
         ['b','l','o'],
         ['b','m','o']]

def change(list_, find_this, followed_by, replace_to):
    return_list = list_.copy()
    idx = list_.index(find_this)
    if list_[idx+1] == followed_by:
        return_list = list_.copy()
        return_list[idx] = replace_to
    return return_list

for lst in lists:
    print(change(lst, 'b', 'l', 'o'))

''' output:
['m', 'r', 'o', 'l']
['m', 'o', 'l']
['o', 'l', 'o']
['b', 'm', 'o']
'''

rawDescription: How to properly set fst rules

description: Properly set fst rules


code: newdate = datetime.datetime.utcnow().replace(tzinfo=utc) - datetime.timedelta(days=30)

rawDescription: setting a datetime in python to utcnow - 30

description: Setting a datetime in python to utcnow - 30


code:
import re

...

link=soup.find_all(
    'a',
    xtclib=re.compile(r"listing_list_\d+_title_link"),
    href=True)

rawDescription: ignoring a part of a string in find_all in beautiful soup

description: Ignoring a part of a string in find_all in beautiful soup


code:
def wait_for_plugged_in_drive(self):
    print("Plugin an external HDD or USB stick.")

    sh.udevadm.monitor(_out=self._scan_and_terminate).wait()

def _scan_and_terminate(self, line, stdin, process):

    match = re.search('add\\s+/.*/block/sd./(sd..)', line)

    if match is not None:

        self.device = '/dev/' + match.group(1)
        print("USB stick recognized {0}".format(self.device))

        process.terminate()
        return True

rawDescription: How to interrupt a subprocess launched by sh?

description: Interrupt a subprocess launched by sh


code: datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')

rawDescription: How can I use DateTime to get the time to this format?

description: Use DateTime to get the time to this format


rawDescription: How to use get_or_create in a way that get doesn't use all the parameters while create does?

description: Use get_or_create in a way that get doesn't use all the parameters while create does


code:
keyList = []
dataList = []
with open('sample_data','r') as f:
    for line in f.readline():
        if line.startswith("#"):
            key, comment = line.split(',')
            keyList.append(key[1:])
        else: # it must be data
            dataList.append(line)

for data in dataList:
    data_list = data.split(',')
    try:
        x = map(float, data_list)
    except ValueError:
        pass

rawDescription: read mixed data types in text file Python

description: Read mixed data types in text file Python


code:
class YEncoder(json.JSONEncoder):
    def encode(self, obj):
        return json.dumps({ 'm': json.dumps({ k: json.dumps(v, cls=XEncoder) for k, v in obj.m.items()})})

class YDecoder(json.JSONDecoder):
    def decode(self, json_string):
        y.m = {k: json.loads(v, cls=XDecoder) for k, v in json.loads(json.loads(json_string)['m']).items()}
        return y

rawDescription: JSON (de)serializing for nested classes

description: JSON (de)serializing for nested classes


code:
from wand.image import Image

with Image(filename='file.pdf') as img:
    img.save(filename='file.jpg')
    if len(img.sequence) > 1:
        images = ['file-{0.index}.jpg'.format(x) for x in img.sequence]
    else:
        images = ['file.jpg']

rawDescription: Get list of result files converted via Wand


rawDescription: evaluating an operation with operators contained within a string

description: Evaluating an operation with operators contained within a string


code:
#!/usr/bin/python
import sys
from PySide import QtGui

class Window(QtGui.QMainWindow):
  def __init__(self):
    super(Window,self).__init__()
    self.initUI()
  def initUI(self):
    self.setGeometry(200,500,400,400)
    self.setWindowTitle("A Grid Layout")
    l1 = QtGui.QLabel("Label 1")
    l2 = QtGui.QLabel("Label 2")
    l3 = QtGui.QLabel("Label 3")
    le1 = QtGui.QLineEdit()
    grid = QtGui.QGridLayout()
    grid.setSpacing(10)
    grid.addWidget(l1,1,0)#widget,row,column
    grid.addWidget(l2,2,1)
    grid.addWidget(l3,3,2)
    grid.addWidget(le1,4,0,1,2)#row,column span

    centralWidget = QtGui.QWidget()
    centralWidget.setLayout(grid)
    self.setCentralWidget(centralWidget)

    self.show()

def main():
  app = QtGui.QApplication(sys.argv)
  win = Window()
  exit(app.exec_())

if __name__ == "__main__":
  main()

rawDescription: Widgets not showing up on a Grid layout (PySide)


code:
row = cursor.fetchone()
while row is not None:
    # do something
    row = cursor.fetchone()

rawDescription: Iterating over PyoDBC result without fetchall()


code:
from pylab import *

# make a square figure and axes
figure(1, figsize=(10, 3))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]

explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

gca().set_aspect('1')
show()

rawDescription: i need to plot a piechart in PyQt4 GUI using MatPlotLib

description: I need to plot a piechart in PyQt4 GUI using MatPlotLib


code:
txt_list = []
with open("filename.txt", "r") as x:
    for line in x:
        line = line.rstrip()
        txt_list.append(line)

i = 0
while i < len(txt_list):
    if txt_list[i] == "62":
        txt_list[i+1] = "256"
    i += 1

rawDescription: Search, edit next line in python

description: Search, edit next line in python


code:
list1 = [
    {
        'IP': '1.1.1.1',
        'ID': 1,
    },
    {
        'IP': '2.2.2.2',
        'ID': 2
    }]

list2 = [
    {
        'vulnerability_id': 4567,
        'ID': 1,
    },
    {
        'vulnerability_id': 6578,
        'ID': 2
    }]

list3 = [
    {
        'vulnerability_id': 4567,
        'description': 'blah',
    },
    {
        'vulnerability_id': 6578,
        'description': 'blah blah'
    }]

def find(data, key, value):
    for row in data:
        if row[key] == value:
            return row
    raise ValueError('Row with %s = %s not found' % (key, value))

ID = find(list1, 'IP', '1.1.1.1')['ID']
vulnerability_id = find(list2, 'ID', ID)['vulnerability_id']
print(find(list3, 'vulnerability_id', vulnerability_id)['description'])

rawDescription: Manipulating a list of dictionaries based on values in another list


rawDescription: iterating over two values of a list at a time in python

description: Iterating over two values of a list at a time in python


code:
class MyClass(object):

    FLAG = 1

@shared_task
def add_var():
    myclass = MyClass()
    while(1):
        myclass.FLAG += 1
        print( myclass.FLAG )

@shared_task
def print_var():
    myclass = MyClass()
    while(1):
        print( myclass.FLAG )

rawDescription: Django & Celery use a singleton class instance attribute as a global


code:
class FooModelResource(ModelResource):
    file = fields.FileField()

    class Meta:
        queryset = FooModel.objects.all()

    def override_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/download%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('download_detail'), name="api_download_detail"),
            ]

    def download_detail(self, request, **kwargs):
        """
        Send a file through TastyPie without loading the whole file into
        memory at once. The FileWrapper will turn the file object into an
        iterator for chunks of 8KB.

        No need to build a bundle here only to return a file, lets look into the DB directly
        """
        filename = self._meta.queryset.get(pk=kwargs[pk]).file
        wrapper = FileWrapper(file(filename))
        response = HttpResponse(wrapper, content_type='text/plain') #or whatever type you want there
        response['Content-Length'] = os.path.getsize(filename)
        return response

rawDescription: FileField in Tastypie

description: FileField in Tastypie


code: value = ", ".join("'{}'".format(val) for val in result)

rawDescription: Joining in python with quotes

description: Joining in python with quotes


code:
import sys
from PyQt4 import QtGui, QtCore, QtNetwork

class Main(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)

    def loadIconFromUrl(self, url):
        manager = QtNetwork.QNetworkAccessManager(self)
        manager.finished.connect(self._setIconFromReply)
        manager.get(QtNetwork.QNetworkRequest(QtCore.QUrl(url)))

    def _setIconFromReply(self, reply):
        p = QtGui.QPixmap()
        p.loadFromData(reply.readAll(), format="ico")
        self.setWindowIcon(QtGui.QIcon(p))

app = QtGui.QApplication(sys.argv)
main = Main()
main.loadIconFromUrl("http://en.wikipedia.org/favicon.ico")
main.show()
sys.exit(app.exec_())

rawDescription: PyQt4 - setWindowIcon from external website


code:
def searched_year(self, year):
    return [rec for rec in self.student.parse_student_info() if rec[0] is year]

rawDescription: Evaluating an item of a certain index in a list within a list


code:
import numpy as np

a = np.array([
    [1, 0, 0],
    [0, np.nan, 0],
    [0, 0, 0],
    [np.nan, np.nan, np.nan],
    [2, 3, 4]
])

mask = np.all(np.isnan(a) | np.equal(a, 0), axis=1)
a[~mask]

rawDescription: Numpy: Drop rows with all nan or 0 values


code:
with open("file.txt", 'r') as fd:
    d = dict(line.rstrip().split(":") for line in fd)

rawDescription: Adding to dictionary in a loop while reading file


code:
s = c_char_p("string")
libx.foo(s)

rawDescription: pass Python str to C function

description: Pass Python str to C function


rawDescription: How to find the indexes of matches in two lists

description: Find the indexes of matches in two lists


code:
import imp

# import the configuration as a module
(path, name) = os.path.split(filename)
(name, _) = os.path.splitext(name)
(file, filename, data) = imp.find_module(name, [path])

try:
    module = imp.load_module(name, file, filename, data)
except ImportError as e:
    print(e)
    sys.exit(1)
finally:
    file.close()

rawDescription: How to get results out of a Python exec()/eval() call?

description: Get results out of a Python exec()/eval() call


code:
import re
re.compile(',\s*').split('keyword_1, keyword_2, keyword_3')

rawDescription: Python: convert string to list

description: Python: convert string to list


code:
import os
os.system("abq6131 job=Fish1")

rawDescription: Launch successive calculations of Abaqus


code:
L, N = 3,3
cc = combinations_with_replacement(range(1, N+1), L)
for c in cc: print(c)

rawDescription: Python generating all nondecreasing sequences


code:
dat = np.linspace(0.1, 0.9, 4) * np.ones((4,1))
fig, ax = plt.subplots()
cax = ax.imshow(dat, interpolation='none', vmin=0, vmax=0)
cbar = fig.colorbar(cax)
plt.show()

rawDescription: adding ticks to matplotlib colorbar

description: Adding ticks to matplotlib colorbar


code:
class Workgroup(Base):
    __tablename__ = 'workgroups'
    id = sqlalchemy.Column(sqlalchemy.Integer,

                           primary_key=True,
                           autoincrement=True
                           )
    name = sqlalchemy.Column(sqlalchemy.String(16))
    shorthand = sqlalchemy.Column(sqlalchemy.String(4))

    def __unicode__(self):
        return self.name

    def __repr__(self):
        return '<Workgroup %r>' % (self.name)

rawDescription: Flask-admin, editing relationship giving me object representation of Foreign Key object


code:
def attribute_text_is_in_element(text, locator, attribute):
    try:
        element_text = driver.find_element(locator).get_attribute(attribute)
        if text == element_text:
            return True
        else:
            return False
    except StaleElementReferenceException:
        return False

rawDescription: WebDriver python equivalent of "refreshed" expected condition


code:
if serialIndex < 200:
    serialBuffer[serialIndex] = serialData
    serialIndex += 1

rawDescription: Not able to increment inside an array in python


code:
L = [{'x':11}, {'y':2}, {'z':3}]

def addItem(L, key, value):
    for index, element in enumerate(L):
        if key in element:
            L.remove(element)
            L.insert(index, {key, element[key] + value})
    return L

L[:] = addItem(L, 'x', 4)
print(L)

rawDescription: Data append in a list using the previous data in Python


code:
@app.route("/getVM/<int:scId>", methods=['GET'])
def getVM(scId):
    xmlContent = db.getXML(scId)
    generatorAddr = sgAdd + "/generateVM"

xml_str = some_method_to_generate_xml()
data_str = urllib.urlencode({'xml': xml_str})
urllib.urlopen(generatorAddr, data=data_str).read()
return json.dumps(testReturn)

rawDescription: Flask : understanding POST method to transmit data


rawDescription: How does NumPy implement its complex number literal?


code: user_input = input('Enter the date')

rawDescription: How to find out day of the week from given date in python?

description: Find out day of the week from given date in python


code:
Npoints = 100

t   = np.linspace(0,np.pi,Npoints)
r   = 1

a   = 20
phi = a*t

X = r*np.sin(t)*np.cos(phi)
Y = r*np.sin(t)*np.sin(phi)
Z = r*np.cos(t)

rawDescription: How to produce coordinates to cover a sphere with a single line?

description: Produce coordinates to cover a sphere with a single line


code:
import json

list_of_metros = [Metro(...), Metro(...)]

fields = ('code', 'name', 'country', 'continent', 'timezone',
          'coordinates', 'population', 'region',)

d = {
    'metros': [
        {f:getattr(metro, f) for f in fields}
        for metro in list_of_metros
    ]
}
json_output = json.dumps(d, indent=4)

rawDescription: building dictionary to be JSON encoded - python

description: Building dictionary to be JSON encoded - python


code:
import cerealizer
#import cPickle as cerealizer

def save(data, filename):
    f = open(filename,"wb")
    cerealizer.dump(data, f, protocol=2)
    f.close()

def load(filename):
    f = open(filename,"rb")
    p = cerealizer.load(f)
    f.close()
    return(p)

if __name__ == "__main__":
    import PIL.Image
    import cStringIO as StringIO

    stringIO = StringIO.StringIO()
    im = PIL.Image.open("picture.jpg")
    im.save(stringIO, "JPEG")

    stringIO.seek(0)
    save(stringIO.read(), "testCerealizerIm.txt")

    binaryImageData = load("testCerealizerIm.txt")

    stringIO2 = StringIO.StringIO()
    stringIO2.write(binaryImageData)

    stringIO2.seek(0)
    im = PIL.Image.open(stringIO2)
    im.show()

rawDescription: cPickle file using protocol option

description: CPickle file using protocol option


code:
df = pd.DataFrame({'Color': ['Red', 'Red', 'Blue'], 'State': ['MA', 'PA', 'PA']})
df.Color.value_counts().reset_index().rename(columns={'index': 'Color', 0: 'count'})

rawDescription: Create a pandas dataframe of counts

description: Create a pandas dataframe of counts