code:
import os
import re

r = re.compile(r'log_\d{8}-\d{2}-\d{2}-\d{2}_\d{4}\.txt$')

latest_file = \
    max(filter(r.search,os.listdir('/path/to/logs')))

print(latest_file)

rawDescription: How to search the file with recent timestamp using Python?

description: Search the file with recent timestamp using Python


code:
import collections
import random

cnt = collections.Counter()
for i in range(101):
  number = random.randint(1, 100)
  if number % 2 == 0:
    cnt['even'] += 1
  else:
    cnt['odd'] += 1
print(cnt)

rawDescription: Can someone help me with my program keeping a counter in python


code:
from BeautifulSoup import BeautifulSoup
BeautifulSoup(myString).text

rawDescription: Regex Remove Markup Python

description: Regex Remove Markup Python


code:
import numpy
numpy.test('full')

import scipy
scipy.test('full')

rawDescription: Is there a test suite for numpy / scipy?

description: Is there a test suite for numpy / scipy


code:
from pylons import session
session["something"] = whatever()
session.save()

# somewhen later
something = session["something"]

rawDescription: What can I attach to pylons.request in Pylons?


code:
currentCount = 0
currentValue = lst[0]
for val in lst:
   if val == currentValue:
      currentCount += 1
   else:
      currentCount -= 1

   if currentCount == 0:
      currentValue = val
      currentCount = 1

rawDescription: Determine if a Python list is 95% the same?


code:
test[:, ~np.all(test.mask, axis=0)]
#masked_array(data =
# [[1 --]
# [-- 3]
# [1 4]],
#             mask =
# [[False  True]
# [ True False]
# [False False]],
#       fill_value = 0)

rawDescription: Remove columns where every value is masked


code:
for apple in tree:
    if (apple.weight + basket.weight) > 10:
       send(basket)
       basket.clear()
    basket.add(apple)

rawDescription: Pythonic equivalent of unshift or redo?

description: Pythonic equivalent of unshift or redo


code:
for row in itertools.islice(read, stop = rownum):
    out_writer.writerow(row)

rawDescription: For row in read limitation python

description: For row in read limitation python


code:
DatabaseFifoQueue = _serializable_queue(myqueue.DatabaseQueue, \
_pickle_serialize, pickle.loads)
...

rawDescription: Storing scrapy queue in a database

description: Storing scrapy queue in a database


code: J = nltk.pos_tag(J)

rawDescription: How to use a POS Tagger NLTK for an Imported CSV File in Python 3

description: Use a POS Tagger NLTK for an Imported CSV File in Python 3


code:
import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

rawDescription: Gaussian fit for Python

description: Gaussian fit for Python


code:
import contextlib
import os

filenames = ['a','b','c','d','e']
output_file = 'fred'

# setup files for test
for filename in filenames:
    with open(filename, 'w') as fp:
        for i in range(10):
            fp.write('%s %d\n' % (filename, i))
if os.path.exists('fred'):
    os.remove('fred')

# open all the files and use zip to interleave the lines
with open(output_file, 'w') as out_file, contextlib.ExitStack() as in_files:
    files = [in_files.enter_context(open(fname)) for fname in filenames]
    for lines in zip(*files):
        # if you're not sure last line has a \n
        for line in lines:
            out_file.write(line)
            if not line.endswith('\n'):
                out_file.write('\n')
        # if you are sure last line has a \n
        # out_file.write(''.join(lines))

print(open('fred').read())

rawDescription: Copy each line of file1 into every other line of file2 (Python)


code:
import re

re_name = re.compile(r'-\(([^)]+)\)')
re_args = re.compile(r'{([^}]+)}')

def parse(chars, history=[]):
  body = ''
  while chars:
    char = chars.pop(0)
    if char == '[':
      name = re_name.search(body).group(1)
      args = re_args.search(body)
      start = '<'+name
      if args:
        for arg in args.group(1).split(','):
          start += ' '+arg.strip().replace(':', '=')
      start += '>'
      end = '</'+name+'>'
      history.append(start)
      history.append(parse(chars))
      history.append(end)
      body = ''
      continue
    if char == ']':
      return body.strip()
    body += char
  return history

code = '''
-(head)[
    -(title)[Nested tags]
    -(random)[Stuff]
]

-(body){class:"nav", other:stuff, random:tests}[
    -(div)[
        -(h1)[Nested tags]
        -(p)[Paragraph]
    ]
]
'''

parsed = parse(list(code))
print(''.join(parsed))

rawDescription: How to split a string into a list but not brackets?

description: Split a string into a list but not brackets


code:
grid_x.ravel()
grid_y.ravel()
grid_z.ravel()
interpolated_quantity.ravel()

rawDescription: How to unravel data interpolated with griddata

description: Unravel data interpolated with griddata


code:
import re
s = 'Hi, How are you?'
[x for x in re.split('(\s|!|\.|\?|\n)', s) if x.strip()]

rawDescription: Python: Regex Search

description: Python: Regex Search


code:
MatFile = pkgutil.get_data('impy.implosions', 'LILAC_Materials.csv')
dataReader = csv.reader(MatFile.decode('utf-8').splitlines(), delimiter=',')

rawDescription: Reading a csv (text) file with pkgutil.get_data


code:
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import scipy.interpolate
import numpy
import matplotlib
import matplotlib.pyplot as plt

# close old plots
plt.close("all")

# some parameters
N = 300             # number of points for interpolation
xy_center = [2,2]   # center of the plot
radius = 2          # radius

# mostly original code
meanR = [9.95184937,   9.87947708,   9.87628496,   9.78414422,
         9.79365258,   9.96168969,   9.87537519,   9.74536093,
        10.16686878,  10.04425475,  10.10444126,  10.2917172 ,
        10.16745917,  10.0235203 ,   9.89914   ,  10.11263505,
         9.99756449,  10.17861254,  10.04704248]

koord = [[1,4],[3,4],[1,3],[3,3],[2,3],[1,2],[3,2],[2,2],[1,1],[3,1],[2,1],[1,0],[3,0],[0,3],[4,3],[0,2],[4,2],[0,1],[4,1]]

x,y = [],[]
for i in koord:
    x.append(i[0])
    y.append(i[1])

z = meanR

xi = numpy.linspace(-2, 6, N)
yi = numpy.linspace(-2, 6, N)
zi = scipy.interpolate.griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')

# set points > radius to not-a-number. They will not be plotted.
# the dr/2 makes the edges a bit smoother
dr = xi[1] - xi[0]
for i in range(N):
    for j in range(N):
        r = numpy.sqrt((xi[i] - xy_center[0])**2 + (yi[j] - xy_center[1])**2)
        if (r - dr/2) > radius:
            zi[j,i] = "nan"

# make figure
fig = plt.figure()

# set aspect = 1 to make it a circle
ax = fig.add_subplot(111, aspect = 1)

# use different number of levels for the fill and the lines
CS = ax.contourf(xi, yi, zi, 60, cmap = plt.cm.jet, zorder = 1)
ax.contour(xi, yi, zi, 15, colors = "grey", zorder = 2)

# make a color bar
cbar = fig.colorbar(CS, ax=ax)

# add the data points
# I guess there are no data points outside the head...
ax.scatter(x, y, marker = 'o', c = 'b', s = 15, zorder = 3)

# draw a circle
# change the linewidth to hide the
circle = matplotlib.patches.Circle(xy = xy_center, radius = radius, edgecolor = "k", facecolor = "none")
ax.add_patch(circle)

# make the axis invisible
for loc, spine in ax.spines.iteritems():
    # use ax.spines.items() in Python 3
    spine.set_linewidth(0)

# remove the ticks
ax.set_xticks([])
ax.set_yticks([])

# Add some body parts. Hide unwanted parts by setting the zorder low
# add two ears
circle = matplotlib.patches.Ellipse(xy = [0,2], width = 0.5, height = 1.0, angle = 0, edgecolor = "k", facecolor = "w", zorder = 0)
ax.add_patch(circle)
circle = matplotlib.patches.Ellipse(xy = [4,2], width = 0.5, height = 1.0, angle = 0, edgecolor = "k", facecolor = "w", zorder = 0)
ax.add_patch(circle)
# add a nose
xy = [[1.5,3], [2,4.5],[2.5,3]]
polygon = matplotlib.patches.Polygon(xy = xy, facecolor = "w", zorder = 0)
ax.add_patch(polygon)

# set axes limits
ax.set_xlim(-0.5, 4.5)
ax.set_ylim(-0.5, 4.5)

plt.show()

rawDescription: How to fit result of matplotlib.pyplot.contourf into circle?

description: Fit result of matplotlib.pyplot.contourf into circle


code:
top = Tk()
E1 = Entry(top, bd =5)
E1.insert(0, "User Name")
E1.pack(side = RIGHT)
top.mainloop()

rawDescription: Text superimposed in a textbox

description: Text superimposed in a textbox


code:
os.environ['var'] = "foo_bar"
subprocess.call(['echo $var'], shell=True)

rawDescription: How to use bash variables inside a Python code?

description: Use bash variables inside a Python code


code:
import regex

regO = regex.compile(r'''
    \w+ \( (?: name\['([^']*)'] (?: ,[ ] | (?=\)) ) )* \)
    ''', regex.VERBOSE);

regO.sub(lambda m: 'XYZ(' + (', '.join(m.captures(1))) + ')', s)

rawDescription: Replacing repeated captures

description: Replacing repeated captures


code: return HttpResponse(status=204)

rawDescription: Django: Button that updates database without redirection


code: print('\n'.join(filter(bool, [Var1, Var2, Var3, Var4, Var5, Var6])))

rawDescription: Print only variables that are True Python 3.3


code:
A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]

from itertools import cycle
zip_list = zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B)

rawDescription: How to zip two different size list in python

description: Zip two different size list in python


code:
#Labels and Boxes
from Tkinter import *

WD = Tk()
WD.geometry('350x250+50+200')
WD.title("Area")

solution = DoubleVar()
base = DoubleVar()
height = DoubleVar()
def calculate():
    boxSolution.delete(0,END)
    boxSolution.insert(0,(base.get())*(height.get()))

buttonCalculate = Button(WD,text = "Calculate area...", command = calculate)
buttonCalculate.grid(row =4, column =0)

myLabel3=Label(WD,text="Area", fg="black")
myLabel3.grid(row =3, column =0, sticky='w')
boxSolution= Entry(WD,textvariable=solution)
boxSolution.grid(row =3, column =1)

myLabel2=Label(WD,text="Base", fg="black")
myLabel2.grid(row =0, column =0, sticky='w')
boxBase= Entry(WD,textvariable=base)
boxBase.grid(row =0, column =1)

myLabel=Label(WD,text="Height", fg="black",)
myLabel.grid(row =1, column =0, sticky = "w")
boxHeight= Entry(WD,textvariable=height)
boxHeight.grid(row =1, column =1)

WD.mainloop()

rawDescription: How to make Entry Boxes interact w/ each other in Python IDLE Tkinter?

description: Make Entry Boxes interact w/ each other in Python IDLE Tkinter


code:
def find_the_man( T, name,  p = None):
    r = False
    for i in T:
        if type( i ) == list:
            r = find_the_man( i, name, T[0] )
            if r:
               break
        elif i == name:
            return ( p, [ i[0] if type(i) == list else i for i in T[ 1: ] ] ) if T.index(i) == 0 else ( T[0], None )
    return r

T= [ "Kanky", [ "satan", [ "ben", "ian" ], "Alan" ], "malan", [ "yugi", "yuppi" ] ]
# function return tuple ( parent, list_of_children )
find_the_man( T, "Kanky" )  # (None, ['satan', 'malan', 'yugi'])
find_the_man( T, "satan" )  # ('Kanky', ['ben', 'Alan'])
find_the_man( T, "ben" )    # ('satan', ['ian'])
find_the_man( T, "malan" )  # ('Kanky', None)
find_the_man( T, "yugi" )   # ('Kanky', ['yuppi'])
find_the_man( T, "yuppi" )  # ('yugi', None)
find_the_man(T, "stranger" )# False

rawDescription: Does recursive loop not proceed to the next item if it fails?


code:
divisors = {'B': 1, 'M': 1000}
def fn(number):
    if number[-1] in divisors:
        return str(float(number[:-1]) / divisors[number[-1]])
    return number

map(fn, ['34.00B', '65.89B', '346M'])

rawDescription: python remove last character and id

description: Python remove last character and id


code:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('tmp.csv', sep = '\s')
df.plot(kind='bar')
locs, labels = plt.xticks()
plt.xticks(locs, [d if d==d else '' for d in df.index], rotation = 25)
plt.show()

rawDescription: Modify nan index in pandas

description: Modify nan index in pandas


rawDescription: Extracting penultimate folder name from path


code:
# Open "names.dat" for reading and call it namefile
with open('names.dat', 'r') as namefile:
  # read file contents to string and split on "comma space" as delimiter
  name_pairs = namefile.read().split(', ')
  # name_pairs is now a list like ['john:fred', 'fred:bill', 'sam:tony', ...]
# file is automatically closed when we leave with statement
fathers = {}
for pair in name_pairs:  # for each pair like 'john:fred'
  # split on colon, stripping any '\n' from the file from the right side
  father, son = [name.rstrip('\n') for name in pair.split(':')]
  # If pair = 'john:fred', now father is 'john' and son is 'fred'
  fathers[son] = father  # which we enter into a dict named fathers

fathers['fred']  # now fathers['father_name'] maps to value 'son_name'

rawDescription: How to return a key after searching for the value in a dictionary

description: Return a key after searching for the value in a dictionary


code:
@transaction.atomic
def bulk_update_decorated(bulky):
    try:
        for update_this in bulky:
            update_this.save()
    except SoftTimeLimitExceeded:
        pass

rawDescription: Django 1.6 Transaction Management on large list of Model Objects


code:
from xlsxwriter.workbook import Workbook

workbook  = Workbook('chart_combined.xlsx')
worksheet = workbook.add_worksheet()

# Add a format for the headings.
bold = workbook.add_format({'bold': True})

# Add the worksheet data that the charts will refer to.
headings = ['Number', 'Batch 1', 'Batch 2', 'Equal']
data = [
    [2,        3,      4,        5,          6,    7      ],
    [10,       40,     50,       20,        10,    50     ],
    [30,       40,     70,       50,        10,    30     ],
    ['=NA()',  40,     '=NA()',  '=NA()',   10,    '=NA()'],
]

worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])
worksheet.write_column('D2', data[3])

# Create a new column chart. This will use this as the primary chart.
column_chart = workbook.add_chart({'type': 'column'})

# Configure the data series for the primary chart.
column_chart.add_series({
    'name':       '=Sheet1!$B$1',
    'categories': '=Sheet1!$A$2:$A$7',
    'values':     '=Sheet1!$B$2:$B$7',
})

# Create a new line chart. This will use this as the secondary chart.
line_chart = workbook.add_chart({'type': 'line'})

# Configure the data series for the secondary chart.
line_chart.add_series({
    'name':       '=Sheet1!$C$1',
    'categories': '=Sheet1!$A$2:$A$7',
    'values':     '=Sheet1!$C$2:$C$7',
})

# Add a series to represent the intersection points, with markers only.
line_chart.add_series({
    'name':       '=Sheet1!$D$1',
    'categories': '=Sheet1!$A$2:$A$7',
    'values':     '=Sheet1!$D$2:$D$7',
    'marker':     {'type': 'circle', 'size': 10},
    'line':       {'none': True},
})

# Delete/hide series 2 from the legend.
column_chart.set_legend({'delete_series': [2]})

# Combine the charts.
column_chart.combine(line_chart)

# Add a chart title and some axis labels. Note, this is done via the
# primary chart.
column_chart.set_title({ 'name': 'Combined chart'})
column_chart.set_x_axis({'name': 'Test number'})
column_chart.set_y_axis({'name': 'Sample length (mm)'})

# Insert the chart into the worksheet
worksheet.insert_chart('F2', column_chart)

workbook.close()

rawDescription: xlsxwriter Marker in Combined Chart

description: Xlsxwriter Marker in Combined Chart


code:
import multiprocessing

def f(x): return x**2

P = multiprocessing.Pool()
for n in xrange(2000):
    sol = list(P.imap(f, range(20)))

rawDescription: Does python's multiprocessing leak memory?


code: pandas.concat([df1, df2, df3], axis=1)

rawDescription: Merging Pandas DataFrame through Loop

description: Merging Pandas DataFrame through Loop


code:
from tornado.ioloop import IOLoop
import tornado.web
import tornado.httpserver
import aiohttp
from tornado.platform.asyncio import AsyncIOMainLoop
import asyncio

class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        r = await aiohttp.get('http://google.com/')
        text = await r.text()
        self.write("Hello, world, text is: {}".format(text))

if __name__ == "__main__":
    AsyncIOMainLoop().install()
    app = tornado.web.Application([
        (r"/", MainHandler),
    ])
    server = tornado.httpserver.HTTPServer(app)
    server.bind(1234, '127.0.0.1')
    server.start()
    asyncio.get_event_loop().run_forever().start()

rawDescription: Using tornado with aiohttp (or other asyncio-based libraries)


code:
from tkinter import *

tk = Tk()
tk.iconbitmap(default='transparent.ico')
lab = Label(tk, text='Window with transparent icon.')
lab.pack()
tk.mainloop()

rawDescription: Removing the TK icon on a Tkinter window


code:
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')

df.to_sql("table_name", engine)

rawDescription: Automatic PostgreSQL CREATE TABLE and INSERT from CSV or Pandas DataFrame


code:
from multiprocessing.managers import ListProxy

JobQueueManager.register('get_params', callable=lambda: ['123'], proxytype=ListProxy)

rawDescription: Share a constant value using multiprocessing.managers.SyncManager


code:
# First convert back to UTC
utc_time = pacific_now.astimezone(pytz.utc)

# Remove the timezone attribute to make it timezone-naive
utc_time = utc_time.replace(tzinfo=None)

rawDescription: Python - given a timezone-aware datetime object how do I get a timezone-naive UTC datetime object?


code:
intervals = [(132,237),(156,223),(589,605)]
number = 160
for start, stop in intervals:
    if start <= number <= stop:
        print (start, stop)

rawDescription: Is there a faster way to check if a number is within an interval?


code: [estimator.tree_.max_depth for estimator in forest.estimators_]

rawDescription: How do you access tree depth in Python's scikit-learn?

description: Access tree depth in Python's scikit-learn


code:
ax = plt.gca()
ax.yaxis.set_major_formatter(matplotlib.ticker.NullFormatter())
plt.draw()

rawDescription: Python/Matplotlib: How to plot in a subplot with ticks but no tick labels?


code:
reduce(operator.mul, range(1,10**5))
reduce(operator.mul, range(10**5,1,-1))

rawDescription: Why is the "divide and conquer" method of computing factorials so fast for large ints?


code:
string1 = 'red blue white'
string2 = 'first second third'
dict(zip(string1.split(), string2.split()))

rawDescription: How to convert two strings into single dictionary?

description: Convert two strings into single dictionary


code:
import Image

image  = Image.open('images/original.jpg')
width  = image.size[0]
height = image.size[1]

aspect = width / float(height)

ideal_width = 200
ideal_height = 200

ideal_aspect = ideal_width / float(ideal_height)

if aspect > ideal_aspect:
    # Then crop the left and right edges:
    new_width = int(ideal_aspect * height)
    offset = (width - new_width) / 2
    resize = (offset, 0, width - offset, height)
else:
    # ... crop the top and bottom:
    new_height = int(width / ideal_aspect)
    offset = (height - new_height) / 2
    resize = (0, offset, width, height - offset)

thumb = image.crop(resize).resize((ideal_width, ideal_height), Image.ANTIALIAS)
thumb.save('thumb.jpg')

rawDescription: Reducing the width/height of an image to fit a given aspect ratio. How? - Python image thumbnails


code:
import itertools

joined = itertools.chain(q1, q2)
sorter = lambda x: x.sumbooks if has_attr(x, 'sumbooks') else x.sumjournals
all = sorted(joined, key = sorter)

rawDescription: merge sorted querysets - django

description: Merge sorted querysets - django


rawDescription: (Django) define `__str__` in a model with attributes of other model not yet defined


code:
def nlargest(n, l):
    # make a heap of the first n elements
    heap = l[:n]
    heapify(heap)

    # loop over the other len(l)-n elements of l
    for i in xrange(n, len(l)):
        # push the current element onto the heap, so its size becomes n+1
        heappush(heap, l[i])
        # pop the smallest element off, so that the heap will contain
        # the largest n elements of l seen so far
        heappop(heap)

    return sorted(heap, reverse=True)

rawDescription: What are heap queues for?

description: What are heap queues for


code:
class MyTextEdit(QTextEdit):

    def keyPressEvent(self, event):
        event.ignore()

rawDescription: disable writing of character on qtextedit by overriding keypress event in pyqt4 python

description: Disable writing of character on qtextedit by overriding keypress event in pyqt4 python


code: f = t.fileobj.__class__(newfn, 'w')

rawDescription: tarfile: determine compression of an open tarball

description: Tarfile: determine compression of an open tarball


code:
class mouseCollect(QtCore.QThread):
    def __init__(self):

      QtCore.QThread.__init__(self)

    def run (self):
      global e, curve, curve2, data1, data2
      while e.wait():
        tmp = getMouseEvent() #returns tuples in form of  (x,y)
        data1 = np.append(data1, tmp[0] )
        data2 = np.append(data2, tmp[1] )
        sum1= np.cumsum(data1)
        sum2= np.cumsum(data2)

        curve.setData(y=sum1)
        curve2.setData(y=sum2)
        guiPE # process event thingy

    def stop(self):
      e.clear()

rawDescription: Python realtime mousedata with pyqtgraph


code: [innerdict["key3"] for innerdict in list]

rawDescription: Get a list from the dictionary key in a list of dictionaries


code:
import pandas as pd
df = pd.read_csv('test.csv', header=None)
df.rename(columns={0: 'name', 1: 'id'}, inplace=True)
df.to_csv('test_with_col.csv', index=False) # save to new csv file

rawDescription: Adding column names to csv file, python

description: Adding column names to csv file, python


code:
# other commands
lines = pylab.semilogy(...)
#other commands
x,y = lines[0].get_data()

rawDescription: Reading values from a graph in Python

description: Reading values from a graph in Python


code:
actions = ['duplicate']

from copy import deepcopy

def duplicate(self, request, queryset):
    for obj in queryset:
        obj_copy = deepcopy(obj)
        obj_copy.id = None
        obj_copy.save()

        for question in obj.question_set.all():
            question_copy = deepcopy(question)
            question_copy.id = None
            question_copy.save()
            obj_copy.question_set.add(question_copy)

            for choice in question.choice_set.all():
                choice_copy = deepcopy(choice)
                choice_copy.id = None
                choice_copy.save()
                question_copy.choice_set.add(choice_copy)
        obj_copy.save()

rawDescription: Django - Copying a model instance with 2 nested foreignkeys


rawDescription: how to find the location of a character located right-most among all such characters in python?

description: Find the location of a character located right-most among all such characters in python


code:
pattern = '[a-zA-Z_]\w*(?![\(\w])'
re.findall(pattern, "funcname(arg, another_arg)*20 + second_func(arg1, arg2)")
re.findall(pattern, "value1 + value_two")

rawDescription: Regex findall on a function definition. Want to match args but not function


code:
def compute_path_amount(self):
    return [
        self.__class__.userUrls[i:i+9] for i in xrange(
            0, len(self.__class__.userUrls), 10
        )
    ]

rawDescription: Slicing results of Django Query into Sets of 10


code:
def wait_for_visibility(self, selector, timeout_seconds=10):
    retries = timeout_seconds
    while retries:
        try:
            element = self.get_via_css(selector)
            if element.is_displayed():
                return element
        except (exceptions.NoSuchElementException,
                exceptions.StaleElementReferenceException):
            if retries <= 0:
                raise
            else:
                pass

        retries = retries - 1
        time.sleep(pause_interval)
    raise exceptions.ElementNotVisibleException(
        "Element %s not visible despite waiting for %s seconds" % (
            selector, timeout_seconds)
    )

rawDescription: python selenium: does not wait until page is loaded after a click() command

description: Python selenium: does not wait until page is loaded after a click() command


rawDescription: Group by and sum in Pandas

description: Group by and sum in Pandas


code:
import numpy as np
from scipy import interpolate
A = np.array([[1,np.NaN,np.NaN,2],[0,np.NaN,1,2]])
#array([[  1.,  nan,  nan,   2.],
#       [  0.,  nan,   1.,   2.]])

for row in A:
    mask = np.isnan(row)
    x, y = np.where(~mask)[0], row[~mask]
    f = interpolate.interp1d(x, y, kind='linear',)
    row[mask] = f(np.where(mask)[0])
#array([[ 1.        ,  1.33333333,  1.66666667,  2.        ],
#       [ 0.        ,  0.5       ,  1.        ,  2.        ]])

rawDescription: Is there A 1D interpolation (along one axis) of an image using two images (2D arrays) as inputs?


code:
import types
m = types.ModuleType("mymod")
m

rawDescription: Are python modules first class citizens?

description: Are python modules first class citizens


code:
import matplotlib.pyplot as plt
import numpy as np

def plot_histogram_01():
    np.random.seed(1)
    values_A = np.random.choice(np.arange(600), size=200, replace=True).tolist()
    values_B = np.random.choice(np.arange(600), size=200, replace=True).tolist()
    values_A_to_plot = [301 if i > 300 else i for i in values_A]
    values_B_to_plot = [301 if i > 300 else i for i in values_B]

    bins = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325]

    fig, ax = plt.subplots(figsize=(9, 5))
    _, bins, patches = plt.hist([values_A_to_plot, values_B_to_plot], normed=1,  # normed is deprecated and will be replaced by density
                                bins=bins,
                                color=['#3782CC', '#AFD5FA'],
                                label=['A', 'B'])

    xlabels = np.array(bins[1:], dtype='|S4')
    xlabels[-1] = '300+'

    N_labels = len(xlabels)

    plt.xticks(25 * np.arange(N_labels) + 12.5)
    ax.set_xticklabels(xlabels)

    plt.yticks([])
    plt.title('')
    plt.setp(patches, linewidth=0)
    plt.legend()

    fig.tight_layout()
    plt.savefig('my_plot_01.png')
    plt.close()

plot_histogram_01()

rawDescription: Matplotlib histogram with collection bin for high values


code:
def array_front9(nums):   # Define the function "array_front9"
    end = len(nums)       # Get the length of "nums" and put it in the variable "end"
    if end > 4:           # If "end" is greater than 4...
        end = 4           # ...reset "end" to 4

    for i in range(end):  # This iterates through each number contained in the range of "end", placing it in the variable "i"
        if nums[i]==9:    # If the "i" index of "nums" is 9...
            return True   # ...return True because we found what we were looking for
    return False          # If we have got here, return False because we didn't find what we were looking for

rawDescription: Python code explanation need

description: Python code explanation need


code:
def get_hundredth(a,b,c):
    def hundreds(x):
        try:
            return (x // 100) % 10 if (isinstance(x, int) and x > 0) else None
        except TypeError:
            return None
    return tuple(map(hundreds, (a,b,c)))

print(get_hundredth(1234, 509, 80633)) # (2, 5, 6)
print(get_hundredth(-89, 81.85, 'test')) # (None, None, None)

rawDescription: Getting hundredth integer from a tuple (python)


rawDescription: access python member from object without dict

description: Access python member from object without dict


rawDescription: Compare object with the keys in python dictionary/hashtable


rawDescription: Python - ElementTree Library - Search through tree by attribute value


code:
import numpy as np

a = np.ones((10))
print(a) # Original array
# [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
startindex = 2
endindex = 4
a[startindex:endindex] = 0

print(a) # modified array
# [ 1.  1.  0.  0.  1.  1.  1.  1.  1.  1.]

rawDescription: How to change chunks of data in a numpy array

description: Change chunks of data in a numpy array


rawDescription: Case sensitive path comparison in python


code:
if __name__ == '__main__':
     server_class=BaseHTTPServer.HTTPServer
     server_address = ('', 80)
     httpd = server_class(server_address, RequestHandler)
     httpd.serve_forever()

rawDescription: Python share directory over HTTP

description: Python share directory over HTTP


code:
class LinkTextBrowser(QTextBrowser):
    def contextMenuEvent(self, event):
        self.link_pos = event.pos()
        # correct for scrolling
        self.link_pos.setX(self.link_pos.x() + self.horizontalScrollBar().value())
        self.link_pos.setY(self.link_pos.y() + self.verticalScrollBar().value())
        menu = self.createStandardContextMenu(self.link_pos)

        # do stuff to menu

        menu.popup(event.globalPos())

rawDescription: Customising location-sensitive context menu in QTextEdit


code:
'abcdefgh'[2:6] is 'cdef'
'abcdefgh'[2:6] == 'cdef'

rawDescription: Python & MySQL: Matching element from list of with a record from database


code:
def iterpairs(iterable):
    prev = None
    for item in iterable:
        if prev is not None:
            yield prev, item
        prev = item

edges = []
for line in open("sample.txt", "r"):
    parts = line.strip().split()
    edges.extend(iterpairs(parts))

g = Graph.TupleList(edges)

rawDescription: Read relations from file using igraph python


code:
keyName = "hello"

testName = keyName
suffix = 0
while Entry.get_by_key_name(testName):
  suffix += 1
  testName = "%s-%d" % (keyName, suffix)

keyName = testName

rawDescription: avoid duplicate key names by adding suffix

description: Avoid duplicate key names by adding suffix


code:
from django.db.models.signals import post_save

def create_group_links(instance, created, **kwargs):
    if created:
        Link.objects.create(name='FOO', slug='BAR', location='LOC' + instance.slug)
post_save.connect(create_group_links, sender=Group)

rawDescription: Create a row every time another row is created in django


code:
import scrapy
from scrapy.http import Request
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from urlparse import urljoin
#todo
from your_project.items import YourItem

class EventsSpider(CrawlSpider):
    name = "events"
    allowed_domains = ["foo.bar"]
    start_urls = [
        'http://www.foo.bar/events/',
    ]
    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        item = YourItem()
        item['url'] = response.url
        item['language'] = response.xpath('//meta[@name=\'Language\']/@content').extract()
        item['description'] = response.xpath('//meta[@name=\'Description\']/@content').extract()
        yield item

        for url in response.xpath('//a/@href').extract():
            if url and not url.startswith('#'):
                self.logger.debug(urljoin(response.url, url))
                scrapy.http.Request(urljoin(response.url, url))

rawDescription: Recursive spider with scrapy only scraping first page


code:
from docxtpl import DocxTemplate, RichText
import re

tpl=DocxTemplate('test_tpl.docx')

startsentence = 'Here is a sentence with \textbf{bold words} in the middle of it and \textbf{the end of it.}'

latexbold = re.compile(r'\textbf\{([a-zA-Z0-9 .]+)\}')
x = re.split(latexbold, startsentence)
rt = RichText("")
l = len(x)

for i in range(0,l):
    if i%2 == 0:
        rt.add(x[i])
    else:
        rt.add(x[i], bold=True)

context = {
    'example': rt,
}

tpl.render(context)
tpl.save('test.docx')

rawDescription: How to replace latex bold command with Word docx equivalent in python?

description: Replace latex bold command with Word docx equivalent in python


code:
from rpy2 import robjects

robjects.r('''
source('quadro.R')
''')                                   #load the R script

quadro = robjects.globalenv['quadro']  #assign an R function in python
quadro(3)                              #to call in python, which returns a list
quadro(3)[0]                           #to get the first element: 9

rawDescription: Using an R-script in python, which was written for R


code:
from selenium import webdriver

USERNAME = "foo@bar.com"
PASSWORD = "superelite"

# create a driver
driver = webdriver.Firefox()

# get the homepage
driver.get("http://tx3.netease.com/logging.php?action=login")

un_elm = driver.find_element_by_id("username")
pw_elm = driver.find_element_by_id("ori_password")
submit = driver.find_element_by_css_selector("[name=loginsubmit]")

un_elm.send_keys(USERNAME)
pw_elm.send_keys(PASSWORD)

# click submit
submit.click()

# get the PHPSESSID cookie as that has your login data, if you want to use
# it elsewhere
# print driver.get_cookies():

# do something else ...

rawDescription: Python-requests how to call js function to calculate some value before post?


code:
db.session.query(
    PartMaster.name,
    PartMaster.description,
    PartTracker.actual_length,
    func.sum(PartTracker.quantity).label('quantity')
).join(PartTracker).group_by(
    PartTracker.part_master_id,PartTracker.actual_length
).having(
    func.sum(PartTracker.quantity) > 0
)

rawDescription: How to use a labelled column in sqlalchemy filter?

description: Use a labelled column in sqlalchemy filter


code:
import csv
data = []
with open(datafile, 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        data.append(row)
        print(row['Title'], row['Name'])

rawDescription: Add Dictionary to a list python

description: Add Dictionary to a list python


rawDescription: Create 2-dimensional range

description: Create 2-dimensional range


rawDescription: multiple format specifiers in one expression

description: Multiple format specifiers in one expression


code: variable = 1 if something == 1 else 0

rawDescription: Equivalent for ? in Java for Python?

description: Equivalent for ? in Java for Python


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.label = QtGui.QLabel(self)
        self.label.setText('Hello World')
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
        self.label.setMouseTracking(True)
        self.label.installEventFilter(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.label)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            source is self.label):
            pos = event.pos()
            print('mouse move: (%d, %d)' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())

rawDescription: PyQt: how to handle event without inheritance


code:
from typing import Callable, Any

def x(f: Callable[..., Any]) -> Callable[..., Any]:
    def wrapper(*args, **kwargs):
        print("{}({}) has been called".format(f.__name__, ", ".join([repr(i) for i in args] + ["{}={}".format(key, value) for key, value in kwargs])))
        return f(*args, **kwargs)
    return wrapper

rawDescription: Function annotations

description: Function annotations


code:
import pygame

print(pygame.K_UP)    # 273
print(pygame.K_DOWN)  # 274
print(pygame.K_RIGHT) # 275
print(pygame.K_LEFT)  # 276

rawDescription: What are the key constant values in Pygame.key.get_pressed()?


code:
def main():
  while True:
    n = input("Enter number : ")
    recur(1,2,3,4,1,int(n))

def recur(firstNum,secondNum,thirdNum,fourthNum,counter,n):
  if counter==n:
     print (firstNum)
     return
  elif counter < n:
      recur (secondNum,thirdNum,fourthNum,firstNum+secondNum+fourthNum,counter+1,n)

rawDescription: Implement recursion using one recursive call


rawDescription: Diagonal Matrix Exponential in Python

description: Diagonal Matrix Exponential in Python


code:
def ClosestCommonAncestor(otu1, otu2, tree):
    while tree[otu1][0][0] != tree[otu2][0][0]:
        otu1,otu2,tree = tree[otu1][0],tree[otu2][0],tree
    return tree[otu1][0]

rawDescription: How to make this recursive function iterative in python?

description: Make this recursive function iterative in python


code:
from Tkinter import *

class App():
    def __init__(self):
        self.root = Tk()
        self.root.geometry('300x300+100+100')
        self.root.bind('<Configure>', self.root_conf)

        self.top = []

        self.top.append(Toplevel(self.root))
        self.top[0].geometry('200x200+150+150')
        self.top[0].transient(self.root)

        self.x_off = []
        self.y_off = []

        self.x_off.append(50)
        self.y_off.append(50)
        self.top[0].bind('<Configure>', lambda e: self.top_conf(e, 0))

        self.top.append(Toplevel(self.root))
        self.top[1].geometry('200x200+450+150')
        self.top[1].transient(self.root)

        self.x_off.append(350)
        self.y_off.append(50)
        self.top[1].bind('<Configure>', lambda e: self.top_conf(e, 1))

        self.root.mainloop()

    def root_conf(self, e):
        self.top[0].geometry('{}x{}+{}+{}'.format(self.top[0].winfo_width(), self.top[0].winfo_height(), e.x+self.x_off[0], e.y+self.y_off[0]))
        self.top[1].geometry('{}x{}+{}+{}'.format(self.top[1].winfo_width(), self.top[1].winfo_height(), e.x+self.x_off[1], e.y+self.y_off[1]))

    def top_conf(self, e, num):
        self.x_off[num] = e.widget.winfo_x()-self.root.winfo_x()
        self.y_off[num] = e.widget.winfo_y()-self.root.winfo_y()

if __name__== "__main__":
    App()

rawDescription: Anchoring Toplevel window(s) to root window, python 2.7 - windows 7


code:
end = position - width - 1 if position > width else None
down = psi[position:end:-1]

rawDescription: Getting a reversed slice of an array that includes the base element


code:
import cPickle

x = {}
for i in xrange(1000000):
    x["k%i" % i] = "v%i" % i
cPickle.dump(x, open("data", "wb"), -1)

x = cPickle.load(open("data", "rb"))

rawDescription: Python dictionary memory usage

description: Python dictionary memory usage


code: rules = [Rule(LinkExtractor(allow=('/node/.*',), restrict_xpaths=('//div[@class="pane-content"]',)), callback='parse_imgur', follow=True)]

rawDescription: Scrapy crawl extracted links

description: Scrapy crawl extracted links


rawDescription: Python - String Splitting

description: Python - String Splitting


code:
from collections import OrderedDict

kwargs=OrderedDict((k, None) for k in template_vars)

rawDescription: dict.fromkeys return dictionary in reverse order from a list

description: Dict.fromkeys return dictionary in reverse order from a list


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

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        for column in range(columns - 1):
            for row in range(rows - 1):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                self.table.setItem(row, column, item)
        self.buttonOpen = QtGui.QPushButton('Open', self)
        self.buttonSave = QtGui.QPushButton('Save', self)
        self.buttonOpen.clicked.connect(self.handleOpen)
        self.buttonSave.clicked.connect(self.handleSave)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        layout.addWidget(self.buttonOpen)
        layout.addWidget(self.buttonSave)

    def handleSave(self):
        path = QtGui.QFileDialog.getSaveFileName(
                self, 'Save File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'wb') as stream:
                writer = csv.writer(stream)
                for row in range(self.table.rowCount()):
                    rowdata = []
                    for column in range(self.table.columnCount()):
                        item = self.table.item(row, column)
                        if item is not None:
                            rowdata.append(
                                unicode(item.text()).encode('utf8'))
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)

    def handleOpen(self):
        path = QtGui.QFileDialog.getOpenFileName(
                self, 'Open File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'rb') as stream:
                self.table.setRowCount(0)
                self.table.setColumnCount(0)
                for rowdata in csv.reader(stream):
                    row = self.table.rowCount()
                    self.table.insertRow(row)
                    self.table.setColumnCount(len(rowdata))
                    for column, data in enumerate(rowdata):
                        item = QtGui.QTableWidgetItem(data.decode('utf8'))
                        self.table.setItem(row, column, item)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window(10, 5)
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

rawDescription: writing a QTableWidget to a .csv or .xls

description: Writing a QTableWidget to a .csv or .xls


code: label_binarize(yTrue, orderedClasses)

rawDescription: How to label_binarize Multiclass in a specific class order

description: Label_binarize Multiclass in a specific class order


code:
import calendar
import locale

print(calendar.month_name[10])
# -> October
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8') # system-dependent locale name
print(calendar.month_name[10])
# -> Octubre

rawDescription: Python change locale with arrow

description: Python change locale with arrow


code:
from sqlalchemy.types import Unicode
# codes...
Custom.query.filter(Custom.data['value'].cast(Unicode) == "what I want")

rawDescription: how can i query data filtered by a JSON Column in SQLAlchemy?

description: Query data filtered by a JSON Column in SQLAlchemy


code: handler.cgi_directories = ["/"]

rawDescription: Python CGIServer is not redirecting to index.html


code:
def debug_repr(self):
    return "<{} {}: {}>".format(self.__class__.__name__, self.pk, self)

Model.__repr__ = debug_repr

rawDescription: Get Django to include the model id in the string representation of all model instances for debugging


rawDescription: How can I see/scrape the real text value hidden in page source?

description: See/scrape the real text value hidden in page source


code:
i = 0
a = [1,3,3,4,6,6]
numbers = []
while i < len(a):
    if a.count(a[i]) == 1: numbers.append(a[i]); i += 1
    else: numbers.append(a[i]-1); a.remove(a[i])

numbers

rawDescription: How do I search a list of numbers for duplicates and drop the first of 2 duplicated values by 1?

description: Search a list of numbers for duplicates and drop the first of 2 duplicated values by 1


code:
from scipy.sparse import csr_matrix
rows = [0, 0, 0]
columns = [100, 47, 150]
data = [-1, +1, -1]
m = csr_matrix( (data,(rows, columns)), shape=(1, 300) )

indices = m.indices

# right permutation
m.indices = (indices + 1) % m.shape[1]

# left permutation
m.indices = (indices - 1) % m.shape[1]

rawDescription: How to implement Circular Permutation (left and right shift) of CSR_Matrix in Scipy Python Sparse Matrices?

description: Implement Circular Permutation (left and right shift) of CSR_Matrix in Scipy Python Sparse Matrices


code:
for row in result:
    c.writerow(row)

rawDescription: Using python to write mysql query to csv, need to show field names


code:
ids = set()
for rec in blah:
    if rec.id not in ids:
        ids.add(rec.id)
        # process it

rawDescription: Remove duplicate sequences from fasta file based on ID


code:
import re

str = 'ag ct oso gcota'
str = re.sub('[^atcg]', '', str)

"""str is now 'agctgcta"""

rawDescription: Keeping only certain characters in a string using Python?


code:
def seq(a):
    a = str(a)
    k,last,result = 1,a[0],''
    for i in range(1,len(a)):
        if last==a[i]:k+=1
        else:
            result = result+str(k)+last
            k=1
        last = a[i]
    result = result+str(k)+last
    return result

rawDescription: python look-and-say sequence improved

description: Python look-and-say sequence improved


code:
from pylab import *
Z = rand(6, 100) # tried to make it look similar to your plot
c = pcolor(Z)
show()

rawDescription: How to make this plot.ly heatmap-esque plot in "pure" python?

description: Make this plot.ly heatmap-esque plot in "pure" python


code:
from mimetypes import guess_extension

source = urllib.urlopen(download_link)
extension = guess_extension(source.info()['Content-Type'])
if extension:
    app_name += extension
else:
    # what to do? discard?
    pass

# later do source.read()

rawDescription: Download file and rename accroding to file type using python urllib


code:
import pandas as pd
from matplotlib import pyplot as plt
from math import radians

ax = plt.subplot(111, polar=True)
ax.scatter(x=[radians(x) for x in df['windBearing'].values], y=df['windSpeed'].values)
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)

rawDescription: Seaborn: how to plot wind speed v direction on circular plot?


code:
document = UserDocument.objects.first()
fp = StringIO()
fp.write(document.file_.read())  # Also takes about 0.8 sec, but thats still faster than 8 seconds.
for page in PDFPage.get_pages(file('ticket.pdf', 'rb'), pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True): pass

rawDescription: Difference between reading from file and MongoDB GridFS?


code:
f = open("test.txt")

for i in f:
    print(i)
# Print:
    # This is a test first line
    # This is a test second line

for i in f:
    print(i)
# Prints nothig

f.seek(0) # set position to the beginning

for i in f:
    print(i)
# Print:
    # This is a test first line
    # This is a test second line

rawDescription: Creating more than one data structure (dicts) in Python


code:
@app.before_request
def before_request():
    if 'api' == request.host[:-len(app.config['SERVER_NAME'])].rstrip('.'):
        redirect(url_for('api'))

@app.route('/', defaults={'path': ''}, subdomain='api')
@app.route('/<path:path>', subdomain='api')
def api(path):
    return "hello"

rawDescription: How to create dynamic subdomains in a Flask application

description: Create dynamic subdomains in a Flask application


code:
import cPickle as p

# Sender
data_str = p.dumps(array)
sock.sendto(data_str, addr)

# Receiver
data,addr = sock.recvfrom(buf)
data_origin = p.loads(data)

rawDescription: Sending an array over UDP connection

description: Sending an array over UDP connection


code: if item_to_add: d["name_of_item"] = item_to_add

rawDescription: Add item to python dictionary if the bool(item) is True


code:
import numpy
numpy.ndarray
numpy.array
numpy.array([])
isinstance(numpy.array([]), numpy.ndarray)

rawDescription: Convert np.ndarray to np.array in python


code:
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
    if lyr.name() in ['name1', 'name2', 'name3']:
        arcpy.mapping.RemoveLayout(df, lyr)

rawDescription: Beginner - Python 2.7.2, ArcGIS 10.1 Multiple 'or' conditions, same action


code:
from django.db import models
from app2.models import BlogPost

custom_field_name = models.CharField(max_length=200)
custom_field_name.contribute_to_class(BlogPost, "custom_field_name")

rawDescription: Mixin Field into Existing and uneditable django model


code:
def overlap(string1, string2):
  count=0
  for i in range(min(len(string1),len(string2))):
    if string1[i] == string2[i]:
      count += 1
  return count

rawDescription: Any way to count overlapped strings within another string?


code:
import my_prog
from my_prog import *
reload(my_prog); from my_prog import *
reload(my_prog); from my_prog import *

rawDescription: How to reload my Python source file, when interactively interpreting it with "python -i"

description: Reload my Python source file, when interactively interpreting it with "python -i"


code:
from restless.http import Http201, Http400
from restless.views import Endpoint
from .forms import NewCompanyForm

class APIEndpoint(Endpoint):
    """
    Endpoint for posting json data to server
    """
    def post(self, request):
        company_form = NewCompanyForm(request.data)
        if company_form.is_valid():
            # Check for duplicate data
            # ...
            if unique:
                company_form.save()
                return Http201({"message": "Post successful"})
            else:
                return Http400(reason='Data was not unique')
        else:
            return Http400(reason='You did not post a valid input')

rawDescription: How to POST/PUT scraped data to RESTful API

description: POST/PUT scraped data to RESTful API


code:
from subprocess import check_output

with open("/home/user/file.in", "rb") as file:
    output = check_output(["/home/user/executable"], stdin=file)

rawDescription: Executing shell command in python with file as stdin


code:
with transaction.atomic():
    ModelB.objects.update(counter=F('counter') + 1)
    new_counter = ModelB.objects.get().counter
    a_instance.account_number = new_counter
    a_instance.save()

rawDescription: Django concurrent get-and-increment

description: Django concurrent get-and-increment


code:
import base64
import io
from PIL import Image

if request.method == 'GET':
    if request.GET['pos'] and request.GET['frame']:
        pos = json.loads(request.GET['pos'])
        str_frame = json.loads(request.GET['frame'])

        # Converts the base64 string into a byte string, we need to encode
        # str_frame as utf-8 first otherwise python3.2 complains about unicode
        b64decoded_frame = base64.b64decode(str_frame.encode('utf-8'))

        # This puts the decoded image into a buffer so that I don't need to save
        # it to disk to use it in PIL
        byte_stream = io.BytesIO(b64decoded_frame)

        # Open the image and convert it to 8-bit greyscale (mono8)
        img = Image.open(byte_stream).convert('L')

        # Get the 8-bit pixel value
        pixel_val = img.getpixel((pos['x'], pos['y']))

        # Convert the 8-bit pixel value to 16-bit by holding the rations
        # i.e. n8 / (2^8 - 1) == x16 / (2^16 - 1)
        pixel_val = int(pixel_val / 255 * 65535)

rawDescription: Convert Image to binary stream

description: Convert Image to binary stream


code:
from flask import request

@app.route('/summary',methods = ['GET'])
def api_summary_2():
    filename = request.args.get('file', None)
    if filename is None:
        abort(404)
    else:
        return api_summary(filename)

rawDescription: Adding parameter values to a url in flask python


code:
class MyTextEdit(QtGui.QWidget):
    '''Some positioning'''
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.textEditor=QtGui.QLineEdit(self)
        self.textEditor.move(50,15)
        self.textEditor.setPlaceholderText("Hi I'm de fault.")
        self.setGeometry(100, 100, 200, 50)
        self.setFocus()
        self.show()

    def keyPressEvent(self, evt):
        self.textEditor.setFocus()
        self.textEditor.keyPressEvent(evt)

rawDescription: Placeholder text not showing (pyside/pyqt)


code:
#!/usr/bin/env python

import yaml

with open("example.yaml", 'r') as stream:
    try:
        print(yaml.load(stream))
    except yaml.YAMLError as exc:
        print(exc)

rawDescription: How can I parse a YAML file in Python

description: Parse a YAML file in Python


rawDescription: getting user-agent info from flask's socketio

description: Getting user-agent info from flask's socketio


code:
class Example(object):
    def __init__(self, table=None):
        self.__dict__['_fields'] = {}
        self.__dict__['_table'] = table

    ...

    def __setattr__(self, name, value):
        if name in self._fields:
            self._fields[name].value = value
        else:
            raise AttributeError

rawDescription: counter part of __getattr__

description: Counter part of __getattr__


code:
import urllib2

url = "http://theapi.com/getimage"
opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
request = opener.open(url)
return request.url

rawDescription: Passing an image URL from external API in Flask


code:
@api.onchange('girl_id')
def on_change_girl_id(self):
    current_girl_id = self.env.context.get('default_girl_id', False)
    relationship_recordset = self.search([('girl_id', '=', current_girl_id)])
    boy_recordset = relationship_recordset.mapped('boy_id')
    boy_ids = boy_recordset.mapped('id')
    boy_id_domain = [
        ('id', 'not in', boy_ids)
    ]
    result = {
        'domain': {
            'boy_id': boy_id_domain,
        },
    }
    return result

rawDescription: How to set this specific domain on OpenERP/Odoo?

description: Set this specific domain on OpenERP/Odoo


rawDescription: How to rewrite deprecated DDL() statement in SQLAlchemy 0.7+

description: Rewrite deprecated DDL() statement in SQLAlchemy 0.7+


code:
browser = webdriver.Firefox(firefox_profile=fp)
browser.get(url)
browser.implicitly_wait(5)
time.sleep(5)
iframe = browser.find_element_by_css_selector('#crowdTorchTicketingMainContainer > iframe')
browser.switch_to.frame(iframe)
el=browser.find_element_by_id('20160420')
print(el.text)

rawDescription: Unable to locate a visible element with python selenium


code:
l = [1, 2, 3, 4, 5]
['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]

rawDescription: `elif` in list comprehension conditionals


code:
x = [['a','b','c'], ['d','e','f'], ['g','h','i']]
y = [['j','k','l'], ['m','n','o'], ['p','q','r']]

from itertools import chain
import csv
res = zip(*list(chain.from_iterable(zip(x, y))))
with open(r'yourfile.csv', 'wb') as fout:
    csvout = csv.writer(fout)
    csvout.writerows(res)

rawDescription: Write multiple lists to CSV

description: Write multiple lists to CSV


code: map(lambda t: "/".join(map(str, t)), zip(years, monthes, days))

rawDescription: Python Date arrays

description: Python Date arrays


code:
r = requests.get('http://techtv.mit.edu/videos/1585-music-session-02/download.source')
print(r.url) # http://d1baxxa0joomi3.cloudfront.net/2515a9db659b0ab26d869b4ff2dadca9/original.mov

rawDescription: how to get redirect url using python requests

description: Get redirect url using python requests


code:
lst = ['Mark', 'Reynold', 'Peter', 'Randall Macenroe']
[y for x in lst for y in x.split()]

rawDescription: Making a string in a list to two strings in a list


code:
import numpy as np
from PIL import Image
from StringIO import StringIO

# begin and end of each file
low = 0
up = 0
images = [0] *len(p_f_list)

# get each file from the byte file
for i, f in enumerate(p_f_list):
    up += int(f[0])
    # get bytes from the array
    raw_img = p_f_data.data[low:up]
    low = up

    # Convert rawImage to Mat
    pil_image = Image.open(StringIO(raw_img))
    np_image = np.array(pil_image)
    images[i] = np_image

rawDescription: Python string as file in Skimage imread

description: Python string as file in Skimage imread


code:
from PIL import Image

im = Image.open('bird.jpg')
im.putalpha(255)
width, height = im.size
pixels = im.load()
for y in range(int(height*.55), int(height*.75)):
    alpha = 255-int((y - height*.55)/height/.20 * 255)
    for x in range(width):
        pixels[x, y] = pixels[x, y][:3] + (alpha,)
for y in range(y, height):
    for x in range(width):
        pixels[x, y] = pixels[x, y][:3] + (0,)
im.save('birdfade.png')

rawDescription: Vertically fade image to transparency using Python PIL library


rawDescription: python how can I sort a list by a pattern matching with variable names

description: Python how can I sort a list by a pattern matching with variable names


code:
arr = np.arange(150).reshape(5, 10, 3)
x, y, z = arr.shape
indices = np.vstack(np.unravel_index(np.arange(x*y), (y, x))).T
np.hstack((arr.reshape(x*y, z), indices))

rawDescription: Convert an image to 2D array in python

description: Convert an image to 2D array in python


code:
for cfsXYZ in coordsCFS:
    match = numpy.nonzero(
        numpy.max(numpy.abs(coordRMED - cfsXYZ), axis=1) < TOLERANCE)

rawDescription: Slow Row-wise Comparison with For-loops in NumPy - How to improve?


code:
import csv

src = r'C:\apples_before.csv'
dst = r'C:\apples_after.csv'

apples = set([])

# Read file.
with open(src, 'r') as srcfile:
    reader = csv.reader(srcfile, delimiter=',')
    for index, row in enumerate(reader):
        if index == 0:
            continue

        apples.add(row[1])

# Write file.
# @warning: Please note that I am making an assumption in terms of the number
# component. I am assuming it is a row number.
with open(dst, 'w') as dstfile:
    writer = csv.writer(dstfile, delimiter=',')
    for index, apple in enumerate(apples):
        if index == 0:
            writer.writerow(['Name', 'Type'])

        writer.writerow([index + 1, apple])

rawDescription: python csv don't print duplicates

description: Python csv don't print duplicates


code:
name='name'
name.capitalize()

rawDescription: Code not working - upper and lower - Python


code:
from django.contrib.admin.widgets import AdminDateWidget

class MyForm(ModelForm):

    class Meta:
        widgets = {
            'date': AdminDateWidget(),
        }

rawDescription: Django ModelForm with Admin Widgets

description: Django ModelForm with Admin Widgets


code:
import csv

f1 = file('hosts.csv', 'r')
f2 = file('masterlist.csv', 'r')
f3 = file('results.csv', 'w')

c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)

masterlist = list(c2)

for hosts_row in c1:
    row = 1
    found = False
    for master_row in masterlist:
        results_row = hosts_row
        if hosts_row[3] == master_row[1]:
            results_row.append('FOUND in master list (row ' + str(row) + ')')
            found = True
            break
        row = row + 1
    if not found:
        results_row.append('NOT FOUND in master list')
    c3.writerow(results_row)

f1.close()
f2.close()
f3.close()

rawDescription: Python: Comparing two CSV files and searching for similar items


code:
import clr
clr.AddReference("IronPython")

from IronPython.Hosting import Python
engine = Python.CreateEngine()
src = engine.CreateScriptSourceFromString("""
if __name__ == "__main__":
    print "this is __main__"
""")

src.ExecuteProgram()

rawDescription: trouble executing Selenium python unittests in C# with ScriptEngine (.NET 3.5)

description: Trouble executing Selenium python unittests in C# with ScriptEngine (.NET 3.5)


code:
import itertools
import multiprocessing
import numpy as np

class Matcher(object):
    def match_all(self, a1, a2):
        args = ((elem1, elem2) for elem1 in a1 for elem2 in a2)
        args = zip(itertools.repeat(self), args)

        pool = multiprocessing.Pool()
        results = np.fromiter(pool.map(_parallel_match, args))
        # ...

    def match(self, i1, i2):
        return i1 == i2

def _parallel_match(*args):
    return args[0][0].match(*args[0][1:][0])

matcher = Matcher()
matcher.match_all(np.ones(250), np.ones(250))

rawDescription: Python multiprocessing (joblib) best way for argument passing


rawDescription: Python multiple pattern matching from a log file


code:
from pylab import *
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

t = arange(0.0, 100.0, 0.1)
s = sin(0.1*pi*t)*exp(-t*0.01)

ax = subplot(111)
plot(t,s)

ax.xaxis.set_major_locator(MultipleLocator(20))
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(5))

ax.yaxis.set_major_locator(MultipleLocator(0.5))
ax.yaxis.set_minor_locator(MultipleLocator(0.1))

ax.xaxis.grid(True,'minor')
ax.yaxis.grid(True,'minor')
ax.xaxis.grid(True,'major',linewidth=2)
ax.yaxis.grid(True,'major',linewidth=2)

show()

rawDescription: Multiple grids on matplotlib

description: Multiple grids on matplotlib


code: v.get(value, case_generic)()

rawDescription: Using dictionaries for conditional execution instead of if..elif


code:
while len(data) > 1 and data[-1] == data[-2]:
  data.pop()

rawDescription: Trimming trailing duplicates from a list


code:
import pandas as pd

df1 = pd.read_csv("read.csv")

run = 0

def crawl(a):

    global run
    run = run + 1

    #Create x, y

    df2 = pd.DataFrame([[x, y]], columns=["X", "Y"])

    if run == 1:
        df2.to_csv("output.csv")
    if run != 1:
        df2.to_csv("output.csv", header=None, mode="a")

df1["Column A"].apply(crawl)

rawDescription: Pandas: Continuously write from function to csv


code:
from sklearn.preprocessing import Imputer
imp = Imputer(strategy="mean")
a = np.random.random((5,5))
a[(1,4,0,3),(2,4,2,0)] = np.nan
a
a = imp.fit_transform(a)
a

rawDescription: Matrix completion in Python

description: Matrix completion in Python


code:
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0) # for repeatability
x = np.random.rand(30)
x.sort()
y = np.random.rand(30)

x_eval = np.linspace(0, 1, 11)
sigma = 0.1

delta_x = x_eval[:, None] - x
weights = np.exp(-delta_x*delta_x / (2*sigma*sigma)) / (np.sqrt(2*np.pi) * sigma)
weights /= np.sum(weights, axis=1, keepdims=True)
y_eval = np.dot(weights, y)

plt.plot(x, y, 'bo-')
plt.plot(x_eval, y_eval, 'ro-')
plt.show()

rawDescription: gaussian sum filter for irregular spaced points

description: Gaussian sum filter for irregular spaced points


code: read_html('http://money.cnn.com/data/hotstocks/', header =0, flavor = 'bs4')

rawDescription: Use first row as column names? Pandas read_html


code:
namespace = {}
execfile(filename, namespace)

rawDescription: Equivalent ruby load function in python

description: Equivalent ruby load function in python


code: dateutil.parser.parse('Sat Feb 06 07:00:13 -0800 2010')

rawDescription: Convert a ctime (like) timestamp into a tz aware datetime instance


code:
#!/usr/bin/python3

from django.contrib import admin

class MyTemplateView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(admin.site.each_context(self.request))
        return context

rawDescription: Django: Extend context of class based view with Admin context


code:
import numpy as np
import pywt
import cv2

def w2d(img, mode='haar', level=1):
    imArray = cv2.imread(img)
    #Datatype conversions
    #convert to grayscale
    imArray = cv2.cvtColor( imArray,cv2.COLOR_RGB2GRAY )
    #convert to float
    imArray =  np.float32(imArray)
    imArray /= 255;
    # compute coefficients
    coeffs=pywt.wavedec2(imArray, mode, level=level)

    #Process Coefficients
    coeffs_H=list(coeffs)
    coeffs_H[0] *= 0;

    # reconstruction
    imArray_H=pywt.waverec2(coeffs_H, mode);
    imArray_H *= 255;
    imArray_H =  np.uint8(imArray_H)
    #Display result
    cv2.imshow('image',imArray_H)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

w2d("test1.png",'db1',10)

rawDescription: How to Combine pyWavelet and openCV for image processing?


code:
def getUnique(date):
  q = re.compile("\d\d\d\d")
  output = []
  for x in q.findall(date):
     if x not in output:
         output.append(x)
  return output

rawDescription: Regex :How to remove repetition of the same string?


code:
def baseN(base,alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    class _baseN(numbers.Number):
        digits=alphabet[:base]
        def __init__(self,value):
            if isinstance(value,int):
                self.value=value
                if self.value==0:
                    self.string='0'
                else:
                    tmp=[abs(value)]
                    while tmp[0]!=0:
                        tmp[:1]=divmod(tmp[0],base)
                    tmp=[alphabet[i] for i in tmp]
                    tmp[0]='-' if self.value<0 else ''
                    self.string=''.join(tmp)
            elif isinstance(value,str):
                assert(value.isalnum())
                self.string=str(value)
                self.value=0
                for d in value:
                    self.value=self.value*base+self.digits.index(d)
            else:
                self.value=0
                self.string='0'
        def __int__(self):
            return self.value
        def __str__(self):
            return self.string
        def __repr__(self):
            return self.string
        def __add__(self,another):
            return self.__class__(self.value+int(another))
    return None if base>len(alphabet) else _baseN

rawDescription: Is there a good python library that can turn numbers into their respective "symbols"?


code:
string = 'strings'

new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }

sum_of_chars = 0
for character in string:
    if character in new_D:
        sum_of_chars += new_D[character]
    else:
        sum_of_chars += 1 # Default?

print(sum_of_chars)

rawDescription: How to get value for each string index matching key in dictionary in Python

description: Get value for each string index matching key in dictionary in Python


code:
from itertools import combinations

def count_consecutive(l):
    counts = [1]
    counts_index = 0
    for i in range(1, len(l)):
        if l[i] == l[i-1] + 1:
            counts[counts_index] = counts[counts_index] + 1
        else:
            counts.append(1)
            counts_index += 1
    return max(counts)

f = open('C:/combinations.txt', 'w')
for comb in combinations(range(1,36), 7):
    if count_consecutive(comb) not in [5, 6, 7]:
        f.write(str(comb))
        f.write('\n')
f.close()

rawDescription: All combinations in (range(1, 36), 7) with + conditions


code:
from bs4 import BeautifulSoup
import os, sys
from multiprocessing import Pool

source_folder='/Python27/source_xml'

def extract_text(article):
    soup=BeautifulSoup(open(source_folder+'/'+article))

    #I think this strips any tags that are nested in the sample_tag
    clean_text=soup.sample_tag.get_text("  ",strip=True)

    #This grabs an ID which I used as the output file name
    article_id=soup.article_id.get_text("  ",strip=True)

    with open(article_id,"wb") as f:
            f.write(clean_text.encode("UTF-8"))

def main():
    pool = Pool()
    pool.map(extract_text, os.listdir(source_folder))

if __name__ == '__main__':
    main()

rawDescription: Python: Run Script to Write Several Files at Once


code:
def nested_getter(d, keys):
    return reduce(dict.get, keys, d)

rawDescription: Use 'paths' to access different levels of nested dictionaries


code:
s = "Hello, I am 12! I like plankton but I don't like Baseball."
index = 34 #points to the 't' in 'but'
index_of_2nd_I = s.rfind('I', 0, index)
index_of_2nd_I

rawDescription: Python Reverse Find in String

description: Python Reverse Find in String


rawDescription: How can i get unsigned magnitude of the -ve number in python

description: Get unsigned magnitude of the -ve number in python


code:
class WidgetAdmin(admin.ModelAdmin):
    def list_view(self, request):
        widget = Widget.objects.all()[0]
        return HttpResponseRedirect('/admin/my_site/widget/%s' % widget.id)

    def get_urls(self):
        from django.conf.urls.defaults import *
        urls = super(WidgetAdmin, self).get_urls()
        my_urls = patterns('',
                    (r'^$', admin.site.admin_view(self.list_view))
                )
        return my_urls + urls

rawDescription: Django custom list view in admin

description: Django custom list view in admin


code:
my_globals = {'var': None}

def my_func():
    my_globals['var'] = 'something else'

rawDescription: Python: accessing "module scope" vars

description: Python: accessing "module scope" vars


code:
if i==0:
  converters = [mybool]*len(row)

rawDescription: How does this work?

description: How does this work


code:
import csv
data = []
with open('input.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        data.append(row)

duplicate_names = []
while data:
    row = data.pop()
    dup_exists = False
    for other_row in data:
        if row['name'] == other_row['name']:
            duplicate_names.append(other_row)
            data.remove(other_row)
            dup_exists = True
    if dup_exists:
        duplicate_names.append(row)

with open('output.csv', 'w') as csvfile:
    fieldnames = []
    for key in duplicate_names[0]:
        fieldnames.append(key)
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for row in duplicate_names:
        writer.writerow(row)

rawDescription: python script to keep duplicate rows based on condition on columns in csv file

description: Python script to keep duplicate rows based on condition on columns in csv file


code:
df = pd.DataFrame([[100,['item1','item2','item3']],[101,['item5','item8','item9']],[102,['item2','item4']]],columns=['cust_id','Items'])
df
df['Items'] = df['Items'].apply(' '.join)
df

rawDescription: How to perform string replace operation using pandas in python?

description: Perform string replace operation using pandas in python


code:
itemsToProcess = allgroups[:]
while len(itemsToProcess) > 0:
    parseparent = itemsToProcess.pop(0)
    for groupPerm in self.permissions["groups"][parseparent]["permissions"]:
        if self.permissions["groups"][parseparent]["permissions"][groupPerm] and (groupPerm not in allgroups):
            allgroups.append(groupPerm)
            itemsToProcess.append(groupPerm)
            print("found a child- shall we do again?")

rawDescription: break out of a for loop and re-do it with updated list

description: Break out of a for loop and re-do it with updated list


code:
def distance(c1, c2):
    (r1,g1,b1) = c1
    (r2,g2,b2) = c2
    return math.sqrt((r1 - r2)**2 + (g1 - g2) ** 2 + (b1 - b2) **2)

colors = list(rgb_code_dictionary.keys())
closest_colors = sorted(colors, key=lambda color: distance(color, point))
closest_color = closest_colors[0]
code = rgb_code_dictionary[closest_color]

rawDescription: Python PIL - Finding Nearest Color (Rounding Colors)


code:
with open('file') as fin:
    fin.read(5)  # bytesrequested will be 5.

rawDescription: How does Python's `file.read` function figure out the size of the file?


code:
def drawCock(Cock):

    for place in Cock:
        x = place['x'] * size
        y = place['y'] * size
        CART = pygame.transform.scale(image2,(size,size))
        SHOW.blit(CART,(x,y))

    if Cock[2:]:

        HEAD = pygame.transform.scale(image1,(size,size))
        SHOW.blit(HEAD,(Cock[0]['x']*size,Cock[0]['y']*size))

rawDescription: Move image from end of snake in game to front first coordinate in dictionary


code:
input = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
output = []
for item in input:
    items = item.split(',')
    output.append([items[0], int(items[1]), int(items[2])])

rawDescription: python: creating list from string

description: Python: creating list from string


display_name: Python 2

rawDescription: Anaconda: Python 3 and 2 in IPython/Jupyter Notebook


code:
proc = subprocess.Popen(["python", my_program, arguments])
...
proc.terminate()

rawDescription: Run a python program for a specific time


code: ext_modules = [Extension('func1', ['util/func1_pc.py', 'util/funct2_pc.py'],)]

rawDescription: how to compile multiple files in cython

description: Compile multiple files in cython


rawDescription: Shuffle ordering of some rows in numpy array


rawDescription: Combining values in numpy arrays

description: Combining values in numpy arrays


code:
df1 = df.set_index('session')
df1.sum(1)
np.outer(*[df1.sum(1)] * 2)  # same as np.outer(df1.sum(1), df1.sum(1))
np.sqrt(np.outer(*[df1.sum(1)] * 2))
common / np.sqrt(np.outer(*[df1.sum(1)] * 2))

rawDescription: Pandas DataFrame matrix based calculation


rawDescription: How to capture only part of regex

description: Capture only part of regex


code:
from pymongo import MongoClient

client = MongoClient("mongodb://host/db_name")
db = client.get_default_database()

rawDescription: pymongo default database connection

description: Pymongo default database connection


code:
# Just to pre-compile our XPath. This will get all the text from this element from
# each of the child elements that aren't 'script' or 'style'
textXpath = etree.XPath(
    '(.|.//*[not(name()="script")][not(name()="style")])/text()')

# If instead you don't want to include the current element:
# textXpath = etree.XPath(
#   './/*[not(name()="script")][not(name()="style")]/text()')

results = ''.join(textXpath(textTag))

rawDescription: Extract value with XPath, etree and python


code:
import numpy as np
from scipy import ndimage
rows, cols = 500, 500
win_rows, win_cols = 5, 5

img = np.random.rand(rows, cols)
win_mean = ndimage.uniform_filter(img,(win_rows,win_cols))
win_sqr_mean = ndimage.uniform_filter(img**2,(win_rows,win_cols))
win_var = win_sqr_mean - win_mean**2

rawDescription: Calculating variance image python

description: Calculating variance image python


code:
class InvoiceAbstract(models.Model):
    invoiceid = models.CharField(max_length=20)
    totalamount = models.DecimalField(max_digits=15,decimal_places=2,default=0)
    downpayment = models.DecimalField(max_digits=15,decimal_places=2,default=0)
    subtotal = models.DecimalField(max_digits=15,decimal_places=2,default=0)
    tax = models.DecimalField(max_digits=15,decimal_places=2,default=0)
    amountdue = models.DecimalField(max_digits=15,decimal_places=2,default=0)
    payment = models.DecimalField(max_digits=15,decimal_places=2,default=0)
    originaldate = models.DateTimeField()
    changedate = models.DateTimeField()
    version = models.IntegerField(default=1)
    operator = models.CharField(max_length=20)
    class Meta:
        abstract = True

class Invoice(InvoiceAbstract):
    pass
class InvoiceHistory(InvoiceAbstract):
    pass

rawDescription: better django model design

description: Better django model design


code:
empty = gui.Container(width=WIDTH, height=HEIGHT)
gui.init(empty)

rawDescription: Making popup windows in pygame with pgu

description: Making popup windows in pygame with pgu


code:
from collections import OrderedDict
od = OrderedDict()
od[1] = "one"
od[2] = "two"
od[3] = "three"
od.keys()

rawDescription: Order of list obtained by dictionary's keys()


code:
import Console

c = Console.getconsole()
c.text(0, -1, 'And this is the string at the bottom of the console')

rawDescription: Printing a line at the bottom of the console/terminal


code:
class BookingSerializer(Serializer):
    reservation_history_id = serializers.IntegerField()
    credit_card = 'api.v1.serializer.AddCreditCardSerializer()'
    save_credit_card = serializers.BooleanField()
    promo_code = serializers.BooleanField(required=False)

    def __init__(self, *args, **kwargs):
        # initialize fields
        super(BookingSerializer, self).__init__(*args, **kwargs)
        # now modify the creditcard field
        self.fields['credit_card'].required = yourBackendMethod()

rawDescription: Conditional field requirement with DjangoRestFramework serializer


code:
import re
s = """foo bar add_signed_123_548 foo bar
Baddest add_unsigned_77_10 additional"""
print(re.sub(r"\badd_\w+", "adder", s))

rawDescription: Find and replace in python

description: Find and replace in python


code:
import sys

class _Sneaky(object):
  def __init__(self):
    self.download = None

  @property
  def DOWNLOAD_PATH(self):
    if not self.download:
      self.download = heavyComputations()
    return self.download

  def __getattr__(self, name):
    return globals()[name]

# other parts of itun that you WANT to code in
# module-ish ways

sys.modules[__name__] = _Sneaky()

rawDescription: Lazy module variables--can it be done?

description: Lazy module variables--can it be done


code:
# this is the nsteps ahead predictor function
from statsmodels.tsa.arima_model import _arma_predict_out_of_sample
res = sm.tsa.ARMA(y, (3, 2)).fit(trend="nc")

# get what you need for predicting one-step ahead
params = res.params
residuals = res.resid
p = res.k_ar
q = res.k_ma
k_exog = res.k_exog
k_trend = res.k_trend
steps = 1

_arma_predict_out_of_sample(params, steps, residuals, p, q, k_trend, k_exog, endog=y, exog=None, start=len(y))

rawDescription: ARMA out-of-sample prediction with statsmodels


rawDescription: How to get all possible combinations

description: Get all possible combinations


code:
import msvcrt
import win32api
import win32con
import time

def readch():
    """ Get a single character on Windows.
    see http://msdn.microsoft.com/en-us/library/078sfkak
    """
    ch = msvcrt.getch()
    if ch in b'\x00\xe0':  # arrow or function key prefix?
        ch = msvcrt.getch()  # second call returns the actual key code
    return ch

def clickerleft(x,y):
    """Clicks on given position x,y

    Input:
      x -- Horizontal position in pixels, starts from top-left position
      y -- Vertical position in pixels, start from top-left position
    """
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

print('Press Esc to quit or "a" to simulate mouse click')
while True :
    if msvcrt.kbhit():
        key = ord(readch())
        if key == 97:  # ord('a')
            clickerleft(1193,757)
        elif key == 27:  # escape key
            break
    time.sleep(0.1)
print('Done')

rawDescription: exiting a loop by pressing a escape key

description: Exiting a loop by pressing a escape key


code:
special_user_list = User.objects.filter(
    Q(userprofile__user_type='special') |
    Q(pk=request.user.pk)
).distinct()

rawDescription: Append a specific object (but same type) to a filtered object in Django


code:
import ntplib,datetime
x = ntplib.NTPClient()
datetime.datetime.utcfromtimestamp(x.request('europe.pool.ntp.org').tx_time)

rawDescription: How can I get an accurate UTC time with Python?

description: Get an accurate UTC time with Python


code:
import numpy as np
import matplotlib.pyplot as plt

Lx=1345.
Ly=1428.
x0 = Lx/2.
y0 = Ly/2.
YA, XA = np.mgrid[0:Ly, 0:Lx]
XA = XA - x0
YA = YA - y0
ang_rot = 23*np.pi/180.
XAprim = XA*np.cos(ang_rot) - YA*np.sin(ang_rot)
YAprim = XA*np.sin(ang_rot) + YA*np.cos(ang_rot)
Theta1 = np.arctan2((YAprim),(XAprim))*-180./np.pi

plt.imshow(Theta1,aspect='auto',cmap=plt.cm.hot)
plt.colorbar()
plt.show()

rawDescription: Python - Rotation of a meshgrid

description: Python - Rotation of a meshgrid


rawDescription: why return np.random.normal(10 - 1. / (x + 0.1), 0.5) works

description: Why return np.random.normal(10 - 1. / (x + 0.1), 0.5) works


code:
matching_users = Active_Users.select().where(Active_Users.user_id == userID) # returns an array of matching users even if there's just one
if matching_users is not None:
    token = matching_users[0].device_token

rawDescription: How to query a MySQL database via python using peewee/mysqldb?

description: Query a MySQL database via python using peewee/mysqldb


code:
from cmds_core import *
from cmds_basic import *
from cmds_blah import *

rawDescription: Python: import multiple modules AS

description: Python: import multiple modules AS


code:
BAD_SUBSTRINGS = ("FY", "FE", "EX1","EX2")

while True:
    filename = raw_input("Please enter the name of the file:")

    if any(b in filename for b in BAD_SUBSTRINGS):
        print("Sorry, this filename is not valid")
    else:
        print("This filename is valid")
        break

rawDescription: Test for multiple substrings inside a single string in python 2.7?


code:
def digit(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

rawDescription: Python string functions

description: Python string functions


code:
import sys, os

file_list = []

for f in os.listdir(sys.argv[1]):
    file_list.append(f)

for i in range(len(file_list)):
    prevName = file_list[i]
    if prevName != 'stackoverflow.py':  # Mention .py file so that it doesnt get renamed
        newName = '00' + file_list[i]
        os.rename(prevName, newName)

rawDescription: How does one rename multiple files using python?

description: Rename multiple files using python


code:
def chance(i, turn, active_type):
    return ((1/3) ** (i - player_dice_type[turn][active_type])) * ((2/3) ** (total_count - i - player_count[turn] + player_dice_type[turn][active_type]))

rawDescription: Python: Binomial distribution doesn't work when set as a variable


code:
class Testsuite(Base):
    """Testsuite model to map testsuite in progress to SQL DB."""

    __tablename__ = 'testsuites'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    timestamp = Column(DateTime, default=datetime.datetime.utcnow)
    product_name = Column(String)
    serial_number = Column(String)
    total_tests = Column(Integer)
    completed_tests = Column(Integer, default=0)
    console = Column(String, default="Waiting for incoming log data...\n")
    report_id = Column(Integer)
    testcases = relationship('Testcase', backref='testsuite')
    result = Column(String, default='pending')

    def __init__(self, testsuite_name, product_name, serial_number, total_tests=0):
        self.name = testsuite_name
        self.product_name = product_name
        self.serial_number = serial_number
        self.total_tests = total_tests

rawDescription: Modifying existing value in SQLAlchemy object


code:
def search(table_iterator, d, D, B):
    headings = next(table_iterator)
    junk = next(table_iterator)
    key = [d, D]
    for row in table_iterator:
        if row[0:2] != key: continue
        for index, value in enumerate(row[2:-1]):
            if value == B:
                return headings(2 + index)
    return None

rawDescription: Retrieving value from Excel table from an intersection of values using Python


code:
class ABC(object):
    C1 = 1

class DEF(object):
    def __init__(self, v=ABC.C1):
        self.v = v

a = ABC()
d = DEF()
d.v

rawDescription: How to access static members of outer class from an inner class constructor?

description: Access static members of outer class from an inner class constructor


code:
import os
import sys

# ...

sys.path.append(os.path.join(os.path.curdir, "crawlers/myproject"))
os.environ['SCRAPY_SETTINGS_MODULE'] = 'myproject.settings'

settings = get_project_settings()

rawDescription: Scrapy crawler ignores `DOWNLOADER_MIDDLEWARES` when run as a script


code:
import sys,os.path
from PyQt4 import QtGui, QtCore

class TreeExperiment(QtGui.QWidget):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)

        self.tree=QtGui.QTreeWidget(self)                #
        self.tree.setObjectName("treeWidget")            #
        self.add_button=QtGui.QPushButton("Add", self)   # Initialize a simple
        self.save_button=QtGui.QPushButton("Save", self) # form containing a
        gridlayout = QtGui.QGridLayout(self)             # treeWidget, an
        gridlayout.addWidget(self.tree,1,0,1,9)          # 'Add' button, and a
        gridlayout.addWidget(self.add_button,2,0,2,3)    # 'Save' button
        gridlayout.addWidget(self.save_button,2,3,2,3)   #
        self.tree.headerItem().setText(0,"Label")        #

        if os.path.isfile('native_tree_save.qfile'):
            # First look for a previously saved tree. If found, define
            # it as a QFile named 'file', open it, and define a datastream
            # to read from it.
            #
            # Each tree node is saved to and read from the file in pairs:
            # first, the QTreeWidgetItem itself, then the number of children
            # the item has so that the tree structure can be re-created
            #
            # The first item is added directly as the root for simplicity,
            # and is sent to the function which begins the tree reconstruction

            file = QtCore.QFile('native_tree_save.qfile')
            file.open(QtCore.QIODevice.ReadOnly)
            datastream = QtCore.QDataStream(file)
            child=QtGui.QTreeWidgetItem(self.tree.invisibleRootItem())
            child.read(datastream)
            num_childs=datastream.readUInt32()
            self.restore_item(datastream,child,num_childs)
        else: # Otherwise if this is the first use, create a root item
            new_item=QtGui.QTreeWidgetItem(self.tree)
            self.tree.setCurrentItem(self.tree.topLevelItem(0))
            self.tree.currentItem().setText(0,'root')

        self.tree.setItemSelected(self.tree.topLevelItem(0),1)
        self.tree.setCurrentItem(self.tree.topLevelItem(0))

        self.connect(self.add_button, QtCore.SIGNAL("clicked()"), self.add_item)
        self.connect(self.save_button, QtCore.SIGNAL("clicked()"), self.save_tree)
        self.added_item_count=0

    def add_item(self): # Adds an item to whatever is selected
        self.added_item_count+=1
        label=str(self.added_item_count)
        new_item=QtGui.QTreeWidgetItem(self.tree.currentItem())
        new_item.setText(0,label)
        self.tree.setCurrentItem(new_item)

    def restore_item(self,datastream,item,num_childs):
        for i in range(0, num_childs):
            child=QtGui.QTreeWidgetItem(item)
            child.read(datastream)
            num_childs=datastream.readUInt32()
            self.restore_item(datastream,child,num_childs)

    def save_item(self,item,datastream):
        num_childs=item.childCount()
        for i in range(0,num_childs):
            child = item.child(i)
            child.write(datastream)
            num_childs=child.childCount()
            datastream.writeUInt32(num_childs)
            self.save_item(child,datastream)

    def save_tree(self):
        file = QtCore.QFile('native_tree_save.qfile')
        file.open(QtCore.QIODevice.WriteOnly)
        datastream = QtCore.QDataStream(file)
        self.save_item(self.tree.invisibleRootItem(),datastream)

if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    window = TreeExperiment()
    window.resize(200, 120)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt: Saving native QTreeWidgets using QDataStream


code: [(snd, fst) for fst, snd in thelist]

description: Inverse of a list python [(160,177),(198,123)]


code:
from subprocess import Popen, PIPE
output = Popen(["/usr/bin/whois", "abc.com"], stdout = PIPE).communicate()[0]

rawDescription: How do I use python to hit this command and return the result?

description: Use python to hit this command and return the result


code:
new_a = a[:1]
for i in a[1:]:
    if i >= new_a[-1] + 3:
        new_a.append(i)

rawDescription: How to remove values from a list that are less than a target value from the previous number

description: Remove values from a list that are less than a target value from the previous number


code:
f1
f2
f2[~f2.cid.isin(f1.cid)]

rawDescription: Pandas : Merge two Dataframes on a column, but keep only data for unlike Columns


code: items = json.loads('<%= JSON[some_array.sort.reverse] %>')

rawDescription: Dangers of echoing arrays in ERB templates


code:
subprocess.call(["/bin/cp", "-a",
    os.path.join(MOST_POPULAR_REPORTS_LOCATION, MOST_POPULAR_REPORTS_FILE),
        TEMP_DATA_FILE_LOCATION])

rawDescription: Python subprocess.call with variable substitution


code:
hrefs  = []
for entry in orderlink:
   hrefs.append(entry["links"]["order"]["href"])

rawDescription: Get a list from a dict and save an element from that List Python


code:
pixbuf = gtk.gdk.pixbuf_new_from_file(image_filename) #one way to load a pixbuf
pixmap.draw_pixbuf(None, pixbuf, 0, 0, x, y, -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0)

rawDescription: draw an image to gtk.DrawingArea?

description: Draw an image to gtk.DrawingArea


code:
import logging
import logging.handlers

# create logger
root_logger = logging.getLogger()
root_logger.setLevel(0)
# defines logger file and max size
handler = logging.handlers.RotatingFileHandler('request.log', maxBytes=5000000)
# define logger format
formatter = logging.Formatter("test %(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
handler.setFormatter(formatter)
handler.setLevel(0)
# add loggerhandler to applications
root_logger.addHandler(handler)

logger = logging.getLogger('app')

logger.info("Logger started")

rawDescription: Logger for python. Doesn't log custom log entries


rawDescription: python backwards lists

description: Python backwards lists


rawDescription: Python: Regular expression for exactly $n$ [?o], with at least one [o]


code:
MIDDLEWARE_CLASSES = (
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.locale.LocaleMiddleware',
   'django.middleware.common.CommonMiddleware',
   ...
)

rawDescription: 404 on requests without trailing slash to i18n urls


code:
import math

for pos in range(len(self.boids)):
    angle = 2*math.pi / n
    x = radius * math.sin(angle)
    y = radius * math.cos(angle)

rawDescription: Creating a "formation" from a range of any numbers


code: x = data['list_price'].astype('int64')

rawDescription: Setting Data Types with Matplotlib and csv2rec


code:
import re

blocktags = '''\
<address    <article    <aside
<blockquote
<canvas
<dd    <div    <dl
<fieldset    <figcaption    <figure    <footer    <form
<h1    <h2    <h3    <h4    <h5    <h6    <header    <hgroup    <hr
<li
<main
<nav    <noscript
<ol    <output
<p    <pre
<section
<table    <tfoot
<ul
<video'''.split()

pat = re.compile('(' + '|'.join(blocktags) + ')')

blocked_str = pat.sub(r'\n\1', str(soup))

rawDescription: Moderately minify HTML (from Beautiful Soup output)


code:
with open('myfile.json') as fr:
    dicts = [json.loads(line) for line in fr]

rawDescription: PySpark save DataFrame to actual JSON file


code:
f = urllib2.urlopen("http://example.com/foo/bar")
s = f.read()
# s now holds the contents of the site

rawDescription: urllib2 to string

description: Urllib2 to string


code:
import os
import json

directory_path = '.' #Assuming your directory path is the one your script lives in.

txt_filenames = [fname for fname in os.listdir(directory_path) if fname.endswith('.txt')]

with open('file.txt', 'w') as ofile:
    ofile.write(json.dumps({
            'filenames': txt_filenames
        }))

rawDescription: How to loop to directory and json the output to txt file?

description: Loop to directory and json the output to txt file


code:
import pythoncom, win32com.client, threading, time

def start():
    # Initialize
    pythoncom.CoInitialize()

    # Get instance
    xl = win32com.client.Dispatch('Excel.Application')

    # Create id
    xl_id = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, xl)

    # Pass the id to the new thread
    thread = threading.Thread(target=run_in_thread, kwargs={'xl_id': xl_id})
    thread.start()

    # Wait for child to finish
    thread.join()

def run_in_thread(xl_id):
    # Initialize
    pythoncom.CoInitialize()

    # Get instance from the id
    xl = win32com.client.Dispatch(
            pythoncom.CoGetInterfaceAndReleaseStream(xl_id, pythoncom.IID_IDispatch)
    )
    time.sleep(5)

if __name__ == '__main__':
    start()

rawDescription: Using win32com with multithreading

description: Using win32com with multithreading


code:
import urllib

myPort = "8080"
myParameters = { "date" : "whatever", "another_parameters" : "more_whatever" }

myURL = "http://localhost:%s/read?%s" % (myPort, urllib.urlencode(myParameters))

rawDescription: Build HTTP GET request with port number and parameters


code: query = {[(k, v[0] if len(v) == 1 else v) for k, v in query.iteritems()]}

rawDescription: Clean parsing of url query

description: Clean parsing of url query


code:
from decimal import getcontext, Decimal
getcontext().prec = 6
Decimal(1) / Decimal(7)
getcontext().prec = 28
Decimal(1) / Decimal(7)

rawDescription: 100 digit floating point python

description: 100 digit floating point python


code:
def someview(request):
    context = { }
    return render_to_response('some_template.html', context,
                context_instance = RequestContext(request))

rawDescription: How to pass context defined in setting TEMPLATE_CONTEXT_PROCESSORS to my custom views

description: Pass context defined in setting TEMPLATE_CONTEXT_PROCESSORS to my custom views


code:
class SomeModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        #Encript fields values
        super(SomeModelAdmin, self).save_model(request, obj, form, change)

rawDescription: Saving model fields in admin interface in Django


code:
...
mods_in_dir = ['my_mods.frst_mod','my_mods.scnd_mod']
modules = list(map(__import__, mods_in_dir))
# if you want to invoke func1 in my_mods.frst_mod and get result from it
result1 = modules[0].func1()
# if you want to invoke func2 in my_mods.scnd_mod and get result from it
result2 = modules[1].func2()
...

rawDescription: Unable to use dynamically imported modules


code:
import httplib
import os.path

total_size = os.path.getsize('/path/to/file')
infile = open('/path/to/file')
conn = httplib.HTTPConnection('example.org')
conn.connect()
conn.putrequest('POST', '/upload/')
conn.putheader('Content-Type', 'application/octet-stream')
conn.putheader('Content-Length', str(total_size))
conn.endheaders()
while True:
    chunk = infile.read(1024)
    if not chunk:
        break
    conn.send(chunk)
resp = conn.getresponse()

rawDescription: Streaming data of unknown size from client to server over HTTP in Python


code:
def reencode(file):
    for line in file:
        yield line.decode('windows-1250').encode('utf-8')

csv_reader = csv.reader(reencode(open(filepath)), delimiter=";",quotechar='"')

rawDescription: csv with different encoding

description: Csv with different encoding


rawDescription: Why is it so much slower to export my data to .xlsx than to .xls or .csv?


code:
def dvdprintsoftlist():
    list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
    print(list_of_DVDsuppliers)
    print
    ''' printing the available DVDstocks,supplier's details '''
    print("This is your current list of stock")
    print("Supplier Name\t\tSoftwear Name\t\tAmount")
    print("----------------------------------------------------------------")
    for [name, softname, amount] in list_of_DVDsuppliers:
        print("{0:23} {1:23} {2:5}".format(name, softname, amount))
        print("----------------------------------------------------------------")
    print("")

dvdprintsoftlist()

rawDescription: Printing list-of-lists in tabular form in Python


rawDescription: how to parse a string into a dictionary

description: Parse a string into a dictionary


code:
cipherText=[]

for i in range(len(key)):
    for x in range(len(key)):
        item = plainAscii[x] + keyAscii[x]
        cipherText.append(item)

print(cipherText)

rawDescription: How do I add list items from different lists in python?

description: Add list items from different lists in python


code: values, vectors = scipy.sparse.linalg.eigs(P, k=1, sigma=1)

rawDescription: How do I find out eigenvectors corresponding to a particular eigenvalue of a matrix?

description: Find out eigenvectors corresponding to a particular eigenvalue of a matrix


code:
s = "01/31/2000 09:09 PM"
date, space, time = s.partition(' ')
date

rawDescription: Remove time in datetime python

description: Remove time in datetime python


code:
class VehicleType(type):
    registry = {}

    def __init__(self, name, bases, attrs):
        self.registry[name.lower()] = self

    def __call__(self, name):
        cls = self.registry[name]
        inst = cls.__new__(cls)
        inst.__init__()
        return inst

class Vehicle(object):
    __metaclass__ = VehicleType

class Car(Vehicle):
    pass

car = Vehicle("car")
print(type(car))  # <class '__main__.Car'>

rawDescription: How to implement a plugin?

description: Implement a plugin


code:
import pylab as py
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import matplotlib as mpl
from matplotlib import cm

# Create figure and get data
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)

N = (Z-Z.min())/(Z-Z.min()).max()

# Plot surface and colorbar
c1 = ax.plot_surface(Z, Y, X, rstride=8, cstride=8, alpha=0.9, facecolors=cm.PiYG_r(N))

m = cm.ScalarMappable(cmap=cm.PiYG_r)
m.set_array(X)
cbar = plt.colorbar(m)

# Labels
ax.set_xlabel('X')
ax.set_xlim3d(-100, 100)
ax.set_ylabel('Y')
ax.set_ylim3d(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim3d(-40, 40)

plt.show()

rawDescription: Matplotlib 3d plot - associate colorbar with different axis


code:
for key in dict_A.viewkeys() | dict_A.viewkeys():
    some_function(dict_A.get(key, 0), dict_B.get(key, 0))

rawDescription: What is the Pythonic way to iterate over set intersection and exclusions?


code:
table = ... # code for creating table goes here
table_txt = table.get_string()
with open('output.txt','w') as file:
    file.write(table_txt)

rawDescription: Can i write the output format created by prettytable into a file?

description: Write the output format created by prettytable into a file


code:
import string
filter(string.printable.__contains__, '\x00\x01XYZ\x00\x10')

rawDescription: Remove ASCII control characters from text file Python


code:
class FileUploadView(views.APIView):
    parser_classes = (FileUploadParser,)

    def put(self, request, filename, format=None):
        file_obj = request.FILES['file']
        # do some stuff with uploaded file
        return Response(status=204)

rawDescription: Django Rest Framework File Upload

description: Django Rest Framework File Upload


code:
df = pd.read_csv("knop.csv", names=range(6))
df
df = df.dropna(axis=1,how='all')
df

rawDescription: Reading csv files with messy structure with pandas