code:
datafiles.append(('imageformats', [
                'C:\Python27\Lib\site-packages\PySide\plugins\imageformats\qjpeg4.dll'
                ]))

rawDescription: Image is not displayed in pyside exe file by py2exe


code: data.sort(key=lambda x: x[0])

rawDescription: [tricky]Searching for multiple occurrences of word pairs based on vicinity. Python


code:
def main(argv):
    """
    Entry point for the deploy script.

    Arguments:
        argv: All command line arguments save the name of the script.
    """
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='also report if files are the same')
    parser.add_argument('-V', '--version', action='version',
                        version=__version__)
    parser.add_argument('command', choices=['check', 'diff', 'install'])
    fname = '.'.join(['filelist', pwd.getpwuid(os.getuid())[0]])
    args = parser.parse_args(argv)

rawDescription: Creating a Python command line application


rawDescription: How do I find an xml node that does not have an attribute

description: Find an xml node that does not have an attribute


rawDescription: Python: How to add content of file to list from position


code: numpy.array(zip(x, y, ov, aa))

rawDescription: combining numpy arrays and masking

description: Combining numpy arrays and masking


rawDescription: Printing complete coo_matrix

description: Printing complete coo_matrix


code: f(a)

rawDescription: Median sort a list in unordered fashion

description: Median sort a list in unordered fashion


code:
from google.appengine.ext.webapp import Request
from google.appengine.ext.webapp import Response
from StringIO import StringIO
form = 'msg=hello'
handler.response = Response()
handler.request = Request({
    'REQUEST_METHOD': 'POST',
    'PATH_INFO': '/',
    'wsgi.input': StringIO(form),
    'CONTENT_LENGTH': len(form),
    'SERVER_NAME': 'hi',
    'SERVER_PORT': '80',
    'wsgi.url_scheme': 'http',
})
handler.post()

rawDescription: How to simulate POST arguments in python

description: Simulate POST arguments in python


code:
def corr_time2(t, JM1, JM2):
    return np.prod(np.cos(2*JM1[None,...]*t[:,None,None,None]),axis=-1) +\
       np.prod(np.cos(2*JM2[None,...]*t[:,None,None,None]),axis=-1)
result = np.sum(corr_time2(t_output, JM1, JM2),axis=(1,2))

rawDescription: Implementing intereaved products and sums in Python without loop overhead


code:
# hashed += ((hashed << 19) + (hashed >> 13) + ord(char)) & 0xFFFFFFFF
# the above is wrong; it's not masking the final addition.
hashed = (hashed + (hashed << 19) + (hashed >> 13) + ord(char)) & 0xFFFFFFFF

rawDescription: CARP hash in Python

description: CARP hash in Python


rawDescription: Split a delimiter in a list of list when delimiter may be both present and absent


code:
#!python3

with open('stripped.txt') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        line = line.strip()
        if not line:
            continue

        hexnums = [int(hn, 16) for hn in line.split()]
        for num1, num2 in zip(hexnums[0::2], hexnums[1::2]):
            digit = '0' if num2 // num1 == 3 else '1'
            outfile.write(digit)
        outfile.write('\n')

rawDescription: Iterating over lines in a file yields wrong number of lines


code:
from collections import Counter

def list_sub_counter(list1, list2):
    c = Counter(list1) - Counter(list2)
    return (x for l in ([k]*n for k,n in c.iteritems() if n>0) for x in l)

rawDescription: Can I perform minus or join operations on lists in python including duplicate entries

description: Perform minus or join operations on lists in python including duplicate entries


rawDescription: email body from a parsed email object in jython

description: Email body from a parsed email object in jython


code:
import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level
                          # library

d[key] = data   # store data at key (overwrites old data if
                # using an existing key)
data = d[key]   # retrieve a COPY of data at key (raise KeyError if no
                # such key)
del d[key]      # delete data stored at key (raises KeyError
                # if no such key)
flag = d.has_key(key)   # true if the key exists
klist = d.keys() # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4)  # this works as expected, but...
d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()       # close it

rawDescription: Results in CSV should be in lists rather than strings


code:
def check_procs(curr_time, proc_dict):
    running = []
    for key, intervals in proc_dict.items():
        for start, end in intervals:
            if start<=curr_time<=end:
                running.append(key)
                break
    return running

rawDescription: Using a dictionary to determine when 4 processes are concurrently on


code: re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)

rawDescription: Python regex search AND split

description: Python regex search AND split


code:
# -*- coding: latin-1 -*-
myString = u'éÀî'

rawDescription: Getting the correct encoding for strings and csv-files in Python


rawDescription: How to add/substract with c_double_Array?

description: Add/substract with c_double_Array


code:
unq, unq_idx = np.unique(a, return_inverse=True)
unq_cnt = np.bincount(unq_idx)

rawDescription: Checking for and indexing non-unique/duplicate values in a numpy array


code: df1.iloc[(3 <= df1.index.minute) & (df1.index.minute < 5)]

rawDescription: Slicing Pandas Dataframe by minutes

description: Slicing Pandas Dataframe by minutes


code:
from django.shortcuts import render
from django import forms
from django.forms.formsets import formset_factory

class TestForm(forms.Form):
    id = forms.IntegerField(label='id', widget=forms.HiddenInput)
    value = forms.CharField(label='value')

TestFormSet = formset_factory(TestForm, extra=0)

def test(request):
    if request.method == 'POST':
        fs = TestFormSet(request.POST)
    else:
        fs = TestFormSet(initial=[
            dict(id=1, value='foo'),
            dict(id=4, value='bar'),
            dict(id=5, value='baz'),
        ])
    context = {
        'fs': fs,
    }
    return render(request, 'formset/test.html', context)

rawDescription: Multiple text fields with id's in django


code:
with stdout_redirected():
    soln2 = integrate.odeint(f, y2, t2, mxstep = 5000)

rawDescription: Disable warnings originating from scipy

description: Disable warnings originating from scipy


code: conn = pymysql.connect(host='xx', user='xx', passwd='xx', db='xx', use_unicode=True, charset='utf8')

rawDescription: Not getting proper character encoding with Facebook posts data


code:
new_stuff = ['b','o','l']
''.join(new_stuff)

rawDescription: Compare two sets of strings and then return whole strings that are different in Python 3.4


code:
from foo import func as foo
foo()

rawDescription: Dynamically name a function as the script, Python


code: exit()

rawDescription: NLTK Brown Corpus - adding own tagged sentences


code:
dtype=[('MEAT', '<i4'), ('CHEESE', '<i4'), ('TOAST', '<i4'), ('BIRD', 'S4'), ('PLANE', 'S4'), ('SOCK', 'S4')]
nt = numpy.loadtxt('/home/joshua/file.csv', dtype=dtype, delimiter=',')

nt['SOCK']
#>>> array([b'AAA', b'BBB', b'CCC'],
#>>>       dtype='|S4')

rawDescription: Numpy.loadtxt imports data as array of arrays rather than a multidimension array


rawDescription: Casting a custom class to a dict in python


code:
def numbers(first, last, count):
    nums = [first, last]
    width = last - first
    while len(nums) < count:
        width /= 2
        stepper = first
        while stepper < last:
            rounded = round(stepper)
            if rounded not in nums:
                nums.append(rounded)
                if len(nums) == count:
                    break
            stepper += width
    return nums

rawDescription: Generating a list of evenly distributed numbers from range


code: import Math

rawDescription: How to include external Python code to use in other files?

description: Include external Python code to use in other files


code:
required_items = [item for item in items if somecondition(item)]
if required_items:
    # do something
    # if only one required item is ever present, then maybe...
    required_item = required_items[0]

rawDescription: How do I test if a variable that I declared in an inner block exists in the outer block?

description: Test if a variable that I declared in an inner block exists in the outer block


code:
myquery = "select * from players where {}".format(
    ' and '.join('{}={}'.format(k, v) for k, v in mylist.iteritems()))

rawDescription: Looping Through Python Dictionary

description: Looping Through Python Dictionary


code:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def next_word(word):
    splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
    replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
    return [valid for valid in replaces if lookup(valid)]

rawDescription: The Alphabet and Recursion

description: The Alphabet and Recursion


rawDescription: Force print statement to a single line in python


code:
def NullColumn(*args,**kwargs):
    kwargs["nullable"] = kwargs.get("nullable",True)
    return db.Column(*args,**kwargs)

...
username = NullColumn(db.String(80))

rawDescription: SQLAlchemy set default nullable=False

description: SQLAlchemy set default nullable=False


code:
from csvkit.utilities.csvjson import CSVJSON
args = ["--key", "Date", "/path/to/input/file"]
CSVJSON(args).main()

rawDescription: csvkit & django a.k.a. using csvkit as modules instead of from command line

description: Csvkit & django a.k.a. using csvkit as modules instead of from command line


code:
# Configuration file for ipython.
from os.path import join as pjoin
from IPython.utils.path import get_ipython_dir

c = get_config()
c.InteractiveShellApp.exec_files = [
    pjoin(get_ipython_dir(), "profile_default", "launch.py")
]

rawDescription: ipython startup config for spyder IDE

description: Ipython startup config for spyder IDE


code:
class UserOptionsForm(forms.Form):
    user_personal_options = forms.ChoiceField(choices=(),
                                              widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices', None) # return the choices or None
        super(UserOptionsForm, self).__init__(*args, **kwargs)
        if choices is not None:
            self.fields['user_personal_options'].choices = choices

rawDescription: How do you generate a custom form in Django?

description: Generate a custom form in Django


code:
def sets(n):
    for x in xrange(1, (n // 3) + 1):
       for y in xrange(x, ((n - x) // 2) + 1):
           yield x, y, n - (x + y)

rawDescription: Generating products of lists that sum to a parameter N


code:
df = pd.DataFrame(data=file, columns=['Measurement', 'Date', 'Time','CO2', 'Flow'], dtype=object)
df

rawDescription: Pandas DataFrame Cannot Read Data

description: Pandas DataFrame Cannot Read Data


code:
def missingint(whole_list , other_values):
    return sum( whole_list ) - sum( other_values )

rawDescription: Given two of three items, return the missing item


code:
import re

line = re.compile(r'( *)- ([^:\n]+)(?:: ([^\n]*))?\n?')
depth = 0
stack = [{}]
for indent, name, value in line.findall(inputtext):
    indent = len(indent)
    if indent > depth:
        assert not stack[-1], 'unexpected indent'
    elif indent < depth:
        stack.pop()
    stack[-1][name] = value or {}
    if not value:
        # new branch
        stack.append(stack[-1][name])
    depth = indent

result = stack[0]

rawDescription: How can a Markdown list be parsed to a dictionary in Python?


code:
from collections import defaultdict, OrderedDict
from datetime import datetime, timedelta
from itertools import chain, groupby

flat = sorted((datetime.strptime(d, '%m-%d-%Y-%H-%M').date(), f, c)
              for (d, f, c) in chain(*A))
counts = [(d, f, sum(e[2] for e in l))
          for (d, f), l
          in groupby(flat, key=lambda t: (t[0], t[1]))]

# lets assume that there are some data
start = counts[0][0]
end = counts[-1][0]
result = OrderedDict((start+timedelta(days=i), defaultdict(int))
                     for i in range((end-start).days+1))
for day, data in groupby(counts, key=lambda d: d[0]):
    result[day].update((f, c) for d, f, c in data)

rawDescription: Aggregate and fill data for missing dates (days and hours)


code:
def get_ordering(obj):
    if isinstance(obj, LatestNews):
        return obj.publish_date
    else:
        return obj.date_created

rawDescription: Combining & ordering querysets

description: Combining & ordering querysets


code:
self.stDate = datetime.datetime.now() - datetime.timedelta(days=1000)
self.endDate = datetime.datetime.now()

rawDescription: Retrieve data from mongodb based on date condition in pymongo


rawDescription: python string formatting from list with arbitrary item

description: Python string formatting from list with arbitrary item


code:
ere-Hay
are-ay
e-thay
ords-way

rawDescription: String wrong input

description: String wrong input


code:
name = 'John'
string = 'hello {}! You owe 10%'.format(name)
string
string = 'hello {name}! You owe 10%.'.format(name=name)
str

rawDescription: Python Using (%s) in a string that slo contains a (%)?


code:
df = pd.DataFrame()
ids = [''.join([random.choice(string.ascii_lowercase + string.digits) for _ in range(16)]) for i in range(10)]
addresses = [''.join([random.choice(string.ascii_lowercase) for _ in range(10)]) for i in range(10)]
df['ID'] = np.random.choice(ids, size=10000)
df['address'] = np.random.choice(addresses, size=10000)
df['active_seconds'] = np.random.randint(0, 100, 10000)

df['used_at'] = pd.date_range(start=datetime(2016, 1, 1, 0, 0, 0), freq='H', periods=10000)

rawDescription: Report with Pivot Tables like in Excel using Python


code:
somevariable = "1.1"
somevariable = float(somevariable)

rawDescription: How can I use a variable instead of a floating value for time.sleep()

description: Use a variable instead of a floating value for time.sleep()


code:
plant = Plant()
trans1 = Transformer('trans1')
plant.add_transformer(trans1)
plant.print_transformers()

rawDescription: How should I organize my code if I want to define a class which consists of instances of another class?


code:
myList = []
for k in myDict:
    if k.split(',')[0]==prefix:
        myList.append(k)

rawDescription: Python Dictionary Print First occurence

description: Python Dictionary Print First occurence


code:
class LI(list):
    def append(self, item):
        list.append(self,item)
        list.append(self,item)

rawDescription: Overriding list method

description: Overriding list method


code:
b = imread("a.tif")
b

rawDescription: Why do values in my 3D numpy array change when I write it to file?


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

t = np.arange(0.0, 2.0, 0.01)

s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = s1*s2

fig = plt.figure()
ax1 = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2)
ax2 = plt.subplot2grid((4,3), (2,0), colspan=3, sharex=ax1)
ax3 = plt.subplot2grid((4,3), (3,0), colspan=3, sharex=ax1)

ax1.plot(t,s1)
ax2.plot(t[:150],s2[:150])
ax3.plot(t[30:],s3[30:])

fig.subplots_adjust(hspace=0)
for ax in [ax1, ax2]:
    plt.setp(ax.get_xticklabels(), visible=False)
    # The y-ticks will overlap with "hspace=0", so we'll hide the bottom tick
    ax.set_yticks(ax.get_yticks()[1:])

plt.show()

rawDescription: How to sharex when using subplot2grid

description: Sharex when using subplot2grid


code: r'^glossary$', include('glossary.urls')

rawDescription: Django mixes my templates

description: Django mixes my templates


rawDescription: Subtract transpose from a matrix but keep the original diagonal


code:
Char = a, Index = 0
Char = b, Index = 1
Char = c, Index = 2

rawDescription: Is there something similar to python's enumerate for linq


code:
hometeamid = models.IntegerField()
awayteamid = models.IntegerField()

rawDescription: Django - How to link tables

description: Django - How to link tables


code: a.reshape(-1, 2).mean(axis=1)

rawDescription: How can I take a list and add elements in columns in intervals?

description: Take a list and add elements in columns in intervals


code:
import so02
e = so02.example()
e.text
e.text = "foobar"
e.text

rawDescription: boost python won't auto-convert char* data members

description: Boost python won't auto-convert char* data members


code:
from collections import Counter
c = Counter([1,1,2,3,3,4,5,5,5])
[i for i in c if c[i] > 1]

rawDescription: Filtering a list python repeated items

description: Filtering a list python repeated items


code:
import copy
C = copy.copy(D["A"])
C.append(4)
D["A"]

rawDescription: Get a value from a dictionary without linking to the memory location


rawDescription: Is there a python method to set the specified elements to be some value in a list?


rawDescription: Are compound if statements faster, or multiple if statements?


code: df[df['Age'] >= df['Age'].values[-15]]

rawDescription: Pandas - Create new dataframes based on ranked values in select columns


rawDescription: nicer way to merge list of dictionaries by key

description: Nicer way to merge list of dictionaries by key


code: return my_list

rawDescription: Return elements of list as individual items in Python


code:
def makelists_py2(list_count):
    return [[] for _ in xrange(list_count)]

rawDescription: Create lists python

description: Create lists python


code: [(k, v) for k, v in fnames.items() if not test_list(v)]

rawDescription: Python: Compare Filenames in Folder

description: Python: Compare Filenames in Folder


rawDescription: pandas: grabbing value of column based on value of other variable

description: Pandas: grabbing value of column based on value of other variable


code:
import regex
regex = re.compile('(\s?)#(.*?)#(\s+)')
str = 'hello #this# is #some text string# text text'
str = re.sub(regex, '\\1<b>\\2</b>\\3', str)

rawDescription: How can I replace a character with different patterns (HTML tags) in Python?

description: Replace a character with different patterns (HTML tags) in Python


code:
import argparse
the_parser = argparse.ArgumentParser()
the_parser.add_argument('--input_files',nargs='+')
args = the_parser.parse_args()

rawDescription: Infinite input using argparse

description: Infinite input using argparse


code:
my_l = [1,2,3]
copy_my_l = my_l[:]
my_l.append(4)
my_l
copy_my_l

rawDescription: List getting replaced

description: List getting replaced


code:
from functools import partial

func_2 = partial(func_1, b=2, c='asdf')

rawDescription: Changing keyword defaults of a function in Python


code:
self.generate_pdf_file(str_report_name,
                str_report_format,
                str(lst_main_heading),
                str(lst_header),
                str(lst_report_header),
                str(lst_page_header),
                str(lst_footer),
                str(lst_report_footer),
                str(lst_page_footer),
                str(lst_report_data),
                bln_show_column_heading,
                str(lst_col_title))

rawDescription: pass python list to ladon using suds

description: Pass python list to ladon using suds


code:
from collections import defaultdict
from pprint import pprint

books = [['Shakespeare', 'William', 'Rome And Juliet', '5', '5.99'],
         ['Shakespeare', 'William', 'Macbeth', '3', '7.99'],
         ['Dickens', 'Charles', 'Hard Times', '7', '27.00'],
         ['']]

d = defaultdict(list)
for book in (book for book in books if book[0]):
    d[book[0], book[1]].append(book[2:])

pprint(d)

rawDescription: Create dictionary from 2-D list

description: Create dictionary from 2-D list


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, parent):
        super(MainWindow, self).__init__(parent)

        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.button = wx.Button(self, wx.ID_ANY, label="Test")
        self.sizer.Add(self.button)
        self.Bind(wx.EVT_BUTTON, self.password_dialog, self.button)

        self.SetSizer(self.sizer)
        self.sizer.Fit(self)
        self.SetTitle('Test')
        self.SetSize((100, 100))
        self.Centre()
        self.Show(True)

    def password_dialog(self, event):
        wx.MessageBox(
            'Contact `TheHiguty` blah blah blah',
            'Forgotten your password?',
            wx.OK|wx.ICON_ERROR)

if __name__ == '__main__':
    app = wx.App()
    MainWindow(None)
    app.MainLoop()

rawDescription: wxPython Custom Dialog loading incorrectly

description: WxPython Custom Dialog loading incorrectly


code:
entities = first_elem['entities']
pprint(entities)

rawDescription: Python Json loads() returning string instead of dictionary?


code:
import __builtin__
list = []
list()
list = __builtin__.list
list()

rawDescription: REPL - recover callable after redefining it


rawDescription: Invalid syntax in path when changing directory


code:
D = {'a': 1}
try:
    a = D['a']
except KeyError:
    a = print('hah')

rawDescription: why does D.get(k,v) seem to always execute v if v is returned from a function?

description: Why does D.get(k,v) seem to always execute v if v is returned from a function


code: product = models.ForeignKey(Product, limit_choices_to=dict(id__in=BaseModel._product_list))

rawDescription: How do I restrict foreign keys choices to related objects only in django

description: Restrict foreign keys choices to related objects only in django


code:
import pandas

systolic_sex = pandas.DataFrame(systolic_sex)
sex = pandas.DataFrame(sex)

matches = systolic_sex[systolic_sex.sid.isin(sex.sid)]

rawDescription: intersection of two lists of dictionaries by key/value pair

description: Intersection of two lists of dictionaries by key/value pair


code:
lt.favorite_series.append(the_wire)
session.commit()
lt.favorite_series # > [The Wire]
[s.episodes for s in lt.favorite_series] # >> [[The Wire S1E1, The Wire S1E2]]

rawDescription: SQLAlchemy: retrieve all episodes from favorite_series of specific user


code:
import requests

session = requests.Session()

# First, get the cookies.
# The session keeps track of cookies and requests follows redirects for you
r = session.get("https://bpcleproc.in/EPROC/viewtender/13474")

# Then, simulate following the JS redirect
r = session.get("https://bpcleproc.in/EPROC/viewtender/13474")

print(r)
print(r.text)

rawDescription: html content not received over get request

description: Html content not received over get request


code: renderScene()

rawDescription: OpenGL Framebuffer with more than one texture


code: mydatetime = datetime.combine(d, datetime.time())

rawDescription: How do I get datetime from date object python?

description: Get datetime from date object python


code:
class BunchOfStuff(object):
    def __init__(self):
        self.variable1 = 5
        self.variable2 = 10
        self.variable3 = 15
    def variable4(self):
        return self.variable1 + self.variable2 + self.variable3

stuff = BunchOfStuff()
print(stuff.variable4()) # prints 30 -- note that it's a method, so we call it
stuff.variable1 = 10
print(stuff.variable4()) # prints 35

rawDescription: Refreshing a list of variables with one command


rawDescription: Python : Reverse Order Of List

description: Python : Reverse Order Of List


code:
def on_drag(self, evt):
   # No evt.Allow() here, I won't use TreeCtrl's internal DND support
   item = evt.GetItem()
   if item == self.tree.GetRootItem():
      return
   dropsrc = wx.DropSource(self)
   # Populate dropsource
   # ...
   dropsrc.DoDragDrop(wx.Drag_AllowMove)

rawDescription: wx.TreeCtrl drag and drop, copy and move

description: Wx.TreeCtrl drag and drop, copy and move


rawDescription: Format hex digits for character code \x

description: Format hex digits for character code \x


code:
class Parent(object):
    a_list = ['parent_item1', 'parent_item2', ]
    def print_list(self):
        print(self.a_list)

class Child1(Parent):
    def __init__(self, *args, **kwargs):
        super(Child1, self).__init__(*args, **kwargs)
        self.a_list = self.a_list + ['child1_item']  # <-------

class Child2(Parent):
    def __init__(self, *args, **kwargs):
        super(Child2, self).__init__(*args, **kwargs)
        self.a_list = self.a_list + ['child2_item']  # <-------

parent = Parent()
child1 = Child1()
child2 = Child2()
parent.print_list()
child1.print_list()
child2.print_list()

rawDescription: How do I extend a list from a parent class?

description: Extend a list from a parent class


code:
real_re = re.compile('[ ]*real[^:]*::\s+(.*)')
real_re.findall(progtext)

rawDescription: Parsing code with python

description: Parsing code with python


code: fig, axes = plt.subplots(1, 2)

rawDescription: Creating two completely independent plots in matplotlib and going back and forth between them


code:
def packRegister(value, size):
    if value < 0 or value.bit_length() > size:
        raise ValueError("Value won't fit in register of size {} bits".format(size))
    return struct.pack('>I', value)[-(size // 8):]

rawDescription: python conversion int into arbitrary number of bytes

description: Python conversion int into arbitrary number of bytes


code: [x[j:j+4] for j in range(0,len(x),4)]

rawDescription: How to split a list with only one item which is a complex string?

description: Split a list with only one item which is a complex string


code:
import datetime
tdate = datetime.date(2012,1,31)
datetime.datetime.combine(tdate, datetime.time())

rawDescription: Convert a datetime.date object into a datetime.datetime object with zeros for any missing time attributes


code:
import xml.etree.ElementTree as ET
from pprint import pprint

xml = ET.parse('x.xml')
root = xml.getroot()
news_sources = {}
for sourceList in root:
    sourceListName = sourceList.attrib['source']
    news_sources[sourceListName] = []
    for feed in sourceList:
       feedName = feed.text
       news_sources[sourceListName].append(feedName)

pprint(news_sources)

rawDescription: Generating nested lists from XML doc

description: Generating nested lists from XML doc


rawDescription: ElementTree, Python - find element with sub-element containing certain text and add another sub-element to a list


code:
with open('somefile', 'rb') as fh:
    bitstream = fh.read()

rawDescription: Splitting a byte list into a list of dicts


code:
trip = next( d for d in dict_list
               if d["START"] == "Virginia" and d["END"] == "Boston" )

rawDescription: Python: How to access the dictionary that has specific key-values in a list


code:
root = ET.fromstring("c")
root.findall("./b")
lst = root.findall("./b")
lst[0]

rawDescription: What's difference between findall() and iterfind() of xml.etree.ElementTree


code:
if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf.urls.static import static

    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rawDescription: Django Rest app not using media root correctly to serve images


code:
def toggle(self, event):
    # ...
    for children in self.frame.winfo_children():
        children.destroy()
    tk.Label(self.frame, text=text, bg=bg).grid(row=0, column=0)

rawDescription: How to erase the contents of a Frame

description: Erase the contents of a Frame


rawDescription: Rendering vectors in a sphere, with better perception


code:
def update(self):
    # current position is self.rect.topleft
    # starting position is self.start_pos
    # to move the Sprite/Rect, you can also use the move functions
    self.rect.move_ip(10, 20) # moves the Sprite 10px vertically and 20px horizontally

rawDescription: Pygame- Sprite set position with mouseclick


code: i = min((x for x in aList if x[2] == 1), key=lambda k: k[1])

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code:
print([d.func_name for d in foo.bar._decorators])
# ['many', 'decos', 'here']

rawDescription: Introspection to get decorator names on a method?


rawDescription: Sorting and Grouping Nested Lists in Python


rawDescription: Pandas Rolling_std with Window using all previous row counts


rawDescription: Dictionaries containing the biggest values


rawDescription: Query regarding the "width" option for format specifiers in python?


code:
from pprint import pprint
from xml.dom.minidom import parse, Text, parseString

data = """your xml goes here"""

dom = parseString(data)

result = {}

effect = dom.getElementsByTagName('effect')[0]
result['name'] = effect.getElementsByTagName('name')[0].firstChild.nodeValue

parameters = []
for parameter in effect.getElementsByTagName('parameter'):
    id = parameter.getElementsByTagName('parameterid')[0].firstChild.nodeValue
    name = parameter.getElementsByTagName('name')[0].firstChild.nodeValue
    value = parameter.getElementsByTagName('value')[0].firstChild.nodeValue
    parameters.append({'id': id, 'name': name, 'value': value})

result['parameters'] = parameters

pprint(result)

rawDescription: how to parse xml data by the text value name? By python minidom

description: Parse xml data by the text value name? By python minidom


code:
def parse_date(date_str):
    pieces = date_str.split('/')
    try:
        for piece in pieces:
           assert int(piece) > 0
    except (ValueError,AssertionError):
        print ("Bad Date")
    else:
        print ("Good date")

parse_date('01/x1/2010')   #Bad Date
parse_date('01/-1/2010')   #Bad Date
parse_date('01/01/2010')   #Good date

rawDescription: how do i write a statement if there is a character or negative in the date string?

description: Write a statement if there is a character or negative in the date string


code:
import sys
from distutils.core import setup
from distutils.command.build_clib import build_clib
from distutils.extension import Extension
from Cython.Distutils import build_ext

libhello = ('hello', {'sources': ['hello.c']})

ext_modules=[
    Extension("demo", ["demo.pyx"])
]

def main():
    setup(
        name = 'demo',
        libraries = [libhello],
        cmdclass = {'build_clib': build_clib, 'build_ext': build_ext},
        ext_modules = ext_modules
    )

if __name__ == '__main__':
    main()

rawDescription: Using distutils and build_clib to build C library


code:
if section == 'A':
    while tickets < 0 or tickets > 300:
        print('Invalid, enter a value from  0 to 300')
        tickets = int(input('Enter amount of tickets sold: '))
    getSectionA(tickets)

rawDescription: Values aren't stored in python program

description: Values aren't stored in python program


code:
def getMovies():

    movieinfo = {"Movie_Name": [], "Movie_Stars": [], "Movie_Budget": []}
    print ("Your Movies")
    amount_in_list = int(input("How many Movies? "))

    x = 1
    while x <= amount_in_list:
        film = input ("Name of film ... ")
        stars = input ("Main stars ...")
        budget = input ("Budget ...")
        movieinfo["Movie_Name"].append(film)
        movieinfo["Movie_Stars"].append(stars)
        movieinfo["Movie_Budget"].append(budget)
        x+=1

    return movieInfo

rawDescription: Python List in List ("Stuck")

description: Python List in List ("Stuck")


code:
result = result.loc[mask]
result = result.append(row)

rawDescription: pandas: how to aggregate a subset of groupby rows into a single row?

description: Pandas: how to aggregate a subset of groupby rows into a single row


code:
class MasterProcessProxy(object):

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

    # This is called when an attribute is requested on the object.
    def __getattr__(self, name):
        # Create a dynamic function that sends a command through the pipe
        # Keyword arguments are sent as command arguments.
        def proxy(**kwargs):
            self.pipe.send([name, kwargs])
        return proxy

rawDescription: Python use a virtual class to apply a generic "pipe" pattern


code:
print(a, file=my_file)
# ...
print(b, file=my_file)
# ...
print(c, file=my_file)

rawDescription: Three ways to print in Python -- when to use each?


code:
list_of_lists = []
for key in mydict.keys():
    for k in mydict[key].keys():
        this_entry = [k]
        for ordered_field in my_ordered_fields:
            this_entry.append(mydict[key][k][ordered_field])
        list_of_lists.append(this_entry)

rawDescription: Inserting complex dictionaries into a sqlite database?


code:
save_as_binary = string_version.encode('utf-8')
print(save_as_binary)

rawDescription: How to translate from a hexdigest to a digest and vice-versa?

description: Translate from a hexdigest to a digest and vice-versa


code: colnames = [ i[1] for i in cur.fetchall() ]

rawDescription: pySQLite integration to pyGtk treeview

description: PySQLite integration to pyGtk treeview


code:
t = Test()
t.lst
t.dic
t.update_values()
t.lst
t.dic

rawDescription: python update class's list or dictionary when variables change elsewhere

description: Python update class's list or dictionary when variables change elsewhere


code:
var_map = [None, 'some_value', 'another_one', 'text_string', 'one_more', 'final_str']
var = var_map[a]

rawDescription: Reduced if/else block

description: Reduced if/else block


code: b = [str(letter) for letter in a if letter.isalpha()]

rawDescription: checking if the given inputted word is a palindrome or not

description: Checking if the given inputted word is a palindrome or not


code: all(1 in x for x in (a, b, c, d))

rawDescription: Test if value exists in several lists

description: Test if value exists in several lists


code:
#!/usr/bin/env python
from subprocess import Popen

with named_pipes(n=2) as paths:
    someprogram = Popen(['someprogram'] + paths)
    processes = []
    for path, command in zip(paths, ['someprocess', 'anotherprocess']):
        with open(path, 'wb', 0) as pipe:
            processes.append(Popen(command, stdout=pipe, close_fds=True))
    for p in [someprogram] + processes:
        p.wait()

rawDescription: Multiple pipes in subprocess

description: Multiple pipes in subprocess


rawDescription: Using scipy's kmeans2 function in python


code:
# the with statement is not really necessary, but recommended.
with open("/var/log/dpkg.log") as logfile:
    for line in logfile:
        # covers also 'installed', 'half-installed', …
        # for deeper processing you can use re module, but it's very likely not necessary
        if "install" in line.split()[3]:  # or [4]
            # your code here
            print(line)

rawDescription: Get the nth column out of a text document (Python 3)


code:
import numpy as np
f = lambda h: (np.exp(-2*mun*(h/sigma+1.166))-1+2*mun*(h/sigma+1.166))/(2*mun**2)-ARL0

rawDescription: translating matlab code to python: optmizing numerical functions

description: Translating matlab code to python: optmizing numerical functions


code: first

rawDescription: How do I pass a string into subprocess.Popen in Python 2?

description: Pass a string into subprocess.Popen in Python 2


code:
class Foo:
    def bar(self, x):
        x.append(3.14)

foo = Foo()

rawDescription: How to pass non-const std::vector<double> by reference to Python with boost::python?

description: Pass non-const std::vector<double> by reference to Python with boost::python


rawDescription: Python script cannot read Popen output until process is finished (on Windows)


code:
Z = np.zeros((10,20,3), dtype=int)
np.where(((Z == S[:,None,None,:]).all(3)).any(0))
np.where((np.in1d(Z,S).reshape(Z.shape)).all(2))
np.column_stack((np.where(((Z == S[:,None,None,:]).all(3)).any(0))))
np.column_stack((np.where((np.in1d(Z,S).reshape(Z.shape)).all(2))))

rawDescription: Find indices of specific rows in a 3d numpy array


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

rawDescription: How do I pass arguments via bash to Python when running a script

description: Pass arguments via bash to Python when running a script


code:
with open('infilename', 'r') as infile, open('outfilename', 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        row[5] = re.sub(r'^0{3}', '', row[5])
        writer.writerow(row)

rawDescription: stripping the zeros in csv with python

description: Stripping the zeros in csv with python


code:
import see_below as sb
dict = sb.workbookToDict(your_file)
output = []
this_location = None
for row in dict[relevant_sheet_name]:
    output_row = row
    if row['Location'] is not None:
        this_location = row['Location']
    else:
        output_row['Location'] = this_location

rawDescription: Python script to manipulate excel sheets by auto-filling spaces in columns


code:
self.SetLexer(stc.STC_LEX_CONTAINER)
self.custlex = SCT_LEX_ERLANG_IDNOISE(self)

rawDescription: wxPython StyleSetSpec and SetLexer not working?

description: WxPython StyleSetSpec and SetLexer not working


code:
stringy = ''.join([stringy for _ in range(100)])
timeit.timeit('[item for item in stringy.split() if item.isdigit()]', 'from __main__ import stringy', number=10000)
timeit.timeit('integers.findall(stringy)', 'from __main__ import stringy, integers', number=10000)

rawDescription: Python 2.7: Faster/better way to extract all integer values from a string?


code:
w = Word(word='something new')
w.sentences = [Sentence(text='there is somethine new')]
session.add(w)
session.commit()
session.query(WordInSentence).one().word_id
session.query(Word).one().word
session.query(Sentence).one().text

rawDescription: Bidirectional relationship with association_proxy


code:
_Matrix = []
for row in  zip(*Matrix):
    #all(e != ['-'] for e in row)
    _cond = True
    for e in row:
        if e != ['-']:
               _cond = False
               break
    if not _cond:
        _Matrix.append(e)

rawDescription: Delete Column IF all column cell contain NULL value


code:
def roll_up(tree, thresh = 2, level=5):
    for n in tree:
        if n.dodelete or n.visited:
            continue
        if n.level != level:
            continue
        sub_tree = tree.get_by_path(n.id)
        if sub_tree is None:
            continue
        sub_tree_stack = []
        for child in tree.get_by_path(n.id).children:
            if child.val is not None and child.val <= thresh:
                sub_tree_stack.append((child.name, child.id, child.val))
                # Also mark this for deletion
                tree.get_by_path(child.id).dodelete = True
        if sub_tree_stack:
            # Get the parent for these nodes
            node_name = n.name + ": [" + ",".join([subnode[0] for subnode in sub_tree_stack]) + "]"
            node_val = sum([subnode[2]for subnode in sub_tree_stack])
            node_id = sorted([subnode[1] for subnode in sub_tree_stack])[0]
            parent_name = n.parent.name
            parent_level = n.parent.level
            parent_id= n.parent.id
            # Now ensure that you delete the old node before adding new
            tree.get_by_path(n.id).dodelete = True

            tree.get_by_path(parent_id).add_child(Node(node_name, val=node_val, id = n.id, visited=True) )
    return tree

rawDescription: clustering based on thresholds

description: Clustering based on thresholds


code:
sage: cc.scale(3)
6

rawDescription: Changing dynamically one method of a class


code:
keys, values = zip(*d.items())
dict(zip(keys, values))

rawDescription: deconstructing and reconstructing python dictionary

description: Deconstructing and reconstructing python dictionary


code:
for i in range(len(T)):
    q = 1/(1-np.exp(-h*freq/kb/T[i]))
Q = np.prod(q)

rawDescription: python for loop for creating a 2D array form 2 1D array

description: Python for loop for creating a 2D array form 2 1D array


code:
x = tab.cols.x
y = tab.cols.y
z = tab.cols.z
expr = tb.Expr('x+a*y+b*z')
unsorted_res = expr.eval()
idx = z.read_indices()
sorted_res = unsored_res[idx]

rawDescription: What is the most memory efficient way to combine read_sorted and Expr in pytables?


code:
from string import Template

f = Template('{$score-$numrep}')

f.substitute(d)

rawDescription: List of dictionaries - how to format print output


code:
rem_btn = QtGui.QPushButton("X")
rem_btn.clicked.connect(self.remove_item)
layout.addRow(string, rem_btn)

rawDescription: Layout not adding correctly, seems that its not erasing previous widgets


code:
from itertools import product
from operator import mul

L1 = ['b', 'c', 'd', 'e', 't', 'w', 'x', 'y', 'z']
L2 = ['the onion', 'be your self', 'great zoo', 'x men', 'corn day']

phrase_map = {}

for phrase in L2:
    word_count = {word: phrase.count(word) for word in L1 if word in phrase}

    occurrence_map = {}
    for perm in product(word_count, repeat=2):
        occurrence_map[perm] = reduce(mul, (word_count[key] for key in perm), 1)

    phrase_map[phrase] = occurrence_map

rawDescription: Python Co-occurrence matrix of words and phrases


rawDescription: Python code has the following import

description: Python code has the following import


code:
from lxml import etree

parser = etree.XMLParser(remove_blank_text=True)
tree = etree.fromstring("""<Title>
    <Playcount>1</Playcount>
     <Genre>Adventure</Genre>
     <Genre>Comedy</Genre>
     <Genre>Action</Genre>
     <someTag>Text</someTag>
    </Title>""", parser=parser)

rawDescription: Python ElementTree XML Modifying Elements with Multiple Values


code:
import pylab as P
import numpy as np

# Define data
# Define numBoxes

P.figure()

bp = P.boxplot(data)

for i in range(numBoxes):
    y = data[i]
    x = np.random.normal(1+i, 0.04, size=len(y))
    P.plot(x, y, 'r.', alpha=0.2)

P.show()

rawDescription: Adding a scatter of points to a boxplot using matplotlib


code:
import xlrd
import csv

with xlrd.open_workbook('a_file.xls') as wb:
    sh = wb.sheet_by_index(0)  # or wb.sheet_by_name('name_of_the_sheet_here')
    with open('a_file.csv', 'wb') as f:
        c = csv.writer(f)
        for r in range(sh.nrows):
            c.writerow(sh.row_values(r))

rawDescription: How to save an Excel worksheet as CSV from Python (Unix)?

description: Save an Excel worksheet as CSV from Python (Unix)


code:
class Distance(object):

    METER = 1
    FOOT = 0.3048
    MILE = 1609.344
    INCH = 0.0254
    UNITS = {'meters': METER,
         'mts': METER,
         'mt': METER,
         'feet': FOOT,
         'foot': FOOT,
         'ft': FOOT,
         'miles': MILE,
         'mls': MILE,
         'ml': MILE,
         'inch': INCH,
         }
    def __init__(self, s):
        self.number, unit = s.split()
        self._convert(unit)

    def _convert(self, unit):
        self.number = float(self.number)
        if self.UNITS[unit] != 1:
            self.number *= self.UNITS[unit]

    @ property
    def meters(self):
        return self.number

    @ meters.setter
    def meters(self, v):
        self.number = float(v)

    @ property
    def miles(self):
        return self.number / self.MILE

    @ miles.setter
    def miles(self, v):
        self.number = v
        self._convert('miles')

    @ property
    def feet(self):
        return self.number / self.FOOT

    @ feet.setter
    def feet(self, v):
        self.number = v
        self._convert('feet')

    @ property
    def inch(self):
        return self.number / self.INCH

    @ inch.setter
    def inch(self, v):
        self.number = v
        self._convert('inch')

rawDescription: The dateutil.parser.parse() of distance strings?


code:
def f(z):
    exec("Y="+str(z),locals())
    exec("def closure():\n return Y*2",locals())
    return eval("closure")

rawDescription: How to dynamically construct a closure's namespace "pythonically"

description: Dynamically construct a closure's namespace "pythonically"


code:
exclude = set('why kid is upset'.split())
list_of_strings = ['why my kid is upset',
                   'why beautiful kid is upset',
                   'why my 15 years old kid is upset',
                   'why my kid is always upset']
res = []
for item in list_of_strings:
    words = item.split()
    res.append(' '.join(word for word in words if word not in exclude))
    exclude.update(set(words))
print(res)

rawDescription: Extract single words or phrases from list of strings which are not in base string


rawDescription: Remove NaN and convert to float32 in Python Pandas


code: answer = np.array([Z(i[0],i[1]) for i in x]).reshape(15,1)

rawDescription: Passing multiple columns of a 2D array into a lambda function and returning a single column array


code: A = A.loc[(A.coordinate <= one_center - exclusion) | (A.coordinate >= one_center + exclusion)]

rawDescription: Memory usage accumulated in while loop

description: Memory usage accumulated in while loop


rawDescription: Polygon or free-form shape drawing with OpenCV Python


code:
stack = ['testing', 'this']
stack.pop()
stack

rawDescription: Adding a string with spaces to a stack

description: Adding a string with spaces to a stack


code:
radii = np.random.normal(10, 3, 100)
points = np.array([spherical_to_cartesian([r, 2 * np.pi * u, np.arccos(2*v - 1)]) for r,u,v in zip(radii, U,V)])

rawDescription: how to generate new points as offset with gaussian distribution for some points in spherical coordinates in python

description: Generate new points as offset with gaussian distribution for some points in spherical coordinates in python


code: result = map(sum, a)

rawDescription: python sum the values of lists of list

description: Python sum the values of lists of list


code:
from collections import defaultdict
values = defaultdict(lambda : defaultdict(list))
for wall in wallList:
    if 'broken' in wall:
        values[wall[:-3].replace('_broken', '')]['broken'].append(wall)
    else:
        values[wall[:-3]]['default'].append(wall)

values.items()

rawDescription: Python: Sort a list into multiple lists or dictionary


rawDescription: Python Data Structure Selection

description: Python Data Structure Selection


rawDescription: Not sure how to parse this

description: Not sure how to parse this


code:
import re
escaped = re.escape(a_string)

rawDescription: How to escape special characters of a string with single backslashes

description: Escape special characters of a string with single backslashes


code:
def spam(self):
    return 'ham'
body = {'bar': 'baz', 'spam': spam}

Foo = type('Foo', (Base1, Base2), body)

rawDescription: Python - type(name,bases,dict)

description: Python - type(name,bases,dict)


code:
i = np.ones((N, 1))
i

rawDescription: Implement this situation in numpy

description: Implement this situation in numpy


code:
import sys

def faker(original, fakefun):

    original = os.getenv
    themod = sys.modules[original.__module__]
    thename = original.__name__

    def dummy(*a, **k):
        try: return fakefun(*a, **k)
        except BaseException: return original(*a, **k)

    setattr(themod, thename, dummy)
    yield
    setattr(themod, thename, original)

rawDescription: Pythonic way to intercept calls to a function?


code:
class SomeBorgClass:
    __metaclass__ = PerArgsBorgMeta

rawDescription: Singleton/Borg pattern based on different parameters passed while creating the object


code:
import itertools
notlast = lambda lst:itertools.islice(lst, 0, len(lst)-1)

rawDescription: How to treat the last element in list differently in Python?

description: Treat the last element in list differently in Python


rawDescription: Pyparsing - Finding Nested Polynomials

description: Pyparsing - Finding Nested Polynomials


code:
peter_mail = {
              "toname": "Peter",
              "toemail": "p@tr",
              "subject": "Hi",
             }
mail.sendmail('from', 'to', content.format(**peter_mail))

rawDescription: Is there any way to use variables in multiline string in Python?


rawDescription: Calling Python Function with string argument


code:
def main():
    rows=3
    col=4
    values=[[0,0,0,0],
        [0,0,0,0],
        [0,0,0,0]]
    for i in range(rows):
        print("".join('.' for j in range(col)))

main()

rawDescription: Printing 2D-array in a grid

description: Printing 2D-array in a grid


code:
from setuptools import setup

requires = [
    'pyramid',
    'pyramid_chameleon',
    'deform',
    'sqlalchemy',
    'pyramid_tm',
    'zope.sqlalchemy'
]

setup(name='tutorial',
      install_requires=requires,
      entry_points="""\
      [paste.app_factory]
      main = tutorial:main
      [console_scripts]
      initialize_db = yourwebapp.some_script:main
      """,
)

rawDescription: Read information stored in an .ini file

description: Read information stored in an .ini file


rawDescription: Rewrite a Python Code

description: Rewrite a Python Code


rawDescription: Editing a string in an Array

description: Editing a string in an Array


code:
replacements = {
    '5': '4',
    'a': 'b',
}
trt = [replacements.get(word, word) for word in trt]

rawDescription: Python - how to replace string in a list?


code:
import subprocess as sp
sp.call('cls',shell=True)

rawDescription: Python: Clear screen in shell

description: Python: Clear screen in shell


code: ", ".join(item[0][i][1] for i in range(len(item[0])) if item[0][i][1] not in blockedList)

rawDescription: Python: Short way implementation

description: Python: Short way implementation


code:
import random
myUser = User()

b = random.choice([2309,1897,2307])
function( myUser , b )

rawDescription: Use a variable in a function

description: Use a variable in a function


code:
def visit_FunctionDecl(self, node):
    ...
    node.params[-1].set_global()
    node.params[-1].type = ct.POINTER(ct.c_float)()
    node.params.append(SymbolRef('block', ct.POINTER(ct.c_float)()))
    node.params[-1].set_local()
    node.defn = node.defn[0]
    ...
    return node

rawDescription: How do we allocate to local memory in Ctree within a kernel function


code: comments = Comment.query.all()  # perhaps there's an order_by

rawDescription: Iterate through Python Flask/Jinja2 adjacency list


code: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)8s\t%(message)s', )

rawDescription: Is there any way to change the log message format in scrapy?


code:
import shutil

def recwrite(filelist):
    if len(filelist) > 0:
        shutil.copyfile(filelist[0], "input.txt")
        recwrite(filelist[1:])

rawDescription: Python Copying Files

description: Python Copying Files


code: np.argmin(large.cumsum() < limit)

rawDescription: Find index in array to which the sum of all elements is smaller than a limit, quickly


code: {"test_id1" : {"resultValue": resultValue, "timeChecked" : timeChecked }}

rawDescription: python dictionary with two values for each key or class?

description: Python dictionary with two values for each key or class


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

description: Create a hyperlink with a Label in Tkinter


code: {d: [to_time(sum(map(parse_time, ts)))] for d, ts in times.items()}

rawDescription: Pythonic way to add a list of time

description: Pythonic way to add a list of time


code:
A = type('A', (object,), {'my_class_variable':'hello'})
A.my_class_variable

rawDescription: Is it possible to create a class level variable dynamically using python's type function?


code:
date = dt.datetime(2012, 8, 12, 10)    # naive datetime
print(date)
# 2012-08-12 10:00:00

# localize converts naive datetimes to timezone-aware datetimes.
date_in_newyork = newyork.localize(date)  # timezone-aware datetime
print(date_in_newyork)
# 2012-08-12 10:00:00-04:00

rawDescription: What is the local timezone

description: What is the local timezone


code:
import itertools

def gen_users(users, total):
    # assert users and total > 0
    for i, user in enumerate(itertools.islice(users, total)):
        yield user
    for _ in range(total - i - 1): # i -> last index
        yield user

list(gen_users([1,2,3], 5))
list(gen_users([1,2,3], 2))

rawDescription: Is there a better way to define this generator?


code:
#!/usr/bin/env python3
import time
import socket

data = b'''\
HTTP/1.1 200 OK\r\n\
Connection: keep-alive\r\n\
Content-Type: text/html\r\n\
Content-Length: 6\r\n\
\r\n\
Hello!\
'''

def main(server_address=('0.0.0.0', 8000)):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    server.bind(server_address)
    server.listen(5)
    while True:
        try:
            client, client_address = server.accept()
            handle_request(client, client_address)
        except KeyboardInterrupt:
            break

def handle_request(client, address):
    with client:
        client.sendall(data)
        time.sleep(5)  # Keep the socket open for a bit longer.
        client.shutdown(socket.SHUT_RDWR)

if __name__ == '__main__':
    main()

rawDescription: Web server in Python 2.7: Browser not displaying page


code:
global_settings = {'player position' : (50, 50)}
# The player is at X cord 50 and Y cord 50.

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
Name=Jani
Name=Asho

rawDescription: Create a search engine using python ( search from an XML file only )


code:
import pandas as pd, csv
df = pd.read_fwf("filename.txt", widths=(5,11,5), names=["TypeA", "TypeB", "Charles"])
df.to_csv("out.csv", index=False, quoting=csv.QUOTE_ALL)

rawDescription: How to get txt file into CSV?

description: Get txt file into CSV


code:
MAX_FIELD_LEN = 8

def main():
    products = {}
    product_location  = {}
    location = 0
    # This is the file directory being made.
    with open('stockfile.txt', 'r+') as f:
        # This is my file being opened.

        for line in f:
            # keep track of each products location in file  to overwrite with New_Stock
            product_location[line.split(',')[0]] = location
            location += len(line)
            # Need to strip to eliminate end of line character
            line = line[:-1]
            # This gets rid of the character which shows and end of line '\n'
            row = line.split(',')
            # The row is split by the comma
            products[row[0]] = [row[1], row[2], row[3]]
            # The products are equal to row 1 and row 2 and row 3. The GTIN is going to take the values of the product and price so GTIN 12345678 is going to correspond to Fridge and 1.

        print(products)
        total = 0

        while True:
            GTIN = input('Please input GTIN: ')
            # To terminate user input, they just need to press ENTER
            if GTIN == "":
                break
            if (GTIN not in products):
                print('Sorry your code was invalid, try again:')
                break

            row = products[GTIN]
            description, value, stock = row
            print('Stock data: ')
            print('GTIN \t\tDesc. \t\tStock \t\tValue')
            print(GTIN,'\t',description,'\t', stock, '\t', value)

            quantity = input('Please also input your quantity required: ')
            row[2] = str(int(stock) - int(quantity))
            product_total = int(quantity) * int(value)
            for i in range(len(row)):
                row[i]  = row[i].rjust(MAX_FIELD_LEN)
            New_Stock = GTIN.rjust(MAX_FIELD_LEN) + ',' + ','.join(row) + '\n'
            #print(New_Stock, len(New_Stock))
            f.seek(product_location[GTIN])
            f.write(New_Stock)
            print('You bought: {0} {1} \nCost: {2}'.format(GTIN, description, product_total))

            total = total + product_total
        f.close()
        print('Total of the order is £%s' % total)

main()

rawDescription: How to append a file and take out a specific line python 3

description: Append a file and take out a specific line python 3


code:
from setuptools import setup

setup(
    name="foo",
    version = "0.1",
    py_modules=['foo'],
    entry_points = {
        'console_scripts': ['foo = foo:main']
    }
)

rawDescription: install Python module both as module and as script

description: Install Python module both as module and as script


code: [tr.findAll('td')[-1].text for tr in soup.findAll('tr')]

rawDescription: BeautifulSoup HTML extracting tabular data


code:
df2 = pd.DataFrame(np.triu(df))
df2

rawDescription: Geo Pandas Data Frame / Matrix - filter/drop NaN / False values


code:
key = lambda x: x.date()
df.groupby(key).sum()
ts.groupby(key).sum()

rawDescription: Data Cleaning Consequence on a Pre-Built Index


code:
import shelve
data = {'foo':'foo value'}
d = shelve.open('myfile.db')
d['data'] = data
d.close()

rawDescription: Python - Saving Data outside of program

description: Python - Saving Data outside of program


code:
import requests
payload = {"do": "http://webpage.com/?secondary=parameter"}
r = requests.get("http://myserver.appspot.com/", params=payload)

rawDescription: Sending a URL in a GET request to a Python server on Google App Engine


code: "string1 string2 None string4".replace('None ', '')

rawDescription: How do I avoid None as result of a query?

description: Avoid None as result of a query


code: [MyClass(*args) for args in objects.values()]

rawDescription: create multiple objects of a class with different arguments

description: Create multiple objects of a class with different arguments


code:
class SpecificUserProfile(UserProfile):
    referrer = models.ForeignKey('self', related_name='referred')

rawDescription: Defining the name of a ManyToOne relationship in Django


code:
with open(CRACKED) as crackedfile:
    cracked = dict(map(str.strip, line.split(':')) for line in crackedfile if ':' in line)

rawDescription: two lists, faster comparison in python

description: Two lists, faster comparison in python


code:
def play():
    sounds[index].play()
    index = (index + 1) % len(sounds)

rawDescription: Python Kivy: Play sound multiple times at once


code:
x = pd.DataFrame([
    ['best', 'a', 'x'],
    ['worst', 'b', 'y'],
    ['best', 'c', 'x'],
    ['worst','d', 'y'],
    ['worst','d', 'y'],
    ['best','d', 'y'],
    ['best','d', 'z'],
    ['best','d', 'z'],
], columns=['a', 'b', 'c'])

x.groupby(by=['c']) \
 .filter(lambda g: g['a'] == 'best') \
 .groupby(by=['b'], as_index=False) \
 .first() \
 .sort(axis=1)  # the columns get out of order in the second groupby

rawDescription: Filtering duplicates from pandas dataframe with preference based on additional column


code:
class PostManager(object):
    @staticmethod
    def getPost(id):
        return Post.object.get(pk=id)

    @staticmethod
    def addComment(post, comment_text, user):
        comment = Comment(post=post, user=user, text=comment_text)
        # check stuff
        comment.save()
    ...

rawDescription: Django newbie having hard time with models and reusable business logic


code:
for l in lists:
    l[:] = [elem for i, elem in enumerate(l) if i not in idx_to_remove]

rawDescription: Stripping empty elements from lists

description: Stripping empty elements from lists


code: import json

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

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


code: print('The join output is: ' + joined + ' The length is: ' + str(len(seq)))

rawDescription: Print and join statement in python

description: Print and join statement in python


code: content2[:] = [float(x) if x else None for x in content2]

rawDescription: python changing integers/ floats to None in list

description: Python changing integers/ floats to None in list


code:
import serial
if __name__ == '__main__':
    with serial.Serial(port='/dev/ttyUSB0', baudrate=9600, timeout=1,
                       xonxoff=False, rtscts=False, dsrdtr=True) as s:
        for line in s:
            print(s)

rawDescription: get data from usb weatherboard using PySerial

description: Get data from usb weatherboard using PySerial


rawDescription: Python Multiple Variable Declaration

description: Python Multiple Variable Declaration


code:
# views.py

from .forms import DocumentForm

def document_list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            new_doc = form.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('ReadMyPaper.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

rawDescription: Adding additional data fields when uploading file to Database w/ Django


rawDescription: pandas - with restructuring data in data frame

description: Pandas - with restructuring data in data frame


code:
if attr_type == 'edge':
    accepted = pydot.EDGE_ATTRIBUTES
elif attr_type == 'graph':
    accepted = pydot.GRAPH_ATTRIBUTES
elif attr_type == 'node':
    accepted = pydot.NODE_ATTRIBUTES
else:
    raise Exception("Invalid attr_type.")

d = dict( [(k,v) for (k,v) in attrs.items() if k in accepted] )

rawDescription: How to represent networkx graphs with edge weight using nxpd like outptut

description: Represent networkx graphs with edge weight using nxpd like outptut


code:
class BreakIt(Exception): pass
try:
    count = 1
    for index, items in enumerate(sample_final_list):
        sample_1_dict_normalized = {}
        for index, (genes, values) in enumerate(items):
            sample_1_dict_normalized[genes] = values
            count = count + 1
            if count == 29595:
                raise BreakIt
except BreakIt:
    pass

rawDescription: Create multiple dictionaries from a single iterator in nested for loops


code:
t_plus_one.py
#!/usr/bin/env python

from StringIO import StringIO
import plus_one
import unittest

class TestPlusOne(unittest.TestCase):

    def test_main_returns_zero_on_success(self):
        self.assertEquals(plus_one.main(['test', '1']), 0)

    def test_main_returns_nonzero_on_error(self):
        self.assertNotEqual(plus_one.main(['test']), 0)

    def test_get_number_returns_second_list_element_as_integer(self):
        self.assertEquals(plus_one.get_number(['anything', 42]), 42)

    def test_get_number_raises_value_error_with_string(self):
        self.assertRaises(ValueError, plus_one.get_number, ['something',
                                                            'forty-two'])

    def test_get_number_raises_index_error_with_too_few_arguments(self):
        self.assertRaises(IndexError, plus_one.get_number, ['nothing'])

    def test_plus_one_adds_one_to_number(self):
        self.assertEquals(plus_one.plus_one(1), 2)

    def test_output_prints_input(self):
        saved_stdout, plus_one.sys.stdout = plus_one.sys.stdout, StringIO('_')
        plus_one.output('some_text')
        self.assertEquals(plus_one.sys.stdout.getvalue(), 'some_text\n')
        plus_one.sys.stdout = saved_stdout

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

rawDescription: How to test command line scripts with nose?

description: Test command line scripts with nose


code: numpy.random.randint(2, size=100)

rawDescription: An explanation of randint(2) < 1 in python, I cannot understand what the < 1 does


code: value = json.dumps({'data': sorted(data, key=lambda x: x['count'], reverse=True)})

rawDescription: Order list of Json object by value using python


code:
def search_func(lst, x):
    if len(lst) <= 0:   # this is how you test if the list is empty
        return "failure"
    i = 0               # we'll use this as index to traverse the list
    while i < len(lst): # this is how you test to see if the index is valid
        if lst[i] == x: # this is how you check the current element
            return "success"
        i += 1          # this is how you advance to the next element
    else:               # this executes only if the loop didn't find the element
        return "failure"

rawDescription: Search function python

description: Search function python


code:
with open('file') as f:
    next(f)
    content = [x.strip().split()[1:] for x in f]

rawDescription: When reading in a txt matrix, how can i skip first column


code:
s = 'More stuffText inside of the bodymore sample textand then more text and then another and then another  and then endRandom text'
''.join(''.join(s.split('')[1:]).split('')[:-1])

rawDescription: How can I extract the contents of the <body> tag?

description: Extract the contents of the <body> tag


code: [bin(x) for x in range(251)]     # produces list of binary from 0-250

rawDescription: Printing Binary in Python

description: Printing Binary in Python


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

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


code:
import Levenshtein

input_lines = [
    "AAAAAAAAAAAA",
    "TTTTTTTTTTTT",    # Diff by >1 char: Keep
    "AAAAACAAAAAA",    # Diff by 1 char: Delete
    "AAAAACAAACAA",    # Diff by 2 char: Keep
    "AAAAAAAAAAAA",    # Diff by <1 char: Delete
    ]
output_lines = []

for current_line in input_lines:
    for previous_line in output_lines:
        if Levenshtein.hamming(previous_line, current_line) < 2:
            break
    else:
        output_lines.append(current_line)

print('\n'.join(output_lines))

rawDescription: Identify Similar Strings in Python

description: Identify Similar Strings in Python


rawDescription: Pandas: how to plot yearly data on top of each other


code:
c = C()
import gc
gc.collect()  # nothing happens
c = None  # now c is in a trash self-cycle
gc.collect()  # c.a.__del__ *is* called

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


code:
def test_random_fruit(self, fruits_list):
                          # ^ pass argument
    fruits_list = ['kiwi']
              # ^ overwrite it
    ...

rawDescription: How do I patch or modify a list inside of a function when running a unit test?

description: Patch or modify a list inside of a function when running a unit test


code:
class UserAttributes(User):
    last_session_key = models.CharField(blank=True, null=True, max_length=40)

rawDescription: django one session per user

description: Django one session per user


code:
class ExampleGrid(JqGrid):
    model = SomeFancyModel # could also be a queryset
    fields = ['id', 'name', 'desc'] # optional
    url = reverse('grid_handler')
    caption = 'My First Grid' # optional
    colmodel_overrides = {
        'id': { 'editable': False, 'width':10 },
    }

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

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


code:
def date_compare(model, row1, row2, user_data):
    # Returns :
    # - a negative integer if iter1 sorts before iter2,
    # - zero if they are equal,
    # - a positive integer if iter2 sorts before iter1.

    sort_column, _ = model.get_sort_column_id()
    date1 = model.get_value(row1, sort_column)
    date2 = model.get_value(row2, sort_column)

    # We split the date string to an array :
    #  0  |   1   |   2  |    3    |    4
    # day | month | hour | minutes | seconds
    values1 = re.split("[ /:]", date1)
    values2 = re.split("[ /:]", date2)

    if values1[1] < values2[1] :
        return -1
    elif values1[1] == values2[1] : # same month => we compare by day
        if values1[0] < values2[0] :
            return -1
        elif values1[0] == values2[0] : # same month and day => we compare by hour
            if values1[2] < values2[2] :
                return -1
            elif values1[2] == values2[2] : # same month, day and hour => we compare by minute
                if values1[3] < values2[3] :
                    return -1
                elif values1[3] == values2[3] : # same month, day, hour and minute => we compare by second
                    if values1[4] < values2[4] :
                        return -1
                    elif values1[4] == values2[4] : # same month, day, hour, minute and second => it's same date !
                        return 0
                    else :
                        return 1
                else :
                    return 1
            else :
                return 1
        else :
            return 1
    else :
        return 1

rawDescription: Sort a gtk.TreeColumn by date value

description: Sort a gtk.TreeColumn by date value


code:
from django.shortcuts import get_object_or_404

@login_required
def profile(request, user_id):
    context_dict = {}
    u = get_object_or_404(User, pk=user_id)
    context_dict['user'] = u
    r = reg.Reg.objects.get(user=u)
    context_dict['reg'] = r
    return render(request, 'core/reg.html', context_dict)

rawDescription: get_absolute_url with parameters

description: Get_absolute_url with parameters


code:
serializer = UserSerializer(users)
return Response(serializer.data)

rawDescription: using Django Rest framework to serialize custom data types and return response

description: Using Django Rest framework to serialize custom data types and return response


code:
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication

class Main(QTreeView):
    def __init__(self):
        QTreeView.__init__(self)
        model = QFileSystemModel()
        model.setRootPath('C:\\')
        self.setModel(model)
        self.doubleClicked.connect(self.test)

    def test(self, signal):
        file_path=self.model().filePath(signal)
        print(file_path)

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

rawDescription: Python: PyQt QTreeview example - selection


code:
for line in f:
    if "-Version=" in line:
        _, version = line.split("=")
        version = version.strip()  # in case there's trailing whitespace
        break

rawDescription: Reading for a specific value in a file

description: Reading for a specific value in a file


rawDescription: Replace specific values in a matrix using Python


code:
decoded = data.decode('base64')
f = cStringIO.StringIO(decoded)
image = Image.open(f)
needle = image.load()

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

description: Detect if image is present on screen


code:
import pycurl

def prepare_curl_socks5(curl):
    curl.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)

rawDescription: Socks proxy in tornado AsyncHttpClient

description: Socks proxy in tornado AsyncHttpClient


code:
from django import template

from csv_app.models import csv_profile

register = template.Library()

@register.inclusion_tag('_tag_csv_preview.html')
def csv_preview(pk):
    csv = csv_profile.get(pk=pk)
    return {'preview': csv.csv_sample()}

rawDescription: Calling a model function from a template


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

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


code:
from functools import update_wrapper

def predicate(func):
    """Decorator that constructs a predicate (``P``) instance from
    the given function."""
    result = P(func)
    update_wrapper(result, func)
    return result

rawDescription: Pointfree function combination in Python


code:
c=[]

for key,value in b.items():
        value['key']=key
        c.append(value)
#output:[{'yy': '3', 'xx': '2', 'key': 'A'}, {'yy': '5', 'xx': '4', 'key': 'B'}]

rawDescription: How to access this dictionary of dictionaries with a numbered index in Python?

description: Access this dictionary of dictionaries with a numbered index in Python


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


code:
def bar(self, x):
    ...

rawDescription: Equivalent of struct members in Python (mainly for documentation and reading code)


code:
from lxml import etree as ET

x = ET.parse("input.xml")
d = {}
for node in x.iter('NameScope'):
    int_name = str(node.find('Naming/InterfaceName').text)
    d[int_name] = {
        'cost': str(node.find('Cost').text),
        'area': node.xpath(".//preceding::AreaID")[0].text
    }

print(d)

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


code:
from Queue import Queue
from threading import Thread
from time import sleep
tasks = Queue()
map(tasks.put, candidates)
maxthreads = 50
delay = 0.1
try:
    threads = [Thread(target=search_sl, args=tasks.get()) \
               for i in xrange(0,maxthreads) ]
except Queue.Empty:
    pass
map(lambda t:t.start(), threads)

while not tasks.empty():
    threads = filter(lambda t:t.isAlive(), threads)
    while len(threads) < maxthreads:
        try:
            t = Thread(target=search_sl, args=tasks.get())
            t.start()
            threads.append(t)
        except Queue.Empty:
            break
    sleep(delay)

while(any(map(lambda t:t.isAlive(), threads))): sleep(delay)

rawDescription: python, how to incrementally create Threads

description: Python, how to incrementally create Threads


code:
class class_sample(object):

    def __init__(self):
        self.x = ["I", "am", "doing", "something", "with", "Python"]

rawDescription: How to run project files using Anaconda from any directory in Windows

description: Run project files using Anaconda from any directory in Windows


rawDescription: spliting a list into [ ]

description: Spliting a list into [ ]


code:
import pandas as pd
import pandas.tseries.offsets as pto
import numpy as np

# Create some ome test data
d_size = 15
df = pd.DataFrame({"value": np.arange(d_size)}, index=pd.date_range("2014/11/03", periods=d_size, freq=pto.Milli()))

# Define periods to define groups (ticks)
ticks = pd.date_range("2014/11/03", periods=d_size/3, freq=5*pto.Milli())
# find nearest indexes matching the ticks
index_ticks = np.unique(df.index.searchsorted(ticks))

# make a dataframe with the group ids
dgroups = pa.DataFrame(index=df.index, columns=['Group id',])

# sets the group ids
for i, (mini, maxi) in enumerate(zip(index_ticks[:-1], index_ticks[1:])):
    dgroups.loc[mini:maxi] = i

# update original dataframe
df['Group id'] = dgroups['Group id']

rawDescription: Grouping records with close DateTimes in Python pandas DataFrame


code:
total_score = 0
for student in name_list:
    total_score += student.speed
average = total_score / len(name_list)

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

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


code:
class MyClass(MyBaseClass):
    def run(self):
        _normal = numpy.random.normal
        _Lappend = self.L.append
        while True:
            ...
            _Lappend(_normal(0,1))

rawDescription: Putting a function to a local namespace to speeding up access taking descriptors into account


code: fOWOO = firstOperationWithOneOperator

rawDescription: Python: Dealing with a second operator in calculator


code:
def find_indexes(lst, val):
    return [i for i,v in enumerate(lst) if v == val]

rawDescription: Something in python similar to index method for multiple ocurrences


rawDescription: Python: how to create a submatrix discretizing a circle?


rawDescription: Processing two CSV files in parallel

description: Processing two CSV files in parallel


code:
# The compact representation
{'root': {'n1': {'l1': {}, 'l2': {}}, 'n2': {'l3': {}, 'l4': {}}}}

# The desired representation
[{'children': [{'children': [{'children': [], 'name': 'l2'},
                             {'children': [], 'name': 'l1'}],
                'name': 'n1'},
               {'children': [{'children': [], 'name': 'l4'},
                             {'children': [], 'name': 'l3'}],
                'name': 'n2'}],
  'name': 'root'}]

rawDescription: Reconstructing a tree from lists of branches


code: getattr(instance, field.name)

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


code:
import editdistance
tokens1 = ['aa', 'bb', 'cc']
tokens2 = ['a' , 'bb', 'cc']
editdistance.eval(tokens1, tokens2)
out[4]: 1

rawDescription: Token-based edit distance in Python?

description: Token-based edit distance in Python


rawDescription: reverse() does not work on a Python literal?

description: Reverse() does not work on a Python literal


code:
class MyList(list):
    def __init__(self, *args):
        super(MyList, self).__init__(args)

    def __sub__(self, other):
        return self.__class__(*[item for item in self if item not in other])

rawDescription: Python list subtraction operation

description: Python list subtraction operation


code:
def simul(n):
    score = 0
    for i in range(n):
        p1 = choose_rps()
        p2 = choose_rps()
        result = rps(p1, p2)
        score += result
    if score < 0:
        print('Player 1')
    elif score == 0:
        print('Tie')
    else:
        print('Player 2')

rawDescription: Simulate several rounds of rock, paper and scissors


code:
A = lambda x: x + y
def do_something(y):
    return A(2)    # hope it uses the `y` parameter...

do_something(1)

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


code:
file1 = open("example.txt", "r")
alldatainfile1 = file1.read()
file1.close()

file2 = open("example.txt", "r")
alldatainfile2 = file2.read()
file2.close()

rawDescription: How to open read-write file and recreate the file?

description: Open read-write file and recreate the file


code:
import os
from os.path import dirname, realpath, abspath

rawDescription: Python 3.3: Unable to load an image using Pygame if game folder is not in C drive


code: subplot.plot(data_a[:,0] / 1e14, data_a[:,1], label='$T(t)$', linewidth=2)

rawDescription: Remove axis scale

description: Remove axis scale


code: self.arr[x][y] = AttackRobot(team, x, y, direction)

rawDescription: Making a 2d list of objects (Python 2.7)


rawDescription: Get only the first link of a URLs list with BeautifulSoup


code:
class MyOtherClass(MyClass):
    def _new_mf(self):
        # Better code
        return form
    management_form = property(new_mf)

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


code:
for axis in (ax.xaxis, ax.yaxis, ax.zaxis):
    axis._axinfo['grid']['color']  = 0.7, 1.0, 0.7, 1.0

rawDescription: Removing axes margins in 3D plot

description: Removing axes margins in 3D plot


code:
def make_square(seq, size):
    square = zip(*[iter(seq)] * size)
    return [list(t) for t in square]

rawDescription: How to get a split up a list of numbers and insert into another list

description: Get a split up a list of numbers and insert into another list


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

def on_timer(line, x, y):
    x.append(x[-1] + np.random.normal(0, 1))
    y.append(y[-1] + np.random.normal(0, 1))
    line.set_data(x, y)
    line.axes.relim()
    line.axes.autoscale_view()
    line.axes.figure.canvas.draw()

x, y = [np.random.normal(0, 1)], [np.random.normal(0, 1)]
fig, ax = plt.subplots()
line, = ax.plot(x, y, color='aqua', marker='o')

timer = fig.canvas.new_timer(interval=100,
                             callbacks=[(on_timer, [line, x, y], {})])
timer.start()

plt.show()

rawDescription: Pyplot connect to timer event?

description: Pyplot connect to timer event


rawDescription: Speed up writing billions of rows to HDF5


rawDescription: Replacing few values in a pandas dataframe column with another value


code:
class Cebola(Base):
    __tablename__ = 'cebolas'
    id = Column(Integer, primary_key=True, autoincrement=True)

    @hybrid_property
    def number_of_comments(self):
        # return len([c for c in self.checklists if c.notes])
        # @NOTE:1: below will prevent error for those that do not have `notes` column
        # @NOTE:2: in any case this may issue a lot of SQL statements to load all subclasses of checklists relationship, so is not really efficient
        return len([c for c in self.checklists
                    if hasattr(c, 'notes') and c.notes])

    @number_of_comments.expression
    def number_of_comments(cls):
        from sqlalchemy import select
        ce, cl, cla, clb = [
            _.__table__ for _ in (Cebola, Checklist, ChecklistA, ChecklistB)]
        s = (
            select([func.count(cl.c.id).label("number_of_comments")])
            .select_from(cl.outerjoin(cla).outerjoin(clb))
            .where(or_(cla.c.notes != None, clb.c.notes != None))
            .where(cl.c.cebola_id == cls.id)
            .correlate(cls)
            .as_scalar()
        )
        return s

rawDescription: Hybrid expression that counts number rows with condition


code:
resp = """<MAIN>
    <NOSUBEL>abcd</NOSUBEL>
    <NOSUBEL2>adasdasa</NOSUBEL2>
    <MULTISUB>
        <WHATEVER>
            <ANOTHERSUBEL>
                <ANOTHERONE>(how many levels can not be said / can change)</ANOTHERONE>
            </ANOTHERSUBEL>
        </WHATEVER>
    </MULTISUB>
    <SUBEL2>
        <FOO>abcdefg</FOO>
    </SUBEL2>
    <NOSUBEL3>abc</NOSUBEL3>
</MAIN>"""

from collections import OrderedDict
from lxml import etree

def update_dict(element, my_dict):
    # lxml defines "length" of the element as number of its children.
    if len(element):  # If "length" is other than 0.
        for subelement in element:
            # That's where the recursion happens. We're calling the same
            # function for a subelement of the element.
            update_dict(subelement, my_dict)

    else:  # Otherwise, subtree is a leaf.
        my_dict[element.tag] = element.text

if __name__ == "__main__":
    # Change/amend it with your my.request call.
    tree = etree.XML(resp)  # That's a <MAIN> element, too.

    my_dict = OrderedDict()
    # That's the first invocation of the procedure. We're passing entire
    # tree and instance of dictionary.
    update_dict(tree, my_dict)

    print(my_dict)  # Just to see that dictionarty was filled with values.

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


code:
ratios = []

with open('fieldName1', 'r') as f1, open('fieldName2', 'r') as f2:
    for l1, l2 in zip(f1, f2):
        R = difflib.SequenceMatcher(None,l1,l2).ratio()
        ratios.append((l1, l2, R))

rawDescription: difflib.SequenceMatcher not returning unique ratio

description: Difflib.SequenceMatcher not returning unique ratio


code:
c_ulong_type.tp_flags |= Py_TPFLAGS_CHECKTYPES
a >> 2

rawDescription: ctypes reimplementation of rshift for c_ulong

description: Ctypes reimplementation of rshift for c_ulong


rawDescription: Convert number to Italian and Italian to number in python


code:
from datetime import date
from datetime import timedelta

today = date.today()
offset = (today.weekday() - 2) % 7
last_wednesday = today - timedelta(days=offset)

rawDescription: How to get the Python date object for last Wednesday

description: Get the Python date object for last Wednesday


code:
import sys

from PyQt4 import QtCore, QtGui, QtOpenGL
from window import Ui_MainWindow
from MooGraphicsScene import MooGraphicsScene

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

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle('Hello, Qt!')

        # Setup Workspace
        self.scene = MooGraphicsScene()
        self.ui.workspace_view.setScene(self.scene)

        rect = QtCore.QRectF(0, 0, 1000, 1000)
        self.scene.setSceneRect(0, 0, rect.width(), rect.height())

        icon = QtGui.QIcon(QtGui.QPixmap(":/Images/50.png"))
        text = "50's element"
        item = QtGui.QListWidgetItem(icon, text)
        self.ui.element_list.addItem(item)

        icon = QtGui.QIcon(QtGui.QPixmap(":/Images/40.png"))
        text = "40's element"
        item = QtGui.QListWidgetItem(icon, text)
        self.ui.element_list.addItem(item)

if (__name__ == "__main__"):
    app = QtGui.QApplication(sys.argv)
    myApp = Main()
    myApp.show()
    sys.exit(app.exec_())

rawDescription: PyQt event emmitted twice

description: PyQt event emmitted twice


code: re.sub(r'<.+?>', '', text, flags=re.DOTALL)

rawDescription: How to eliminate html tags?

description: Eliminate html tags


rawDescription: Get mean value of certain part of array

description: Get mean value of certain part of array


code:
from subprocess import Popen, PIPE
s = Popen(['cat', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
input = b'hello!' # notice the input data are actually bytes and not text
output, errs = s.communicate(input)

rawDescription: Subprocess writing stdin and reading stdout python 3.4


code: newlist = list(grouper(2, inputlist))

rawDescription: Unify list items pairwise

description: Unify list items pairwise


code:
from collections import OrderedDict
data = OrderedDict([
("top1", OrderedDict([
    ("key1", [
        "there is no spoon", "but dictionaries are hard",
    ]),
    ("key2", [
        "mad max fury road was so good",
    ])
])),
("top2", OrderedDict([
    ("key1", [
        "my item", "foo bar"
    ]),
    ("key2", [
        "blah", "more junk"
    ])
]))])
def get_uniq_by_value(data, val_name):
    return list(OrderedDict.fromkeys(val for value in data.values() for val in value.get(val_name,[])))
get_uniq_by_value(data,"key1")

rawDescription: Get unique list items by nested dictionary key


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

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


code:
def a_function(n, a, b, c):
    if n == 1:
        return ((a,b),)
    else:
        x = a_function(n-1, a, c, b)
        return x + ((a,b),) + a_function(n-1, c, b, a)
a_function(3, 1, 2, 3)

rawDescription: Changing outputs into tuple [python]

description: Changing outputs into tuple [python]


code:
import gmpy2

def primes():
    n = 2
    while True:
        yield n
        n = gmpy2.next_prime(n)

rawDescription: Is there a Python library to list primes?


code:
class bottom(middle_0, middle_1):
    pass

bottom(3, 3).foo()

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


code: X_test = sc.transform(X_test)

rawDescription: Using ranking data in Logistic Regression


code:
df1.index.name = 'year'
df2.index.name = 'year'
df1.reset_index(inplace=True)
df2.reset_index(inplace=True)
df1
df2

rawDescription: Complicated pandas merge operation

description: Complicated pandas merge operation


code:
reader = csv.csvreader(csvfile)
result = np.array([[float(col) for col in row] for row in reader])
# BTW, column headings are in reader.fieldnames at this point.

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


code:
from zope.interface import Interface

class IMyPackageLayer(Interface):
    """Request marker interface"""

rawDescription: how to replace default navigation portlet with my template

description: Replace default navigation portlet with my template


rawDescription: python regular expression irregularity

description: Python regular expression irregularity


rawDescription: repartition a dense matrix in pyspark

description: Repartition a dense matrix in pyspark


code: loaded_data = pickle.load(open('dude.txt', 'rb'))

rawDescription: Can I create an RPG-esque save & quit, and then reload progress?

description: Create an RPG-esque save & quit, and then reload progress


code:
import random
from datetime import datetime
import time

def solve(c, z):
    raise NotImplementedError("In process of programming") # an error because there is still no code for this

now = datetime.now()
print(now.year)
time.sleep(1)
print("WELCOME TO THE JERAXXUS SOFTWARE")
time.sleep(2)
math = True
while math:
    user_input = input("My name is jeraxxus, please put in 2 numbers followed by a operator, *, /, +, -, **, or %.  No commas please")
    user_input = str.split(user_input)
    #a_list = [user_input]
    n1 = user_input[0]
    n2 = user_input[1]
    operate = user_input[2]
    algebra = input("does your mathematical equation contain algebraic values?")
    if algebra == 'no':
        n1 = int(n1)
        n2 = int(n2)
        if operate == '*':
            print(n1 * n2)
        elif operate == '/':
            print(n1 / n2)
        elif operate == '+':
            print(n1 + n2)
        elif operate == '-':
            print(n1 - n2)
        elif operate == '**':
            print(n1 ** n2)
        elif operate == '%':
            print(n1 % n2)
        else:
            print("SHAME YOU SHOULD HAVE FOLLOWED MY COMMANDS")
            math = False
    elif algebra == 'yes':
        problem = input("please state your algebraic problems with spaces after each operation and number, the order is crucial please have only 1 variable and have it first.")
        problem = str.split(problem)
        lop = problem[0]
        b_list = [problem]
        solve(lop, b_list)

rawDescription: python3 algebraic expression solve for x

description: Python3 algebraic expression solve for x


code:
class SubThing(Thing):
    def __init__(self, *args, **kwargs):
        super(SubThing, self).__init__(*args, **kwargs)
        self.time = datetime.now()

rawDescription: How to extend Python class init

description: Extend Python class init


code:
def find_char(text, pos, word, ori):
    x = int(pos % width)
    y = int(pos // height)
    x += ori % 3 - 1
    y += ori // 3 - 1
    if text[pos] != word[0]:
        return None
    if len(word) == 1:
        return (x,y)
    if x < width and y < height and x > -1 and y > -1:
        pos = int(width * y + x)
        if text[pos] == word[1]:
            if len(word) > 1:
                resp = find_char(text, pos, word[1:], ori)
                if resp:
                    return resp
        else:
            return None

word_list = ['COMPUTER', 'SCRAM', 'COURSE', 'LECTURE', 'PROGRAMMING', 'PROJECT', 'SCIENCE', 'STUDENT']
for i in range(len(text)):
    for ori in [0,1,2,3,5,6,7,8]:
        for word in word_list:
            resp = find_char(text, i, word, ori)
            if resp:
                print(word, resp, ori)

rawDescription: Recursively search

description: Recursively search


code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    def get(self, url=None):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Happy New Year '+str(url))

#application = webapp.WSGIApplication(
#                                     [('/', MainPage)],
#                                     debug=True)

application = webapp.WSGIApplication([
                                    (r'/myapp/(?P<url>\d{4})/$', MainPage)
                                    ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

rawDescription: Python webapp dynamic paths

description: Python webapp dynamic paths


code:
import ast
phrase = ast.literal_eval(raw_input("Enter list of students"))
for name in phrase:
    if name[0] in 'ABCDEFGHI':
        print(name)

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


rawDescription: Using MongoDB as a persistent Hashtable

description: Using MongoDB as a persistent Hashtable


code:
This
AAA
This
BBB
This
CCC

That
DDD
That
EEE

rawDescription: Can following-sibling get many attributes?


code: stuff = [[None]*3 for i in xrange(10)]

rawDescription: Python list writing through loop, all previous values being overwritten


code:
data = {'style': '-', 'subCat': '-', 'name': 'Eurodollar Futures', 'oi': '9,774,883', 'floor': 'ED', 'url': '/trading/interest-rates/stir/eurodollar_contract_specifications.html', 'clearing': 'ED', 'cpc': 'ED', 'venues': 'Globex Floor ClearPort ', 'cat': '-', 'vol': '2,026,353', 'globex': 'GE', 'group': 'Interest Rate', 'tags': '-', 'cleared': 'Futures', 'id': 1, 'exch': 'CME', 'subGroup': 'Stirs'}
data.get('name')

rawDescription: Print from List Python

description: Print from List Python


code:
ip1_frac, jp1_frac = np.random.rand(2, items)

unique_coords[:, 0] += 1
data =  rho_coeff*dt*ip1_frac*j_frac
binned_data = np.bincount(indices, weights=data)
rho[tuple(unique_coords.T)] += binned_data

unique_coords[:, 1] += 1
data =  rho_coeff*dt*ip1_frac*jp1_frac
binned_data = np.bincount(indices, weights=data)
rho[tuple(unique_coords.T)] += binned_data

unique_coords[:, 0] -= 1
data =  rho_coeff*dt*i_frac*jp1_frac
binned_data = np.bincount(indices, weights=data)
rho[tuple(unique_coords.T)] += binned_data

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

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


code: update = Users.update(**{what: value}).where(Users.id == some_user_id)

rawDescription: Python peewee update keyword as variable


code:
[9, 4] == array
#>>> array([[ True,  True],
#>>>        [False, False],
#>>>        [False, False]], dtype=bool)

rawDescription: Python - Uniquely determining which text file an element originated from


code:
from collections import Counter
xs = [{'date': 1}, {'date': 1}, {'date': 2}, {'date': 1}, {'date': 4}]
date_counts = Counter(d['date'] for d in xs)
{'date': date_counts.most_common(1)[0][0]}

rawDescription: python: get the most frequent value in a list of dictionaries

description: Python: get the most frequent value in a list of dictionaries


rawDescription: Exclude points from plotting by color definition?


code:
def main():
    make_video(get_sound(), find_key())

rawDescription: How to assign values returned from a function to another function

description: Assign values returned from a function to another function


code:
mock = MagicMock(data={'points': [(0,1), (2,3), (4,5)]})
mock.x_coords = HoldsData.__dict__['x_coords']
mock.x_coords(mock)

rawDescription: Mocking a class's construction

description: Mocking a class's construction


code: file_out.write("%s %s %s %s %s %s" % (ID,A,B,C,D,E)+ "\n")

rawDescription: save a txt file in Python, some tips to improve my code

description: Save a txt file in Python, some tips to improve my code


code: scrollbar.pack(side="right", fill="y")

rawDescription: Can't get this scrollbar to work with Text widet in Tkinter?


code:
import json
twitdict = json.loads(twit)
print(twitdict['id'])

rawDescription: Python treating dictionary as string

description: Python treating dictionary as string


code:
from functools import wraps

def makeObserver(system, originalObserver):
    @wraps(originalObserver)
    def observe(event):
        if event.get("system", None) == system:
            originalObserver(event)

rawDescription: how to use the twistd log system for logging my data?

description: Use the twistd log system for logging my data


rawDescription: partial word search with haystack/elasticsearch

description: Partial word search with haystack/elasticsearch


code:
for key, value in data.items():
    db.arachnid.update({'label': key}, {'$set': {'classification.' + key: value}})

rawDescription: mongodb python Updating a subfield with a condition

description: Mongodb python Updating a subfield with a condition


code:
import ast
call_names = [c.func.id for c in ast.walk(ast.parse(inspect.getsource(source)))
              if isinstance(c, ast.Call)]
return 'target' in call_names

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


code:
from os import listdir
from os.path import isfile, join, abspath, dirname

@app.route('/files')
def files():
    files = [f for f in listdir(app.config['UPLOAD_FOLDER']) if isfile(join(app.config['UPLOAD_FOLDER'], f))]
    return render_template("files.html", files=files)

rawDescription: Link uploaded files on a list

description: Link uploaded files on a list


code: from minu.client import foo

rawDescription: How to structure my little python framework

description: Structure my little python framework


code:
class Pane():

    def __init__(self, textToDisplay, rect, screen, fgColor=(0,0,0), bgColor=(255,255,255), mouseoverBgColor=(255,255,0) ):

        self.textToDisplay = textToDisplay
        self.rect = pygame.Rect(*rect)
        self.screen = screen

        # colors

        self.fgColor = fgColor
        self.bgColor = bgColor

        self.mouseoverBgColor = mouseoverBgColor

        self.currentFgColor = self.fgColor
        self.currentBgColor = self.bgColor

        self.font = pygame.font.SysFont('Palace Script MT', 25)

        self.is_movable = True
        self.is_moving = False
    #---------------------------

    def coordinates(self):
        return self.rect

    #---------------------------

    def text(self):
        return self.textToDisplay

    #---------------------------

    def draw(self):
        # background
        self.screen.fill(self.currentBgColor, self.rect)

        # border
        pygame.draw.rect(self.screen, self.currentFgColor, self.rect, 2)

        # text
        self.screen.blit(self.font.render(self.textToDisplay, True, self.currentFgColor), self.rect)

    #---------------------------

    def test_coordinates(self, posx, posy):
        return self.rect.collidepoint(posx, posy)

    #---------------------------

    def event_handler(self, event):

        # standard pane color
        self.currentFgColor = self.fgColor
        self.currentBgColor = self.bgColor

        # if mouse over pane change color

        if event.type == pygame.MOUSEMOTION:
            if self.rect.collidepoint(event.pos):
                self.currentBgColor = self.mouseoverBgColor

                if self.is_movable and self.is_moving:
                    self.rect.move_ip(event.rel)
                    self.currentBgColor = (0,0,255)

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.currentBgColor = (255,0,0)
                self.is_moving = True

        elif event.type == pygame.MOUSEBUTTONUP:
            if self.rect.collidepoint(event.pos):
                self.currentBgColor = self.mouseoverBgColor
                self.is_moving = False

rawDescription: why is my code still displaying the old panes?

description: Why is my code still displaying the old panes