code:
import numpy as np

# input array
x = np.array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]])

# random boolean mask for which values will be changed
mask = np.random.randint(0,2,size=x.shape).astype(np.bool)

# random matrix the same shape of your data
r = np.random.rand(*x.shape)*np.max(x)

# use your mask to replace values in your input array
x[mask] = r[mask]

rawDescription: Numpy: Replace random elements in an array


rawDescription: Numpy Arrays: Slice y-values array based on threshold, then slice the x-values array correspondingly


code: s = requests.session()

rawDescription: Clear cookies from Requests Python

description: Clear cookies from Requests Python


code:
import shutil

filelist = ["input1.txt","input2.txt","input3.txt"]
for filename in filelist:
    shutil.copyfile(filename,"input.txt")

rawDescription: Python Copying Files

description: Python Copying Files


code:
encoding = sys.stdin.encoding
with codecs.open('norsk.txt','r','utf-8') as fil:
    ordliste = [line.rstrip(u'\n') for line in fil]

rawDescription: UnicodeWarning: special characters in Tkinter


code:
from tkinter import *
import webbrowser

def callback(event):
    webbrowser.open_new(r"http://www.google.com")

root = Tk()
link = Label(root, text="Google Hyperlink", fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", callback)
root.mainloop()

rawDescription: How to create a hyperlink with a Label in Tkinter?

description: Create a hyperlink with a Label in Tkinter


code:
def parse_time(s):
    """ '1h 30m' -> 90 """
    m = 0
    for x in s.split():
        if x.endswith('d'):
            m += int(x[:-1]) * 60 * 8  # NOTE: 8, not 24
        elif x.endswith('h'):
            m += int(x[:-1]) * 60
        elif x.endswith('m'):
            m += int(x[:-1])
    return m

def to_time(m):
    """ 90 -> '1h 30m' """
    d, m = divmod(m, 60 * 8)  # NOTE: 8, not 24
    h, m = divmod(m, 60)
    ret = []
    if d:
        ret.append('{}d'.format(d))
    if h:
        ret.append('{}h'.format(h))
    if m:
        ret.append('{}m'.format(m))
    return ' '.join(ret) or '0m'

rawDescription: Pythonic way to add a list of time

description: Pythonic way to add a list of time


code:
for part in range(1, A):
    if part % 2 > 0: col = black
    else: col = grey
    particles.append( Particle(515, B, col, round(B*part/A)) )

rawDescription: Pygame particle effects

description: Pygame particle effects


code:
import datetime as dt
import pytz

utc = pytz.utc
western = pytz.timezone('US/Pacific')
newyork = pytz.timezone('America/New_York')
chicago = pytz.timezone('America/Chicago')

rawDescription: What is the local timezone

description: What is the local timezone


code:
[k for k in d if True if True if True]
['phone', 'gadget_23', 'gadget_56', 'manufacture_23', 'manufacture_1', 'gadget_1', 'price', 'name']

rawDescription: How to check dynamic key in dictionary?

description: Check dynamic key in dictionary


code:
def f(x, y):
    return x * y

rawDescription: product of arrays of different sizes in numpy

description: Product of arrays of different sizes in numpy


code:
f = open(wor, 'r+')
new_lines = []
for line in f.readlines():

    if '"' + OldPath + '"' in line :
        line.replace(OldPath, NewPath);
    new_lines.append(line)

f.close()

file("path/to/your/new/or/temp/file","w")
file.write("\n".join(new_lines))
file.close()

rawDescription: Python 2.5 - Update folder of text files from values stored in a lookup list


code:
import csv

owner,file =[],[]
with open(filePath,'rb') as f:
    reader = csv.reader(f)
    for line in reader:
        owner.append(line.split('/')[0])
        file.append(line.split('/')[-1])

rawDescription: Separate directories from a column using python


code: {name: MyClass(*args) for name, args in objects.items()}

rawDescription: create multiple objects of a class with different arguments

description: Create multiple objects of a class with different arguments


rawDescription: How to make Python Dict from JSON data using BeautifulSoup

description: Make Python Dict from JSON data using BeautifulSoup


code: fun = ugly_math()

rawDescription: Using events with matplotlib in a for loop


code:
lists = [e['val'] for e in dl]
idx_to_remove = [i for i, elem in enumerate(map(any, zip(*lists))) if not elem]

rawDescription: Stripping empty elements from lists

description: Stripping empty elements from lists


code:
import datetime
adate = datetime.date(2013, 2, 14)
adate.strftime('%d.%m.%Y')
'{0.day}.{0.month}.{0.year}'.format(adate)

rawDescription: python: datetime within module always provides date of first call

description: Python: datetime within module always provides date of first call


code:
def item_to_sort_key(item):
    n, name = item
    return name.lower()

sorted(L, key=item_to_sort_key)

rawDescription: Python: sorting tuple by last name and handling lower cased first letters


code: s = '{"firstname": "John","lastname": "Smith"}'

rawDescription: how I should proceed to extract the value id for keys from the .json file in python using the keys

description: How I should proceed to extract the value id for keys from the .json file in python using the keys


code:
arr
vals = [100, 300]
np.in1d(arr[:,0], vals)
arr[np.in1d(arr[:,0], vals), 1]

rawDescription: How to extract those rows in a 2d array whose first element is in a different list?

description: Extract those rows in a 2d array whose first element is in a different list


rawDescription: Python .net framework reference argument Double[]&


rawDescription: How can I add an additional row and column to an array?

description: Add an additional row and column to an array


code:
m = MIMEUTF8QPText(u'This is the text containing ünicöde')
m.as_string()

rawDescription: Encode MIMEText as quoted printables

description: Encode MIMEText as quoted printables


code:
def efficientalgo(number):
    print("Start with this number... " + str(number))
    # See if a number is dividable by three, if so then divide by 3
    if number % 3 == 0:
        print("Dividing three...")
        number /= 3
        print(number)
        # use recursion to see if the number can be divided again
        return efficientalgo(number)

    # Divide a number by 2 if it is evenly dividable by 2
    if number % 2 == 0:
        print("Dividing two...")
        number /= 2
        print(number)
        # Use recursion to see if the number can be divided again
        return efficientalgo(number)

    # If a number is not one, then subtract one and call the
    if number != 1:
        print("Subtracting one now...")
        number -= 1
        print(number)
        # Use recursion to see if the number can be divided again
        return efficientalgo(number)

    return number

rawDescription: Is this an issue with my method of recursion?


code:
def evaluate(node):
    # evaluate parameters of the call
    params = [ evaluate(child) for child in node ]

    # apply whatever function this node represents
    return node.function.call(*params)

rawDescription: Translating a declarative DSL into nested function calls


code:
import re
line = '''\
1 h words words words
bla 2 h words words
'''

scanner = re.Scanner([
    (r"([0-9]+(?:\ h|h))",    lambda scanner, token: ("HOURS", token)),
    (r'.', lambda scanner, token: None),
    ], flags=re.DOTALL)

results, remainder = scanner.scan(line)
print(results)

rawDescription: re.scanner only searching start of string

description: Re.scanner only searching start of string


code: letter_map = dict(zip(string.lowercase, string.lowercase[1:] + string.lowercase[0]))

rawDescription: How to create a letter progression for a variable in a loop in Python?

description: Create a letter progression for a variable in a loop in Python


code: arr = ser.readlines()

rawDescription: get data from usb weatherboard using PySerial

description: Get data from usb weatherboard using PySerial


code:
soup = BeautifulSoup('upload_success
http://www.filepup.net/files/R6wVq1405781467.html
http://www.filepup.net/delete/Jp3q5w1405781467/R6wVq1405781467.html')
soup.find('br')
soup.find('br').next_sibling

rawDescription: Python HTML Parsing Between two tags

description: Python HTML Parsing Between two tags


code:
myresults = db.megas.aggregate( [ { "$unwind": "$items" },
    {"$group": { '_id':'$_id' , 'minitem': {'$min': "$items.item" } } } ] )

rawDescription: MongoDB: Find the minimum element in array and delete it


code:
import webbrowser
webbrowser.open('https://docs.python.org/2/library/webbrowser.html',
new=2, autoraise=True)

rawDescription: Python : New Url instead of New Webbrowser


rawDescription: How to get the number of elements returned from a function in Python

description: Get the number of elements returned from a function in Python


rawDescription: Counter in Pandas groupby apply

description: Counter in Pandas groupby apply


code:
import datetime
holiday_tuple = (datetime.date(2015, 3, 1), 'some description')
print("{:%d/%m} {}".format(*holiday_tuple))
print("{0[0]:%d/%m} {0[1]}".format(holiday_tuple))

rawDescription: Using .format() with tuples instead of dictionaries


code:
data = sock.recv(1024)
jsondata = json.loads(data)
jsondata[1] = decrypt(b64decode(jsondata[1]))

rawDescription: Python: Can JSON be used to send a message to a Python Server which contains encrypted sections?


code:
def search_func(lst, x):
    if not lst:    # shorter way to test if the list is empty
        return "failure"
    for e in lst:  # look how easy is to traverse the list!
        if e == x: # we no longer care about indexes
            return "success"
    else:
        return "failure"

rawDescription: Search function python

description: Search function python


code:
Z = np.concatenate((X, labels[:,None]), axis=1)
df = pd.DataFrame(Z, columns=("x", "y", "label"))
df[df['label']>-1].groupby("label").mean()

rawDescription: Is there a way to vectorize this loop

description: Is there a way to vectorize this loop


code:
s = 'long string that I want to split up'
indices = [0,5,12,17]
parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])]

rawDescription: Splitting a string by list of indices

description: Splitting a string by list of indices


code:
d, s = {}, 0
for i in l:
    d[i] = len(i)
    s += len(i)

rawDescription: python create a set / dict / list and the sum of its values from a single list comprehension

description: Python create a set / dict / list and the sum of its values from a single list comprehension


code: ["{:b}".format(x) for x in range(251)]

rawDescription: Printing Binary in Python

description: Printing Binary in Python


code: df['increasing'] = (df['Open'].diff() > 0).astype(int)

rawDescription: New colum in pandas, based on another colums last value


code:
AAAAAAAAAAAA
TTTTTTTTTTTT
AAAAACAAACAA

rawDescription: Identify Similar Strings in Python

description: Identify Similar Strings in Python


code:
class App(QtGui.QApplication):
    def __init__(self):
        super(App, self).__init__()
        message = self.tr('Apple')
...
app = App()
...
print(app.tr('Apple'))

rawDescription: PySide Qt tr() does not translate, context wrong?


code:
xs = []
n = 0

class A:
    def __del__(self):
        global n
        n += 1
        print("time {} calling __del__".format(n))
        xs.append(self)

print("creating an A immediately thrown away")
A()
for _ in range(5):
    print("popping from xs")
    xs.pop()

rawDescription: How many times can `__del__` be called per object in Python?


code:
str = "ABCD"
[elem.encode("hex") for elem in str]

rawDescription: Python: convert string to byte array

description: Python: convert string to byte array


code:
def _generate_bar(x, y, z):
    return x + y + z

class Foo():
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        self.bar = _generate_bar(x, y, z)

rawDescription: How do I define a Python method that I only want to use in the __init__ method, i.e., that is not accessible from outside the class definition?

description: Define a Python method that I only want to use in the __init__ method, i.e., that is not accessible from outside the class definition


code:
match.group("Section")
match.group(1)
match.group("SubSection")
match.group(2)

rawDescription: Python regex optional capture group or lastindex


code:
import shutil
with open('downloaded', 'wb') as f:
    shutil.copyfileobj(br.submit(), f)

rawDescription: Mechanize submit a form that creates a dynamic flie that needs to be downloaded


code:
def grid_handler(request):
    # handles pagination, sorting and searching
    grid = ExampleGrid()
    return HttpResponse(grid.get_json(request), mimetype="application/json")

def grid_config(request):
    # build a config suitable to pass to jqgrid constructor
    grid = ExampleGrid()
    return HttpResponse(grid.get_config(), mimetype="application/json")

rawDescription: does anyone have any examples of using jqGrid with twisted / python

description: Does anyone have any examples of using jqGrid with twisted / python


code:
interp = scipy.interpolate.interp1d(x1, y1.T, kind='quadratic')

fig = plt.figure()
ax = fig.add_subplot(111)

x = linspace(1,4,200)
ip = interp(x)
ax.plot(x, ip[0], 'b')
ax.plot(x, ip[1], 'g')
ax.plot(x, ip[2], 'r')

ax.plot(x1, y1[:,0], 'bo')
ax.plot(x1, y1[:,1], 'go')
ax.plot(x1, y1[:,2], 'ro')

rawDescription: Interpolating array columns with PiecewisePolynomial in scipy


code:
from itertools import cycle, islice, chain

a = range(1, 11)
b = reversed(a)
c = cycle(chain(a, b))
d = list(islice(c, 100)) # `c` is infinite - hence the `islice` to stop at some point...

rawDescription: Python: cycle through elements in list reversing when the end is reached


code:
def func(fx):
    d = {'AAA':1,'BBB':2,'CCC':3}
    return [d["".join(x).upper()] for x in zip(*[iter(fx)]*3)]

rawDescription: Dictionary works for len(string) multiple of 3. Function deletes remainders but now doesn't translate with dictionary. Python 2.7.1


code:
listStore = gtk.ListStore(str, str, str, str, str, str, str, str)
listStore.set_sort_func(0, date_compare, None)
treeview = gtk.TreeView()
treeview.set_model(listStore)

cell = gtk.CellRendererText()
column = gtk.TreeViewColumn('Date', cell, text=0)
column.set_sort_column_id(0)
treeview.append_column(column)
...

rawDescription: Sort a gtk.TreeColumn by date value

description: Sort a gtk.TreeColumn by date value


code:
def match_both(arg):
    if arg == "listGrid-price" or arg == "listGrid-price-outOfStock":
        return True
    return False

rawDescription: Issue in scraping data from a website using beautiful soup


rawDescription: 2D Histogram out of array data set

description: 2D Histogram out of array data set


rawDescription: How do I extend the Django "login" form?

description: Extend the Django "login" form


rawDescription: How to parse a json file from context_data with html in django

description: Parse a json file from context_data with html in django


code:
class C:

    def discovery(self):
        yield 1; yield 2

    # Register all the functions for wich you want to have a generator
    # object.
    REGISTERED_GEN_FUNCTIONS = [discovery]

    def __init__(self):

        for func in self.REGISTERED_GEN_FUNCTIONS:
            name = func.__name__
            # All generators objects will be called <function_name>_gen.
            setattr(self, "{0}_gen".format(name), getattr(self, name)())

a = C()
for i in a.discovery_gen:
    print(i)

rawDescription: Python generator function/object naming convention


code:
A = numpy.random.randn(5,5)
numpy.linalg.eig(A+A.T)[0] #Actual Eigenvalues
sp.eigsh(A+A.T,3)[0] #Three Largest (in Magnitude). What you don't want
sp.eigsh(A+A.T,3,which='LA')[0] #Three Largest. What you do want

rawDescription: Finding 2 largest eigenvalues of large-sparse matrix in Python


code:
import numpy as np
import scipy       #older versions may require `import scipy.sparse`

matrix = np.matrix(np.random.randn(10, 5))
maxes = matrix.argmax(axis=1).A1
                      # was .A[:,0], slightly faster, but .A1 seems more readable
n_rows = len(matrix)  # could do matrix.shape[0], but that's slower
data = np.ones(n_rows)
row = np.arange(n_rows)
sparse_matrix = scipy.sparse.coo_matrix((data, (row, maxes)),
                                        shape=matrix.shape,
                                        dtype=np.int8)

rawDescription: Replace specific values in a matrix using Python


code:
screenshot = ImageGrab.grab()
haystack = screenshot.load()

rawDescription: How to detect if image is present on screen?

description: Detect if image is present on screen


rawDescription: How to chain django query filters to conditionally filter by certain criteria

description: Chain django query filters to conditionally filter by certain criteria


code:
class P(object):
    def __init__(self, predicate):
        self.pred = predicate

    def __call__(self, obj):
        return self.pred(obj)

    def __copy_pred(self):
        return copy.copy(self.pred)

    def __and__(self, predicate):
        def func(obj):
            return self.pred(obj) and predicate(obj)
        return P(func)

    def __or__(self, predicate):
        def func(obj):
            return self.pred(obj) or predicate(obj)
        return P(func)

rawDescription: Pointfree function combination in Python


code: session.query((Table.revenue - Table.loss).label('profit')).order_by('profit desc').all()

rawDescription: Compare difference between two columns in SQLAlchemy ORM


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle

class Annotate(object):
  def __init__(self,x,y):
      self.figure = plt.gcf()
      self.ax = plt.gca()
      self.x = x
      self.y = y
      self.rect = Rectangle((0,0), 0, 0, facecolor='None', edgecolor='red')
      self.im = plt.imshow(np.zeros((150,150)))
      self.x0 = None
      self.y0 = None
      self.x1 = None
      self.y1 = None
      self.is_pressed = False
      self.ax.add_patch(self.rect)
      self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
      self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
      self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
  def on_press(self, event):
      print ('press')
      self.is_pressed = True
      self.x0 = event.xdata
      self.y0 = event.ydata
      self.x1 = event.xdata
      self.y1 = event.ydata
      self.rect.set_width(self.x1 - self.x0)
      self.rect.set_height(self.y1 - self.y0)
      self.rect.set_xy((self.x0, self.y0))
      #self.rect.set_linestyle('dashed')
      self.ax.figure.canvas.draw()
  def on_motion(self,event):
      if self.is_pressed is False:
          return
      self.x1 = event.xdata
      self.y1 = event.ydata
      #if type(self.x1) is float and type(self.y1) is float:
      self.rect.set_width(self.x1 - self.x0)
      self.rect.set_height(self.y1 - self.y0)
      self.rect.set_xy((self.x0, self.y0))
      #self.rect.set_linestyle('dashed')
      if self.is_pressed == True:
          self.ax.figure.canvas.draw()
  def on_release(self, event):
      print ('release')
      self.is_pressed= False
      self.x1 = event.xdata
      self.y1 = event.ydata
      self.rect.set_width(self.x1 - self.x0)
      self.rect.set_height(self.y1 - self.y0)
      self.rect.set_xy((self.x0, self.y0))
      self.rect.set_linestyle('solid')
      update_data(self)
      #self.ax.set_ylim( min(self.y0, self.y1), max(self.y0, self.y1))
      #self.ax.set_xlim( min(self.x0, self.x1), max(self.x0, self.x1))
      self.ax.figure.canvas.draw()

      print (self.x0,self.x1,self.y0,self.y1)
      return [self.x0,self.x1,self.y0,self.y1]

#x = np.random.randint(0,500, size=10000)
x = np.arange(5000)
y = np.random.randint(0,500, size=5000)

Z, xedges, yedges = np.histogram2d(x, y, bins=150, normed=True)

def update_data(selection):
    ymin= min(selection.y0, selection.y1)
    ymax= max(selection.y0, selection.y1)
    xmin= min(selection.x0, selection.x1)
    xmax= max(selection.x0, selection.x1)
    low_index = np.argmax(selection.x>xmin)
    high_index = np.argmax(selection.y>xmax)
    Z, xedges, yedges = np.histogram2d(x[high_index:low_index],y[high_index:low_index], bins=150, normed=True)

    selection.ax.figure.clf(keep_observers=True)
    selection.ax = selection.ax.figure.add_subplot(111)
    selection.im=plt.imshow(Z, interpolation='none', extent=[xmin, xmax, ymin, ymax])
    plt.colorbar(selection.im)

selection = Annotate(x,y)

selection.im=plt.imshow(Z, interpolation='none', extent=[y.min(), y.max(), y.min(), y.max()])
plt.colorbar(selection.im)

plt.show()

rawDescription: Rebin data and update imshow plot

description: Rebin data and update imshow plot


rawDescription: Skip first two characters in (key=lambda) sorting


code:
def create_pyramid(rows):
    for i in range(rows):
        print((' ' * ( rows- i - 1 ) + '*' * ( 2 * i + 1)))

print((create_pyramid(5)))

def create_upside_down_pyramid(rows):
    for i in reversed(list(range(rows))):
        print((' ' * ( rows- i - 1 ) + '*' * ( 2 * i + 1)))

print((create_upside_down_pyramid(5)))

rawDescription: Asterisk triangle in python

description: Asterisk triangle in python


rawDescription: Traversing from one node in xml to another using Python


code: myenv/bin/nosetests

rawDescription: GAE on linux CI server

description: GAE on linux CI server


code: list(map(lambda y: expression_involving_y, elements))

rawDescription: How can I rewrite this map() example using list comprehension?

description: Rewrite this map() example using list comprehension


code:
def factors(n):
    return filter(lambda i: n % i == 0, range(1, n + 1))

rawDescription: How many factors in an integer

description: How many factors in an integer


code:
sublist_size = 3
L = ["Afghanistan", 647500.0, 25500100, "Albania",28748.0,2821977]
grouped = [ L[i:i+sublist_size] for i in range(0, len(L), sublist_size) ]
grouped

rawDescription: spliting a list into [ ]

description: Spliting a list into [ ]


code:
group = models.Class()
...
group.append(models.Student(new_name, typing_speed))

rawDescription: deleting a name from a list input by user and averaging a class score

description: Deleting a name from a list input by user and averaging a class score


rawDescription: Insertions algorithm in sequence python

description: Insertions algorithm in sequence python


rawDescription: Python getattr from locals() fails with AttributeError


code:
df
group_ids = (df["strike"] > (df["strike"].shift() + 100)).cumsum()
grouped = df.groupby(group_ids)
for k,g in grouped:
    print("-----")
    print(g)

rawDescription: How to split pandas dataframe based on difference of values in a column

description: Split pandas dataframe based on difference of values in a column


code: xaxes = []

rawDescription: Condensing Large Unpythony if statement

description: Condensing Large Unpythony if statement


code:
import singleton
print(singleton.news)

rawDescription: In python, How to use singleton patten?

description: In python, How to use singleton patten


code:
import json

data = json.loads(json_string)

first = data['1']
for key in sorted(data):
    if data[key] < first:
        data[key] += 1
        break
else:
    data['1'] += 1

json_string = json.dumps(data)

rawDescription: Python 3.4.1 Find different keep the same


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

driver = webdriver.Firefox()
driver.get("http://stivconsultasexternas.cnbv.gob.mx/ConsultaInformacionEmisoras.aspx")

elem = driver.find_element_by_id("ctl00_DefaultPlaceholder_ComboFiltroPersonalizado_B-1")
elem.click()

elem = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'ctl00_DefaultPlaceholder_ComboFiltroPersonalizado_DDD_L_LBI3T0')))
elem.click()

rawDescription: Select a hidden item using Selenium Python


code:
def get_model_fields(model):
    return model._meta.fields

rawDescription: Exporting items from a model to CSV Django / Python


rawDescription: Find points in cells through pandas dataframes of coordinates


code:
x = np.linspace(0,20, 1000)
y = np.sin(x)
h1 = hyst(y, -0.5, 0.5)
h2 = hyst(y, -0.5, 0.5, True)
plt.plot(x, y, x, -0.5 + h1, x, -0.5 + h2)
plt.legend(('input', 'output, start=0', 'output, start=1'))
plt.title('Thresholding with hysteresis')
plt.show()

rawDescription: How to find zero crossings with hysteresis?

description: Find zero crossings with hysteresis


code:
list("Pla\net")
list("Plan\et")

rawDescription: How is this weird behaviour of escaping special characters explained?


code:
from functools import partial
def my_function(a,b,c,d,e):
    print (a,b,c,d,e)

func_with_defaults = partial(my_function, 1, 2, e=5)
func_with_defaults(3, 4)

rawDescription: A way to automatically pass parameters to a function?


code:
for i in range(len(a)):
    if (i >= len(b)) or a[i] > b[i]:
        counter += 1

rawDescription: Python comparing two uneven arrays

description: Python comparing two uneven arrays


code:
from xml.dom import minidom
xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml')

rawDescription: python parse xml text

description: Python parse xml text


code:
def scientificNotation(value):
    if value == 0:
        return '0'
    else:
        e = np.log10(np.abs(value))
        m = np.sign(value) * 10 ** (e - int(e))
        return r'${:.0f} \times 10^{{{:d}}}$'.format(m, int(e))

# x is the tick value; p is the position on the axes.
formatter = mpl.ticker.FuncFormatter(lambda x, p: scientificNotation(x))
plt.gca().xaxis.set_major_formatter(formatter)

rawDescription: Remove axis scale

description: Remove axis scale


code:
import images
...
myimage1 = PhotoImage(data=images.image1)
myimage2 = PhotoImage(data=images.image2)
...

rawDescription: Python tkinter image

description: Python tkinter image


code:
import os
working_dir = os.path.dirname(__file__)
os.chdir(working_dir)
import settings
import django.core.management
django.core.management.setup_environ(settings)

rawDescription: how to start django shell with ipython in qtconsole mode?

description: Start django shell with ipython in qtconsole mode


rawDescription: Python: How to replace a property with a regular attribute?


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
###patch start###
from mpl_toolkits.mplot3d.axis3d import Axis
if not hasattr(Axis, "_get_coord_info_old"):
    def _get_coord_info_new(self, renderer):
        mins, maxs, centers, deltas, tc, highs = self._get_coord_info_old(renderer)
        mins += deltas / 4
        maxs -= deltas / 4
        return mins, maxs, centers, deltas, tc, highs
    Axis._get_coord_info_old = Axis._get_coord_info
    Axis._get_coord_info = _get_coord_info_new
###patch end###

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
    xs = np.arange(20)
    ys = np.random.rand(20)

    # You can provide either a single color or an array. To demonstrate this,
    # the first bar of each set will be colored cyan.
    cs = [c] * len(xs)
    cs[0] = 'c'
    ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

rawDescription: Removing axes margins in 3D plot

description: Removing axes margins in 3D plot


code: test_array[np.array(xs)[:, None], ys].reshape(-1, test_array.shape[-1])

rawDescription: NumPy fancy indexing of a multidimensional array: case not covered (explicitly) by documentation


code:
from templated_email import send_templated_mail
send_templated_mail(
        template_name='welcome',
        from_email='from@example.com',
        recipient_list=['to@example.com'],
        context={
            'username':request.user.username,
            'full_name':request.user.get_full_name(),
            'signup_date':request.user.date_joined
        },
        # Optional:
        # cc=['cc@example.com'],
        # bcc=['bcc@example.com'],
        # headers={'My-Custom-Header':'Custom Value'},
        # template_prefix="my_emails/",
        # template_suffix="email",
)

rawDescription: Send_email in django with data from a view as an HTML page


code:
from itertools import chain, combinations
a = [1,2,3]
n = 2
cc = chain.from_iterable(combinations(a, i) for i in range(n, len(a)+1))
list(cc)

rawDescription: how to find combinations of elements with minimum length of N using itertools-Python

description: Find combinations of elements with minimum length of N using itertools-Python


code:
def unwrap(v):
    v[0] if isinstance(v, list) else v

rawDescription: How to remove extra list from the result in python

description: Remove extra list from the result in python


code:
def truncate(string, width):
    if len(string) > width:
        string = string[:width-3] + '...'
    return string

"{0:<10s}".format(truncate("Foo Bar Baz", 10))

rawDescription: Python .format slice long string and add dots


code:
q = session.query(Cebola, Cebola.number_of_comments)
for cebola, number_of_comments in q.all():
    print(cebola, number_of_comments)

rawDescription: Hybrid expression that counts number rows with condition


code:
if request.method == 'POST':
    form = SomeForm(request.POST)
    if form.is_valid():
        model.attr = form.cleaned_data['attr']
        model.attr2 = form.cleaned_data['attr2']
        model.save()
else:
    form = SomeForm()
return render_to_response('page.html', {'form': form, })

rawDescription: How do I associate input to a Form with a Model in Django?

description: Associate input to a Form with a Model in Django


code:
import pygame,random
from pygame.locals import *
from collections import namedtuple

pygame.init()
clock=pygame.time.Clock()
screen=pygame.display.set_mode((640,480))

max_gravity = 100

class Block(object):
    sprite = pygame.image.load("dirt.png").convert_alpha()
    def __init__(self, x, y):
        self.rect = self.sprite.get_rect(centery=y, centerx=x)

class Player(object):
    sprite = pygame.image.load("dirt.png").convert()
    sprite.set_colorkey((0,255,0))
    def __init__(self, x, y):
        self.rect = self.sprite.get_rect(centery=y, centerx=x)
        # indicates that we are standing on the ground
        # and thus are "allowed" to jump
        self.on_ground = True
        self.xvel = 0
        self.yvel = 0
        self.jump_speed = 10
        self.move_speed = 8

    def update(self, move, blocks):

        # check if we can jump
        if move.up and self.on_ground:
            self.yvel -= self.jump_speed

        # simple left/right movement
        if move.left: self.xvel = -self.move_speed
        if move.right: self.xvel = self.move_speed

        # if in the air, fall down
        if not self.on_ground:
            self.yvel += 0.3
            # but not too fast
            if self.yvel > max_gravity: self.yvel = max_gravity

        # if no left/right movement, x speed is 0, of course
        if not (move.left or move.right):
            self.xvel = 0

        # move horizontal, and check for horizontal collisions
        self.rect.left += self.xvel
        self.collide(self.xvel, 0, blocks)

        # move vertically, and check for vertical collisions
        self.rect.top += self.yvel
        self.on_ground = False;
        self.collide(0, self.yvel, blocks)

    def collide(self, xvel, yvel, blocks):
        # all blocks that we collide with
        for block in [blocks[i] for i in self.rect.collidelistall(blocks)]:

            # if xvel is > 0, we know our right side bumped
            # into the left side of a block etc.
            if xvel > 0: self.rect.right = block.rect.left
            if xvel < 0: self.rect.left = block.rect.right

            # if yvel > 0, we are falling, so if a collision happpens
            # we know we hit the ground (remember, we seperated checking for
            # horizontal and vertical collision, so if yvel != 0, xvel is 0)
            if yvel > 0:
                self.rect.bottom = block.rect.top
                self.on_ground = True
                self.yvel = 0
            # if yvel < 0 and a collision occurs, we bumped our head
            # on a block above us
            if yvel < 0: self.rect.top = block.rect.bottom

blocklist = []
player = []
colliding = False
Move = namedtuple('Move', ['up', 'left', 'right'])
while True:
    screen.fill((25,30,90))
    mse = pygame.mouse.get_pos()
    key = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == QUIT: exit()

        if key[K_LSHIFT]:
            if event.type==MOUSEMOTION:
                if not any(block.rect.collidepoint(mse) for block in blocklist):
                    x=(int(mse[0]) / 32)*32
                    y=(int(mse[1]) / 32)*32
                    blocklist.append(Block(x+16,y+16))
        else:
            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    to_remove = [b for b in blocklist if b.rect.collidepoint(mse)]
                    for b in to_remove:
                        blocklist.remove(b)

                    if not to_remove:
                        x=(int(mse[0]) / 32)*32
                        y=(int(mse[1]) / 32)*32
                        blocklist.append(Block(x+16,y+16))

                elif event.button == 3:
                    x=(int(mse[0]) / 32)*32
                    y=(int(mse[1]) / 32)*32
                    player=[]
                    player.append(Player(x+16,y+16))

    move = Move(key[K_UP], key[K_LEFT], key[K_RIGHT])

    for b in blocklist:
        screen.blit(b.sprite, b.rect)
    for p in player:
        p.update(move, blocklist)
        screen.blit(p.sprite, p.rect)
    clock.tick(60)
    pygame.display.flip()

rawDescription: Add collision detection to a plattformer in pygame


code:
the_same = []
for i in deck[1:]:
    if i == deck[0]:
        the_same.append(i)

rawDescription: how to make a script recognize number which are the same in python 3.3

description: Make a script recognize number which are the same in python 3.3


code: OrderedDict([('NOSUBEL', 'abcd'), ('NOSUBEL2', 'adasdasa'), ('ANOTHERONE', '(how many levels can not be said / can change)'), ('FOO', 'abcdefg'), ('NOSUBEL3', 'abc')])

rawDescription: Python: Parsing XML autoadd all key/value pairs


code:
while True:
    secret_word = input("Please enter a word to be guessedthat does not contain ? or white space: ")
    if not set("? ").intersection(secret_word):
        break
    else:
        print("Invalid input")

rawDescription: How do I keep asking the user to input the valid characters?

description: Keep asking the user to input the valid characters


code: LookupElement = namedtuple('LookupElement', ReadElement._fields[0:2] + ('lookups', ReadElement._fields[2]))

rawDescription: Python: Iterating through tuples which are related as subclassed tuples


rawDescription: difflib.SequenceMatcher not returning unique ratio

description: Difflib.SequenceMatcher not returning unique ratio


code:
def print_board(board):
    xs, ys = zip(*board) # separate out the x and y coordinates
    min_x, max_x = min(xs), max(xs) # find the mins and maxs
    min_y, max_y = min(ys), max(ys)
    dimensions = [[min_x, min_y], [max_x, max_y]] # make the dimensions array

rawDescription: Python: short coordinate function unexpectedly changes incoming argument value


code: re.findall(r'<.+?>', text, re.DOTALL)

rawDescription: How to eliminate html tags?

description: Eliminate html tags


code:
def my_filter_2(X):
    Y = np.empty(len(X))
    Y[0] = X[0]
    a = .99 * Y[0]
    for i in range(1, len(X)):
        a = max(a, X[i])
        Y[i] = a
        a *= .99
    return Y

rawDescription: Iteratively-defined Numpy Array Creation


rawDescription: How do you sort a list which is inside a dictionary?

description: Sort a list which is inside a dictionary


code:
A = sp.Matrix([[4, 0, 3], [2, 4, -2], [-2, -3, 7]])
C = np.array(A) #.astype(new_dtype)
C[np.triu_indices(C.shape[0])]

rawDescription: copying only upper triangular values of sympy Matrix into array from numpy.triu()?

description: Copying only upper triangular values of sympy Matrix into array from numpy.triu()


rawDescription: Gevent async server with blocking requests


code:
import gmpy2

def primes2(table=None):

    def sieve(limit):
        sieve_limit = gmpy2.isqrt(limit) + 1
        limit += 1
        bitmap = gmpy2.xmpz(3)
        bitmap[4 : limit : 2] = -1
        for p in bitmap.iter_clear(3, sieve_limit):
            bitmap[p*p : limit : p+p] = -1
        return bitmap

    table_limit=1000000
    if table is None:
        table = sieve(table_limit)

    for n in table.iter_clear(2, table_limit):
        yield n

    n = table_limit
    while True:
        n = gmpy2.next_prime(n)
        yield n

rawDescription: Is there a Python library to list primes?


code:
big_regex = re.compile('|'.join(map(re.escape, words)))
big_regex.sub("swords", 'a sample message with random words')

rawDescription: Replace all words from word list with another string in python


rawDescription: Python simple string cycle

description: Python simple string cycle


code:
class bottom(middle_0, middle_1):
    pass

rawDescription: What's the Pythonic way to implement "diamond inheritance"?


code:
sc = proprocessing.StandardScaler().fit(X)
X = sc.transform(X)

rawDescription: Using ranking data in Logistic Regression


rawDescription: Complicated pandas merge operation

description: Complicated pandas merge operation


code:
import re
import numpy as np

fieldFilter = re.compile(r'^"?([^"]*)"?$')
def filterTheField(s):
    m = fieldFilter.match(s.strip())
    if m:
        return float(m.group(1))
    else:
        return 0.0 # or whatever default

#...

# Yes, sorry, you have to know the number of columns, since the NumPy docs
# don't say you can specify a default converter for all columns.
convs = dict((col, filterTheField) for col in range(numColumns))
data = np.genfromtxt(csvfile, dtype=None, delimiter=',', names=True,
    converters=convs)

rawDescription: Reading CSV files in numpy where delimiter is ","


code:
_decorated = []

def memoize(obj):
    cache = obj.cache = {}

    # add to the decorated list
    _decorated.append(obj)

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        if args not in cache:
            cache[args] = obj(*args, **kwargs)
        return cache[args]
    return memoizer

# make the list accessible from the decorator:
memoize.decorated = _decorated

rawDescription: How to register within a decorator all functions it decorates?

description: Register within a decorator all functions it decorates


code:
import Gnuplot
from numpy import *

x1 = arange(1,10)
y1 = arange(1,10)

d1 = Gnuplot.Data(x1,y1, with_="lines lt rgb 'red'", title="1")
g = Gnuplot.Gnuplot()

g.title("aaa")
g('set grid')
g('set logscale x')
g('set xtics 1,2,110')
g.plot(d1)
g.hardcopy("aaa.svg", terminal='svg', size=[800,400])

rawDescription: hardcopy of gnuplot.py plot

description: Hardcopy of gnuplot.py plot


code:
tf = 'textfile.txt'
f2 = open(tf, 'a+')
f2.write(', '.join([str(data) for data in [title,des,img,tag,tag2,tag3]]) + '\n')
f2.close()

rawDescription: Python, Writing Multiple Lines

description: Python, Writing Multiple Lines


rawDescription: python regular expression irregularity

description: Python regular expression irregularity


code:
mat =  Matrices.dense(100, 100, np.arange(10000))

n_par = 10
n_row = 100

rdd = (sc
    .parallelize(
        # Add indices
        enumerate(
            # Extract and reshape values
            mat.values.reshape(n_row, -1)))
    # Partition and sort by row index
    .repartitionAndSortWithinPartitions(n_par, lambda i: i // n_par))

rawDescription: repartition a dense matrix in pyspark

description: Repartition a dense matrix in pyspark


code: re.sub(r'''['"\n\\]''', lambda m: '\\{:X} '.format(ord(m.group())), inputstring)

rawDescription: Encoding a string the CSS way with python


code:
def __setattr__(self, attr, value):
    if attr == "color":
        return super(ColoredRectangle,self).setattr(attr,value)
    raise YourFavoriteException

rawDescription: Subclassing in python of instantiated superclass


code:
def vectorized_app1(s_image,i_mask,pixel_counts):
    matches = i_mask.ravel() == np.arange(numCells)[:,None]
    return matches.dot(s_image.ravel())/pixel_counts

def vectorized_app2(s_image,i_mask,pixel_counts):
    matches = i_mask.ravel() == np.arange(numCells)[:,None]
    return np.einsum('ij,j->i',matches,s_image.ravel())/pixel_counts

def org_app(s_image,i_mask,pixel_counts):
    z = np.zeros(numCells)
    for i in range(numCells):
        z[i] = ((i_mask == i)*s_image).sum()/pixel_counts[i]
    return z

rawDescription: Vectorized version of array calculation

description: Vectorized version of array calculation


code:
def calculator():
    exp = input("x= ")
    print("x=", eval(exp) )

rawDescription: python3 algebraic expression solve for x

description: Python3 algebraic expression solve for x


code:
myListOfLists = [[1,2,3],[4,5,6],[7,8,9]]
zipped = zip(*myListOfLists)
zipped

rawDescription: In Python, how can I create lists that contain a certain index of other lists?


code:
inputStr='acc'
indices=[pool.index(l) for l in inputStr]

rawDescription: Python bruteforce combinations given a starting string


code:
from difflib import SequenceMatcher
SequenceMatcher(None, string, pattern).ratio()
# => 0.7536231884057971

rawDescription: Partial Regex Matching

description: Partial Regex Matching


code:
phrase = input("Enter list of students")
for name in phrase:
    if name[0] in 'ABCDEFGHI':
        print(name)

rawDescription: Python 3 - Creating a program inputing a list and printing the strings from it alphabetically


code:
import os
os.environ['TERM'] #"linux" in console mode, "xterm" on graphic terminal

rawDescription: How to check graphical mode in Python PyGame?

description: Check graphical mode in Python PyGame


code:
self.cursor = []
for n in range(3):
    self.cursor.append(self.conn.cursor())
    self.cursor[n].execute("SET NAMES utf8")
    self.cursor[n].execute('SET CHARACTER SET utf8;')
    self.cursor[n].execute('SET character_set_connection=utf8;')

rawDescription: Creating multiple cursors

description: Creating multiple cursors


rawDescription: Print from List Python

description: Print from List Python


code:
rows, cols = 100, 100
items = 1000

rho = np.zeros((rows, cols))
rho_coeff, dt, i_frac, j_frac = np.random.rand(4, items)
pi = np.random.randint(1, rows-1, size=(items,))
pj = np.random.randint(1, cols-1, size=(items,))

# The following code assumes pi and pj have the same dtype
pij = np.column_stack((pi, pj)).view((np.void,
                                      2*pi.dtype.itemsize)).ravel()

unique_coords, indices = np.unique(pij, return_inverse=True)
unique_coords = unique_coords.view(pi.dtype).reshape(-1, 2)
data = rho_coeff*dt*i_frac*j_frac
binned_data = np.bincount(indices, weights=data)
rho[tuple(unique_coords.T)] += binned_data

rawDescription: How to use an additive assignment with list based indexing in Numpy

description: Use an additive assignment with list based indexing in Numpy


rawDescription: Between double curly braces: replace particular text


code:
new_list = ['one', 'two', 'three']
my_list[:len(new_list)] = new_list
my_list

rawDescription: Google App Engine template loop through two variables


rawDescription: Sum lists of variable lengths element-wise


code:
import tensorflow as tf
import numpy as np

trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 # create a y value which is approximately linear but with some random noise

X = tf.placeholder("float") # create symbolic variables
Y = tf.placeholder("float")

w = tf.Variable(0.0, name="weights") # create a shared variable (like theano.shared) for the weight matrix
y_model = tf.mul(X, w)
cost = tf.square(Y - y_model) # use square error for cost function
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost) # construct an optimizer to minimize cost and fit line to my data

# Launch the graph in a session
with tf.Session() as sess:
    # you need to initialize variables (in this case just variable W)
    tf.initialize_all_variables().run()

    for i in range(100):
        for (x, y) in zip(trX, trY):
            sess.run(train_op, feed_dict={X: x, Y: y})

    print(sess.run(w))  # It should be something around 2

rawDescription: How to make simple logistic regression in tensorflow?

description: Make simple logistic regression in tensorflow


code:
if request.method == "POST":
    article_id = request.POST.get('article_id') # You are getting passed article id
    a = Article.objects.get(pk=article_id)      # You are getting instance by id
    a_form = ArticleForm(request.POST, instance=a)
    a_form.save()

rawDescription: Keeping track of object id in Django view


rawDescription: In Python, how do I search a TinyDB database for substrings in the values?


rawDescription: Replace comma by newline using django

description: Replace comma by newline using django


code:
import dis
def ops(code):
    i, n = 0, len(code)
    while i < n:
        op = ord(code[i])
        i += 1
        if op == dis.EXTENDED_ARG:
            ext = ord(code[i]) + ord(code[i+1])*256
            op = ord(code[i + 2])
            i += 3
        else:
            ext = 0
        if op >= dis.HAVE_ARGUMENT:
            arg = ord(code[i]) + ord(code[i+1])*256 + ext*65536
            i += 2
            yield op, arg
        else:
            yield op, None

source_ops = list(ops(source.func_code.co_code))

rawDescription: In Python, determine if a function calls another function


rawDescription: parsing HTML table using python - HTMLparser or lxml

description: Parsing HTML table using python - HTMLparser or lxml


code:
def convert(item):
    ls = list(map(int, item.strip('()').split('/')))
    l = len(ls)
    if l == 1:
        return ls[0]
    elif l == 2:
        a, b = ls
        return float(a) / b if b else 0
    raise RuntimeError('More than 2 values!')

rawDescription: converting string list of fractions into float from scraped html / cleanest method

description: Converting string list of fractions into float from scraped html / cleanest method


code:
def first_letter_count(word, letter):
    for  number in word:
        if number[:1] in letter:
            return True
        else:
            return False

def check(letter):
    letter_count = 0
    fin = open('words.txt')
    for line in fin:
        word = line.strip()
        if first_letter_count(word, letter):
            letter_count += 1
    return str(letter) + ": " + str(letter_count)

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
oldstdout = sys.stdout
newfile = open('words_writing.txt', 'w')
for letter in alphabet:
    newfile.write(str(check(letter)))
newfile.close()
newfile2 = open('words_writing.txt', 'r')

rawDescription: writing information to a .txt file and getting None as my result

description: Writing information to a .txt file and getting None as my result


code:
import client
import collection
import database

rawDescription: How to structure my little python framework

description: Structure my little python framework


code:
_clicks = 0
while True:
    if _clicks != clicks:
        _clicks = clicks
        print(_clicks)

rawDescription: How do I get a variable from a running python function

description: Get a variable from a running python function


code:
urls.append(i.split('"')[3])
names.append(data[ind-2].split('"')[3])
# (1) relies on name being 2 lines before url
# (2) fails if there is a `"` in the name
# example: "name": "The \"Fubar\" website",

rawDescription: python display unicode in html

description: Python display unicode in html


code:
#!/usr/bin/env python3
import collections
import itertools

def pairs_of_pairs(n):
    for (i, j, k, m) in itertools.combinations(range(n), 4):
        (yield ((i, j), (k, m)))
        (yield ((i, k), (j, m)))
        (yield ((i, m), (j, k)))

def columns(n):
    return itertools.product(range(2), repeat=n)

def satisfied(pair_of_pairs, column):
    ((i, j), (k, m)) = pair_of_pairs
    return ((column[i] + column[j]) == (column[k] + column[m]))

def pop_count(valid_columns):
    return bin(valid_columns).count('1')

def main(n):
    pairs_of_pairs_n = list(pairs_of_pairs(n))
    columns_n = list(columns(n))
    universe = ((1 << len(columns_n)) - 1)
    counter = collections.defaultdict(int)
    counter[universe] = (- 1)
    for pair_of_pairs in pairs_of_pairs_n:
        mask = 0
        for (i, column) in enumerate(columns_n):
            mask |= (int(satisfied(pair_of_pairs, column)) << i)
        for (valid_columns, count) in list(counter.items()):
            counter[(valid_columns & mask)] -= count
    counter[universe] += 1
    return sum(((count * (pop_count(valid_columns) ** n)) for (valid_columns, count) in counter.items()))
if (__name__ == '__main__'):
    for n in range(4, 9):
        print(n, main(n))

rawDescription: Finding a better way to count matrices

description: Finding a better way to count matrices


code:
def private_encrypt(self, msg):
    modBits = Crypto.Util.number.size(self._key.n)
    k = ceil_div(modBits,8) # Convert from bits to bytes
    PS = bchr(0xFF) * (k - len(msg) - 3)
    m = self._key.decrypt(b("\x00\x01") + PS + bchr(0x00) + msg)
    S = bchr(0x00)*(k-len(m)) + m
    return S

rawDescription: python rsa private-encrypt to comunicate with node.js

description: Python rsa private-encrypt to comunicate with node.js


code: psutil.Process(pid=16822, name='sleep')

rawDescription: How to "adopt" a child process in python

description: "adopt" a child process in python


code: map(np.correlate, i, j)

rawDescription: Operations between two dataframes or equivalently between two multidimensional arrays


code: [{"name": n, "data": [h]} for n, h in zip(name, hits)]

rawDescription: Python loops:  Precise way to handle mapping matching lists


code:
# server1.py

poller = zmq.Poller()
poller.register(s)

while True:
    events = dict(poller.poll(0))
    if s in events:
        msg = s.recv()
        print("received %r" % msg)
        if msg == 'quit':
            break
    else:
        # no message to recv, do other things
        time.sleep(1)

rawDescription: PyZMQ one-way communication

description: PyZMQ one-way communication


code:
class Form(BaseForm):
    "A collection of Fields, plus their associated data."
    # This is a separate class from BaseForm in order to abstract the way
    # self.fields is specified. This class (Form) is the one that does the
    # fancy metaclass stuff purely for the semantic sugar -- it allows one
    # to define a form using declarative syntax.
    # BaseForm itself has no way of designating self.fields.
    __metaclass__ = DeclarativeFieldsMetaclass

rawDescription: Difference between returning modified class and using type()


code:
df['C_sign'] = np.sign(df.C)
df.groupby('A').C_sign.value_counts()
df.groupby('A').C_sign.value_counts().unstack()

rawDescription: How to count all positive and negative values in a pandas groupby?

description: Count all positive and negative values in a pandas groupby


code:
import re
re.search(r"[a-zA-Z]*", "ABC123XYZ").group()

rawDescription: Regex match till the first number occurs in a string in python


code:
list1 = [1,2,4,6,8,9,2]

dict1 = {}

for ele in list1:
    # you iterate through the list once
    if ele in dict1:
        # if a key is already in the dictionary
        # you increase the corresponding value by one
        dict1[ele] += 1
    else:
        # if a key is not yet in the dictionary
        # you set its corresponding value to one
        dict1[ele] = 1

rawDescription: Search through list with duplicates

description: Search through list with duplicates


code:
payload = {'fname': 'homer', 'lname': 'simpson',
    'favefood': ['raw donuts', 'free donuts']
}
# 'json' param is supported from requests v2.4.2
rtt = requests.post("http://httpbin.org/post", json=payload)

rawDescription: handling duplicate keys in HTTP post in order to specify multiple values

description: Handling duplicate keys in HTTP post in order to specify multiple values


rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


code: [[sum(list(a)) for a in b] for b in temp_list]

rawDescription: Sum Lists' value with corresponding index value in Python


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.layout import Layout

kv = '''
<Foo>:
    on_touch_down: print(self.size)
'''
Builder.load_string(kv)

class Foo(Layout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print (self.size)

class MyApp(App):
    def build(self):
        return Foo()

MyApp().run()

rawDescription: How can I get widget's/layout's actual size in Kivy?

description: Get widget's/layout's actual size in Kivy


code:
#!/usr/bin/env python
from httplib import HTTPConnection
from urlparse import urlsplit

urls = ["http://bit.ly/NKEIV8", "http://bit.ly/1niCdh9"]
for url in urls:
    host, path = urlsplit(url)[1:3]
    conn = HTTPConnection(host)
    conn.request("HEAD", path)
    r = conn.getresponse()
    if r.status != 404:
       print("{r.status} {url}".format(**vars()))

rawDescription: Use httplib to check if a URL will return a certain page?


code:
def myfunc():
    x = 3
    class MyClass(object):
        x = x
    return MyClass

myfunc().x

rawDescription: Creating a class within a function and access a function defined in the containing function's scope


code:
if 'from' in headers:
    do_something()

rawDescription: Python 3.x - How to check if "From:" header exists in an email file?


code:
A.x
A().x

rawDescription: Can Python classes have members that are accessible, but not from an instance of the class?


code:
def foo():
  nums = []
  for x in range(0,10):
    nums = nums.append(x)
  return mums

rawDescription: Why are integers immutable in Python?

description: Why are integers immutable in Python


code:
import matplotlib.pyplot as plt
y_data = [[1,1],[2,2],[3,3]]  #just some dummy data
x = [0,1]
fig,ax = plt.subplots()
for y in y_data:
    #generate id
    ax.cla()  #clear the axis
    ax.plot([0,1],y)
    fig.savefig(filename + id)

rawDescription: matplotlib: creating new figure and saving to file

description: Matplotlib: creating new figure and saving to file


code:
X(sub2ind(size(X), a, b))
# This is roughly equal to numpy's
X[a, b]

rawDescription: Logical indexing in Numpy with two indices as in MATLAB


code:
import re

with open(path) as f:
    queries = re.split(r"\n\n+",f.read())

rawDescription: Retrieve text blocks from file

description: Retrieve text blocks from file


code:
import re
if re.match("for([\w|\S]+)[{|\S]", line.strip()):
    from_first_bracket = line.split("(")[1]
    for_loop_conditions = from_first_bracket.split(";")
    # last item in for_loop_conditions list has extra punctuation:
    for_loop_conditions[2] = for_loop_conditions[2].split(")")[0]

rawDescription: Reading selectable portions of a line from an existing file


code: [list(item) for item in zip(a, b)]

rawDescription: How combine two list into list of list at python?


code:
df['e-mail'] = [x.split("|")[0] for x in df.index]
df['date'] = [x.split("|")[1] for x in df.index]
df.set_index(['e-mail', 'date'])

rawDescription: Coverting Index into MultiIndex (hierachical index) in Pandas


code:
class Foo():
    def __init__(self):
        self.val = 0

    def f1(self):
        self.val += 1
    def f2(self):
        self.val += 1
    def f3(self):
        self.val += 1
    def all(self):
        self.f1()
        self.f2()
        self.f3()
f = Foo()
f.all()
print(f.val)
3

rawDescription: What is the cleanest way to maintain the latest state of a variable which is used in multiple functions?


code:
x = [True, True, True, True]
x[:] = [not y for y in x]
x

rawDescription: How do I toggle a boolean array in Python?

description: Toggle a boolean array in Python


rawDescription: Using regular expressions in Python

description: Using regular expressions in Python


code:
hashtags = []

while True:                      # Read and clean each line of input.
  tweet = input('Tweet: ').lower().rstrip('\'\"-,.:;!?')
  if tweet == '':                # Check for empty input.
    break
  print('cleaned tweet: '+tweet) # Review the cleaned tweet.
  for word in tweet.split():     # Extract hashtags.
    if word[0] == '#':
      hashtags.append(word)

from collections import Counter
trend = Counter(hashtags)

for item in trend:
  print (item, trend[item])

rawDescription: Joining Strings on New Lines Error Python


code: z.base is y

rawDescription: Adding and multiplying columns of a numpy array with another array


code:
for order in Order.objects.all():
    types = order.details.values_list('product_type', flat=True)

rawDescription: Django query in One to Many relationship


code:
from os import walk, path
from fnmatch import fnmatch
[path.join(dpath, file) for dpath, _, files in os.walk("/folder/test") for file in files if fnmatch(file, 'text*')]

rawDescription: Recursively find files in python

description: Recursively find files in python


code:
from collections import namedtuple

MyStruct = namedtuple('MyStruct', 'ThreadInstance ThreadName Mnemonic IpAddr IpGW Status Mode')

NodeDb = []
Node = MyStruct(None, '', '', '', '',  -1, 0)
for id in range(4):
    NodeDb.append(Node)

NodeDb[2] = NodeDb[2]._replace(ThreadName='T2',
                               Mnemonic='ABCD',
                               IpAddr='192.0.1.2',
                               IpGW='192.0.1.3',
                               Status=0,
                               Mode=2)

print(NodeDb)

rawDescription: Python list of named tuples, replacing attributes


code:
#!/usr/bin/python
import graph

class MyVertex(graph.Vertex):
    def __init__(self,key):
        super(Vertex,self).__init__(key)

        # extensions for BFS
        self.predecessor = None
        self.dist = 0
        self.color = 'w' # white, grey, and black

class BFSGraph(Graph):

    def __init__(self):
        super(BFSGraph, self).__init__(MyVertex)

    def getColor(self,k):
        return self.getVertex(k).color

def test():
    g=BFSGraph()
    g.addVertex('a')
    g.getColor('a')

rawDescription: How do I use a new extended class instead of the original in another loaded class

description: Use a new extended class instead of the original in another loaded class


code:
import datetime

NOW = datetime.datetime.now()+datetime.timedelta(0, 44999, 178350)
msg = str(NOW)+"\n"
with open("/tmp/croncheck_output.txt", "a") as myfile:
    myfile.write(msg)

rawDescription: cronjob not running in godaddy

description: Cronjob not running in godaddy


code:
da = array(df2.to_records())
df4 = pd.DataFrame.from_records(da)
df4.columns=['Country','Series','Year','Trait']

rawDescription: Issue with transposing a data set using pandas


code: event = wx.PyEvent()

rawDescription: wxWidgets/wxPython: Do two identical events cause two handlings?

description: WxWidgets/wxPython: Do two identical events cause two handlings


code:
# filename: myapp/models.py

from django.db import models
from django.utils.translation import ugettext as _
from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import AbstractUser, Group

class MyUser(AbstractUser):

    birth_date = models.DateField(null=True)
    photo = models.ImageField(upload_to=..., null=True, blank=True, verbose_name=_("photo"))

rawDescription: Custom User's and implementations with forms


code:
import httplib
from StringIO import StringIO

msg = \
"""Set-Cookie: Foo
Set-Cookie: Bar
Set-Cookie: Baz

This is the message"""

msg = StringIO(msg)

msg = httplib.HTTPMessage(msg)

assert msg['Set-Cookie'] == 'Foo, Bar, Baz'

rawDescription: urllib2 multiple Set-Cookie headers in response

description: Urllib2 multiple Set-Cookie headers in response


code:
import scipy.integrate as spi
import scipy.special as sps
import numpy as np
import matplotlib.pyplot as plt

def Efield_r_integrand(k, z, r, R, V):
    return np.exp(-k*z)*k*R*V*sps.jv(1,k*r)*sps.jv(1,k*R)

def Efield_z_integrand(k, z, r, R, V):
    return np.exp(-k*z)*k*R*V*sps.jv(0,k*r)*sps.jv(1,k*R)

x_max, z_max, n_pts = 3.0, 3.0, 20
R, V = 2, 10

Z, X = np.mgrid[0:z_max:n_pts*1j, 0:x_max:n_pts*1j] # note that this creates a grid with the boundaries (0 and 3.0) included!

def integrate_on_grid(func, lo, hi, *args):
    """Returns a callable that can be evaluated on a grid."""
    return np.vectorize(lambda n,m: spi.quad(func, lo, hi, (n,m)+args)[0])

Efield_r, Efield_z = [integrate_on_grid(func, 0, np.inf, R, V)(Z,X)
    for func in (Efield_r_integrand, Efield_z_integrand)]

plt.quiver(X, Z, Efield_r, Efield_z)

rawDescription: Integrate using SciPy with variable integrand members and put into meshgrid


code:
import matplotlib.pyplot as plt
import numpy as np
y_values = [0.1, 0.3, 0.4, 0.2]
text_values = ["word 1", "word 2", "word 3", "word 4"]
x_values = np.arange(1, len(text_values) + 1, 1)

plt.bar(x_values, y_values, align='center')
# Decide which ticks to replace.
new_ticks = ["word for " + str(y) if y != 0.3 else str(y) for y in y_values]
plt.yticks(y_values, new_ticks)
plt.xticks(x_values, text_values)
plt.show()

rawDescription: Using text on y axis in matplotlib instead of numbers


code:
restaurant.latitude = local_lat
restaurant.longitude = local_lng

rawDescription: How can I create two views function in a models Django

description: Create two views function in a models Django


rawDescription: Smart handling of Python array with many indices


code:
def whois(k,  i):
    k = str(k[i])
    print (k)
    whois = subprocess.Popen(['whois',  k], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    ou, err = whois.communicate()
    who = str(ou)
    print (who.find('NetName:'))
    who = re.split('NetName:',  who)[1]
    who = re.split('NetHandle',   who)[0]
    who = who.replace(r'\n', '')
    return who # return who

rawDescription: re.split return None in function but normaly works OK

description: Re.split return None in function but normaly works OK


code:
# imported file
if __name__ == "__main__":
    raw_input()

rawDescription: nose test freezing at raw_input

description: Nose test freezing at raw_input


code:
def ndbincount(x, weights=None, shape=None):
    if shape is None:
        shape = x.max(1) + 1

    x = np.ravel_multi_index(x, shape)
    out = np.bincount(x, weights, minlength=np.prod(shape))
    out.shape = shape
    return out

rawDescription: Row, column assignment without for-loop

description: Row, column assignment without for-loop


code:
def intersection_graph(sets):
    adjacency_list = {}
    for i, s1 in enumerate(sets):
        for j, s2 in enumerate(sets):
            if j == i:
                continue
            try:
                lst = adjacency_list[i]
            except KeyError:
                adjacency_list[i] = lst = []
            weight = len(s1.intersection(s2))
            lst.append( (j, weight) )
    return adjacency_list

rawDescription: construct graph from python set type

description: Construct graph from python set type


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
from matplotlib.patches import PathPatch

def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
    x, y, z = xyz
    if zdir == "y":
        xy1, z1 = (x, z), y
    elif zdir == "y":
        xy1, z1 = (y, z), x
    else:
        xy1, z1 = (x, y), z

    text_path = TextPath((0, 0), s, size=size, usetex=usetex)
    trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])

    p1 = PathPatch(trans.transform_path(text_path), **kwargs)
    ax.add_patch(p1)
    art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)

# main
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, .25)
Y = np.arange(-5, 5, .25)

Xg, Yg = np.meshgrid(X, Y)
R = np.sqrt(Xg**2 + Yg**2)
Z = np.sin(R)
surf = ax.plot_surface(Xg, Yg, Z, rstride=1, cstride=1, cmap=cm.winter,
                       linewidth=0, antialiased=True)

ax.set_zlim(-2.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# add pathces with values
for i,x in enumerate(X[::4]):
    for j,y in enumerate(Y[::4]):
        text3d(ax, (x, y, -2.01), "{0:.1f}".format(Z[i][j]), zdir="z", size=.5, ec="none", fc="k")

plt.show()

rawDescription: Matplotlib: how to add a base image to a 3D plot?


code: df = df[[col_start.extend(col_add)]]

rawDescription: Pandas append list to list of column names


code:
predicted = dt_clf.predict(np.hsplit(np.dstack(predict).flatten(),
                           len(face.flatten())))

rawDescription: dealing with dimensions in scikit-learn tree.decisiontreeclassifier

description: Dealing with dimensions in scikit-learn tree.decisiontreeclassifier


code:
major_students = {}
for i in range(num_students):
    name = input("Enter Student Name: ")
    major = input("enter major: ").upper()
    major_students[major] = major_students.get(major, []) + [name]

rawDescription: Python program - Help pairing elements together without using a dictionary


code:
def f(s_month):
    date = s_month.index[0]
    # create the month long range
    rng = pd.date_range(date, date + pd.offsets.MonthEnd(1), freq='D')
    # throw away results longer than month length
    s_month = s_month.iloc[0:len(rng)]
    # reindex those remaining
    s_month.index = rng
    return s_month

rawDescription: Python: indexing pandas series by datetime


rawDescription: Shutting Down SSH Tunnel in Paramiko Programatically


rawDescription: How to get the size of tar.gz in (MB) file in python

description: Get the size of tar.gz in (MB) file in python


code:
for rownum in range (rows ):
    PrintingList.append([])
    newValues = map(int, raw_input().strip().split())
    PrintingList[rownum] += newValues

rawDescription: User input for triangles in python

description: User input for triangles in python


rawDescription: Searching and replacing in binary file

description: Searching and replacing in binary file


code:
class Datacenter:
    def __init__(self,name,location,cpu,mem):
        self.name=name
        self.location=location
        self.cpu=cpu
        self.mem=mem

class Workstation:
    def __init__(self,name,location,cpu,mem,datacenter):
        self.name=name
        self.location=location
        self.cpu=cpu
        self.mem=mem
        self.datacenter=datacenter

class Computer:
    def __init__(self,name,location,cpu,mem,workstation):
        # This line does nothing:
        self.name=name
        self.location=location
        self.cpu=cpu
        self.mem=mem
        self.workstation=workstation

rawDescription: Designing classes in python

description: Designing classes in python


rawDescription: Custom Class - Change attribute in array


rawDescription: Filter a numpy array based on largest value


code: chan.request_x11 (handler=testFunc())

rawDescription: Paramiko X11 mode with python programming


code: list = [friend for friend in list if friend.user not in blocked_users]

rawDescription: Django, exclude() function on list

description: Django, exclude() function on list


rawDescription: Pandas to_csv always substitute long numpy.ndarray with ellipsis


code:
1
do

rawDescription: passing class variables to decorator

description: Passing class variables to decorator


rawDescription: numpy gradient function and numerical derivatives

description: Numpy gradient function and numerical derivatives


code:
from django.core.serializers import serialize
from django.db.models.query import QuerySet, ValuesListQuerySet
from django.utils.safestring import mark_safe
from django.template import Library

import json

register = Library()

def jsonify(object):

    if isinstance(object, ValuesListQuerySet):
        return mark_safe(json.dumps(list(object)))
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(json.dumps(object))

register.filter('jsonify', jsonify)
jsonify.is_safe = True

rawDescription: Django Template - Convert a Python list into a JavaScript object


code:
asg.Tags= [autoscaling.Tag('Name','MyTagName','true'),
  autoscaling.Tag('Version','123456','true')]

rawDescription: Using troposphere for cloud formation, how do I add "propagate at launch" to tags


code: str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]

rawDescription: in Python, how to convert list of float numbers to string with certain format?

description: In Python, how to convert list of float numbers to string with certain format


rawDescription: Pretty-printing of numpy.array

description: Pretty-printing of numpy.array


code:
def removeslash(method):
    """Use this decorator to remove trailing slashes from the request path.

    For example, a request to '/foo/' would redirect to '/foo' with this
    decorator. Your request handler mapping should use a regular expression
    like r'/foo/*' in conjunction with using the decorator.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.request.path.endswith("/"):
            if self.request.method == "GET":
                uri = self.request.path.rstrip("/")
                if self.request.query: uri += "?" + self.request.query
                self.redirect(uri)
                return
            return self.status(404)
        return method(self, *args, **kwargs)
    return wrapper

rawDescription: How to do some code before get() and post() are called?

description: Do some code before get() and post() are called


rawDescription: Python Tkinter Text-Widget scroll to specific line


rawDescription: Groupby separate sum with commas

description: Groupby separate sum with commas


rawDescription: Call a function in a class from different class


code:
"1233",  "jake", "jake@mailinator.com", "USA"
"5678", "natalia", "natalia@mailinator.com", "USA"

rawDescription: comparing 2 large unsorted CSV files based on 2 columns

description: Comparing 2 large unsorted CSV files based on 2 columns


code:
import re
example = "This has one pattern that you're expecting, 01-234-5678, and another that maybe you aren't: 23:456:7"
pattern = re.compile(r'\b(\d{2}(?P<sep>[-:\s]?)\d{3}(?P=sep)\d(?:\d{3})?)\b')
pattern.findall(example)

rawDescription: regex conditional matching

description: Regex conditional matching


code:
from collections import defaultdict
d = defaultdict(list)
with open("in.txt") as f:
    for line in f:
        spl = line.split(":")[2]
        d[spl].append(line)
repeated  =  [v for v in d.values() if len(v) > 1]

rawDescription: Identify duplicate values in specific fields of a multi line file in python


code: long_name_tag_text = bsObj.find('type', text='route').findPreviousSibling('long_name').text

rawDescription: Look for XML tag value and select the parent which contains the requested tag value


code: setText(doc, node, "textinsidetest2")

rawDescription: How to set text on an xml node without any children in xml.minidom in python?

description: Set text on an xml node without any children in xml.minidom in python


rawDescription: What's the relationship between 'BeautifulSoup' and 'lxml'?


code:
# coding: utf-8

from Tkinter import *

root = Tk()
text = Text(root)
text.pack()

QUERY = u'\u0627\u0631\u062c\u0648'
TEXT = u'word=\\u0631\\u064e\\u062c\\u0627'  # escaped!!
TEXT = TEXT.decode('unicode-escape')
word = re.findall(u'word=.*', TEXT, re.UNICODE)[0]
header = " ".join([QUERY, word])
text.insert('1.0', "".join([header,'\n']))

root.mainloop()

rawDescription: How to insert arabic script into Tkinter text widget correctly?

description: Insert arabic script into Tkinter text widget correctly


code:
foo = 1
bar = foo
baz = foo

rawDescription: How do I get the string representation of a variable in python?

description: Get the string representation of a variable in python


code:
import os

import redis
from rq import Worker, Queue, Connection

from after_hours import after_6_hours

listen = ['high', 'default', 'low'] # while scheduling the task in views.py we sent it to default

redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')

conn = redis.from_url(redis_url)

if __name__ == '__main__':
    with Connection(conn):
        worker = Worker(map(Queue, listen))
        worker.work()

rawDescription: How to schedule a single-time event in Django in Heroku?

description: Schedule a single-time event in Django in Heroku


code:
[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]

rawDescription: Converting two lists into a matrix

description: Converting two lists into a matrix


code: parser_class = parser2.Parsers()

rawDescription: Converting functions into a methods of a class in python


rawDescription: Python: Way to speed up a repeatedly executed eval statement?


code:
c1 = myclass()
c2 = myclass(argument2='weekend')

rawDescription: Python27: Subclassing a class by using type


code:
from matplotlib import pyplot as plt

# default parameters
fs1, ps1 = welch(x, sfreq, nperseg=256, noverlap=128)

# 8x the segment size, keeping the proportional overlap the same
fs2, ps2 = welch(x, sfreq, nperseg=2048, noverlap=1024)

# no overlap between the segments
fs3, ps3 = welch(x, sfreq, nperseg=2048, noverlap=0)

fig, ax1 = plt.subplots(1, 1)
ax1.hold(True)
ax1.loglog(fs1, ps1, label='Welch, defaults')
ax1.loglog(fs2, ps2, label='length=2048, overlap=1024')
ax1.loglog(fs3, ps3, label='length=2048, overlap=0')
ax1.legend(loc=2, fancybox=True)

rawDescription: Efficiently compute 50Hz content of signal


code:
inner = List[0]
inner.insert(1,'Another Value')

rawDescription: Python - is it possible to insert() into a list inside of a list?


rawDescription: decision trees from features of multiple datatypes

description: Decision trees from features of multiple datatypes


code: response.content_type = "text/xml"

rawDescription: Set http response Content-Type to "xml" in python


code:
class PowerUp(QtGui.QGraphicsRectItem):
    def __init__(self):
        QtGui.QGraphicsRectItem.__init__(self)
        self.images = ['data/images/objects/bonus_block/full-0.png',
                       'data/images/objects/bonus_block/full-1.png',
                       'data/images/objects/bonus_block/full-2.png',
                       'data/images/objects/bonus_block/full-3.png',
                       'data/images/objects/bonus_block/full-4.png']
        self.image = self.images[0]
        self.current = 0
        self.position()
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.animation_step)
        self.timer.start(175)
        #random.choice([slide(), ghost()])

    def position(self):
        self.pos_x = random.randint(-300, 300)
        self.pos_y = random.randint(-200, 200)

    def boundingRect(self):
        return QtCore.QRectF(0, 0, 32, 32)

    def paint(self, painter, option, widget):
        painter.setBrush(QtGui.QBrush(self.image))
        painter.setPen(QtGui.QPen(QtCore.Qt.NoPen))
        painter.drawRect(0, 0, 32, 32)
        self.setPos(self.pos_x, self.pos_y)

    def animation_step(self):
        self.image = QtGui.QPixmap(self.images[self.current])
        self.current += 1
        if self.current == len(self.images):
            self.current = 0

rawDescription: PyQT4 and tiles animation

description: PyQT4 and tiles animation


code: zip(*map(a.get, sorted(a)))

rawDescription: zipping a python dict of lists

description: Zipping a python dict of lists


code:
interpreter = code.InteractiveInterpreter(locals())
interpreter.runsource( parsed_line )

rawDescription: referring to self from within self in python

description: Referring to self from within self in python


rawDescription: Is it better to use globals or pass in arguments to map functions?


code:
for item in iterable:
    print(item)

rawDescription: Is there any single function to print iterables values


code:
X,Y,Z = np.meshgrid(x,y,z)
out = np.column_stack((X.ravel('F'),Y.ravel('F'),Z.ravel('F')))

rawDescription: Combine multi-dimentional data in numpy

description: Combine multi-dimentional data in numpy


rawDescription: Django: ForeignKey to_field and db_column doesn't seem to work


code:
collection = (line.split()[1] for line in open("/etc/mtab")
              if line.split()[1].startswith('/foo/bar'))

rawDescription: python way to get mounted filesystems

description: Python way to get mounted filesystems


rawDescription: Used a for loop to create a certain number of entry boxes but can only .get last value from last entrybox


code: d = collections.OrderedDict(sorted(d.items(), key=lambda key_value_pair: key_value_pair[1]['b']))

rawDescription: python: sorting an ordered dictionary

description: Python: sorting an ordered dictionary


code:
value_manual = fields.Float()
manual = fields.Boolean(compute='_is_manual', default=True)

@api.one
@api.depends('child_ids')
def _is_manual(self):
    self.manual = len(self.child_ids) == 0

rawDescription: How to make a field computed only if some condition is fulfilled in Odoo 8?

description: Make a field computed only if some condition is fulfilled in Odoo 8


rawDescription: Dot notation string manipulation

description: Dot notation string manipulation


code:
a = make_ticker()
a()
a()
a()

rawDescription: Best way to make a counter based on time

description: Make a counter based on time


code:
s = '''"Hello this is

me

Dr Pablov

"'''

soup = BeautifulSoup(s, 'html.parser') # force html.parser to avoid lxml's auto-inclusion of

unwrapper(soup)

soup
Out[63]: "Hello this is

me

Dr Pablov

"

rawDescription: BeautifulSoup4 parse everything except specific tags


code:
kitchen_items = [
    "Rice", "Chickpeas", "Pulses", "bread", "meat",
    "Milk", "Bacon", "Eggs", "Rice Cooker", "Sauce",
    "Chicken Pie", "Apple Pie", "Pudding"
    ]

rawDescription: Is this a cleanest way to write a long list in Python?


rawDescription: Django post_save get attribute of instance


code:
import wtforms
import wtforms.validators as validators
from flask.ext.wtf import Form

class RegistrationForm(Form):
    """
    This Form class contains all of the fileds that make up our registration
    Form.
    """
    #Get all of the text fields out of the way.
    first_name_field = wtforms.TextField(
            label="First Name",
            validators=[validators.Length(max=70), validators.Required()])
    last_name_field = wtforms.TextField(
            label="Last Name",
            validators=[validators.Length(max=70), validators.Required()])
    address_line_one_field = wtforms.TextField(
            label="Address",
            validators=[validators.Length(max=256), validators.Required()])
    address_line_two_field = wtforms.TextField(
            label="Second Address",
            validators=[validators.Length(max=256), ])
    city_field = wtforms.TextField(
            label="City",
            validators=[validators.Length(max=50), validators.Required()])
    # Now let's set all of our select fields.
    state_select_field = wtforms.SelectField(label="State", coerce=int)
    country_select_field = wtforms.SelectField(label="Country", coerce=int)

rawDescription: Creating flask form with selects from more than one table


code:
text/html
image/x-png
text/html
application/ogg

rawDescription: How to check the url is either web page link or file link in python

description: Check the url is either web page link or file link in python


rawDescription: Restructuring Nested Dictionaries Python


code:
newurl = urlparse.urlunparse(
[newqs if i == 4 else x for i,x in enumerate(parsed)])
newurl

rawDescription: Updating Query In URL With Urlib In Python


code: env = dict(envvar.split(b'=', 1) for envvar in iter(iter(environ).next, None))

rawDescription: python: getting actual environment variables to modify and pass to subprocess

description: Python: getting actual environment variables to modify and pass to subprocess


code:
import collections

class CountedOrderedDict(collections.OrderedDict):
    def __init__(self, key=lambda k: k, *args, **kwargs):
        self.counter = collections.Counter()
        self.key_transform = key
        super(CountedOrderedDict, self).__init__(*args, **kwargs)

    def __delitem__(self, key):
        super(CountedOrderedDict, self).__delitem__(key)
        self.counter[self.key_transform(key)] -= 1

    def __setitem__(self, key, value):
        if key not in self:
            self.counter[self.key_transform(key)] += 1

        super(CountedOrderedDict, self).__setitem__(key, value)

rawDescription: Get key count from OrderedDict where key is a tuple


code:
def obfuscation(character_list):
    return {k: sorted(character_list, key=lambda k: random.random()) for k in character_list}

rawDescription: itertools.izip (and _longest) dictionary incomplete

description: Itertools.izip (and _longest) dictionary incomplete


code:
from bs4 import BeautifulSoup
sample1 = BeautifulSoup('''\

 Hello I have a link

 I have a bullet point

foo

''').find('div')
sample2 = BeautifulSoup('''\

 I only have paragraph

''').find('div')
sample1.get_text()
sample2.get_text()

rawDescription: Python: Parse all elements under a div

description: Python: Parse all elements under a div


code: dt = weight_now.weight_date - weight_then.weight_date

rawDescription: How do I subtract two dates in Django/Python?

description: Subtract two dates in Django/Python


code:
if data=="":
    break

rawDescription: reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2

description: Reading binary data and retrieving per condition : working fine in Python 2.6.x but not in Python 3.2


code: foreign_numbers = list(filter(find_non_uk, number_plates))

rawDescription: How can I explain the function of filter and lambda in a line of code?

description: Explain the function of filter and lambda in a line of code


rawDescription: Python Challenge level 17 in Python 3

description: Python Challenge level 17 in Python 3


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

videos = {}

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html', my_videos=videos)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler),
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            debug=True,
        )
        tornado.web.Application.__init__(self, handlers, **settings)

    def update_categories(self):
        videos.clear()
        for path, subdirs, files in os.walk(self.settings['static_path'] + '/videos/'):
            category_name = os.path.basename(path)
            videos[category_name] = []
            for name in files:
                videos[category_name].append(name)

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = Application()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.PeriodicCallback(app.update_categories, 1000).start() # run every second
    tornado.ioloop.IOLoop.instance().start()

rawDescription: how do i design a tornado static handler to serve lots of f video files using the same statichandler?

description: Design a tornado static handler to serve lots of f video files using the same statichandler


code:
xmin = -100
xmax = 100
binsize = 20

rawDescription: Weighted mean in numpy/python

description: Weighted mean in numpy/python


code: res.merge(df2, on=['RevID', 'Date'])

rawDescription: Merging Dataframes with Arrays?

description: Merging Dataframes with Arrays


rawDescription: Tkinter: How to make a button center itself?


code:
def switch(**variables):
    if 'x' in variables:
        switch_x = True
    if 'y' in variables:
        switch_y = True
    if 'z' in variables:
        switch_z = True

rawDescription: Python: Detect if certain variable is inputted into function argument


code:
df = pd.DataFrame(ts)
df.ix[df.index.indexer_between_time(datetime.time(10), datetime.time(14))]

rawDescription: Pandas Drop Rows Outside of Time Range

description: Pandas Drop Rows Outside of Time Range


code:
from collections import deque

def generate_children(tree):
    queue = deque()
    queue.append((tree, None))

    while queue:
        node, parent = queue.pop()
        children = []
        for child in node['children']:
            queue.append((child, node['id']))
            children.append(child['id'])
        yield node['id'], parent, children

rawDescription: keeping the child and parent relationship while traversing a json tree in python

description: Keeping the child and parent relationship while traversing a json tree in python


code:
dzip = lambda f, a, b: {key: f(a.get(key, ""), b.get(key, ""))
    for key in set.intersection(set(a.keys()), set(b.keys()))}

rawDescription: Merge values of a dictionary by key based on custom function


code:
def mousePressEvent(self, event):
    self.setAutoScroll(False)
    QtGui.QTreeWidget.mousePressEvent(self, event)
    self.setAutoScroll(True)

rawDescription: How do I stop the QTreeWidget from moving the scroll position?

description: Stop the QTreeWidget from moving the scroll position


rawDescription: How to find urdu words in a string using python

description: Find urdu words in a string using python


code:
import config
import functions

class MyClass(object):
    def __init__(self, key=config.key):
        config.key = key

rawDescription: Passing a parameter between python classes


rawDescription: NetworkX multi-directed graph possible?

description: NetworkX multi-directed graph possible


code:
'a.csv'.endswith(('.txt', '.csv'))
'a.txt'.endswith(('.txt', '.csv'))
'a.bin'.endswith(('.txt', '.csv'))

rawDescription: FTP_ASCII in Python

description: FTP_ASCII in Python


code:
import pprint
pprint.pprint(dic)

rawDescription: Scanning and replacing values inside nested dictionary


code:
encoding=req.headers['content-type'].split('charset=')[-1]
ucontent = unicode(content, encoding)

rawDescription: urllib2 read to Unicode

description: Urllib2 read to Unicode


code:
fields = [{'name':'xxx', 'age':24, 'location':'city_name'},
          {'name':'yyy', 'age':24, 'location':'city_name'}]
for field in fields:
    field['location'] = 'loc'
fields

rawDescription: How to update a list that contains values as dictionaries?

description: Update a list that contains values as dictionaries


code:
class FreezableDict (dict):
    __frozen = False

    def freeze (self):
        self.__frozen = True

    def __setitem__ (self, key, value):
        if self.__frozen and key not in self:
            raise ValueError('Dictionary is frozen')
        super().__setitem__(key, value)

rawDescription: Python: Freeze dict keys after creation

description: Python: Freeze dict keys after creation


code: data = conn.recv(1024).strip()

rawDescription: Simple Python Socket Server Not Taking Conditional Statement


code:
def isListSorted(l):
  for i in range(len(l)-1):
    if l[i] > l[i+1]: return False

  return True

rawDescription: Bubble Sort following an algorithm

description: Bubble Sort following an algorithm


code:
def savetxt_compact(fname, x, fmt="%.6g", delimiter=','):
    with open(fname, 'w') as fh:
        for row in x:
            line = delimiter.join("0" if value == 0 else fmt % value for value in row)
            fh.write(line + '\n')

rawDescription: How to format in numpy savetxt such that zeros are saved only as "0"

description: Format in numpy savetxt such that zeros are saved only as "0"


code:
#file GUI.py
from base import *
import tkinter as tk # in 3.X, Tkinter in 2.X

def compute():
    i1 = e1.get()
    r1 = f1(i1)

    i2 = e2.get()
    r2 = f2(r1, i2)
    r3 = f3(r2)

    l1.configure(text = r3) #if r3 is a string else str(r3)

app = tk.Tk()
e1 = tk.Entry(app)
e1.grid()

e2 = tk.Entry(app)
e2.grid()

b1 = tk.Button(app, text = "Compute", command = compute)
b1.grid()

l1 = tk.Label(app)
l1.grid()

app.mainloop()

rawDescription: How to create a light GUI with TkInter

description: Create a light GUI with TkInter


code:
class SaleFilterForm(forms.Form):
    ...

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(SaleFilterForm, self).__init__(*args, **kwargs)

rawDescription: Django - can I get the current user when I'm not in a view function


code:
def matrix_cofactor(matrix):
    return np.linalg.inv(matrix).T * np.linalg.det(matrix)

rawDescription: Speed up python code for computing matrix cofactors


code:
import re

characters, numbers = re.search(r'([A-Z]+)(\d+)', inputstring).groups()

rawDescription: Parsing String with Python

description: Parsing String with Python


rawDescription: Is there an IPython notebook server status query?


code:
import numpy as np
np.fill_diagonal(coocc.values, 0)
coocc

rawDescription: Constructing a co-occurrence matrix in python pandas


rawDescription: In Python how do I create a data frame with a list that contains multiple levels of dictionaries?


code: sum(sum(c.values()) for c in numbers.values())

rawDescription: Sum of values across all nested dictionaries in python


code:
import sys
import os
from cx_Freeze import setup, Executable
import scipy

scipy_path = os.path.dirname(scipy.__file__) #use this if you are also using scipy in your application

build_exe_options = {"packages": ["pyface.ui.wx", "tvtk.vtk_module", "tvtk.pyface.ui.wx", "matplotlib.backends.backend_tkagg"],
                     "excludes": ['numarray', 'IPython'],
                     "include_files": [("C:\\Python27\\Lib\\site-packages\\tvtk\\pyface\\images\\", "tvtk\\pyface\\images"),
                                       ("C:\\Python27\\Lib\\site-packages\\pyface\\images\\", "pyface\\images"),
                                       ("C:\\Python27\\Lib\\site-packages\\tvtk\\plugins\\scene\\preferences.ini", "tvtk\\plugins\\scene\\preferences.ini"),
                                       ("C:\\Python27\\Lib\\site-packages\\tvtk\\tvtk_classes.zip", "tvtk\\tvtk_classes.zip"),
                                       ("C:\\Python27\\Lib\\site-packages\\mayavi\\core\\lut\\pylab_luts.pkl","mayavi\\core\\lut\\pylab_luts.pkl"),
                                       ("C:\\Python27\\Lib\\site-packages\\mayavi\\preferences\\preferences.ini","mayavi\\preferences\\preferences.ini"),
                                       ("C:\\Python27\\Lib\\site-packages\\numpy\\core\\libifcoremd.dll","numpy\\core\\libifcoremd.dll"),
                                       ("C:\\Python27\\Lib\\site-packages\\numpy\\core\\libmmd.dll","numpy\\core\\libmmd.dll"),
                                       (str(scipy_path), "scipy") #for scipy
                                       ]
                     ,"create_shared_zip": False #to avoid creating library.zip
                     }

executables = [
    Executable('myfile.py', targetName="myfile.exe", base=None)
]

setup(name='myfile',
      version='1.0',
      description='myfile',
      options = {"build_exe": build_exe_options},
      executables=executables
      )

rawDescription: Packaging a python application ( with enthought, matplotlib, wxpython) into executable


code:
import os

with open('output_file', 'wb') as fout:
    fout.write(os.urandom(1024)) # replace 1024 with size_kb if not unreasonably large

rawDescription: Creating random binary files

description: Creating random binary files


code:
lines = []
while True:
    line = input()
    if line:
        lines.append(line)
    else:
        break
text = '\n'.join(lines)

rawDescription: How to get multiline input from user

description: Get multiline input from user


code:
if __name__ == "__main__":
    answer = raw_input("Do you want to restart this program ? ")
    if answer == "yes":
        restart_program()

rawDescription: How to make process to do some action upon user request in Python?

description: Make process to do some action upon user request in Python


code:
def doThisString (mystr, path):
    def function (): write (mystr, path)
    doThis (function)

rawDescription: Reference function's scope while inside another function


code:
import pygame
pygame.init()

pygame.mixer.music.load("alert.ogg")
pygame.mixer.music.play()
pygame.event.wait()

rawDescription: How would I go about playing an alarm sound in python?


code:
class cons:
    def __init__(self, head, tail=None):
        self.head = head
        self.tail = tail

    def flip(self):
        if not self.tail == None:
            tmp = self.head
            self.head = self.tail.head
            self.tail.head = tmp

def llsort(head):
    changed = True
    while changed:
        changed = False
        current = head
        while current.tail != None:
            if current.head > current.tail.head:
                current.flip()
                changed = True
            current = current.tail

rawDescription: Sorting a Sublist in a Linked List Python


code: f.apply(clean, axis=1)

rawDescription: Changing data in a dataframe with hierarchical indexing


rawDescription: Python regexp for data of byte numbers

description: Python regexp for data of byte numbers


code:
from scipy.spatial import cKDTree
gal_tree = cKDTree(gal_pos)
np.all(np.equal(count_neighbours(rand_pos, gal_pos, 0.1),
                [len(x) for x in gal_tree.query_ball_point(rand_pos, 0.1)]))

rawDescription: Trying to perform an operation on all sub arrays inside a numpy array without using a for (or similar) loops


rawDescription: Python parse int from string

description: Python parse int from string


code: print("You can get {}% back with text corrections".format(wrong))

rawDescription: Invalid syntax with if

description: Invalid syntax with if


code:
s1
s2
pd.concat([s1, s2], axis=1)

rawDescription: Combining two series in pandas along their index


code: popen_cmd_shell('su -c ls - root')

rawDescription: Automating switching from normal user to root with subproccess in python


code:
@patch.object(datetime, 'now')
def test_next_date(self, nowfunc):
    nowfunc.return_value = ... # required result
    # the rest of the test

rawDescription: How to test methods that compute relative time in python using unitttest?

description: Test methods that compute relative time in python using unitttest


code:
import re

class AClass:

    def __dir__(self):
        return [x for x in super().__dir__() if not re.match(r'__\S+__$', x)]

    def method(self):
        pass

rawDescription: Modifying built-in function

description: Modifying built-in function


code:
import os

tab = 4 * ' '

def writedirs(fhandle, path, depth=0):
    ''' Recursively walk the directory tree starting at path,
        writing all directory names to open file handle fhandle.
        Nodes are traversed depth-first, top-down, and names
        are indented proportional to their depth.
    '''
    data = os.listdir(path)
    # Names returned by listdir are in file system order;
    # If you want them sorted alphabetically, call
    # data.sort()
    # or
    # data.sort(key=str.lower)
    # for case-insensitive sorting.

    indent = depth * tab
    depth += 1
    for filename in data:
        fullpath = os.path.join(path, filename)
        if os.path.isdir(fullpath):
            fhandle.write(indent + filename + '\n')
            writedirs(fhandle, fullpath, depth)

#Test
rootdir = 'testfolder'
outname = 'file.txt'
with open(outname, 'w') as fhandle:
    writedirs(fhandle, rootdir)

rawDescription: Python move "met conditional value" outside of loop


rawDescription: how to transform element then insert into numpy array

description: Transform element then insert into numpy array


code: y = line.strip().split(",")

rawDescription: Python: How to separate string with comma


rawDescription: Django store regular expression in DB which then gets evaluated on page


rawDescription: Use a symbol for multiplication operator in sympy output in ipython notebook


code: g.filter(lambda x: len(x) > 1)

rawDescription: Pandas groupby: get size of a group knowing its id (from .grouper.group_info[0])


code:
# othermodule
import mainmodule

def print_user():
    print("user input: " + mainmodule.main_window().input_user())

rawDescription: PyQt lineEdit is empty when called from another script


code:
import copy

def preserveMember(func):
    def dec(self):
        oldMember = self.myMember
        self.myMember = copy.deepcopy(self.myMember)
        func(self)
        self.myMember = oldMember
    return dec

rawDescription: Python: a decorator to save and restore data member


code: pd.merge(df1.reset_index(), df2.reset_index(), how='inner', on=['id'])

rawDescription: How to merge two grouped-by Pandas Dataframes by a common column(ID) together?

description: Merge two grouped-by Pandas Dataframes by a common column(ID) together


code:
import glob

for file in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
    print(file)

rawDescription: Find and rename files using a Python script


code: queries &= Q(**{key: options[key]})

rawDescription: Django: How do I use a string as the keyword in a Q() statement?


code:
def func():
    list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
    with open('example.txt') as f:
        for line in f:
            yield dict(zip(list_of_keys,line.strip().split(',')))

print(list(func()))
[{'P_Width': '0.2', 'S_Length': '2.1', 'Predicate': 'Iris', 'S_Width': '3.5', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '4.9', 'Predicate': 'Ilia', 'S_Width': '3.0', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '3.7', 'Predicate': 'Iridium', 'S_Width': '3.2', 'P_Length': '1.3'}]

rawDescription: Make a list of dynamic dictionary python


code:
E=Example()
E.example()#explicitly call example method in the class

rawDescription: Why object's attributes are not there when the class is instantiated?


code:
from scrapy.spider import BaseSpider

class MySpider(BaseSpider):
    name = 'filtertest'
    start_urls = ['http://www.altria.com']

    def parse(self, response):
        self.log(response.url)

rawDescription: Allow redirects in Scrapy

description: Allow redirects in Scrapy


code:
new_doc = [' '.join([word for word in sent.split() if word not in exclude]) for sent in documents]

new_doc

rawDescription: Deleting words from text list

description: Deleting words from text list