code:
with open("test.txt","w") as fin:
    #izip_longest create consecutive tuples of elements from the list of iterables
    #where if any of the iterable's length is less than the longest length of the
    #iterable, fillvalue is taken as default
    #If you need formatted output, you can use str.format
    #The format specifier here used specifies the length of each column
    #to be five and '^' indicates that the values would be center alligned
    for e in izip_longest(a,b,fillvalue=''):
         print >>fin,"{:^5} {:^5}".format(*e)
         #if you are using Python 3.x
         #fin.write("{:^5} {:^5}\n".format(*e))

rawDescription: Writing two lists with different length as columns to a data file


code:
import logging
import time

logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('server time')

logging.Formatter.converter = lambda self, current: time.localtime(current-3600*3)

logging.warning('time at your zone')

rawDescription: How to use logging module in python with different timestamp?

description: Use logging module in python with different timestamp


code: from django.http import HttpResponseRedirect

rawDescription: How to create sub domains in django and redirect each sub domain to some vanity domain like abc.mydomain.com--> www.yourdomain.com?

description: Create sub domains in django and redirect each sub domain to some vanity domain like abc.mydomain.com--> www.yourdomain.com


code:
@app.route("/", methods=['GET', 'POST'])
def index():
    form = StandardForm()

    std = form.data.get('standard')
    group = form.data.get('group')

    q = Standard.query
    for fieldname, value in form.data.items():
        if fieldname == 'standard' and value != "All":
            q = q.filter(Standard.stdname.has(name=std))
        elif fieldname == 'group' and value != "All":
            q = q.filter(Standard.group == group)

    return render_template(
        'index.html',
        form=form,
        standards=q.all())

rawDescription: Improving view function in Flask

description: Improving view function in Flask


code: rooms = set([r for resort in otas.values() for room in resort.values() for r in room])

rawDescription: Simplifying a nested for loop with comprehension


code:
listA = [1,20,12,4]
pd.DataFrame(data = listA , columns=['listA'])

rawDescription: How to convert a simple list into a data frame in python

description: Convert a simple list into a data frame in python


code: m = zipfile.ZipFile("test.jar", "a")

rawDescription: Add a file to a jar using python zipfile


code:
from xml.etree import ElementTree
from xml.etree.ElementTree import iterparse

level = 0

for (event, node) in iterparse( fileName, ['start', 'end', 'start-ns', 'end-ns'] ):

    if event == 'end':
        level -= 1

    if event == 'start':
        level += 1

    # do soething with node ...

rawDescription: (Python) How to get the level of a node in xml?


code:
a = [1, 2, 3]
for index, item in enumerate(a):
    print(item)
    a.insert(index, '{0}{0}'.format(index))
    print(a)

rawDescription: Why is a loop over a list infinite when I use insert()


rawDescription: Solve for constants of 4-parameter (Rodbard Equation) using Python


code:
from operator import itemgetter
callme(*itemgetter(0, 1, 4)(alist))

rawDescription: Is it possible to concatenate list indices in one statement in Python?


code:
class MyThread(QObject):
    send_data_to_gui = pyqtSignal(str)

    def __init__(self,*args,**kwargs):
        QObject.__init__(self,*args,**kwargs)

    @pyqtSlot()
    def run(self):
        while True:
            # get data from device
            self.send_data_to_gui.emit(data_from_device)
            time.sleep(10)

...

thread = QThread()
my_thread = MyThread()
my_thread.send_data_to_gui.connect(my_slot)
my_thread.moveToThread(thread)
thread.started.connect(my_thread.run)
thread.start()

rawDescription: QtCore.QTimer.singleShot lags when calling a function iteratively


code:
from itertools import izip, islice
l1 = ['a', 'b', 'c', 'd', 'e']
l2=[x for (a,b) in izip(l1, islice(l1, 1,None)) for x in ([a,a],[a,b])] ; l2 += [[b,b]]
l2

rawDescription: Slice pattern for list

description: Slice pattern for list


rawDescription: Control search depth findall Lxml

description: Control search depth findall Lxml


code:
# Sometimes it's useful to process bad headers or bad HTML:
response = br.response()  # this is a copy of response
headers = response.info()  # currently, this is a mimetools.Message
headers["Content-type"] = "text/html; charset=utf-8"
response.set_data(response.get_data().replace("<!---", "<!--"))
br.set_response(response)

rawDescription: Is it possible to hook up a more robust HTML parser to Python mechanize?


code:
mapping = {
    'domain': 'domain',
    'db_user': 'username',
}

key = mapping.get(obj_type, 'name')

rawDescription: Python: long if expression vrs. small if blocks


code:
import time
with open(file) as f:
    for line in f:
        identifier, t0, score, date, hour = line.split()

        # You can also get a time_struct from the time
        timer = time.strptime(date + hour, "%d/%m/%Y%H:%M:%S")

rawDescription: python read data from file

description: Python read data from file


code:
from goose import Goose
from requests import get

response = get('http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&ref=general')
extractor = Goose()
article = extractor.extract(raw_html=response.content)
text = article.cleaned_text

rawDescription: Extract News article content from stored .html pages


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

data = np.random.random((10,10))

# To make a standalone example, I'm skipping initializing the
# `Figure` and `FigureCanvas` and using `plt.figure()` instead...
# `plt.draw()` would work for this figure, but the rest is identical.
fig, ax = plt.subplots()
ax.set(title='Click to update the data')
im = ax.imshow(data)

def update(event):
    im.set_data(np.random.random((10,10)))
    fig.canvas.draw()

fig.canvas.mpl_connect('button_press_event', update)
plt.show()

rawDescription: Matplotlib figure not updating on data change


code:
import numpy as np

A = np.asarray([[1,2,3],[4,5,6],[7,8,9]])
eig_vals, eig_vecs = np.linalg.eig(A)

eig_vals_sorted = np.sort(eig_vals)
eig_vecs_sorted = eig_vecs[:, eig_vals.argsort()]

# Alternatively, to avoid making new arrays
# do this:

sort_perm = eig_vals.argsort()

eig_vals.sort()     # <-- This sorts the list in place.
eig_vecs = eig_vecs[:, sort_perm]

rawDescription: python numpy sort eigenvalues

description: Python numpy sort eigenvalues


code:
import numpy
numpy.version.version

rawDescription: How to check which version of Numpy I'm using?

description: Check which version of Numpy I'm using


code:
spark_df.write.format('com.databricks.spark.csv') \
  .mode('overwrite').option("header", "true").save(self.output_file_path)

rawDescription: overwriting a spark output using pyspark

description: Overwriting a spark output using pyspark


code:
ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)
x = ser.read()          # read one byte
s = ser.read(10)        # read up to ten bytes (timeout)
line = ser.readline()   # read a '\n' terminated line
ser.close()

rawDescription: Python - Fetching data from two serial ports in realtime


code:
user_filters = [and_(Users.name == name, Users.age == age)
                for name, age in users]
self.session.query(Users).filter(or_(*user_filters))

rawDescription: Sqlalchemy query: select using list of tuples


code:
db_conn = mdb.connect(
    host="localhost", user="username", passwd="password", db="db_name",
    charset='utf8', cursorclass=mdb.cursors.DictCursor)

rawDescription: Read database entries from mysql in the form of dictionary in python


code:
def _bisect2(dasList, word,lidx=0):
    mid = int(len(dasList)/2)
    if word.lower() > dasList[mid].lower():
        return _bisect2(dasList[mid:], word,lidx=lidx+mid)
    elif word.lower() < dasList[mid].lower():
        return _bisect2(dasList[:mid], word,lidx=lidx)
    return lidx+mid

words=sorted(["one","two","three","four","five","twenty","foo"])
print (words)
print (_bisect2(words,'three'))

rawDescription: python, string comparison not working?

description: Python, string comparison not working


code:
class Guestbook(webapp.RequestHandler):
  def post(self):
    guestbook_name = self.request.get('guestbook_name')
    user = users.get_current_user()
    nickname = None
    if user:
      nickname = user.nickname()
      greeting = Greeting.gql('WHERE author = :1 AND ANCESTOR IS :2',
          nickname, guestbook_key(guestbook_name)).get()
    if not greeting:
      greeting = Greeting(parent=guestbook_key(guestbook_name))
      greeting.author = nickname

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))

rawDescription: Overwrite in datastore using python for GAE - Guestbook Example


code:
@patch('twilio.rest.resources.SmsMessages')
def test_send_msg_valid_args(self, MockClass):
    instance = MockClass.return_value
    instance.create.return_value = None
    to_number = '+15555555555'
    msg = 'Hello world'
    send_sms(to_number, msg)

    instance.create.assert_called_once_with(to=to_number, body=msg, from_=default_from_number)

rawDescription: Mock patch is not working with class in __init__.py


code:
def decorator(func):
    def wrapped(a, b, c):
        return c + func(a, b)
    return wrapped

@decorator
def add(a, b):
    return (a+b)

rawDescription: Can some function arguments be passed through decorators?


code:
def getpath():
    os.path.abspath(os.path.dirname(__file__))

rawDescription: Django: Getting path of module being imported from views.py


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

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');

with con:

    cur = con.cursor()
    cur.execute("DROP TABLE IF EXISTS Writers")
    cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
             Name VARCHAR(25))")
    cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
    ...

rawDescription: Catching Errors in MySQLdb Library

description: Catching Errors in MySQLdb Library


code:
def unique_items(iterable):
    tuples = map(tuple, iterable)
    counts = collections.Counter(tuples)
    unique = []
    non_unique = []
    for t in tuples:
        if counts[t] == 1:
            unique.append(t)
        else:
            non_unique.append(t)
    return unique, non_unique

rawDescription: Finding items that occur exactly once in an array


code:
class BoolChange:
    def __init__(self):
        self.count = 0

    def __bool__(self):
        self.count += 1
        return self.count <= 5

x = BoolChange()
while x:
    print("Running")

rawDescription: python expression that evaluates to True n times

description: Python expression that evaluates to True n times


code:
images = {'a': load_image('assets/A/x.png'),
          'b': load_image('assets/B/x.png'),
          'c': load_image('assets/C/x.png'),
          'd': load_image('assets/D/x.png')}
...
class TestSprite(pygame.sprite.Sprite):
    def __init__(self, image_key):
        super(TestSprite, self).__init__()
        self.image = images[image_key]
...
def GetRandomAsset():
    image_key = random.choice(images.keys())
    return TestSprite(image_key)

rawDescription: Using Pygame, draw a copy of an image in a different location


code:
basepath = '/path/to/directory'
for fname in os.listdir(basepath):
    path = os.path.join(basepath, fname)
    if os.path.isdir(path):
        # skip directories
        continue

rawDescription: Python - how to find files and skip directories in os.listdir


code:
dll_excludes = ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll',
                'tk84.dll','MSVCP90.dll']

setup(
    data_files = data_files,
    options = {"py2exe": {"compressed": 2,
                          "optimize": 2,
                          "includes": includes,
                          "excludes": excludes,
                          "packages": packages,
                          "dll_excludes": dll_excludes,
                          "bundle_files": 1,
                          "dist_dir": "dist",
                          "xref": False,
                          "skip_archive": False,
                          "ascii": False,
                          "custom_boot_script": '',
                         }
              },
    zipfile = None,
    windows = [filename]
    )

rawDescription: wxPython py2exe app not bundling properly?

description: WxPython py2exe app not bundling properly


code:
from __future__ import division
from math import *
def solution_handler(self, input):
    return eval(input)

rawDescription: exec cos(x) freezes program if x not in [-9,9]

description: Exec cos(x) freezes program if x not in [-9,9]


code:
from itertools import islice
g = (i for i in range(10))
next(islice(g, 2, 2 + 1))
next(g)

rawDescription: Can I pick a specific item from generator?

description: Pick a specific item from generator


code:
X = np.linspace(0, 2 * np.pi, 100)
Y = np.sin(X)
Z = np.sin(2 * X)

fig, ax1 = plt.subplots()
ax1.set_ylim([-1.1, 1.1])
ax2 = ax1.twinx() # <--------------- Move it here

ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax1.spines['right'].set_visible(False)

ax1.tick_params(axis='both',
                which='both',
                bottom='off',
                top='off',
                left='off',
                right='off')

ax1.plot(X, Y, color='b')

ax2.spines['top'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['right'].set_visible(False)

ax2.tick_params(axis='both',
                which='both',
                bottom='off',
                top='off',
                left='off',
                right='off')

ax2.plot(X, Z, color='r')

rawDescription: Left tick marks remain in matplotlib despite call to tick_params and use of NullLocator


code:
import sys

def in_shell():
    # Interactive prompt sets sys.ps1
    if hasattr(sys, 'ps1'):
        return True

     # __IPYTHON__ is defined when running under IPython
    return '__IPYTHON__' in __builtins__

rawDescription: python: is it possible to detect whether I am in the paster shell?

description: Python: is it possible to detect whether I am in the paster shell


code:
subprocess.call(
    ["boto-rsync", "..."],
    env={"PATH":"/Library/Frameworks/Python.framework/Versions/2.7/bin/"},
    )

rawDescription: subprocess.call env var

description: Subprocess.call env var


code:
for item in results['result']:
    print(item['name'])

rawDescription: Outputting dictionary results for all indexes


code:
from Tkinter import *
import ttk
import time

MAX = 30

root = Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = DoubleVar() #here you have ints but when calc. %'s usually floats
theLabel = Label(root, text="Sample text to show")
theLabel.pack()
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=MAX)
progressbar.pack(fill=X, expand=1)

def loop_function():

    k = 0
    while k <= MAX:
    ### some work to be done
        progress_var.set(k)
        k += 1
        time.sleep(0.02)
        root.update_idletasks()
    root.after(100, loop_function)

loop_function()
root.mainloop()

rawDescription: Python: Tkinter simple updating progress bar


code:
import numpy as np

def correlation(pixel, image):
    c, m, n = image.shape
    image = image.reshape(c, m * n)

    pixel_mean = pixel.mean()
    pixel_std = pixel.std()
    means = image.mean(0)
    stds = image.std(0)

    # calculate the covariance between `pixel` and each image pixel
    covs = np.dot(pixel - pixel_mean, image - means) / float(c)

    # calculate Pearson's correlation coefficient
    corr = covs / (pixel_std * stds)
    return corr.reshape(m, n)

# generate a random image to test
c = 21
m = 500
n = 900
image = np.random.randn(c, m, n)
corr = correlation(image[:,10,10], image)

# check an arbitrary point to make sure it works
assert np.allclose(corr[302, 411],
                   np.corrcoef(image[:,10,10], image[:,302,411])[0,1])

rawDescription: Numpy calculating corrcoef for large multispectral images


code:
class Player(object):
    # ... snip ...

    def fire(self):
        bullet = Bullet()
        bullet.owner = self
        bullet_list.append(bullet)

rawDescription: Getting an objects name during instantiation


code:
import timeit

def auto_timeit(stmt='pass', setup='pass'):
    n = 1
    t = timeit.timeit(stmt, setup, number=n)

    while t < 0.2:
        n *= 10
        t = timeit.timeit(stmt, setup, number=n)

    return t / n # normalise to time-per-run

rawDescription: Forcing timeit to automatically choose number of times statement is executed


code:
arr = numpy.memmap(f, '>u1', 'r', shape=(size, rows, cols))
arr = arr / float(max_value)
arr -= 0.5

rawDescription: Fastest way to convert ubyte [0, 255] array to float array [-0.5, +0.5] with NumPy


code:
for i, S_Cell in enumerate(S_Row.findall('S_Cell')):
    for S_CellBody in S_Cell.getchildren():
          S_CellBody.text = str(i)

rawDescription: Catching selected portion of xml files

description: Catching selected portion of xml files


code:
directoryPath=raw_input('Directory for csv files: ')
myindex=[''] #'event 1','event 2','event 3','event 4','event 5','event 6'

count = 0
for file in os.listdir(directoryPath):
    if file.endswith(".csv"):
        count += 1
        myindex.append('event '+str(count))

rawDescription: Python: how to create a list with names based on the content of a given folder?


code:
import dis
dis.dis(compile('print "Hello world!"', '<demo>', 'exec'))

rawDescription: Print skipping newline

description: Print skipping newline


code:
for form in forms:
    d.update(form)

rawDescription: More Pythonic Way to Merge a list of dictionaries into one?


rawDescription: How can I get amount of rows in Excel file via xlwt

description: Get amount of rows in Excel file via xlwt


code:
def stream_encode_multipart(values, use_tempfile=True, threshold=1024 * 500,
                            boundary=None, charset='utf-8'):
    """Encode a dict of values (either strings or file descriptors or
    :class:`FileStorage` objects.) into a multipart encoded string stored
    in a file descriptor.
    """

    ...

rawDescription: Python - What type is flask.request.files.stream supposed to be?


code:
from lmfit import minimize, Parameters, Parameter, report_fit
import numpy as np

# create data to be fitted
x = np.arange(150)/100.
data = 2e-6*x-5e-7 + np.random.normal(size=len(x), scale=5e-7)

# define objective function: returns the array to be minimized
def fcn2min(params, x, data):
    """ model decaying sine wave, subtract data"""
    slope = params['slope'].value
    offset = params['offset'].value

    model = slope * x + offset
    return model - data

# create a set of Parameters
params = Parameters()
params.add('slope',   value= 1.,  min=0)
params.add('offset', value= 0.)

# do fit, here with leastsq model
result = minimize(fcn2min, params, args=(x, data))

# calculate final result
final = data + result.residual

# write error report
report_fit(result.params)

# [[Variables]]
#     slope:    2.1354e-06 +/- 9.33e-08 (4.37%) (init= 1)
#     offset:  -6.0680e-07 +/- 8.02e-08 (13.22%) (init= 0)
# [[Correlations]] (unreported correlations are <  0.100)
#     C(slope, offset)             = -0.865

# plot results
import matplotlib.pyplot as plt
plt.plot(x, data, 'k+')
plt.plot(x, final, 'r')
plt.show()

rawDescription: Python- doing least square fitting on time series data?


code:
def roll(sides, times):
    final_sum = 0
    for i in range(times):
        randnum = random.randrange(sides)
        final_sum += randnum if randnum % 2 else 0
    return final_sum

rawDescription: Python: random module with sum accumulator for odd numbers


code:
# Compute the batch size based on the shape of the (presumably fed-in) `input`
# tensor. (Assumes that `input = tf.placeholder(..., shape=[None, input_size])`.)
batch_size = tf.shape(input)[0]

_seq_len = tf.fill(tf.expand_dims(batch_size, 0),
                   tf.constant(n_steps, dtype=tf.int64))
outputs, state1, state2 = rnn.bidirectional_rnn(rnn_fw_cell, rnn_bw_cell, input,
                                                dtype=tf.float32,
                                                sequence_length=_seq_len)

rawDescription: How to use variable batch size for bidirectional RNN in tensorflow

description: Use variable batch size for bidirectional RNN in tensorflow


code:
# given a user instance (and assuming Django ORM)
social = user.social_auth.get(provider='twitter')
backend = social.get_backend()
form_data = {
    'status': 'The new twitter status goes here'
}
response = backend.get_json(
    'https://api.twitter.com/1.1/statuses/update.json',
    method='POST',
    auth=backend.oauth_auth(social.extra_data['access_token']),
    data=form_data
)

rawDescription: Tweet on behalf of users who have authenticated my app to post tweet?


code:
from collections import Counter, defaultdict

x = Counter(['a', 'a', 'ab', 'c', 'hij', 'k']) # OR ['a','a','ab','c','hij','k']
by_length = defaultdict(list)
for key in x:
    by_length[len(key)].append(key)

print(by_length[1]) # prints: ['a', 'k', 'c']
print(by_length[2]) # prints: ['ab']
print(by_length[3]) # prints: ['hij']

rawDescription: Is there a simpler way to filter out Counter keys by length? python


code:
from rest_framework.response import Response

def list(self, request, *args, **kwargs):
    pks = []
    qs = self.get_queryset()
    for obj in qs:
        pks.append(obj.pk)
    return Response(data=pks)

rawDescription: Django REST specify which fields when viewing a list


code:
words
[words[i:i+3] for i in range(len(words) - 2)]

rawDescription: Python, creating triplets from array of words


code:
from Xlib import display
data = display.Display().screen().root.query_pointer()._data
locationtuple = (data["root_x"], data["root_y"])

rawDescription: How do I find which monitor the mouse pointer is in with python?

description: Find which monitor the mouse pointer is in with python


code:
def process_item(self, item, spider):
    if spider.name not in ['spider1', 'spider2']:
        return item

    # process item

rawDescription: Python Scrapy - Direct spider to specific Pipeline


code: users = User.objects.filter(username__in=['foo', 'bar'])

rawDescription: getting multiple user objects using filter

description: Getting multiple user objects using filter


code:
from collections import Counter
import re

sentence = "I love TV show makes me happy, I love also comedy show makes me feel like flying"
words = re.findall(r'\w+', sentence)
two_words = [' '.join(ws) for ws in zip(words, words[1:])]
wordscount = {w:f for w, f in Counter(two_words).most_common() if f > 1}
wordscount

rawDescription: Word frequency count based on two words using python


code:
def ballSnapTop():
    ballRect.top = playerRect.bottom - distance

rawDescription: How to Use the Pygame Rect

description: Use the Pygame Rect


code:
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, scoped_session, sessionmaker

def camel_to_under(name):
    import re
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

def configure_database(app_name):
    """ @return: dictionary with all the classes mapped to proper tables for
    specific application.  """
    from sqlalchemy.ext.declarative import declared_attr
    from sqlalchemy.ext.declarative import declarative_base

    class Base(object):
        # docs: http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative.html#augmenting-the-base
        @declared_attr
        def __tablename__(cls):
            return camel_to_under(cls.__name__) + "_" + app_name

        def __repr__(self):
            attrs = class_mapper(self.__class__).column_attrs # only columns
            # attrs = class_mapper(self.__class__).attrs # show also relationships
            return u"{}({})".format(self.__class__.__name__,
                ', '.join('%s=%r' % (k.key, getattr(self, k.key))
                    for k in sorted(attrs)
                )
            )

    Base = declarative_base(cls=Base)

    class Class1(Base):
        id = Column(Integer, primary_key=True)
        name = Column(String)

    class Class1Child(Base):
        id = Column(Integer, primary_key=True)
        parent_id = Column(Integer, ForeignKey(Class1.id))
        name = Column(String)
        # relationships
        parent = relationship(Class1, backref="children")

    # return locals()
    return {
        "app_name": app_name,
        "Base": Base,
        "Class1": Class1,
        "Class1Child": Class1Child,
        }

def _test():
    """ Little test for the app.  """
    engine = create_engine(u'sqlite:///:memory:', echo=True)
    session = scoped_session(sessionmaker(bind=engine))

    app_name = "app1"
    x = configure_database(app_name)

    # assign real names
    app_name = x["app_name"]
    Base = x["Base"]
    Class1 = x["Class1"]
    Class1Child = x["Class1Child"]

    # create DB model (not required in production)
    Base.metadata.create_all(engine)

    # test data
    cc = Class1Child(name="child-11")
    c1 = Class1(name="some instance", children=[cc])
    session.add(c1)
    session.commit()

_test()

rawDescription: Sqlalchemy: Mapping a class to different tables depending on attribute


rawDescription: Regex to replace 4.7uF to 4U7

description: Regex to replace 4.7uF to 4U7


code:
self.driver = webdriver.Ie("C://IEDriverServer.exe")
self.driver.get("http://python.org/")

rawDescription: Unable to run Selenium tests on Internet Explorer using Python


code:
class Timer:
    def __init__(self):
        self.accumulated_time = 0
        self.start_time = pygame.time.get_ticks()
        self.running = True

    def pause(self):
        if not self.running:
            raise Exception('Timer is already paused')
        self.running = False
        self.accumulated_time += pygame.time.get_ticks() - self.start_time

    def resume(self):
        if self.running:
            raise Exception('Timer is already running')
        self.running = True
        self.start_time = pygame.time.get_ticks()

    def get(self):
        if self.running:
            return (self.accumulated_time +
                    (pygame.time.get_ticks() - self.start_time))
        else:
            return self.accumulated_time

rawDescription: Tracking time for pygame Python

description: Tracking time for pygame Python


code:
for x in loss:
    if x.startswith(('s','c')): profit.append(x)

profit

rawDescription: Appending matches into a new empty list by using a condition inside a for loop on an non-empty list in Python


code:
if 'foo' not in myString:
    print("foo not found in", myString)

rawDescription: Elegant check for -1 in Python

description: Elegant check for -1 in Python


code:
class MyClass(object):
    def __init__(self):
        self.storage = {}

    def __getitem__(self, key):
        return self.storage[key]

    def __setitem__(self, key, value):
        self.storage[key] = value

rawDescription: How to overload the subscript operator with swig Python

description: Overload the subscript operator with swig Python


code:
import numpy as np
b1 = np.array([1,2,3])
b2 = np.array([3,2,1])
x = np.array([1.0, 2.0, 3.0])
plt.bar(left=x-0.3, width=0.3, height=b1)
plt.bar(left=x, width=0.3, height=b2, color='g')

rawDescription: Multiple bars on a single plot (Python)

description: Multiple bars on a single plot (Python)


code:
import dateutil.parser
date1 = dateutil.parser.parse("December 12th, 2008")
date2 = dateutil.parser.parse("January 1st, 2009")

rawDescription: python datetime strptime wildcard

description: Python datetime strptime wildcard


code:
import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()

unicode_font = QtGui.QLabel(u"Unicode Font: H\u2082O")
unicode_font.setStyleSheet("font-family: 'Arial Unicode MS', Arial, sans-serif; font-size: 15px;")

normal_font = QtGui.QLabel(u"Normal Font: H\u2082O")
normal_font.setStyleSheet("font-family: Arial, sans-serif; font-size: 15px;")

layout = QtGui.QVBoxLayout()
layout.addWidget(unicode_font)
layout.addWidget(normal_font)
widget.setLayout(layout)
widget.show()
sys.exit(app.exec_())

rawDescription: Can't display unicode character for subscript 2 on Windows


rawDescription: how do you split a string to create nested list?

description: Split a string to create nested list


rawDescription: Generate a Unique String in Python/Django


code:
import pygame

quit = False
pygame.init()
display = pygame.display.set_mode((640,480))
sprite_sheet = pygame.image.load('sprite.bmp').convert()

# by default, display the first sprite
image_number = 0

while quit == False:
    event = pygame.event.poll()
    no_more_events = True if event == pygame.NOEVENT else False

    # handle events (update game state)
    while no_more_events == False:
        if event.type == pygame.QUIT:
            quit = True
            break
        elif event.type == pygame.NOEVENT:
            no_more_events = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                image_number = 0
            elif event.key == pygame.K_RIGHT:
                image_number = 1

        event = pygame.event.poll()

    if quit == False:
        # redraw the screen
        display.fill(pygame.Color('white'))
        area = pygame.Rect(image_number * 100, 0, 100, 150)
        display.blit(sprite_sheet, (0,0), area)
        pygame.display.flip()

rawDescription: Pygame: Sprite changing due to direction of movement


rawDescription: How do i round integers to the highest multiple of 10, not rounding down just round up, in python

description: Round integers to the highest multiple of 10, not rounding down just round up, in python


code:
anim = animation.FuncAnimation(fig, update, frames=25,
                               interval=1000, blit=True, repeat=False)

rawDescription: Matplotlib animation not saving properly


code:
from scipy.ndimage import convolve

not_one = (mri_data != 1.0) # are you sure you want to compare with float like that?!

conv = convolve(not_one, np.ones((2*radius, 2*radius)))
all_not_one = (conv == (2*radius)**2)

mask[all_not_one] = 0

rawDescription: Nested for loop to numpy convolve

description: Nested for loop to numpy convolve


code:
import tkinter
import time

class ReDraw():
    def __init__(self):
        self._tk = tkinter.Tk()

        self._myframe = tkinter.Frame(master = self._tk)
        self._myframe.grid(row = 0, column = 0, sticky = tkinter.NSEW)

        self._mycanvas = tkinter.Canvas(master = self._tk, width = 850, height = 400, bg = 'grey', highlightthickness = 0)
        self._mycanvas.grid(row = 0, column = 0, sticky = tkinter.NSEW)

        self._mycanvas.bind("<Configure>", self._on_resize)

        self._tk.rowconfigure(0, weight = 1)
        self._tk.columnconfigure(0, weight = 1)

        self.fracX = 1
        self.fracY = 1

        self._oval1 = self._mycanvas.create_oval(50*self.fracX,50*self.fracY,160*self.fracX,160*self.fracY, fill="black", tags = 'oval1')
        self._oval2 = self._mycanvas.create_oval(210*self.fracX,50*self.fracY,320*self.fracX,160*self.fracY, fill="black", tags = 'oval2')
        self._oval3 = self._mycanvas.create_oval(370*self.fracX,50*self.fracY,480*self.fracX,160*self.fracY, fill="black", tags = 'oval3')
        self._oval4 = self._mycanvas.create_oval(530*self.fracX,50*self.fracY,640*self.fracX,160*self.fracY, fill="black", tags = 'oval4')
        self._oval5 = self._mycanvas.create_oval(690*self.fracX,50*self.fracY,800*self.fracX,160*self.fracY, fill="black", tags = 'oval5')

    def _on_resize(self, event):
        self._mycanvas.delete(tkinter.ALL)
        self.fracX = event.width/850
        self.fracY = event.height/400
        self._oval1 = self._mycanvas.create_oval(50*self.fracX,50*self.fracY,160*self.fracX,160*self.fracY, fill="black", tags = 'oval1')
        self._oval2 = self._mycanvas.create_oval(210*self.fracX,50*self.fracY,320*self.fracX,160*self.fracY, fill="black", tags = 'oval2')
        self._oval3 = self._mycanvas.create_oval(370*self.fracX,50*self.fracY,480*self.fracX,160*self.fracY, fill="black", tags = 'oval3')
        self._oval4 = self._mycanvas.create_oval(530*self.fracX,50*self.fracY,640*self.fracX,160*self.fracY, fill="black", tags = 'oval4')
        self._oval5 = self._mycanvas.create_oval(690*self.fracX,50*self.fracY,800*self.fracX,160*self.fracY, fill="black", tags = 'oval5')

def main():
    canvas = ReDraw()
    # Some widgets to the canvas
    def red0(a):
        for i in range(a):
            canvas._mycanvas.delete('oval1')
            canvas._oval1 = canvas._mycanvas.create_oval(50*canvas.fracX,50*canvas.fracY,160*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval1')
            canvas._tk.update()
            time.sleep(0.05)
    def red1(a):
        for i in range(a):
            canvas._mycanvas.delete('oval1')
            canvas._oval1 = canvas._mycanvas.create_oval(50*canvas.fracX,50*canvas.fracY,160*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval1')
            canvas._mycanvas.delete('oval2')
            canvas._oval2 = canvas._mycanvas.create_oval(210*canvas.fracX,50*canvas.fracY,320*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval2')
            canvas._tk.update()
            time.sleep(0.05)
    def red2(a):
        for i in range(a):
            canvas._mycanvas.delete('oval1')
            canvas._oval1 = canvas._mycanvas.create_oval(50*canvas.fracX,50*canvas.fracY,160*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval1')
            canvas._mycanvas.delete('oval2')
            canvas._oval2 = canvas._mycanvas.create_oval(210*canvas.fracX,50*canvas.fracY,320*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval2')
            canvas._mycanvas.delete('oval3')
            canvas._oval3 = canvas._mycanvas.create_oval(370*canvas.fracX,50*canvas.fracY,480*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval3')
            canvas._tk.update()
            time.sleep(0.05)
    def red3(a):
        for i in range(a):
            canvas._mycanvas.delete('oval1')
            canvas._oval1 = canvas._mycanvas.create_oval(50*canvas.fracX,50*canvas.fracY,160*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval1')
            canvas._mycanvas.delete('oval2')
            canvas._oval2 = canvas._mycanvas.create_oval(210*canvas.fracX,50*canvas.fracY,320*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval2')
            canvas._mycanvas.delete('oval3')
            canvas._oval3 = canvas._mycanvas.create_oval(370*canvas.fracX,50*canvas.fracY,480*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval3')
            canvas._mycanvas.delete('oval4')
            canvas._oval4 = canvas._mycanvas.create_oval(530*canvas.fracX,50*canvas.fracY,640*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval4')
            canvas._tk.update()
            time.sleep(0.05)
    def red4(a):
        for i in range(a):
            canvas._mycanvas.delete('oval5')
            canvas._oval5 = canvas._mycanvas.create_oval(690*canvas.fracX,50*canvas.fracY,800*canvas.fracX,160*canvas.fracY, fill="red", tags = 'oval5')
            canvas._tk.update()
            time.sleep(0.05)
    def green(a):
        for i in range(a):
            canvas._mycanvas.delete(tkinter.ALL)
            canvas._oval1 = canvas._mycanvas.create_oval(50*canvas.fracX,50*canvas.fracY,160*canvas.fracX,160*canvas.fracY, fill="green", tags = 'oval1')
            canvas._oval2 = canvas._mycanvas.create_oval(210*canvas.fracX,50*canvas.fracY,320*canvas.fracX,160*canvas.fracY, fill="green", tags = 'oval2')
            canvas._oval3 = canvas._mycanvas.create_oval(370*canvas.fracX,50*canvas.fracY,480*canvas.fracX,160*canvas.fracY, fill="green", tags = 'oval3')
            canvas._oval4 = canvas._mycanvas.create_oval(530*canvas.fracX,50*canvas.fracY,640*canvas.fracX,160*canvas.fracY, fill="green", tags = 'oval4')
            canvas._oval5 = canvas._mycanvas.create_oval(690*canvas.fracX,50*canvas.fracY,800*canvas.fracX,160*canvas.fracY, fill="green", tags = 'oval5')
            canvas._tk.update()
            time.sleep(0.05)
    def lights():
        canvas._mycanvas.delete(tkinter.ALL)
        canvas._oval1 = canvas._mycanvas.create_oval(50*canvas.fracX,50*canvas.fracY,160*canvas.fracX,160*canvas.fracY, fill="black", tags = 'oval1')
        canvas._oval2 = canvas._mycanvas.create_oval(210*canvas.fracX,50*canvas.fracY,320*canvas.fracX,160*canvas.fracY, fill="black", tags = 'oval2')
        canvas._oval3 = canvas._mycanvas.create_oval(370*canvas.fracX,50*canvas.fracY,480*canvas.fracX,160*canvas.fracY, fill="black", tags = 'oval3')
        canvas._oval4 = canvas._mycanvas.create_oval(530*canvas.fracX,50*canvas.fracY,640*canvas.fracX,160*canvas.fracY, fill="black", tags = 'oval4')
        canvas._oval5 = canvas._mycanvas.create_oval(690*canvas.fracX,50*canvas.fracY,800*canvas.fracX,160*canvas.fracY, fill="black", tags = 'oval5')
        canvas._tk.update()

    # tag all of the drawn widgets
    for i in range(20):
        lights()
        red0(30)
        red1(30)
        red2(30)
        red3(30)
        red4(30)
        green(30)
        lights()

if __name__ == "__main__":
    main()

rawDescription: Resizing causes errors?

description: Resizing causes errors


code: [map(int, grp) for grp in c]

rawDescription: remove apostrophe around items in nested list in python

description: Remove apostrophe around items in nested list in python


code:
def inject_request(fun):

    def helper(*args, **kwargs):
        finst = fun(*args, **kwargs)
        finst.request = request
        return finst

    helper._meta = fun._meta
    return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request,*args, **kwargs)

rawDescription: Pass request to model form using generic view in Django


code:
def load_everything_from(module_names):
    g = globals()
    for module_name in module_names:
        m = __import__(module_name)
        names = getattr(m, '__all__', None)
        if names is None:
            names = [name for name in dir(m) if not name.startswith('_')]
        for name in names:
            g[name] = getattr(m, name)

rawDescription: Dynamic import in Python

description: Dynamic import in Python


rawDescription: pass email as regx in django url

description: Pass email as regx in django url


code:
...
ready = gevent.event.Event()
ready.clear()

def callback():
    ready.set()

lst = [gevent.spawn(first), gevent.spawn(second)]
for g in lst:
    g.link(callback)

ready.wait()
...

rawDescription: Wait until one of several greenlets finished


code:
import numpy as np
from scipy.interpolate import interp1d, pchip
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

list_points = [(-3,0.1),(-2,0.15),(0,4),(2,-6),(4,-2),(7,-0.15),(8,-0.1)]
(xp,yp) = zip(*list_points)
fun = interp1d(xp,yp,kind='cubic')

xc = np.linspace(min(xp),max(xp),300)

plt.plot(xp,yp,'o',color='black',ms=5)
plt.plot(xc,fun(xc))
fun2 = interp1d(xp,yp,kind='linear')
plt.plot(xc,fun2(xc))

p = pchip(xp, yp)
plt.plot(xc, p(xc), 'r', linewidth=3, alpha=0.6)

plt.show()

rawDescription: Interpolation method that does not add unnecessary extremums


code:
LANG_INFO = {
    # ...
    'vi': {
        'bidi': False,
        'code': 'vi',
        'name': 'Vietnamese',
        'name_local': 'Tiếng Việt',
    },
    # ...
}

rawDescription: How to store locale in django model?

description: Store locale in django model


code:
mydict = dict((s[0], s[1:]) for s in myseq)

myseq = tuple(sorted((k,) + v for k, v in mydict.iteritems()))

rawDescription: Convert a sequence of sequences to a dictionary and vice-versa


rawDescription: How do I remove an item from a Python list by value?

description: Remove an item from a Python list by value


code:
import collections
import bisect

class FastTable:

    def __init__(self):
        self.__deque = collections.deque()

    def __len__(self):
        return len(self.__deque)

    def head(self):
        return self.__deque.popleft()

    def tail(self):
        return self.__deque.pop()

    def peek(self):
        return self.__deque[-1]

    def insert(self, obj):
        index = bisect.bisect_left(self.__deque, obj)
        self.__deque.rotate(-index)
        self.__deque.appendleft(obj)
        self.__deque.rotate(index)

rawDescription: Anyone know this Python data structure?

description: Anyone know this Python data structure


code:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.suptitle('This sentence is\nbeing split\ninto three lines')
plt.show()

rawDescription: How to write a plot title in more than one line using suptitle in Python?

description: Write a plot title in more than one line using suptitle in Python


code:
import Tkinter as tk

def on_enter(event):
    widget = event.widget
    print(widget.get())

root = tk.Tk()
entry = tk.Entry()
entry.pack(padx=5, pady=5)
entry.focus()
entry.bind('<Return>', on_enter)
root.mainloop()

rawDescription: How do I execute a callback when the Enter key is pressed after entering text into a Text widget?

description: Execute a callback when the Enter key is pressed after entering text into a Text widget


code: end = datetime.datetime.combine(datetime.date(2014, 1, 24), datetime.time.max)

rawDescription: Django - Datetime range end time excluded


code:
jarr_class=some_method_that_returns_an_array_of_ints_in_java.__class__
factor_lists=[jarr_class.cast_(i) for i in Prime.factorLists(10)]
factor_lists

rawDescription: Including system classes in JCC module

description: Including system classes in JCC module


code:
def random_combination(iterable, r):
    "Random selection from itertools.combinations(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(xrange(n), r))
    return tuple(pool[i] for i in indices)

rawDescription: Choose at random from combinations

description: Choose at random from combinations


rawDescription: Removing HTML tags from a unicode string in Python


code:
nlarge = pct.nlargest(5)

for ind in nlarge.index:
    high = ind + 100
    low = ind - 100
    window = data.C_TRQENG[low:high]
    window = window.convert_objects(convert_numeric=True)
    window.plot()

rawDescription: Plot at indexes in pandas Series

description: Plot at indexes in pandas Series


code:
import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')

def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""
    result = []
    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)
    return unicode(delim.join(result))

rawDescription: Webapp username security

description: Webapp username security


code:
import itertools
["".join(seq) for seq in itertools.product("01", repeat=2)]
["".join(seq) for seq in itertools.product("01", repeat=3)]

rawDescription: all permutations of a binary sequence x bits long

description: All permutations of a binary sequence x bits long


code:
for route in LiveRoutes.objects.filter(calculated=False).iterator():
    # Do your calculation

    route.calculated = True
    route.save()

rawDescription: How to check every single rows of Django database table for True or False values in a field and perform calculation based on it?

description: Check every single rows of Django database table for True or False values in a field and perform calculation based on it


rawDescription: Measure Network Data with Python

description: Measure Network Data with Python


code:
class TestManager:
    def __init__(self, *args, **kwargs):
        print('creating TestManager')

    def get(self, id):
        return self._tests[id]

class TestMetaClass(type):
    def __new__(mcl, name, bases, classdict):
        # add an "objects" attribute to the class being created
        classdict['objects'] = tm = TestManager()
        cls = type.__new__(mcl, name, bases, classdict)
        # add a "_tests" attribute to the TestManager instance just created
        # (can't use class's name, since it hasn't been returned yet)
        tm._tests = [cls(name='Name {}'.format(i)) for i in range(100)]
        return cls

class Test(metaclass=TestMetaClass):
    def __init__(self, name=''):
        self.name = name

t = Test.objects.get(3)
print(t.name)

rawDescription: How to create and store instances of a class at initialization?

description: Create and store instances of a class at initialization


code:
utf8 = [u'\u0123'.encode('utf8'), u'\u0234'.encode('utf8')]
''.join(utf8)
u''.join(utf8)
''.join(utf8 + [u'unicode object'])

rawDescription: python 2.7 string.join() with unicode

description: Python 2.7 string.join() with unicode


code:
import numpy as np
import random as random
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 50), ylim=(0, 50))
line, = ax.plot([], [], lw=2)

n=5
a = [0,1,2,4,5,8,9,12,14,18,22,17,30,37,29,45]

x = []
y = []

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x.append(np.linspace(i,i+1,n))
    y.append(np.linspace(a[i],a[i+1],n))
    line.set_data(x,y)

    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, np.arange(0,len(a)-1) ,init_func=init,
                               interval=200, blit=True, repeat=False)

plt.show()

rawDescription: Slow and smooth drawing lines python matplotlib


rawDescription: How to sort the outer and inner sublist of a nested list in Python?

description: Sort the outer and inner sublist of a nested list in Python


code:
globals()[string1 + string2]()
locals()[string1 + string2]()

rawDescription: How to convert two strings to give you a function name in Python

description: Convert two strings to give you a function name in Python


rawDescription: Python Slicing Newbie

description: Python Slicing Newbie


code:
import time
from flask import Flask
from flask.ext.cache import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'redis'})

@cache.memoize(timeout=60)
def query_db():
    time.sleep(5)
    return "Results from DB"

@app.route('/')
def index():
    return query_db()

app.run(debug=True)

rawDescription: How to cache sql alchemy calls with Flask-cache and redis?

description: Cache sql alchemy calls with Flask-cache and redis


code:
from itertools import combinations, product, chain, starmap
[p for c in combinations(a, 2) for p in product(*c)]

rawDescription: combinations of list of lists with length

description: Combinations of list of lists with length


code:
# Sum of a list of numbers divided by the number of numbers in the list
def average(numbers):
    return sum(numbers)/len(numbers)

# This is your data
scores = [[100,100,1,100,100],
          [20,50,60,10,30],
          [0,10,10,0,10],
          [0,100,50,20,60]]

# enumerate() allows you to write FOR loops naming both the list element and its index
for (i, row) in enumerate(scores):
    print("Average for row ", i, "is ", average(row))

rawDescription: Using for loops and nested lists in python


code:
import re
aa = 'nilesh-sharma-is-learning-python'
re.split('-',aa,3)

rawDescription: maxsplit functionality for regex split

description: Maxsplit functionality for regex split


code:
from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible=1
book = xlApp.Workbooks.Open("FileName")
sheet1 = book.Worksheets(1)
sheet1.Cells(1,1).Value="ABC"

rawDescription: Python: Modifying Excel files while maintaing formatting


code:
m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
m.group(0)       # The entire match
m.group(1)       # The first parenthesized subgroup.

rawDescription: Regex: How do I exclude commas when in my pattern?


code:
import numpy as np
import cv2

def save_to_vid(video):
    path = ".../output.avi"
    height , width , layers =  video[0].shape
    out = cv2.VideoWriter(path, cv2.cv.FOURCC("X", "V", "I", "D"),
                          20.0, (width, height))
    for frame in frames:
        out.write(frame)

    out.release()

##CAPTURING SOME TEST FRAMES
cap = cv2.VideoCapture(0)
frames = list() #THIS IS YOUR VIDEO
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)
        frames.append(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

#SOMETIMES LATER IN THE RPOGRAM
doYouWantToSave = True
if doYouWantToSave:
    save_to_vid(frames)
else:
    del frames

rawDescription: Sending OpenCV2 Videowrite input to buffer instead of file


code:
root = etree.Element('root')

a = etree.SubElement(root, 'a')
b = etree.SubElement(a, 'b')
c = etree.SubElement(b, 'c')

rawDescription: Python XML - appending multiple elements to multiple parents elegantly


code:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

rows = []
for x in range(0,14):
    rows.append(['a',14-x])

df = pd.DataFrame(rows)
# df = df.set_index(0)
df.plot(ax=ax)

ax.set_xticks(df.index)
ax.set_xticklabels(list(df[0]))

rawDescription: Pandas skipping x tick labels

description: Pandas skipping x tick labels


code:
from scipy import ndimage
import matplotlib.pyplot as plt

# Load
img = ndimage.imread("image.png")

# Threshold based on pixel (0,0) assumed to be background
bg = img[0, 0]
mask = img != bg
mask = mask[:, :, 0]  # Take the first channel for RGB images

# Connected components
label_im, nb_labels = ndimage.label(mask)

# Plot
plt.figure(figsize=(9, 3))
plt.subplot(131)
plt.imshow(img, cmap=plt.cm.gray)
plt.axis('off')
plt.subplot(132)
plt.imshow(mask, cmap=plt.cm.gray)
plt.axis('off')
plt.subplot(133)
plt.imshow(label_im, cmap=plt.cm.spectral)
plt.axis('off')
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)
plt.show()

rawDescription: Split image containing multiple, irregularly shaped images in Python


code:
with open(myfilename, 'w') as csvfile:
    writer = csv.DictWriter(csvfile)
    for a,b,c in zip(zmin_limits,zmax_limits,mlim_limits):
        info = id_match(data_zcosmo_lastz,data_zphot_lastz,a,b,c)
        writer.writerow(info)

rawDescription: Saving multiple return values from a Python function


code:
from datetime import date

def add_years(d, years):
    try:
        return d.replace(year = d.year + years)
    except ValueError:
        return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))

today = datetime.date.today()
ago18 = add_years(today, -18)
ago25 = add_years(today, -25)

# < 18
User.objects.filter(profile__birthdate__gt=ago18)
# 18 <= and < 25
User.objects.filter(profile__birthdate__lte=ago18, profile__birthdate__gt=ago25)
# 25 <=
User.objects.filter(profile__birthdate__lte=ago25)

rawDescription: How to count users in JOINed models?

description: Count users in JOINed models


code:
import wx

########################################################################
class MyDialog(wx.Dialog):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Dialog.__init__(self, None, title="Information")

        self.numbers = [1, 2, 3]
        self.names = ['mike', 'nick', 'george']

        #--------------------------------------------------
        # create the number panel
        self.number_panel = wx.Panel(self)
        self.number_text = wx.TextCtrl(self.number_panel)
        self.number_text.SetFocus()
        next_btn = wx.Button(self.number_panel, label='Next')
        next_btn.Bind(wx.EVT_BUTTON, self.onNext)
        panel_sizer = wx.BoxSizer(wx.VERTICAL)
        panel_sizer.Add(self.number_text, 0, wx.ALL|wx.EXPAND, 5)
        panel_sizer.Add(next_btn, 0, wx.ALL, 5)
        self.number_panel.SetSizer(panel_sizer)

        #--------------------------------------------------
        # create the name panel
        self.name_panel = wx.Panel(self)
        self.name_panel.Hide()
        self.name_text = wx.TextCtrl(self.name_panel)

        ok_btn = wx.Button(self.name_panel, label='OK')
        ok_btn.Bind(wx.EVT_BUTTON, self.onOK)

        name_sizer = wx.BoxSizer(wx.VERTICAL)
        name_sizer.Add(self.name_text, 0, wx.ALL, 5)
        name_sizer.Add(ok_btn, 0, wx.ALL, 5)
        self.name_panel.SetSizer(name_sizer)

        #--------------------------------------------------
        # layout panels
        self.my_sizer = wx.BoxSizer(wx.VERTICAL)
        self.my_sizer.Add(self.number_panel, 1, wx.EXPAND)
        self.my_sizer.Add(self.name_panel, 1, wx.EXPAND)
        self.SetSizer(self.my_sizer)

        #--------------------------------------------------
        self.ShowModal()
        wx.CallAfter(self.my_sizer.Layout)

    #----------------------------------------------------------------------
    def onNext(self, event):
        """"""
        number = int(self.number_text.GetValue())
        if number in self.numbers:
            wx.MessageBox('Code number is currently in use',
                          'Warning', wx.OK | wx.ICON_INFORMATION)
            self.number_text.SetFocus()
            return
        else:
            self.my_sizer.Detach(self.number_panel)
            self.name_panel.Show()
            self.Layout()
            self.numbers.append(number)

    #----------------------------------------------------------------------
    def onOK(self, event):
        """"""
        name = self.name_text.GetValue()
        if name.lower() in self.names:
            wx.MessageBox('Code name is currently in use',
                          'Warning', wx.OK | wx.ICON_INFORMATION)
            return
        else:
            self.names.append(name)
            self.Close()

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        info_button = wx.Button(self, label="Get Info")
        info_button.Bind(wx.EVT_BUTTON, self.onGetInfo)

    #----------------------------------------------------------------------
    def onGetInfo(self, event):
        """"""
        dlg = MyDialog()
        dlg.Destroy()

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='Demo')
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: wxPython - checking for empty text dialogs

description: WxPython - checking for empty text dialogs


code:
from Tkinter import *

class GuiCreate:

    def __init__(self,parent):

        #Textbox
        window  = Frame(width=620, height=50)
        window.place(x=25,y=320)
        vscroll = Scrollbar(window)
        hscroll = Scrollbar(window, orient='horizontal')
        #  create instance variable with "self"
        self.listbox = Text(window, height=10)
        self.listbox.pack(side=LEFT, fill=X, padx=5, pady=5, expand=1)
        vscroll.config(command=self.listbox.yview, relief=SUNKEN)
        hscroll.config(command=self.listbox.xview, relief=SUNKEN)
        self.listbox.config(yscrollcommand=vscroll.set, relief=SUNKEN)
        self.listbox.config(xscrollcommand=hscroll.set)

        f7 = Frame(width=30, height=20)
        f7.place(x=20,y=260)
        srcButton = Button(f7, text="START", command=self.startProcess)
        srcButton.pack(side='left')

    def startProcess(self):
        textinsert = 'abcdefg'
        self.listbox.insert('end', textinsert)

root = Tk()
root.title("Clipfinder")
root.geometry('650x550+200+100')
gui = GuiCreate(root)
root.configure(background = 'gray')
root.mainloop()

rawDescription: Python tkinter inserting string in texttbox out of a function


rawDescription: find column max and column average by using python programming

description: Find column max and column average by using python programming


code:
import Tkinter as tk
root = tk.Tk()
tk.Label(master=root, text="Line1\nLine2").grid(row=0)
root.mainloop()

rawDescription: Two lines of text in a single grid row

description: Two lines of text in a single grid row


code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider

class Plotter:
    def __init__(self):
        self.fig, self.ax = plt.subplots()

    def plot(self, obj):
        self.obj = obj
        self.l = plt.plot(obj.t,obj.series())
        _vars = obj.get_variables()
        plt.subplots_adjust(bottom=0.03*(len(_vars)+2))
        self.sliders = []
        for i,var in enumerate(_vars):
            self.add_slider(i*0.03, var[0], var[1], var[2])
        plt.show()

    def add_slider(self, pos, name, min, max):
        ax = plt.axes([0.1, 0.02+pos, 0.8, 0.02], axisbg='lightgoldenrodyellow')
        slider = Slider(ax, name, min, max, valinit=getattr(self.obj, name))
        self.sliders.append(slider)
        def update(val):
            setattr(self.obj, name, val)
            self.l[0].set_ydata(self.obj.series())
            self.fig.canvas.draw_idle()
        slider.on_changed(update)

class SinFunction:
    def __init__(self):
        self.freq = 1.0
        self.amp = 0.5
        self.t = np.arange(0.0, 1.0, 0.001)

    def series(self):
        return self.amp*np.sin(2*np.pi*self.freq*self.t)

    def get_variables(self):
        return [
            ('freq', 0.1, 10),
            ('amp', 0.1, 1)
        ]

k = Plotter()
k.plot(SinFunction())

rawDescription: matplotlib - Add sliders to a figure dynamically

description: Matplotlib - Add sliders to a figure dynamically


code:
name = "bugra"
names = ["github","bugra","turkey","developers"]
name == names
name in names

rawDescription: Python Random Function for Payload function is not working


code:
def rebinds(lst):
    lst = ['foo', 'bar', 'baz']

def slice_assigns(lst):
    lst[:] = ['foo', 'bar', 'baz']

somelist = [42, 81]
rebinds(somelist)
somelist
slice_assigns(somelist)
somelist

rawDescription: Is the purpose in slice-copying any more than to save a memory address?


code:
self.house = None
self.save()

rawDescription: How to set to null the reference on a ForeignKey - Django

description: Set to null the reference on a ForeignKey - Django


code:
import re

# key : value regexp
KV_RE = re.compile(r'^\s*(?P<key>[^\s]+)\s+:\s+(?P<value>.+?)\s*$')
# dict start regexp
DS_RE = re.compile(r'^\s*(?P<key>[^\s]+)\s+{\s*$')
# dict end regexp
DE_RE = re.compile(r'^\s*}\s*$')

def parse(s):
    current = {}
    stack = []
    for line in s.strip().splitlines():
        match = KV_RE.match(line)
        if match:
            gd = match.groupdict()
            current[gd['key']] = gd['value']
            continue
        match = DS_RE.match(line)
        if match:
            stack.append(current)
            current = current.setdefault(match.groupdict()['key'], {})
            continue
        match = DE_RE.match(line)
        if match:
            current = stack.pop()
            continue
        # Error occured
        print('Error: %s' % line)
        return {}
    return current

rawDescription: Python: How do I parse a string into a recursive dictionary


code: (lambda success, error_message: None if success else print(error_message))(*someOperation("aVar"))

rawDescription: Neatest (or most readable yet still one line way) to print second tuple if first one false


code:
# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
    # __new__ is the method called before __init__
    # it's the method that creates the object and returns it
    # while __init__ just initializes the object passed as parameter
    # you rarely use __new__, except when you want to control how the object
    # is created.
    # here the created object is the class, and we want to customize it
    # so we override __new__
    # you can do some stuff in __init__ too if you wish
    # some advanced use involves overriding __call__ as well, but we won't
    # see this
    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attr):

        attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)

        return type(future_class_name, future_class_parents, uppercase_attr)

rawDescription: How do Django models work?

description: How do Django models work


code:
import numpy as np
import matplotlib
import mplh5canvas

matplotlib.use('module://mplh5canvas.backend_h5canvas')

import matplotlib.cbook as cbook
import matplotlib.image as image
import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)

ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')

ax.grid()

plt.show(open_plot=True)

rawDescription: How to embed python tkinter window into a browser?

description: Embed python tkinter window into a browser


code:
import unittest
import blognodes

class meta_Test_base62(type):
  testset = { 0: '0', 10: 'a', 61: 'Z', 62: '10', 3844: '100'}

  @classmethod
  def __prepare__(mcls, name, bases):
    d = dict()
    d['testme'] = 5
    for b10, b62 in mcls.testset.items():
      fname = "test_base62_value_{}".format(b10)
      d[fname] = mcls.build_test_base62_values(b10, b62)
      fname = "test_int_value_{}".format(b10)
      d[fname] = mcls.build_test_int_values(b10, b62)
    return d

  @classmethod
  def build_test_base62_values(cls, b10, b62):
    def f(self):
      target = blognodes.base62(b10)
      self.assertEqual(target.str(), b62)
    return f

  @classmethod
  def build_test_int_values(cls, b10, b62):
    def f(self):
      target = blognodes.base62(b10)
      self.assertEqual(target.int(), b10)
    return f

class Test_base62(unittest.TestCase, metaclass=meta_Test_base62):

  def test_nothing(self):
    self.assertEqual(5, self.testme)

rawDescription: how to add tests dynamically to python unittest

description: Add tests dynamically to python unittest


code:
import matplotlib.pyplot as plt
x = range(1,21)
plt.xlabel('1st X')
plt.ylabel('1st Y')
plt.plot(x,x,'r') # against 1st x, 1st y
plt.axis([0,50,0,25])
plt.twinx()
plt.ylabel('2nd Y')
plt.plot(x,x,'g') # against 1st x, 2nd y
plt.axis([0,50,0,20])
plt.twiny()
plt.xlabel('2nd X')
plt.plot(x,x,'b') # against 2nd x, 2nd y
plt.axis([0,10,0,20])
plt.show()

rawDescription: Ploting an x-y graph with "four" axes

description: Ploting an x-y graph with "four" axes


code:
import unittest

class TestMixin(object):
    def test_method(self):
        # do something, e.g.
        pass

class TestSub1(unittest.TestCase, TestMixin):
    def setUp(self):
        self.some_parameter = 1

class TestSub2(unittest.TestCase, TestMixin):
    def setUp(self):
        self.some_parameter = 2

if __name__ == '__main__':
    unittest.main()

rawDescription: How should a Python (unittest) superclass method reference a variable in its calling subclass?


code:
with open('filename.txt', 'w') as fout:
     for line in sorted(open('filename.txt', 'r').readlines(), key=lambda x:float(x.split()[0])):
         fout.write(line)

rawDescription: Sorting a file based on Ist column and simultaneously modifing the 2nd column also in the file


code:
while True:
    # The rest of your code
    if not input("Do you want to encrypt or decrypt another message [y/n]? ").lower().startswith("y"):
        break
print("Coded with Python by QuantumShadow.")

rawDescription: How to loop a code in Python?

description: Loop a code in Python


code:
from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

for result in powerset([1, 2, 3]):
    print(result)

results = list(powerset([1, 2, 3]))
print(results)

rawDescription: Powersets in Python using itertools

description: Powersets in Python using itertools


code:
def addVignette(inputPic, vignette):
  # Create empty canvas
  canvas = makeEmptyPicture(getWidth(inputPic), getHeight(inputPic))

  for x in range(0, getWidth(inputPic)):
    for y in range(0, getHeight(inputPic)):
      px = getPixel(canvas, x, y)
      inputPixel = getPixel(inputPic, x, y)
      vignettePixel = getPixel(vignette, x, y)

      # Make a new color from those values
      newColor = getNewColorValues(inputPixel, vignettePixel)

      # Assign this new color to the current pixel of the input image
      setColor(px, newColor)

  explore(canvas)

def getNewColorValues(inputPixel, vignettePixel):

  inputRed = getRed(inputPixel)
  vignetteRed = getRed(vignettePixel)
  inputGreen = getGreen(inputPixel)
  vignetteGreen = getGreen(vignettePixel)
  inputBlue = getBlue(inputPixel)
  vignetteBlue = getBlue(vignettePixel)

  newR = inputRed - (255 % vignetteRed) / 3
  newG = inputGreen - (255 % vignetteGreen) / 3
  newB = inputBlue - (255 % vignetteBlue) / 3

  newC = makeColor(newR, newG, newB)
  return newC

rawDescription: need guidance my vignette code in Jython/Python

description: Need guidance my vignette code in Jython/Python


code:
import csv

from django.utils.six.moves import range
from django.http import StreamingHttpResponse

class Echo(object):
    """An object that implements just the write method of the file-like
    interface.
    """
    def write(self, value):
        """Write the value by returning it, instead of storing in a buffer."""
        return value

def some_streaming_csv_view(request):
    """A view that streams a large CSV file."""
    # Generate a sequence of rows. The range is based on the maximum number of
    # rows that can be handled by a single sheet in most spreadsheet
    # applications.
    rows = (["Row {}".format(idx), str(idx)] for idx in range(65536))
    pseudo_buffer = Echo()
    writer = csv.writer(pseudo_buffer)
    response = StreamingHttpResponse((writer.writerow(row) for row in rows),
                                     content_type="text/csv")
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
    return response

rawDescription: use django to serve downloading big zip file with some data appended

description: Use django to serve downloading big zip file with some data appended


code:
from django.core.files.base import ContentFile
somemodel.image.save('{0}/photos/{1}.jpg'.format(settings.MEDIA_ROOT, username), ContentFile(your_byte_string))

rawDescription: Retrieving thumbnailPhoto from Active Directory in Django/Python


code:
activeXlApp = win32com.client.GetActiveObject('Excel.Application')

objExcel1 = ExcelDocument(PATH_TABLE,False) # uses GetObject()
objExcel1.update_sheets()
...
objExcel2 = ExcelDocument(PATH_BACKG, False)

if activeXlApp is not None:
    activeXlApp.Close()

rawDescription: Interaction between open and dispatched excel processes, win32com


code:
from collections import OrderedDict as od
a = ["dorian", "strawberry", "apple"]
b = ["sweet", "delicious", "tasty"]
dic=od(zip(a,b))
dic

rawDescription: How to keep the dictionary in order after zipping

description: Keep the dictionary in order after zipping


rawDescription: efficient way to compute numpy.ndarray internal multiplication

description: Efficient way to compute numpy.ndarray internal multiplication


code:
import os
import shutil

root = r"H:\test_vectors"
destination = r"dstpath"

file_list = []
dir_dict = {}

with open('aiq.txt', 'r') as f:
    for line in f:
        file_list.append(line.strip())

for d, dirs, files in os.walk(root):
    if files:
        dir_dict[d] = files

for key, item in dir_dict.items():
    for x in item:
        if x in file_list:
              try:
                  shutil.move(os.path.join(key, x), destination)
              except:
                  pass

rawDescription: Moving large files using shutil.move

description: Moving large files using shutil.move


code:
for host in hosts:
    reactor.connectTCP(host, PORT, BlastFactory())
reactor.run()

rawDescription: twisted: one client, many servers

description: Twisted: one client, many servers


code:
__author__ = 'Ehsan'
from mininet.node import CPULimitedHost
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.log import setLogLevel, info
from mininet.node import RemoteController
from mininet.cli import CLI
from mininet.link import TCLink
"""
Instructions to run the topo:
    1. Go to directory where this fil is.
    2. run: sudo -E python <file name>
       In this case it is: sudo -E python Tree_Generic_Topo.py
"""

class GenericTree(Topo):
    """Simple topology example."""

    def build( self, depth=1, fanout=2 ):
        # Numbering:  h1..N, s1..M
        self.hostNum = 1
        self.switchNum = 1

    def build( self, depth=1, fanout=2 ):
        # Numbering:  h1..N, s1..M
        self.hostNum = 1
        self.switchNum = 1
        # Build topology
        self.addTree(depth, fanout)

    def addTree( self, depth, fanout ):
        """Add a subtree starting with node n.
           returns: last node added"""
        isSwitch = depth > 0
        if isSwitch:
            node = self.addSwitch( 's%s' % self.switchNum )
            self.switchNum += 1
            for _ in range( fanout ):
                child = self.addTree( depth - 1, fanout )
                self.addLink( node, child )
        else:
            node = self.addHost( 'h%s' % self.hostNum )
            self.hostNum += 1
        return node

def run():
    c = RemoteController('c', '0.0.0.0', 6633)
    # Change the args of GenericTree() to your desired values. You could even get them from command line.
    net = Mininet(topo=GenericTree(depth=2, fanout=3), host=CPULimitedHost, controller=None)
    net.addController(c)
    net.start()

    # installStaticFlows( net )
    CLI(net)
    net.stop()

# if the script is run directly (sudo custom/optical.py):
if __name__ == '__main__':
    setLogLevel('info')
    run()

rawDescription: Mininet script for generic Tree topology with custom bandwidth links


rawDescription: Selecting data based on values in multiple columns in Pandas


rawDescription: converting from numpy array of one type to another by re-interpreting raw bytes

description: Converting from numpy array of one type to another by re-interpreting raw bytes


code:
import csv

from collections import OrderedDict # to save keys order

with open('data.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    next(reader) #skip header
    d = OrderedDict((rows[2], {"val": rows[1], "flag": False}) for rows in reader)

with open('data1.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    next(reader) #skip header
    for rows in reader:
        if rows[0] in d:
            d[rows[0]]["flag"] = True

import sys
sys.stdout = open("rs_pos_ref_alt.csv", "w")

for k, v in d.iteritems():
    if v["flag"]:
        print [v["val"], k]

rawDescription: Python Killed: 9 when running a code using dictionaries created from 2 csv files


rawDescription: How does Python's triple-quote string work?


code:
import itertools
import random
import turtle

# change step size if you like
STEP = 1
PTS = [-STEP, 0, STEP]
DIRS = [(x, y) for x in PTS for y in PTS if x or y]

turtle.setup(width=400, height=400, startx=0, starty=0)
turtle.trace = False
pos = turtle.pos()

for i in range(1000):
    px, py = turtle.pos()
    # direction of next move
    xd, yd = random.choice(DIRS)
    # set pos to current pos + direction vector
    turtle.goto(px + xd, py + yd)

rawDescription: Random Walk Problem(Escape Recursion)

description: Random Walk Problem(Escape Recursion)


rawDescription: Python - Scapy Choosing an interface to sniff


code:
class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        btn = QtGui.QPushButton('Button', self)
        self.show()
        self.background = MyThread(self)
        t = threading.Thread(target=self.background.process)
        t.start()
        self.background.notify.connect(self.notify)

    @QtCore.pyqtSlot()
    def notify(self):
        print("I have been notified")

class MyThread(QtCore.QObject):

    notify = QtCore.pyqtSignal()

    def __init__(self, parent):
        super(MyThread, self).__init__(parent)
        self.should_continue = True

    def process(self):
        while self.should_continue:
            # Here, do your server stuff.
            time.sleep(1)
            self.notify.emit()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt: Window stops responding when listening to ip, port


code:
f = open('in_file.dat')

num_lines = 0
tot_words = 0

for line in f:
    num_lines += 1
    tot_words += len(line.split())

average = tot_words / num_lines

print(average)

rawDescription: How do I count the number of lines in a text file?

description: Count the number of lines in a text file


code:
ls = ["Arsenal","10-5","10","Chelsea","20-5","0+25"]

newLs = sorted([ls[i:i+3] for i in range(0,len(ls),3)],key= lambda x: (eval(x[2]),eval(x[1])))

print(newLs)

rawDescription: Python - Sorting lists which have string objects


code: df3 = df1[~df1.isin(d2)].dropna()

rawDescription: How to do a left inner join in python / pandas?

description: Do a left inner join in python / pandas


code:
from itertools import islice

names = [ p.find('name').text for p in islice(eroot.iter('data'), 0, 3)]

rawDescription: Python xml ElementTree: find values of only first 3 elements with same name


code:
c = [sum(i*j for i,j in zip(a[k:], b)) for k in range(4)]
c

rawDescription: python creating convolve function for arrays

description: Python creating convolve function for arrays


code: time = timeit.timeit(lambda: module.expensive_func(data))

rawDescription: Importing a local variable in a function into timeit


rawDescription: Pandas: Series of arrays to series of transposed arrays


code:
obj = SomeModel(None, "a_stuff", "b_stuff", "c_stuff", "d_stuff", "e_stuff", "f_stuff")
obj.save()

rawDescription: Django creating model instances without keyword arguments


code:
import requests

KEY = ''
TASK_ID = ''
url = 'https://app.asana.com/api/1.0/tasks/{0}/attachments'.format(TASK_ID)

with open('file.txt') as f:
    files = {'file': f.read()}
    r = requests.post(url, auth=(KEY, ''), files=files)

print(r.status_code)
print(r.json())

rawDescription: How to translate this curl post of an actual file to python request?

description: Translate this curl post of an actual file to python request


code:
#!/usr/bin/env python

import csv
import datetime
import copy
from collections import defaultdict

with open(r"testin.csv") as i, open(r"TestSingleParaSRResuls.csv", "wb") as o:
    rdr = csv.reader(i)
    wrt = csv.writer(o)

    data, currdate = defaultdict(lambda:[0, 0, 0, 0]), None
    for line in rdr:
        date, name = datetime.datetime.strptime(line[0], '%d/%m/%Y'), line[7]

        if date != currdate or not currdate:
            for v in data.itervalues():
                #print v[:2]
                #print v[2:]
                #print "\n"

                v[:2] = v[2:]
            currdate = date

        top,bottom = data[name][0:2]
        try:
            quotient = float(top)/bottom
        except ZeroDivisionError:
            quotient = 0
        wrt.writerow(line + data[name][:2]+ [quotient])

        data[name][3] += 1
        if line[6] == "1": data[name][2] += 1

rawDescription: Appending simple calculation in csv within particular script


code:
array = ['value1', 'value2', 'value3', 'value4', 'value50', 'something', 'something2']
array = [x for x in array if not x.startswith('value')]  # NOTE: used `not`
array

rawDescription: How to delete values from array by using mask?

description: Delete values from array by using mask


code:
# first create a generator that parses your structure, one residue at time

def createDesiredList(structure, desired_atoms):
    residues = structure.get_residues()

    for residue in residues:
        return_list = []
        for atom_id in desired_atoms:
            return_list.append((residue[atom_id].get_coord(), residue))
        yield return_list

# then I copy and paste your code ....

pdb = "1dly.pdb"
name = pdb[:3]

from Bio import PDB
from ast import literal_eval

p = PDB.PDBParser()
s = p.get_structure(name, pdb)

# then I decide which atoms I desire from every residue...

wish_list = ['N', 'CA', 'C', 'CB']

# and finally I run my generator, putting the results in a list.

your_coords_list = [x for x in createDesiredList(s, wish_list)]

rawDescription: converting a string to list in python in easy way

description: Converting a string to list in python in easy way


code:
df
df['salary'] = df['salary'].diff().fillna(df['salary'].iloc[0])
df

rawDescription: How can I get back real value from cumulative sum in pandas

description: Get back real value from cumulative sum in pandas


code:
# Read file
f = open('path_to_file.json')
json_string = f.read()
f.close()

# Convert json string to python object
import json
data = json.loads(json_string)

# Create model instances for each item
items = []
for item in data:
   # create model instances...
   item = YourModel(*item)
   items.append(item)

# Create all in one query
YourModel.objects.bulk_create(items)

rawDescription: JSON file reading by Django

description: JSON file reading by Django


rawDescription: Numpy arrays with elements as indices to other objects


code:
def sub_partition(array, start, end, idx_pivot):

    'returns the position where the pivot winds up'

    if not (start <= idx_pivot <= end):
        raise ValueError('idx pivot must be between start and end')

    array[start], array[idx_pivot] = array[idx_pivot], array[start]
    pivot = array[start]
    i = start + 1
    j = start + 1

    while j <= end:
        if array[j] <= pivot:
            array[j], array[i] = array[i], array[j]
            i += 1
        j += 1

    array[start], array[i - 1] = array[i - 1], array[start]
    return i - 1

def quicksort(array, start=0, end=None):

    if end is None:
        end = len(array) - 1

    if end - start < 1:
        return

    idx_pivot = random.randint(start, end)
    i = sub_partition(array, start, end, idx_pivot)
    #print array, i, idx_pivot
    quicksort(array, start, i - 1)
    quicksort(array, i + 1, end)

rawDescription: In-place QuickSort in Python

description: In-place QuickSort in Python


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

def fig1():
    x = np.arange(-5,5,0.01)
    f1 = lambda x: x**2 +x -6
    f2 = lambda x: x*0
    fig = plt.figure(figsize=(5,8)) # IT IS HERE THAT WE SPECIFY THE FIGSIZE
    ax = fig.add_subplot(111)
    ax.plot(x, f1(x))
    ax.plot(x, f2(x),'black')
    ax.set_ylim([-10,10])
    ax.set_xlim([-5,5])
    plt.show()

rawDescription: Figure dimensions, matplotlib, python3.4


rawDescription: How to get rid of \x00 in my array of bytes?

description: Get rid of \x00 in my array of bytes


code:
import re
import Orange

word = re.compile("\w+")

s = """Bread, Milk
Bread, Diapers, Beer, Eggs
Milk, Diapers, Beer, Cola
Bread, Milk, Diapers, Beer
Bread, Milk, Diapers, Cola"""

all_items = set(word.findall(s))
domain = Orange.data.Domain([])
domain.add_metas({Orange.orange.newmetaid(): Orange.feature.Continuous(n)
                  for n in all_items}, True)

data = Orange.data.Table(domain)
for e in s.splitlines():
    ex = Orange.data.Instance(domain)
    for m in re.findall("\w+", e):
        ex[m] = 1
    data.append(ex)

rawDescription: How to create a basket from a string in orange?

description: Create a basket from a string in orange


code:
for property, value in vars(your_class).iteritems():
    print(property, ":", value)

rawDescription: Get all attributes of a class in Python

description: Get all attributes of a class in Python


code:
class Thing(object):
    def __contains__(self, x):
        return x == 'potato'

t = Thing()
'potato' in t
'spam' in t

rawDescription: Make objects support "in"

description: Make objects support "in"


code:
from dateutil.parser import parse
s = 'Mar 31st, 2014'
parse(s)

rawDescription: How to convert date with suffix to another format in python

description: Convert date with suffix to another format in python


code:
handlers = [ (dict1, do_stuff_dict1), (dict2, do_stuff_dict2), (dict3, do_stuff_dict3) ]
for whichDict, whichFunc in handlers:
    try:
        val = whichDict[key]
    except KeyError:
        continue
    else:
        whichFunc()
        break
else:
    do_stuff_not_found()

rawDescription: Python nested try except vs if, elif, else


code:
global_votecount = Vote.objects.all().values('user', 'user__username').annotate(votesTotal=Count('user__username')).order_by('-votesTotal')

import datetime
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)

votesToday = dict(Vote.objects.filter(date__range=(today_min, today_max)).values_list('user__username').annotate(votesToday=Count('user__username')))

for item in global_votecount:
    item['votesToday'] = votesToday[item['user__username']]

rawDescription: How to count a field and this same field but filtered, in one query in Django?

description: Count a field and this same field but filtered, in one query in Django


code:
def gethost(request, hostname, template_file="gethost.html"):
  from django.db import connection, transaction
  cursor = connection.cursor()
  cursor.execute("SELECT * FROM inventory WHERE hosts='%s'" % hostname)
  rows = cursor.fetchall()
  t = Context({'results': rows})
  return render_to_response(template_file, t)

rawDescription: Django + MySQL, form/create mysql query to pass a valid argument to the url


code:
from pandas.tseries.frequencies import to_offset
to_offset('2H')

rawDescription: Build a Pandas pd.tseries.offsets from string


code:
def postview(request, *args, **kw):
    post_type = guess_the_post_type_from(request)
    view = get_the_view_for(post_type)
    return view(request, *args, **kw)

rawDescription: Django Single View to get response from multiple apps


code:
def your_view(request):

    if request.method == 'POST':
        num_results = request.POST.get('num_results')
    #rest of the code . . .

rawDescription: Grabbing Filter Options in Django

description: Grabbing Filter Options in Django


rawDescription: Finding the intersection of a curve from polyfit


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

driver = webdriver.PhantomJS()
driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '.archive_loading_bar')))
tree = html.fromstring(driver.page_source)

rawDescription: Selenium PhantomJS webdriver failing to grab ajax content


code:
for entity in root.find('output'):
   if oc_entities.get(entity.tag):
     if type(oc_entities.get(entity.tag)) == 'dict':
       oc_entities[entity.tag] = [oc_entities[entity.tag]]
     oc_entities[entity.tag].append({'keyword' : entity.text, 'relevance' : entity.get('relevance')})
   else:
     oc_entities[entity.tag] = {'keyword' : entity.text, 'relevance' : entity.get('relevance')}

rawDescription: Dictionary of a dictionary with duplicate keys


code: output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

rawDescription: How to retrieve result of calling a script from within a Python function?

description: Retrieve result of calling a script from within a Python function


code:
ax[0].hist(qtime[jobs['charge_rate']==1], weights=area[jobs['charge_rate']==1],
           bins=bins, label='Normal', color='b')
ax[1].hist(qtime[jobs['charge_rate']==3], weights=area[jobs['charge_rate']==3],
           bins=bins, label='Express', color='g')

rawDescription: Histogram of sum instead of count using numpy and maplotlib


code:
import json
import urllib2
data = json.dumps([1, 2, 3])
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()

rawDescription: submit raw body containing json to REST api

description: Submit raw body containing json to REST api


code:
import bcrypt
salt = bcrypt.gensalt()
hash = bcrypt.hashpw('secret', salt)
hash.find(salt)
hash == bcrypt.hashpw('secret', hash)

rawDescription: How to store and compare password in db using py-bcrypt

description: Store and compare password in db using py-bcrypt


code:
def input_default(prompt, default):
    return raw_input("%s [%s] " % (prompt, default)) or default

name = input_default("What is your name?", "Not Sure")

rawDescription: Starting raw_input() with pre determined text


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

fig = plt.figure()
ax = fig.add_subplot(311) # This represents a (3x1) grid (row x col) and we are plotting the (1) subplot. The last number increments row-wise.

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50

# the histogram of the data
n, bins, patches = ax.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax.plot(bins, y, 'r--')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

ax2 = fig.add_subplot(312) # Second subplot

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50

# the histogram of the data
n, bins, patches = ax2.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax2.plot(bins, y, 'r--')

ax3 = fig.add_subplot(313) # And the third subplot

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50

# the histogram of the data
n, bins, patches = ax3.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax3.plot(bins, y, 'r--')
plt.show()

rawDescription: Adding subplot to a program changes the way histograms are displayed


code:
from operator import itemgetter

# Make the word list.
word_list = ['my', 'bro', 'myline']

# Do your code here to create ave_list

# Fetch the min index and min value of ave_list
min_index, minvalue = min(enumerate(ave_list), key = itemgetter(1) )

# Now get the word at the same min index location.
min_word = word_list[min_index]

rawDescription: How to return the smallest average within a nested loop

description: Return the smallest average within a nested loop


code:
class Test:
    def __init__(self):
        self._var = 1

    @property
    def var(self):
        return self._var

    @var.setter
    def var(self, value):
        # add stuff here that you want to happen on var assignment
        self._var = value

rawDescription: how to create nicer variable interface in python class

description: Create nicer variable interface in python class


code:
class StringListProperty(ListProperty):
  def __init__(self, verbose_name=None, default=None, **kwds):
    super(StringListProperty, self).__init__(basestring,
                                             verbose_name=verbose_name,
                                             default=default,
                                             **kwds)

rawDescription: ListProperty vs StringListProperty on Google App Engine


code:
def unique_items(L):
    found = set()
    for item in L:
        key = (item[1], item[3])  # use tuple as key
        if key not in found:
            yield item
            found.add(key)

rawDescription: Removing duplicates in list of lists

description: Removing duplicates in list of lists


code:
total = Message.objects.all().count()
for i in xrange(0,total,500):
   batch = Message.objects.all()[i:500]

rawDescription: Group query results in batches of Python


code:
array = [1,2,3,4,5,6,7,8,9]

newarray = [array[i] for i in range(0, len(array), 2)]

print(newarray)

rawDescription: how do i write a list comprehension?

description: Write a list comprehension


code: a.repeat(2, axis=0).repeat(2, axis=1)

rawDescription: Quick way to upsample numpy array by nearest neighbor tiling


code:
class SubConfig(object):
    def __init__(self, config, key_types):
        self.__dict__.update(
            _SubConfig__config=config,
            _SubConfig__values={},
            _SubConfig__key_types=key_types
            )

rawDescription: Dynamic configuration object based on __setattr__ and _getattr__


code:
def process(infilename):
    outfilename = os.path.splitext(infilename)[0] + "-out.csv"
    with open(infilename, 'r') as istr:
        with open(outfilename, 'w') as ostr:
            for line in istr:
                line = line.rstrip('\n') + ',1'
                print(line, file=ostr)

def process_files(path):
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            process(name)

rawDescription: generalize python script to run on all files in a directory

description: Generalize python script to run on all files in a directory


code:
z = np.zeros((5,5))
rng = np.arange(4)
z[rng, rng+1] = np.sqrt(rng+1)
z

rawDescription: numpy: fill offset diagonal with different values

description: Numpy: fill offset diagonal with different values


code: import flask.ext.wtf

rawDescription: ImportError: No module named flask_wtf

description: ImportError: No module named flask_wtf


code:
from Tkinter import *
from ttk import *

class Results():

    def __init__(self, frame, name):
        self.lab_frame = LabelFrame(master=frame, text=name)
        self.lab_frame.grid(sticky='we', padx=10, pady=10, columnspan=10)

        self.l1 = Label(master=self.lab_frame, text='Result 1:')
        self.l1.grid(sticky='e', row=0, column=0, pady=2)

        self.l2 = Label(master=self.lab_frame, text='Result 2:')
        self.l2.grid(sticky='e', row=1, column=0, pady=2)

        self.l3 = Label(master=self.lab_frame, text='Result 3:')
        self.l3.grid(sticky='e', row=2, column=0, pady=2)

        self.r1 = Label(master=self.lab_frame, text='')
        self.r1.grid(sticky='w', row=0, column=1, pady=2)

        self.r2 = Label(master=self.lab_frame, text='')
        self.r2.grid(sticky='w', row=1, column=1, pady=2)

        self.r3 = Label(master=self.lab_frame, text='')
        self.r3.grid(sticky='w', row=2, column=1, pady=2)

class App():
    def __init__(self, master):
        self.master = master
        self.master.title('Question')
        self.create_main_frame()

    def create_main_frame(self):
        self.main_f = Frame(self.master)
        nb = Notebook(padding=5)
        nb.pack(anchor='w')
        self.tab1(nb)

    def tab1(self, nb):
        tab1_frame = Frame(nb)
        nb.add(tab1_frame, text='Tab 1', underline=0)

        prod_lab = Label(tab1_frame, text='Entry:')
        prod_lab.grid(row=1, column=0, padx=(10,0), pady=(10,5), sticky='e')

        self.product_e = Entry(tab1_frame, width=40)
        self.product_e.grid(row=1, column=1, padx=(0,10), pady=(10,5))

        self.button1 = Button(tab1_frame,
                               text="Run",
                               command=self.run1
                               )
        self.button1.grid(row=2, column=1, padx=(0,10), pady=(0,10), sticky='ne')

        self.results1 = Results(tab1_frame, 'Results Section 1')
        self.results2 = Results(tab1_frame, 'Results Section 2')
        self.results3 = Results(tab1_frame, 'Results Section 3')

    def run1(self):
        #This is the method that will be used to find the results I need
        #For the sake of this question, let's pretend I want to put whatever text is in Entry 1, into results section 2 result 2
        print (self.product_e.get())
        print ('How do I use "widget.config()" to modify the 3 results sections separately???')
        self.results1.r2.config(text='1111111111')
        self.results2.r2.config(text='xxxxxxxxxx')
        self.results3.r2.config(text='----------')

master = Tk()
app = App(master)
master.mainloop()

rawDescription: How to use tkinter's widget.config() to modify separate widgets that were created by the same method?

description: Use tkinter's widget.config() to modify separate widgets that were created by the same method


code:
for files in curDir:
    if files.endswith('.srt'):  # Filename ends in .srt
        ...
    else:                       # Filename does not end in .srt
        ...

rawDescription: Check file extensions with Regex

description: Check file extensions with Regex


code:
first_parameter = 10
second_parameter = 2
result = eval("first_parameter * second_parameter")
result

rawDescription: Using a config file to specify operations to execute in Python


code:
for a in range(0, len(list_a)):
    for b in range(0, len(list_b)):
        sum_foo = float(sum([x[a][b][0] for x in foo]))
        foobar[a][b].append(sum_foo)

rawDescription: List manipulation in python

description: List manipulation in python


code:
import argparse

class Q2TAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string):
        self.query2target = values

parser = argparse.ArgumentParser()
q2taction = parser.add_argument("query2target.bam", action=Q2TAction)
parser.parse_args()

print(q2taction.query2target)

rawDescription: . (dot) in argparse argument and variable name


code:
from datetime import datetime
days = 736420
datetime.fromordinal(days - 365)

rawDescription: Is there any pythonic way to convert mysql TO_DAYS output into datetime?


code:
closet['date_key']=closet['date_key'].astype(str)
definedRIDS['date_key'] = definedRIDS['date_key'].astype(str)

icloset = closet.set_index(['date_key','user_uuid'])

RIDdata = definedRIDs.join(icloset,on=['date_key','user_uuid'],how='inner')

rawDescription: Join with MultiIndex DataFrames Creates Empty Fields [pandas]


code:
import csv

with open('test.csv', 'rb') as old_csv:
    csv_reader = csv.reader(old_csv)
    with open('testMODIFIED2.csv', 'wb') as new_csv:
        csv_writer = csv.writer(new_csv)
        for i, row in enumerate(csv_reader):
            if i != 0:
                row.append(float(row[10]) / float(row[37]))
                csv_writer.writerow(row)

rawDescription: How to perform a simple calculation in a CSV and append the results to the file

description: Perform a simple calculation in a CSV and append the results to the file


code:
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")

ws = excel.Workbooks.Add().Worksheets(1)
qtNew = ws.QueryTables.Add( "TEXT;C:\\DRIVE D\\graphme\\result.txt", ws.Range("A1"))

qtNew.TextFilePlatform = 866
qtNew.TextFileStartRow = 1
qtNew.TextFileParseType = 1
qtNew.TextFileTextQualifier = 1
qtNew.TextFileConsecutiveDelimiter = False
qtNew.TextFileTabDelimiter = True
qtNew.TextFileSemicolonDelimiter = False
qtNew.TextFileCommaDelimiter = False
qtNew.TextFileSpaceDelimiter = False
qtNew.TextFileColumnDataTypes = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
qtNew.TextFileTrailingMinusNumbers = True
qtNew.Refresh()

rawDescription: Translating Excel VBA script to Python

description: Translating Excel VBA script to Python


code:
import urllib

url = 'http:......'
filename = 'your_filename'
urllib.urlretrieve(url, filename)

rawDescription: Python - wget check when process has completed


code:
from PIL.ExifTags import TAGS

def get_exif(fn):
    ret = {}
    i = Image.open(fn)
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret

rawDescription: How to group images by "bursts?"

description: Group images by "bursts?"


code:
list_of_extensions = ['flv','mp4','avi'] # Supplement it with what you find.
list_of_files = []

import os

def callback(arg, directory, files):
    for file in files:
        extn = file.split('.')[-1]
        if extn in arg:
               list_of_files.append(os.path.join(directory,file))

os.path.walk(".", callback, list_of_extensions)

rawDescription: What are the popular video formats

description: What are the popular video formats


rawDescription: Why in python loop for line in file is not going through all lines after using readline before?


rawDescription: How to get the Style name of a paragraph in a libreoffice document with a python macro?

description: Get the Style name of a paragraph in a libreoffice document with a python macro


code:
Show.objects.filter(
    is_active=True,
).annotate(
    e_count=Count('episodes'),
    start=Min('episodes__start'),
).filter(
    e_count__gt=0,
    start__gt=timezone.now(),
).order_by('start')

rawDescription: Django queryset order by related model with distinct


code:
class ModelBAdmin(admin.ModelAdmin):

    def modelA_Codes(self, inst):
        return ','.join([b.code for b in inst.modela_set.all()])

    list_display = ('name', 'modelA_Codes')

rawDescription: Add field from another model Django

description: Add field from another model Django


code:
def get_parent_groups(self, cr, uid, ids, grp_id, context=None):
    res = []
    grp_obj = self.pool.get('res.groups')
    grp = grp_obj.browse(cr, uid, grp_id)
    if grp.implied_ids:
        for parent_grp in grp.implied_ids:
            res.append(parent_grp.id)
            if parent_grp.implied_ids:
                parent_ids = self.get_parent_groups(cr, uid, ids, parent_grp.id)
                for parent_id in parent_ids:
                    res.append(parent_id)
    return res

rawDescription: Get all parent 'objects'?

description: Get all parent 'objects'