code:
INITIAL = object()
foo = INITIAL

rawDescription: Python: How to check if a variable has been already declared


rawDescription: Ansicon doesn't install from python but only from cmd


code:
def inverse(mdg):
    """This function reversed string without quotemark of reversed list of splitted input by ','
    """
    return ",".join(reversed(mdg.split(','))).join(["[", "]"])

rawDescription: How to return a list with brackets?

description: Return a list with brackets


code:
import itertools
class FindableList(list):
    def find(self, sub, start=None, end=None):
        """
        @param sub: list, pattern to look for in self

        @param start: int, first possible start-of-list
            If not specified, start at first item

        @param: end: int, last+1 possible start-of-list
            If not specified, end such that entire self is searched

        Returns;
            Starting offset if a match is found, else -1
        """
        if start is None or start < 0:
            start = 0

        # N.B. If end is allowed to be too high,
        # zip() will silently truncate the list comparison
        # and you will probably get extra spurious matches.
        lastEnd = len(self) - len(sub) + 1
        if end is None or end > lastEnd:
            end = lastEnd

        rng = xrange if xrange else range
        iz  = itertools.izip
        isl = itertools.islice

        for pos in rng(start, end):
            if all(a==b for a,b in iz(sub, isl(self, pos, end))):
                return pos

        # no match found
        return -1

rawDescription: Simplifying for-if messes with better structure?


code:
class MyDocTemplate(BaseDocTemplate):
     def __init__(self, filename, **kw):
         self.allowSplitting = 0
         apply(BaseDocTemplate.__init__, (self, filename), kw)
         template = PageTemplate('normal', [Frame(1*inch, 1*inch, 6.5*inch, 9.5*inch, id='F1')])
         self.addPageTemplates(template)

     def afterFlowable(self, flowable):
         "Registers TOC entries."
         if flowable.__class__.__name__ == 'Paragraph':
             text = flowable.getPlainText()
             style = flowable.style.name

             if style == 'reportHeading1':
                 toc_el = [ 0, text, self.page ] # basic elements
                 toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
                 if toc_bm:
                     toc_el.append( toc_bm )
                 self.notify('TOCEntry', tuple(toc_el) )

             elif style == 'reportHeading2':
                 toc_el = [ 1, text, self.page ] # basic elements
                 toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
                 if toc_bm:
                     toc_el.append( toc_bm )
                 self.notify('TOCEntry', tuple(toc_el) )

             elif style == 'TableTitleStyle':
                 toc_el = [ 1, text, self.page ] # basic elements
                 toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
                 if toc_bm:
                     toc_el.append( toc_bm )
                 self.notify('TOCTable', tuple(toc_el) )

             elif style == 'GraphicTitleStyle':
                 toc_el = [ 1, text, self.page ] # basic elements
                 toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
                 if toc_bm:
                     toc_el.append( toc_bm )
                 self.notify('TOCFigure', tuple(toc_el) )

rawDescription: Add figure and tables list to Table of Content using reportlab


code:
class C(object):
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

rawDescription: python properties and inheritance

description: Python properties and inheritance


code:
import sympy as sm
lhs = sm.sympify('e*x + f')
rhs = sm.sympify('g*y + t*x + h')
eq = sm.Eq(lhs, rhs)

rawDescription: Isolate all variables to LHS in sympy?

description: Isolate all variables to LHS in sympy


code:
from collections import Counter
cn = Counter(aDict.values())
print(sorted(k for k,v in aDict.items() if cn[v] == 1))

rawDescription: Check for unique values in a dictionary and return a list


code: dosomething if test else dosomethingelse

rawDescription: How to don't evaluate both functions in list choice if/else alternative?

description: Don't evaluate both functions in list choice if/else alternative


rawDescription: Python creating Covariance matrix from List


rawDescription: Preferred arguments for redirect function


code:
df2['total'] = df2.sum(axis=1)
df2

rawDescription: Pandas: How to groupby and get a count of uniques in a given column?


code: [field.name for field in User._meta.fields if not field.primary_key]

rawDescription: Get all fields except one

description: Get all fields except one


code: args = parser.parse_args()

rawDescription: Python argparse ignore unrecognised arguments


rawDescription: Parallelizing array row similarity calculations in python


code:
emoticons = {":)":0, ":P":1, ":(":2}
vect = TfidfVectorizer(vocabulary=emoticons)
matrix = vect.fit_transform(traindata)

rawDescription: TfidfVectorizer in sklearn how to specifically INCLUDE words


rawDescription: How to get the filtered dataframe for calculations while retaining the original one in pandas?

description: Get the filtered dataframe for calculations while retaining the original one in pandas


code:
class MyModel(models.Model):
    ...
    def contents_substring(self):
        # do stuff
        return the_substring

rawDescription: Django substring

description: Django substring


code:
def get_old_file(check, a_file):
    if not check[0]:
        old_file = a_file
    else:
        old_file = check[1]
    return old_file

rawDescription: Cleaner way to move renamed files when walking over directory


rawDescription: Convert float to string with cutting zero decimals afer point in Python


code:
while True:
  line = p.stdout.readline()
  if not line: break
  ...

rawDescription: Getting realtime output using subprocess


code:
for item in List1:
    key, value = item.split(None, 1)
    print(key)
    print(value)

rawDescription: Breaking List value with space delimiter - Python


code:
change = 0
cars = [pygame.image.load('Car{}.png'.format(num)) for num in range(1, 3)]

rawDescription: Using a String to Call a Variable in Python 3.3 with Pygame


code:
def adjacent(array,x_orig, y_orig):
    """generates all elements in 2d array around given origin"""
    for x_off in (-1,0,1):
        for y_off in (-1,0,1):
            if x_off == 0 == y_off:
                continue #when they are both 0 it is original space, skip
            x = x_orig + x_off
            y = y_orig + y_off
            if x<0 or y<0:
                continue #don't check negative indices
            try:
                yield array[x][y]
            except IndexError:
                continue #indices were out of bounds

rawDescription: Given the indices of a 2 dimensional list, how can I get the next item over?


code:
zeros_count = 0
for i in myNum:
    divideNum = int(myNum) % int(i)
    print(divideNum)
    if divideNum == 0:
        # value is 0, add 1 to the count
        zeros_count = zeros_count + 1
print("number of zeros: %d" % zeros_count)

rawDescription: How to calculate numbers from loop?

description: Calculate numbers from loop


code:
import uuid, binascii
username = binascii.b2a_base64(uuid.uuid4().bytes)

rawDescription: how do I change 'username-password login' to 'email-password login' on django-registration

description: Change 'username-password login' to 'email-password login' on django-registration


code:
A
B
C

rawDescription: Efficent insertion of not aligned elements in a numpy array


code:
def text_display_csv(filename,surface):
    '''Display .csv file contents on surface'''
    f = csv.reader(open(filename)) # open the csv file in one line!

    for row in f:
        y = f.line_num                # assign y as Row no.
        for x,item in enumerate(row): # Get column number(x) and item
            disp(item, (64*x+10,64*y+10), surface) # display item

rawDescription: Python - Display Excel database in a grid


rawDescription: Python3 List: How do I remove el in list_a if el[0] is not in list_b?


code:
url = br.open( page/needed/after/login )
returnPage = url.read()

rawDescription: Python Mechanize - Login

description: Python Mechanize - Login


code:
result = {1,2,3,4,-1}
isinstance(result, collections.Sequence)
isinstance({1:2, 3:3}, collections.Sequence)

rawDescription: How can I tell if a structure in Python has order?

description: Tell if a structure in Python has order


rawDescription: Adding tuples to produce a tuple with a subtotal per 'column'


rawDescription: Python Sort List, Skipping a Character

description: Python Sort List, Skipping a Character


code:
from subprocess import types
types
import sys
sys.modules['subprocess']

rawDescription: Is there a way to access parent modules in Python


code:
class card:
    'Fields: suit, value'
    def __init__(self, suit, value):
        self.suit = suit
        self.value = value
    def __repr__(self):
        return '{suit} {value}'.format(suit=self.suit,value=self.value)
    def __eq__(self, other):
        return (isinstance(other, self.__class__) and
                self.suit == other.suit and self.value == other.value)

all_cards = [card(s, v)
             for s in ('clubs', 'diamonds', 'hearts', 'spades')
                 for v in range(1, 11)]

def higher_in_rank(base_card):
    return all_cards[all_cards.index(base_card)+1:]

rawDescription: Create a function that produces a list of all cards that have a rank higher than base_card?


code:
import re

from bs4 import BeautifulSoup

source_code = """.....ABC
......"""
soup = BeautifulSoup(source_code, "lxml")

for elm in soup.find_all('span', style=re.compile(r"font-family:'Noto Sans'")):
    elm.string = elm.text.replace("A", "X")

print(soup.prettify())

rawDescription: BeautifulSoup: how to replace content with in span tag


code:
users = session.query(User).\
                  options(subqueryload(User.attempts), joinedload(UserAttempt.challenge)).all()

rawDescription: SQLAlchemy Many-To-Many performance

description: SQLAlchemy Many-To-Many performance


code:
template = """

%(text)s

"""

count=capture.getvalue().count('\n')-1
html_message = template %{"text":capture.getvalue().replace('\n', "
\n           ", count)[::-1].replace('\n', "", 1)[::-1]}

rawDescription: direct Python output to text file and html

description: Direct Python output to text file and html


code: body='{"mode":"async", "messageType":"1", "messages":[{"Name of Value1":{0}]}'.format(value1)

rawDescription: Python and variables

description: Python and variables


code:
e = 2
f = 8
g = 4
h = 5
values = [(6, x, y) for x in xrange(0, g * h, h) for y in xrange(e, f * e + 1, e)]
gen = (values[((x + 1) * f) - f:(x + 1) * f] for x in xrange(g))
for i in gen:
    for j in starmap(lambda x, y, z:(x, y, z, (x * y) + z), i):
        print('(%d * %d) + %d = %d' % j)

    print('')

rawDescription: Iterations With Unequal Steps

description: Iterations With Unequal Steps


code:
import sys
sys.path.append("/home/spatel/cx/lib/python3.2/site-packages")
print (sys.path)

rawDescription: How do I manually install cx_Oracle rpm?

description: Manually install cx_Oracle rpm


code: y <- tapply(Weight, f, mean)

rawDescription: Python's barchart equivalent in R

description: Python's barchart equivalent in R


rawDescription: Python in vs iteration for nested list

description: Python in vs iteration for nested list


code:
for line in response.body.splitlines():
    if line:
        line = map(int, line.split())
        opg, opc, value = line[2], line[3], line[5]
        if opg == 160 and opc == 129:
            ret['success'] = "valore: %s" % (value)
            self.write(tornado.escape.json_encode(ret))

rawDescription: Comparing string and integer in Python

description: Comparing string and integer in Python


code:
@register.simple_tag
def render_help_text(field):
    if hasattr(field, 'help_text'):
        return mark_safe(
            "".format(**{'help_text': field.help_text})
        )
    return ''

rawDescription: Django - Python help_text as a clickable icon


rawDescription: Python Use Regex Sub Multiple Times in 1 Pass


code:
bar = treeWidget.verticalScrollBar()
yScroll = bar.value()
# repopulate here ...
treeWidget.scrollContentsBy(0, yScroll)

rawDescription: Remembering Scroll value of a QTreeWidget in PyQt


rawDescription: Select unique value in many lists in python


code:
import math

terms_number = float(input("Enter terms number: "))

sign = 1
divNum = 1
npower = 0
sumPi = 0.0
count = 0

for x in range(terms_number):

    sumPi += sign/(divNum * (3**npower))

    # values for next term
    sign = -sign
    divNum += 2
    npower += 1
    count += 1

sumPi = math.sqrt(12) * sumPi
pythonPi = math.pi
approxError = abs (sumPi - pythonPi)

print("The approximate value of pi is %.14e\n" \
        "       Python's value of pi is %.14e\n"
        "The error in the approximation of pi is %.6e\n"
        "The number of terms used to calculate the value of pi is %g " %
        (sumPi, pythonPi, approxError, count))

rawDescription: Can anyone tell me why is my code showing the wrong value of pi?


code:
# Calculate "((a + b * np.dot(tab[i], vectors[n])) ** d)" part
p1 = (a + b*np.einsum('ij,kj->ki',tab,vectors))**d

# Include "+= coef[0][n] *" part to get the final output
y_vectorized = np.dot(coef,p1)

rawDescription: How to vectorize the following python code?

description: Vectorize the following python code


code:
x = np.arange(4)
x

rawDescription: Create an array from n copies of subarray in python


code: results = zip(data)

rawDescription: fetchall for loop multiple list to one

description: Fetchall for loop multiple list to one


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

numdata = 100
t = np.linspace(0.05, 0.11, numdata)
x1 = np.cumsum(np.random.random(numdata) - 0.5) * 40000
x2 = np.cumsum(np.random.random(numdata) - 0.5) * 0.002

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

# Plotting the data
plot_ax1, = ax1.plot(t, x1, 'r-', label='x1')
plot_ax2, = ax2.plot(t, x2, 'g-', label='x2')

# Setting the label colors
ax2.yaxis.set_offset_position('right') # To set the power indicator of ax2
ax1.yaxis.label.set_color(plot_ax1.get_color())
ax2.yaxis.label.set_color(plot_ax2.get_color())

# Setting the ticker properties
tkw = dict(size=4, width=1.5)
ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
ax1.tick_params(axis='y', colors=plot_ax1.get_color(), **tkw)
ax2.tick_params(axis='y', colors=plot_ax2.get_color(), **tkw)

ax1.yaxis.get_offset_text().set_color(plot_ax1.get_color())
ax2.yaxis.get_offset_text().set_color(plot_ax2.get_color())

ax1.tick_params(axis='x', **tkw)

# Setting the legend
lines = [plot_ax1, plot_ax2]
ax1.legend(lines, [l.get_label() for l in lines],'upper left')

plt.show()

rawDescription: Changing the color of the offset in scientific notation in matplotlib


code:
a = [1, 2, 3, 6, 9, 10]
list(yield_adjacent(a))
a = []
list(yield_adjacent(a))
a = [1, 3]
list(yield_adjacent(a))
a = [1, 3, 4, 9]
list(yield_adjacent(a))

rawDescription: Create a list of tuples containing adjacent numbers?


code:
def are_sinonims(a, b):
    return a in synonym.get(b,[]) \
           or b in synonym.get(a,[]) \
           or any(a in words and b in words for words in synonym.values())

rawDescription: Python: comparing two synonyms through a dictionary


code: btn.Bind(wx.EVT_BUTTON, self.onButton)

rawDescription: wxpython how to display button label into xlwt

description: Wxpython how to display button label into xlwt


code:
dic = {}
for line in f2:
    word, val  = line.split()
    dic[word] = int(val)

rawDescription: opening 2 files and adding values python

description: Opening 2 files and adding values python


code:
with open('<filename>','r') as f:
    numlines = int(f.readline())
    file_list = [f.readline().strip() for _ in range(numlines)]

rawDescription: In Python, how can I read a yet-unknown number of lines from a txt file?


code:
query = query.join(Primate, Primate.id == PrimateToMetricBlock.primate_id).\
    filter(Primate.genus == 'human')

rawDescription: SQLAlchemy: One-Way Relationship, Correlated Subquery


code:
first_pass = df.groupby(['test', 'analysis']).apply(lambda x: {fruit: x.loc[x.fruit==fruit, 'first_pass'] for fruit in x.highest_fruit.iloc[0]}).reset_index()
df =df.merge(first_pass, on=['test', 'analysis'], how='left').rename(columns={0: 'first_pass_highest_fruit'})

rawDescription: Pandas DataFrame Window Function

description: Pandas DataFrame Window Function


code:
rx = np.outer(np.ones((m,)), np.linspace(1, m, m))
ry = np.outer(np.linspace(1, m, m), np.ones((m,)))
s1 = np.chararray((m, m),itemsize=1)
s1[:]=''
strarray = s1+'x'+np.array(rx, dtype='str')+'-'+'y'+np.array(ry, dtype='str')

rawDescription: Faster string assignment using Numpy

description: Faster string assignment using Numpy


rawDescription: Slice endpoints invisibly truncated

description: Slice endpoints invisibly truncated


code:
import datetime

class Eastern(datetime.tzinfo):

    def utcoffset(self, dt):
      return datetime.timedelta(hours=-5)

    def tzname(self, dt):
        return "EST"

    def dst(self, dt):
        return datetime.timedelta(0)

EST = Eastern()

rawDescription: Query mongodb datetime output to be for certain timezone


rawDescription: Find the indices of the lowest closest neighbors between two lists in python


code:
import re
p = re.compile(r'Header [^\n]*[\s\S]*?(?=Header|$)')
test_str = "Header A\ntext text\ntext text\nHeader B\ntext text\ntext text\nHeader C\ntext text\nhere is the end"

re.findall(p, test_str)

rawDescription: extract specific text using multiple regex in python?

description: Extract specific text using multiple regex in python


code:
class MyNode(template.Node):
  def render(self, context):
     if '_included_faceboxify_deps' in context:
       # render your <script> dependency includes
       context['_included_faceboxify_deps'] = True
     # render your <script>s that are specific for this call

rawDescription: Custom Django tag & jQuery

description: Custom Django tag & jQuery


rawDescription: Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row


rawDescription: How to merge item in list

description: Merge item in list


rawDescription: Python3 convert Unicode String to int representation


code:
import struct
msg = 'some message'
length = len(msg)
encoded_length = struct.pack('>I', length)

rawDescription: Python String Prefix by 4 Byte Length

description: Python String Prefix by 4 Byte Length


code:
return binarySearch( array, desiderata, midP + 1, iMax )

# ...

return binarySearch( array, desiderata, iMin, midP - 1 )

rawDescription: Python function returns None (all trivial solutions checked and they do not work)


code:
class Thing(object):
    foo = None

rawDescription: Use class variables as instance vars?

description: Use class variables as instance vars


code: y = lambda: x(whatever)

rawDescription: python function with arguments assigned to a variable

description: Python function with arguments assigned to a variable


code:
import urllib.request
import ast

url = ("https://gist.githubusercontent.com/eldridgejm/76c78b7d11a66162687b/" +
      "raw/60a76770970715f859d1e3d33c8e2afcac296a31/gistfile1.txt")

r = urllib.request.urlopen(url).read()
d = ast.literal_eval(r.decode())

print(d)

rawDescription: Fetching and evaluating a Python code from an HTTP response in Python 3.X


code:
from datetime import datetime
time_string = "[15/Apr/2013:23:55:00 +0530]"
format = "[%d/%b/%Y:%H:%M:%S %z]"
dt = datetime.strptime(time_string, format)
dt
the_time = dt.time()
the_time
the_time.strftime("%H:%M:%S")

rawDescription: Get only time data out of date and time string.


code:
Vendor,Name,Model
vfoo,nhi,m1
vbar,nho,m4
vbaz,nhe,m7

Vendor,Name,Model
vZ,nX,m2
vY,nZ,m6
vX,nY,m8

Vendor,Name,Model
v,n3,m3
v,na,m5
v,n_,m9

rawDescription: Concatenate large files in sql-like way with limited RAM


code:
with open("/usr/share/dict/words","rU") as dictionary:
    with open("word_integer.txt", "a") as foo:
        while dictionary:
            try:
                w1, w2 = next(dictionary), next(dictionary)
                foo.write(str(word_to_int(w1) ^ word_to_int(w2)))
            except StopIteration:
                print("We've run out of words!")
                break

rawDescription: how to perform XOR of all words in a file

description: Perform XOR of all words in a file


code:
class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(Anniversary)
    address = models.ForeignKey(Address)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

rawDescription: Django Python During Restart Data Loss

description: Django Python During Restart Data Loss


code:
REPLACEMENTS = [
    (re.compile(r'(sample_pattern_1)'), r'REPLACE_1'),
    (re.compile(r'(sample_pattern_2)'), r'REPLACE_2'),
    # ..
    (re.compile(r'(sample_pattern_99)'), r'REPLACE_99'),
    (re.compile(r'(sample_pattern_100)'), r'REPLACE_100'),
]

rawDescription: List of compiled regexes in Python

description: List of compiled regexes in Python


code:
A
B
sort_idx = A.argsort()
sort_idx[np.searchsorted(A,B,sorter = sort_idx)]
np.nonzero(B[:,None] == A)[1]

rawDescription: Finding indices of matches of one array in another array


code:
print(u"\N{EURO SIGN}")
u"\N{EURO SIGN}".encode('utf-8') # 3 bytes
u"\N{EURO SIGN}".encode('cp1252') # 1 byte
u"\N{EURO SIGN}".encode('utf-16le') # 2 bytes

rawDescription: Calculate bytes of the unicode character in python


code:
from io import StringIO
from pprint import pprint
sample = StringIO('''\
; commentary
[owner]
name=Justin Case
organization=Chilling Inc.

[database]
; more commentary
server=192.0.0.1
port=123
file=something.csv

[third section]
attribute=value,
that extends to
the third line,
but not the fourth
''')
section = None  # current section
name = None     # current name being stored
result = {}
for line in sample:
    line = line.strip()
    if not line or line.startswith(';'):
        # skip comments and empty lines
        continue
    if line.startswith('[') and line.endswith(']'):
        # new section
        section_name = line.strip('[]')
        section = result[section_name] = {}
        continue
    # add entries to the existing section
    if '=' in line:
        name, _, value = line.partition('=')
        name = name.strip()
        section[name] = value.strip()
    else:
        # adding to last-used name
        section[name] += ' ' + line

pprint(result)

rawDescription: Dictionary of ini file data

description: Dictionary of ini file data


code:
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.db import models
User.email = models.EmailField(_('e-mail address'), blank=True, max_length=200)

rawDescription: django auth User truncating email field

description: Django auth User truncating email field


code:
class Child(object): pass

class Parent(object): pass

c = Child()
p = Parent()
c.parent = p
p.child = c

rawDescription: What are cycles ? in relation to python

description: What are cycles ? in relation to python


code: numberofvalues = len(groupA[name])

rawDescription: When i add to the list in my dictionary, it doesn't actually add to the list? python


code:
from itertools import combinations

c = combinations(a, 2)
f = filter(lambda x, y: isTrue(x, y), c)

rawDescription: How to select element pairs of a list that satisfy some criterion in Python?

description: Select element pairs of a list that satisfy some criterion in Python


code:
from collections import Counter
from operator import or_
original_dict_list = [{'foo': 3, 'bar': 10}, {'foo': 42, 'spam': 20}, {'bar': 5, 'ham': 10}]
reduce(or_, map(Counter, original_dict_list))

rawDescription: Merge multiple dictionaries conditionally


code: filenames = ["path/to/file1", "path/to/file2", "path/to/file3"]

rawDescription: How to compose my loop?

description: Compose my loop


rawDescription: Python: list vs. np.array: switching to use certain attributes


rawDescription: Combine data from two different text files in just one line (Python)


code:
@app.route('/')
def hello_world():
    # note key is an int, not just a string with leading digits
    # in your case this could be a mongodb object
    return jsonify({1: {'name': 'bob'}})

rawDescription: Flask jsonify: key starting with digit

description: Flask jsonify: key starting with digit


rawDescription: How to know the filetype through python

description: Know the filetype through python


code:
location = Location(city='Atlanta')
# or if you already have Atlanta in your database:
# location = session.query(Location).filter_by(city='Atlanta').first()

for id in hotelIDs:
    hotel = Hotel( ... )
    location.location.append(hotel)  # append hotel instance here
    ...

# now add to session and commit

rawDescription: Save relational sqlalchemy object from a dict


code:
df = pd.DataFrame(a)
df.groupby(0, sort=False, as_index=False).sum().values

rawDescription: Consolidate duplicate rows of an array

description: Consolidate duplicate rows of an array


rawDescription: How to force a regex to be as conservative as possible when some elements are optional?

description: Force a regex to be as conservative as possible when some elements are optional


rawDescription: Pandas - Replace Integers with Floats

description: Pandas - Replace Integers with Floats


rawDescription: Error while I use math.atan in Python!

description: Error while I use math.atan in Python!


code:
with open('file.txt') as file:
    print(file.read().replace('\n', ''))

rawDescription: How to merge specific lines positioned between certain characters

description: Merge specific lines positioned between certain characters


code: fun = lambda x: x + (1 if x < y else -1)

rawDescription: Calling lambda-created functions returns functions?


code: {i: X[np.where(estimator.labels_ == i)] for i in range(estimator.n_clusters)}

rawDescription: cluster points after KMeans clustering (scikit learn)

description: Cluster points after KMeans clustering (scikit learn)


code:
# subfile.py

import settings

def stuff():
    settings.myList.append('hey')

rawDescription: Using global variables between files in Python?


code: filename = template.format(**fields)

rawDescription: Dynamic fields in a Python string

description: Dynamic fields in a Python string


code:
import itertools
def grouper(S, n):
    iterator = iter(S)
    while True:
        items = list(itertools.islice(iterator, n))
        if len(items) == 0:
            break
        yield items

rawDescription: For every x number of files; create new directory and move files -- using Python


code:
import urllib2
url = 'https://graph.facebook.com/oauth/access_token?client_id=%(id)s&redirect_uri=http://127.0.0.1:8000/facebook/return&client_secret=%(secret)s&code=%(code)s'%{'id':fb_id,'secret':fb_s,'code':code}
response = urllib2.urlopen(url)
html = response.read()

rawDescription: Capture access_token from facebook's server-side authentication in Django


code:
def stop_serving_forever(self):
    """Stop handling requests"""
    self.should_be_running = 0
    # Make a fake request to the server, to really force it to stop.
    # Otherwise it will just stop on the next request.
    # (Exercise for the reader.)
    self.make_a_fake_request_to_myself()

rawDescription: How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?

description: Stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass


code:
DATABASE_ENGINE = 'mysql'
DATABASE_OPTIONS = {"init_command": "SET storage_engine=INNODB"}

rawDescription: In Django, how do I set the default so that every model is created with INNODB?


code:
#!/usr/bin/env python
import subprocess
import tempfile

with tempfile.TemporaryFile() as file:
    subprocess.check_call("date", stdout=file)
    file.seek(0) # sync. with disk
    result = file.read()

rawDescription: Use NamedTemporaryFile to read from stdout via subprocess on Linux


rawDescription: Using Amazon SWF To communicate between servers


code:
xi, yi, zi = [np.arange(3) for i in range(3)]
xx, yy, zz = np.broadcast_arrays(xi,yi[:,np.newaxis],zi[:,np.newaxis,np.newaxis])
xx.shape
xx.strides

rawDescription: numpy 3D meshgrid only as a view

description: Numpy 3D meshgrid only as a view


code: print("The index is", str(infileData[n]) + ".")

rawDescription: python using data from a list, where by you call the data from its index number

description: Python using data from a list, where by you call the data from its index number


rawDescription: Page not found (404) Error in Django

description: Page not found (404) Error in Django


rawDescription: How to work with data from NBA.com?

description: Work with data from NBA.com


code:
q = (
    db.session
    .query(Video)
    .join(MediaItem, Video.Parent)
    .filter(MediaItem.tags.any(Tags.tag == tag))
)

rawDescription: Flask-SQLAlchemy filter on many to many relationship with parent model


code:
import re
regex = re.compile(r'(?<=[^\s])\s')
regex.split('this  is a   string')

rawDescription: python regex: use first blank as sep but maintain rest of blank sequence

description: Python regex: use first blank as sep but maintain rest of blank sequence


rawDescription: Pivot on log event category and group by day


code:
import matplotlib.pyplot as pyplot
import numpy

x = range(5)
y = numpy.array([(1.,0.001), (1.1, 0.002), (numpy.nan, numpy.nan),
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')
import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (None, None),
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

# I'd like to plot
#     k[:,0] + k[:,1]
# but I can't add None

arr_none = np.array([None])
mask = (k[:,0] == arr_none) | (k[:,1] == arr_none)

ax.plot(numpy.arange(len(y))[mask], k[mask,0]+k[mask,1], 'k--')

rawDescription: matplotlib: Plot numpy arrays with None as values

description: Matplotlib: Plot numpy arrays with None as values


code:
input_dictionary = [{"name":"kishore", "playing":["cricket","basket ball"]},
                    {"name":"kishore", "playing":["volley ball","cricket"]},
                    {"name":"kishore", "playing":["cricket","hockey"]},
                    {"name":"kishore", "playing":["volley ball"]},
                    {"name":"xyz","playing":["cricket"]}]
import itertools
import operator

by_name = operator.itemgetter('name')
result = []
for name, grp in itertools.groupby(sorted(input_dictionary, key=by_name), key=by_name):
    playing = set(itertools.chain.from_iterable(x['playing'] for x in grp))
    # If order of `playing` is important use `collections.OrderedDict`
    # playing = collections.OrderedDict.fromkeys(itertools.chain.from_iterable(x['playing'] for x in grp))
    result.append({'name': name, 'playing': list(playing)})

print(result)

rawDescription: Merging list of dictionary in python

description: Merging list of dictionary in python


code:
data = genfromtxt("temp_mean.txt", skiprows=3, delimiter=(4,)+(7,)*12, usecols=range(1,13), skip_footer=1)
data.shape
data[:,0]  # JAN
data[:,1]  # FEB
data[-1,:]  # Last row.

rawDescription: How to read columns of varying length from a text file in NumPy using genfromtxt()?

description: Read columns of varying length from a text file in NumPy using genfromtxt()


code:
factors = [set() for n in range(N)]
factored = collections.defaultdict(set)
for n in range(2, N):
    if not factors[n]:           # no factors yet -> n is prime
        for m in range(n, N, n): # all multiples of n up to N
            factors[m].add(n)
            factored[n].add(m)

rawDescription: Optimizing list comprehension to find pairs of co-prime numbers


code: lst = filter(None, lst)

rawDescription: How to remove blank 2D list rows?

description: Remove blank 2D list rows


code:
x=Table(...)
x1 = x[x['Dec'] > -10*u.degree] # Remove everything below -10degree declination
x2 = x[x['Apparent Magnitude'] < 20] # Remove every star with a magnitude above 20

rawDescription: How to index observable coordinates in an astropy Table

description: Index observable coordinates in an astropy Table


rawDescription: matplotlib colorbar tick label formatting

description: Matplotlib colorbar tick label formatting


code:
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)

rawDescription: Python 2d grid : Assigning values to coordinates in the grid


rawDescription: Retrieve rows from Monday to Friday in Django?


rawDescription: How to retrieve sub documents in a Array from mongoDB using python script

description: Retrieve sub documents in a Array from mongoDB using python script


code:
base = '16'
int(da_number, base) # wrong! base should be an int.
int(da_number, int(base)) # correct

rawDescription: putting a variable inside of quotes in python

description: Putting a variable inside of quotes in python


rawDescription: Python hexadecimal comparison

description: Python hexadecimal comparison


rawDescription: Python regex parsing and putting into a multidimensional list


code:
class Map:
    def __init__(self, height, width, player_x, player_y, paths):
        self.height = height
        self.width = width
        self.x = player_x
        self.y = player_y
        self.paths = paths

rawDescription: Python Drawing ASCII Map

description: Python Drawing ASCII Map


rawDescription: Loading and reading JSON file is very slow after writing in python


code: [i[0] for i in re.findall(r'(([a-z])\2)', 'abbbbcppq')]

rawDescription: Find "one letter that appears twice" in a string


code:
# glob files
files = glob('file_*.csv')
target = open('combined.csv', 'w')
for f in files:
   target.write(open(f).read())
   target.write(new_line_speparator_for_your_platform)
target.close()

rawDescription: csv rows into separate txt files?

description: Csv rows into separate txt files


code:
def gcd2(a, b):
    if (0 == a % b):
        # calculate s and t
        return b, s, t
    else:
        g, s, t = gcd2(b, a % b)
        # calculate new_s and new_t
        return g, new_s, new_t

rawDescription: Calculate the extended gcd using a recursive function in Python


code:
def serverlist():
    ips = []
    with open("file.txt", "r") as f:
        for line in f.readlines():
            if line.strip().startswith("Server["):
                ips.append(line.split()[1]) # split on spaces
    return ips

rawDescription: Slice variable from specified letter to specified letter in line that varies in length


code:
def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

rawDescription: Python setting Decimal Place range without rounding?


code: rsa = M2Crypto.RSA.gen_key (2048, 65537, callback=lambda x, y, z:None)

rawDescription: Is there a way to suppress Python M2Crypto's RSA.gen_key output?


code:
a = 100
while a:
    shave = int(raw_input("Input a number to subtract from %i:" % a))
    if ( shave > 0 ) and ( shave <= a ):
        a -= shave
    else:
        print ("Number needs to be positive and less than %i." % a)

rawDescription: Basic decrement loop - PYTHON

description: Basic decrement loop - PYTHON


code:
num=raw_input ("enter the numbers : ")
[int(num[i:i+2]) for i in range(0,len(num),2)]

rawDescription: Python parsing, convert string to list of integers


code:
@classmethod
def my_class_method(cls, foo):
   ...

rawDescription: python: When to use static method over class method?

description: Python: When to use static method over class method


code:
import numpy as np
import pandas as pd

nan = np.nan
df = pd.DataFrame([
    (nan, nan, nan, 'Auto loan', nan)
    , ('Branch Code', 'Branch Name', 'Region', 'No of accounts'
       , 'Portfolio Outstanding')
    , (3000, 'Name1', 'Central', 0, 0)
    , (3001, 'Name2', 'Central', 0, 0)
])

rawDescription: Pandas: parse merged header columns from Excel


rawDescription: Shorten the IF condition for 2 variables (same comparison)


rawDescription: h5py order of dataset by dataset name

description: H5py order of dataset by dataset name


rawDescription: Generating variable amounts of parameters for function call in code


code:
def pre_save(self, obj):
    obj.owner = self.request.user

rawDescription: Django rest framework auto-populate filed with user.id


rawDescription: Is it possible to copy and update a python dictionary in a single chained expression?


code:
from functools import wraps

def send_timing(f):
    @wraps(f)
    def wrapper(*args, **kw):
        # probably do a little more than just proxy
        return f(*args, **kw)
    return wrapper

rawDescription: In Python 3 how can I patch a function inside a module for unit testing?


code: df1.set_index('Date', inplace=True)

rawDescription: How do I efficiently combine similar dataframes in Pandas into one giant dataframe

description: Efficiently combine similar dataframes in Pandas into one giant dataframe


code:
for team, runs in league.iteritems():
    runs_scored, runs_allowed = map(float, runs)

rawDescription: Iterating Over Dictionary Key Values Corresponding to List in Python


rawDescription: converting numbers to metric unit in python

description: Converting numbers to metric unit in python


code: tokenize("this is, a test, you know")

rawDescription: Python Not Removing Char From String

description: Python Not Removing Char From String


code:
# Server
import socket

HOST = ''                      # All available interfaces
PORT = 50007                   # Same port as client
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1)        # receive data with bufsize 1; a larger bufsize will break this code
    if not data: break
    conn.sendall(data)
conn.close()

rawDescription: ctypes in python size with the `sys.getsizeof(Var)` method vs `ctypes.sizeof(Var)`

description: Ctypes in python size with the `sys.getsizeof(Var)` method vs `ctypes.sizeof(Var)`


rawDescription: Looking for a way to shard a MongoDB collection from within Python code


code:
from itertools import product

p=['x1','x2','x3']
q=['y1','y2','y3']

for t in product(*zip(p,q)):
    print(t)

rawDescription: Specific Permutations

description: Specific Permutations


code:
if i in results:
    results[i].append(val)
else:
    results[i] = [val]

rawDescription: python dictionary with list as values

description: Python dictionary with list as values


code:
input_dict={}
for i in range(100):
    new_A = matrix([[A11,A12,A13],[A21,A22,A23],[A31,A32,A33]]) # new input matrix (A)
    input_dict[i] = new_A

rawDescription: create module in python for diagonalizing matrix

description: Create module in python for diagonalizing matrix


code:
next = driver.find_element_by_xpath("//a[text()='Next']")
prev = driver.find_element_by_xpath("//a[text()='Previous']")

rawDescription: python, locating and clicking a specific button with selenium

description: Python, locating and clicking a specific button with selenium


code: data

rawDescription: Writing Multiple Rows to CSV using Numpy Arrays without Brackets?


code:
[u'\n\n\nHere is text 3 and this is what I want.\n']
[u'Here is text 3 and this is what I want.']

rawDescription: How to use python beautiful soup to get only the level 1 navigableText?

description: Use python beautiful soup to get only the level 1 navigableText


code:
image = '1.png'
watermark = '2.png'

wmark = Image.open(watermark)
img = Image.open(image)

ia, wa = None, None
if len(img.getbands()) == 4:
    ir, ig, ib, ia = img.split()
    img = Image.merge('RGB', (ir, ig, ib))
if len(wmark.getbands()) == 4:
    wa = wmark.split()[-1]

img.paste(wmark, (0, 0), wmark)
if ia:
    if wa:
        # XXX This seems to solve the contradiction, discard if unwanted.
        ia = max_alpha(wa, ia)
    img.putalpha(ia)

img.save('result.png')

rawDescription: PIL merge of two images with alpha channels - not working as expected


code:
s='Preceding Text:the rest'
s[s.find('Text'):].partition(':')[2]
s[s.find('Text'):].partition(';')[2]

rawDescription: Returning NoneType vs. returning "" in re.search


code: column = search_in_table(table_name, search_for)[1]

rawDescription: How do I satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function?

description: Satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function


code:
import pychebfun
def min_dist(p):
    f_cheb = pychebfun.Chebfun.from_function(lambda x: diff_d(x, p), domain = (0,2*np.pi))
    potential_minimizers = np.r_[0, f_cheb.roots(), 2*np.pi]
    return np.min([d(x, p) for x in potential_minimizers])

rawDescription: Find global minimum using scipy.optimize.minimize


code:
def convert_arg_line_to_args(self, arg_line):
    return [arg_line]

rawDescription: using fromfile_prefix_chars with multiple arguments (nargs="*")

description: Using fromfile_prefix_chars with multiple arguments (nargs="*")


rawDescription: Can named arguments be used with Python enums?


code:
tweets = data['results']
tweets.sort(key=lambda tw: tw['from_user_name'], reverse=True)

rawDescription: Python extract top user name from json

description: Python extract top user name from json


code:
i = s.get(file_url, allow_redirects=False)
urlpath = i.headers['location']

rawDescription: How to get redirected URL without downloading file

description: Get redirected URL without downloading file


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

Turkish

The.Mist[2007]DvDrip[Eng]-aXXo

Vietnamese

The.Mist.2007.720p.Bluray.x264.YIFY

''')
[s.get_text().strip() for s in soup.find_all('span', class_=True)]

rawDescription: Why isn't this regexp working

description: Why isn't this regexp working


rawDescription: python 2.7 - is there a more succint way to do this series of yield statements (in python 3, "yield from" would help)

description: Python 2.7 - is there a more succint way to do this series of yield statements (in python 3, "yield from" would help)


code:
import gc

a = [1, 2, 3]
b = [a, a]
gc.collect()
refs = gc.get_referrers(a)

rawDescription: In Python, how do I determine if an object still exists?


rawDescription: Blender Scripting - Import Collada file and save it as .blend


code:
import os.path
os.path.join('first_part', 'second_part')
os.path.join('first_part', r'/second_part')

rawDescription: New folder that is created inside the current directory


code: prompt = '\x1b[32mipdb> \x1b[0m'

rawDescription: Make ipdb prompt colored

description: Make ipdb prompt colored


rawDescription: List Comprehension with Varible Length Outputs


code:
dt = np.dtype([('values',float,(41,)),('labels','S10')])
data=np.genfromtxt(f, delimiters=',',dtype=dt)
X = data['values']
Y = data['labels']

rawDescription: IndexError: too many indices for array. Numpy array with 42 features not homogeneous


code:
with open ('new.txt','w') as f:
 for i in range(1,10):
     system = i,i+2*i
     f.write(str(system)+'\n')

rawDescription: save output values in txt file in columns python

description: Save output values in txt file in columns python


rawDescription: Python - matplotlib - PyQT: Copy image to clipboard


code: np.arange(k-i) == ix[:-i]

rawDescription: Numpy: Affect diagonal elements of matrix prior to 1.10


rawDescription: Why does division become faster with very large numbers


code:
from django.test.simple import DjangoTestSuiteRunner
from django.conf import settings

class AppsTestSuiteRunner(DjangoTestSuiteRunner):
    """ Override the default django 'test' command, include only
        apps that are part of this project
        (unless the apps are specified explicitly)
    """

    def run_tests(self, test_labels, extra_tests=None, **kwargs):
        if not test_labels:
            PROJECT_PREFIX = 'my_project.'
            test_labels = [app.replace(PROJECT_PREFIX, '')
                for app in settings.INSTALLED_APPS
                if app.startswith(PROJECT_PREFIX)]
        return super(AppsTestSuiteRunner, self).run_tests(
              test_labels, extra_tests, **kwargs)

rawDescription: Testing specific apps in Django

description: Testing specific apps in Django


code:
a
b
out

rawDescription: Updating a NumPy array with another

description: Updating a NumPy array with another


code:
['directionNonSpecific',
 'niceGreetings',
 'referToCollective',
 'referToObject',
 'referToSelf',
 'travelPastTense']

rawDescription: Get a list of lists out of a Python object


rawDescription: Does the global keyword inline the global exactly as a local variable declaration in python?


code:
def test_list_change(lst):
    if len(lst) < 3:
        lst.append("the last one")
        test_list_change_2(lst)

def test_list_change_2(lst):
    lst[:] = ["the very last one"] # changes original list object

string_list = ["first", "another one"]
test_list_change(string_list)
print (string_list)
['the very last one']

rawDescription: python: changing list value in sub-routine

description: Python: changing list value in sub-routine


code:
import pandas as pd
v1 = pd.DataFrame.from_records(v1)
v2 = pd.DataFrame.from_records(v2)
v = v1 + v2
print(v)

rawDescription: numpy add dtype array

description: Numpy add dtype array


rawDescription: Reshaping two-column data using pandas pivot


code:
# ensure all images are loaded
for image in images:
  get_image(image)

rawDescription: Pre-loading images pygame

description: Pre-loading images pygame


code: help(isinstance)

rawDescription: How to compare inheritance with several classes?

description: Compare inheritance with several classes


rawDescription: How to find shortest path for raw data

description: Find shortest path for raw data


rawDescription: Twitter API - how to have a user log in via Twitter to submit text to a database


rawDescription: Analytical solution for Linear Regression using Python vs. Julia


code:
from django_extensions.db.fields import RandomCharField

class Inbox(models.Model):
    pin_code = RandomCharField(length=4, unique=True, include_alpha=False)
    owner = models.ForeignKey(User)
    creation_time = models.DateTimeField(auto_now_add=True)

rawDescription: Tricky coding logic for Django web app

description: Tricky coding logic for Django web app


rawDescription: Sorting array into table by first two characters


code: from copy import deepcopy

rawDescription: Python global variable changes itself.... Why?


rawDescription: Randomize a generator

description: Randomize a generator


code:
#!/usr/bin/env python
from datetime import date, timedelta
from itertools import groupby

epoch = date(1970, 1, 1)

result = {}
assert timestamps == sorted(timestamps)
for day, group in groupby(timestamps, key=lambda ts: ts // 86400):
    # store the interval + day/month in a dictionary.
    same_day = list(group)
    assert max(same_day) == same_day[-1] and min(same_day) == same_day[0]
    result[epoch + timedelta(day)] = same_day[0], same_day[-1]
print(result)

rawDescription: Finding time intervals per day from a list of timestamps in Python


code: [(u'olive', u'leaf', u'plucked'), (u'rider', u'falls', u'backward'), (u'sewed', u'fig', u'leaves'), (u'yield', u'royal', u'dainties'), (u'during', u'mating', u'season'), (u'Salt', u'Sea', u').'), (u'Their', u'hearts', u'failed'), (u'doing', u'forced', u'labor'), (u'El', u'Beth', u'El'), (u'own', u'droves', u'apart')]

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
import numpy as np
a = np.random.randint(0,9,(4,2,3))
b = np.random.randint(0,9,(2,1)).ravel()
whos
given_axis = 1

rawDescription: multiply numpy ndarray with 1d array along a given axis

description: Multiply numpy ndarray with 1d array along a given axis


rawDescription: What features of images will produce good result used in SVM multiclass image classification?


rawDescription: how to preserve types when using pyparsing and returning the result as a dictionary

description: Preserve types when using pyparsing and returning the result as a dictionary


code:
def circle(symbol):

    def lines1(aa):
        print(symbol * 20)
        aa()
        print(symbol * 20)
    return(lines1)

rawDescription: How can I pass input to a function, then have it use that input across 5 internal functions that are chaining each other?

description: Pass input to a function, then have it use that input across 5 internal functions that are chaining each other


code:
f = forex.to_frame('value')
f.index.name =  'ccy'
pd.merge(df.reset_index(),f.reset_index(),on='ccy')

rawDescription: Multiply all columns of a multi-indexed DataFrame by appropriate values in a Series


code:
import xlwt
xlwt.Utils.cell_to_rowcol2('A12') # Your original coords
xlwt.Utils.cell_to_rowcol2('AB31') # ex by @nooodl

rawDescription: converting excel positioning to numbers

description: Converting excel positioning to numbers


code:
wine = Wine.objects.get(...)
review = Review(..., content_object=wine)
review.save()

rawDescription: Django sharing one model between two others


rawDescription: How to extract only text from the div containing more divs using scrapy

description: Extract only text from the div containing more divs using scrapy


code:
@route('/myform')
def submit():
    the_package = zzz  # get the value however your application chooses
    return template('form1', package=the_package)  # your template file is form1.tpl

rawDescription: how to pass value into html form in Bottle?

description: Pass value into html form in Bottle


code:
from tkinter import Label, Frame, Entry, Button, LEFT, RIGHT, END, TOP, END, StringVar
from tkinter.messagebox import showinfo
from random import randrange

class Ed(Frame):
    """Simple arithmetic education app"""
    def __init__(self,parent=None):
        """constructor"""
        super().__init__(parent)
        self.tries = 0
        self.problem = StringVar()
        self.make_widgets()
        self.new_problem()
        self.pack()

    def make_widgets(self):
        """defines Ed widgets"""
        self.label = Label(self, textvariable=self.problem)
        self.label.pack(side=LEFT)
        self.ent = Entry(self)
        self.ent.pack(side=LEFT)
        Button(self, text='Enter', command=self.evaluate).pack(side=RIGHT)

    def new_problem(self):
        """creates new arithmetic problem"""
        self.tries = 0
        self.a = randrange(1,10,1)
        self.b = randrange(1,10,1)
        if randrange(1,10,1) < 5:
            self.total = self.a + self.b
            self.plusminus = '+'
        else:
            self.total = self.a - self.b
            self.plusminus = '-'
        self.problem.set( (self.a , self.plusminus, self.b) )

    def evaluate(self):
        """handles button "Enter" clicks by comparing answer in entry to correct result"""
        if self.total == int(self.ent.get()):
            showinfo(title='YAY', message='You are CORRECT!')
            self.ent.delete(0,END)
            self.new_problem()
        else:
            self.ent.delete(0,END)
            self.ent.insert(END, 'Wrong. Try again.')
            self.tries += 1

Ed().mainloop()

rawDescription: Label does not update on button click

description: Label does not update on button click


code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'Value':['1', 'foo', '1.23', 'bar', '3.14e6']})
df['Value_Num'] = pd.to_numeric(df['Value'], errors='coerce')
mask = pd.notnull(df['Value_Num'])
df.loc[mask, 'Value'] = np.nan
df = df.rename(columns={'Value':'Value_Txt'})
print(df)

rawDescription: Python filtering for numeric and string in a single data frame column


code: pairs = [(row_idx, item) for row_idx, row in enumerate(data) for item in row]

rawDescription: quick way to convert a list of lists (ie from scipy.spatial.KDTree.query_ball_tree) to an array of pairs?

description: Quick way to convert a list of lists (ie from scipy.spatial.KDTree.query_ball_tree) to an array of pairs


code:
test = list(range(20))
even_pos(test)

rawDescription: What does isinstance with a dictionary and abc.Mapping from collections doing?


rawDescription: Performance of looping with pandas

description: Performance of looping with pandas


rawDescription: Using duplicates to create different text files


code: bg_pixmap[state] = "<parent>"

rawDescription: Disable pixmap background defined by GTK theme per application


code:
from itertools import combinations
dictionary = {'foo': 'bar', 'spam': 'eggs', 'monty': 'python'}
for (key1, val1), (key2, val2) in combinations(dictionary.items(), 2):
    print('Combining {!r}: {!r} with {!r}: {!r}'.format(key1, val1, key2, val2))

rawDescription: Iterating over dictionary keys in python after a certain key in python


code:
import numpy as np

dx = dy = 0.1
nx = ny = 100
x, y = np.meshgrid(np.arange(0, nx * dx, dx),
                   np.arange(0, ny * dy, dy))
cx = cy = 5
s = 2

rawDescription: Initialising a vector field in numpy

description: Initialising a vector field in numpy


code:
class obj():
    def __init__(self,id):
        self.id = id
    def __repr__ (self):
        return "obj({})".format(self.id)
obj1 = obj(6)
obj2 = obj(4)
obj3 = obj(2)
x = MyArray([obj1, obj2, obj3])
x
x[4]
x[2, 4]

rawDescription: Accessing numpy array based on attribute of object


code:
import timeit

weighted_choice_functions = [
"""import numpy
wc = lambda weights: numpy.random.choice(
    range(len(weights)),
    p=weights/weights.sum())
""",
"""import numpy
# Adapted from http://stackoverflow.com/a/19760118/1274613
def wc(weights):
    cs = numpy.cumsum(weights)
    return cs.searchsorted(numpy.random.random() * cs[-1], 'right')
""",
"""import numpy, bisect
# Using bisect mentioned in http://stackoverflow.com/a/13052108/1274613
def wc(weights):
    cs = numpy.cumsum(weights)
    return bisect.bisect(cs, numpy.random.random() * cs[-1])
""",
"""import numpy
wc = lambda weights: numpy.random.multinomial(
    1,
    weights/weights.sum()).argmax()
"""]

for setup in weighted_choice_functions:
    for ps in ["numpy.ones(40)",
               "numpy.arange(10)",
               "numpy.arange(200)",
               "numpy.arange(199,-1,-1)",
               "numpy.arange(4000)"]:
        timeit.timeit("wc(%s)"%ps, setup=setup)
    print()

rawDescription: Fast way to obtain a random index from an array of weights in python


rawDescription: Efficiently drop dataframe rows where *index* contains nulls (NaT)


code:
x_mask = (np.diff(x_idx) != 0)
x_mask

rawDescription: How to coarse grain xy coordinates

description: Coarse grain xy coordinates


code:
target_list1 = expression
target_list2 = expression

rawDescription: Semantics of 'x = y = z' assignment in Python


code:
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
tar.addfile(tarfile.TarInfo("/home/user/file.txt"), "/home/user/file.txt")
tar.close()

rawDescription: How to compress a file with shutil.make_archive in python?

description: Compress a file with shutil.make_archive in python


code: lastLink = list(br.links(text_regex=re.compile("Display charges")))[-1]

rawDescription: python mechanize find_link find the final matching link

description: Python mechanize find_link find the final matching link


code:
from re import search
f = '"bob smith" <bob5@xxxxx.org>'
search('<(.*?)>$', f)
search('<(.*?)>$', f).group(1)

rawDescription: How can I get actual email address as a string from python email object

description: Get actual email address as a string from python email object


rawDescription: String parsing in Python with various unique cases


code: format(yournumber, '.3f')

rawDescription: Formatting display of numbers in Python 3


code: set(wordList) - set(string.punctuation)

rawDescription: Python NLTK not taking out punctuations correctly


code:
import sympy.simplify.fu
import sys

fu_module = sys.modules['sympy.simplify.fu']

rawDescription: Python: Importing a module with the same name as a function


code:
import Tkinter
import tkFont as font

class Gui(Tkinter.Tk):
    def __init__(self, logic):
        Tkinter.Tk.__init__(self)

        self.logic = logic

        self.geometry("370x170")
        self.resizable(width=False, height=False)

        rock_button = Tkinter.Button(self, text="Rock", command=self.rock_clicked)
        rock_button.place(width=100, height=30, x=10, y=30)

        paper_button = Tkinter.Button(self, text="Paper", command=self.paper_clicked)
        paper_button.place(width=100, height=30, x=10, y=70)

        scissors_button = Tkinter.Button(self, text="Scissors", command=self.scissors_clicked)
        scissors_button.place(width=100, height=30, x=10, y=110)

        score_font = font.Font(family="Helvetica", size=20)

        own_score_lbl = Tkinter.Label(self, text="0", relief=Tkinter.RIDGE, font=score_font)
        own_score_lbl.place(width=50, height=110, x=120, y=30)

        ai_score_lbl = Tkinter.Label(self, text="0", relief=Tkinter.RIDGE, font=score_font)
        ai_score_lbl.place(width=50, height=110, x=200, y=30)

        ai_choice = Tkinter.Label(self, relief=Tkinter.RIDGE)
        ai_choice.place(width=100, height=110, x=260, y=30)

        self.render_title()

    def render_title(self):
        logic = self.logic
        templ = "Rock({logic.rock_counter}), Paper({logic.paper_counter}), Scissors({logic.scissors_counter})"
        title = templ.format(logic=logic)
        self.title(title)

    def rock_clicked(self):
        self.logic.play_rock()
        self.render_title()

    def paper_clicked(self):
        self.logic.play_paper()
        self.render_title()

    def scissors_clicked(self):
        self.logic.play_scissors()
        self.render_title()

class GameLogic():
    def __init__(self):
        self.rock_counter = 0
        self.paper_counter = 0
        self.scissors_counter = 0

    def play_rock(self):
        self.rock_counter += 1

    def play_paper(self):
        self.paper_counter += 1

    def play_scissors(self):
        self.scissors_counter += 1

logic = GameLogic()
game = Gui(logic)
game.mainloop()

rawDescription: How to properly organize this code?

description: Properly organize this code


code:
from string import ascii_uppercase

alphabet = list(ascii_uppercase) + [",", ".", "-", "_"]

rawDescription: Modified Vigenere Cipher in python - Alphabet


code: new_list = [sublist[0] for sublist in item]

rawDescription: How to create a nested list from an object?

description: Create a nested list from an object


code:
import urllib2
handler = urllib2.HTTPHandler()
opener = urllib2.build_opener(handler)
request = urllib2.Request('http://httpbin.org/post')
request.get_method = lambda: 'POST'
opener.open(request)

rawDescription: Python urllib2 setting timeout

description: Python urllib2 setting timeout


code:
with open("savegame", "rb") as f:
    foo = pickle.load(f)

rawDescription: how to make save / load game functions in pygame?

description: Make save / load game functions in pygame


rawDescription: generate a list of permutations that preserve a given partitioning (context: Graph Isomorphism)

description: Generate a list of permutations that preserve a given partitioning (context: Graph Isomorphism)


code: panel.SetHelpText("This is a wx.Panel.")

rawDescription: wxPython: Context dialog popup

description: WxPython: Context dialog popup


code:
#!/usr/bin/env python2
"""Communicate with a dummy controller from 10 worker threads.

- start controller subprocess, worker threads
- send all requests and check responses in worker threads concurrently
- wait until all responses are received
"""
import json
import logging
import sys
from Queue import Queue
from subprocess import Popen, PIPE
from threading import Thread

log = logging.getLogger(__name__).debug

def worker(tid, send_queue, receive_queue):
    """Send some dummy requests, get responses."""
    log('starting worker tid=%s', tid)
    for i in range(5):
        log('sending request key=%s, data=%d', tid, i)
        send_queue.put(dict(key=tid, data=i)) # send request
        response = receive_queue.get() # get response
        # check response
        log('got response %s, key=%s, data=%d', response, tid, i)
        assert response['key'] == tid and response['data'] == i**2

def reader(pipe, thread_queues):
    """Read responses from the controller (*pipe*).

       Dispatch them to the corresponding threads.
    """
    log('starting reader')
    with pipe:
        for line in iter(pipe.readline, b''): # read response from the controller
            log('got line %r', line)
            response = json.loads(line)
            # dispatch to the corresponding thread
            thread_queues[response['key']].put(response)

def writer(pipe, send_queue):
    """Write requests to the controller (*pipe*) from *send_queue*."""
    log('starting writer')
    with pipe:
        for request in iter(send_queue.get, None):
            log('sending request %s', request)
            print >>pipe, json.dumps(request)

def start_daemon_thread(*args, **kwargs):
    """Start and return daemonic thread."""
    t = Thread(*args, **kwargs)
    t.daemon = True # die with the program
    t.start()
    return t

def main():
    nthreads = 10
    timeout = 1 # seconds, for Ctrl+C
    logging.basicConfig(format="%(asctime)-15s %(threadName)s %(message)s",
                        datefmt='%F %T', level=logging.DEBUG)
    # start controller
    controller = Popen([sys.executable, "-u", "dummy_controller.py"],
                       stdin=PIPE, stdout=PIPE, bufsize=1)
    # start threads
    send_queue = Queue(maxsize=50) # limit number of queued requests (backlog)
    thread_queues = {tid: Queue() for tid in range(1, nthreads + 1)}
    threads = [start_daemon_thread(name='worker-' + str(tid),
                                   target=worker, args=[tid, send_queue, q])
               for tid, q in thread_queues.items()]

    # read/write until there are requests
    start_daemon_thread(name='writer', target=writer,
                        args=[controller.stdin, send_queue])
    log('about to start a reader')
    reader_thread = start_daemon_thread(name='reader', target=reader,
                                        args=[controller.stdout, thread_queues])
    # wait until workers are done
    while threads:
        for t in threads:
            t.join(timeout) # workaround, enable Ctrl+C on Python 2.7
            if not t.is_alive():
                threads.remove(t)
                break
    log('no worker threads')
    send_queue.put(None) # no more requests
    # wait until all responses are received
    while reader_thread.is_alive():
        reader_thread.join(timeout) # workaround, enable Ctrl+C on Python 2.7
    controller.wait() # wait for the subprocess to exit (to avoid zombies)
    log('done')

if __name__ == "__main__":
    main()

rawDescription: Reading and writing from a single serial port simultaneously from multiple threads


rawDescription: Create a 3-dimension list from two 2-dimension lists with a common element in each


rawDescription: How to test if all rows are equal in a numpy

description: Test if all rows are equal in a numpy


code:
def multiple_draws(count=5):
    results = []
    for i in range(count):
        results.append(generate_draw())
    return results

rawDescription: How can I loop a lottery number generator?

description: Loop a lottery number generator


code:
meter = ProgressMeter()
meter.process_with_timer()

rawDescription: Python, calculating the status of computation slows down the computation itself


code:
for i in xrange(multiprocessing.CPU_count()):
    mp = multiprocessing.Process(target=foo, args=(bar,), name=i).start()

rawDescription: Python multiprocessing: knowing the thread/CPU number


code:
def avg(l):
    if l:
        return sum(l)/len(l)
    return 0

def score(s, d):
    return avg([d.get(x,[0])[0] for x in s.lower().split()])

rawDescription: List comprehension with averages

description: List comprehension with averages


code:
n = 0
spacesLocation = []
while(True):
    try:
        spacesLocation.append(userInput.index(' '))
        userInput = userInput.replace(' ', '', 1)
        n+=1
    except:
        n = 0
        break

rawDescription: Python: Moving letters within the alphabet in a string


code:
if {}.viewkeys() < kargs.viewkeys() < {'dollar', 'euro'}:
    raise ValueError('One keyword argument is required: dollar=x or euro=x')

rawDescription: Require one out of two keyword arguments


code: [l.split('\\')[-1] for l in list_dirs]

rawDescription: Remove string from list if from substring list


code:
class myClass:
    def __init__(self, myFunc = lambda:None):
        self.doIt = myFunc

rawDescription: Is there a python construct that is a dummy function?


code:
with open("infile") as f:
    d = {}
    for k,v in csv.reader(f,delimiter=" "):
        d.setdefault(k , 0)
        d[k] += int(v)

rawDescription: From list getting keys and values

description: From list getting keys and values


code:
def traverse(rootdir):
    names = []
    dirs, files = [], []
    for filename in os.listdir(rootdir):
        filepath = os.path.join(rootdir, filename)
        if os.path.isdir(filepath):
            names.append([filename, traverse(filepath)])
        else:
            names.append(filename)
    return sorted(names, key=lambda x: (0, x[0]) if isinstance(x, list) else (1, x))

rawDescription: Python File Transversal

description: Python File Transversal


code:
# importer.py
import importee
importee.call_me(4)

rawDescription: Is there a way to get importer's variable in importee?


code:
def transform(d, k, f):
    d[k] = f(d[k])

rawDescription: Is there a shorthand for using the same variable being assigned for the argument in a function?


rawDescription: How can I plot multiple lines using the same array and set disconnect points in python?

description: Plot multiple lines using the same array and set disconnect points in python


code:
import datetime
df = pd.DataFrame({'person':[1,1,1,2,2,3,3,3],
                  'record':[1,2,3,1,2,1,2,3],
                  'date' : [datetime.date(2015, 8, i) for i in range(1,9 )]})

df.pivot('person', 'record', 'date')

rawDescription: Pandas DataFrame Self-Join on Key1 == Key1 and Key2 +1 == Key2


code:
print(df.describe())
print(df_2)

rawDescription: Create DataFrame from another DataFrame.describe() - Pandas


code:
initparms = {k:v for k,v in kwargs.items()
             if k in ['text','and','other','valid','params']}

rawDescription: how to pythonically pass arguments to methods of subclassed widgets?

description: Pythonically pass arguments to methods of subclassed widgets


code:
import datetime as dt
def read_file():
    user_input = raw_input("Please put cost folder with date in form Costmm.dd: ")
    path = r'C:\\Users\\CP\\documents\\' + user_input
    allFiles = glob.glob(path + '/*.csv')

    l = []
    for file in allFiles:
        df = pd.read_csv(file,index_col=None,header=0)
        l.append(df)
    frame =pd.concat(l,ignore_index=True)
    frame['Date'] = dt.datetime.strptime(user_input, '%m.%d')
    return frame

rawDescription: How do I fill a column with a user inputted value?

description: Fill a column with a user inputted value


code:
from itertools import groupby
import re

str1 = "A>1 and A>3 and B<2 and B<3"
comparisions = [s.strip() for s in str1.split("and")]
operands = [re.search(r'(\w+)([<>][=]?)(\w+)',c).groups() for c in comparisions]#

tot={}#total results
for k,g in groupby(operands,lambda x:x[0]):#group by variable1
    for arg in g:#arg is the match with list [var1,compareitem,var2]
        if k not in tot:tot[k] = {}
        if arg[1] in tot[k]:
            print("do the overwrite handling!")
        tot[k][arg[1]] = arg[2]

#sort tot
sortedkeys = sorted(tot, key=lambda x: x[0])

resub_str = " and ".join([comp+"".join([k+tot[comp][k] for k in tot[comp]]) for comp in sortedkeys])
print(resub_str)

rawDescription: What is the fastest way to do this string patten substitution based on the logical relations in Python?


rawDescription: Getting datetime from binary

description: Getting datetime from binary


code:
engine = sqlalchemy.create_engine("sqlite:///:memory:/")
raw_con = engine.raw_connection()
raw_con.create_function("cos", 1, math.cos)
raw_con.create_function("acos", 1, math.acos)

class Location(...):
    ...
    @hybrid_method
    def great_circle_distance(self, other):
        """
        Tries to calculate the great circle distance between
        the two locations by using the Haversine formula.

        If it succeeds, it will return the Haversine formula
        multiplied by 3959, which calculates the distance in miles.

        If it cannot, it will return None.

        """
        return math.acos(  self.cos_rad_lat
                         * other.cos_rad_lat
                         * math.cos(self.rad_lng - other.rad_lng)
                         + self.sin_rad_lat
                         * other.sin_rad_lat
                         ) * 3959

    @great_circle_distance.expression
    def great_circle_distance(cls, other):
        return sqlalchemy.func.acos(  cls.cos_rad_lat
                         * other.cos_rad_lat
                         * sqlalchemy.func.cos(cls.rad_lng - other.rad_lng)
                         + cls.sin_rad_lat
                         * other.sin_rad_lat
                         ) * 3959

rawDescription: Python - SqlAlchemy: Filter query by great circle distance?


rawDescription: Python 2.7 rounding vs Python 3

description: Python 2.7 rounding vs Python 3


code:
# app/templatetags/attr_tags.py

from django import template

register = template.Library()

@register.filter
def get_attribute(value, arg):
    return getattr(value, arg)

rawDescription: Using a variable to extract data from a database in Django


code:
class MyDialog(QtGui.QDialog):
    # ...
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)

        # when you want to destroy the dialog set this to True
        self._want_to_close = False

    def closeEvent(self, evnt):
        if self._want_to_close:
            super(MyDialog, self).closeEvent(evnt)
        else:
            evnt.ignore()
            self.setWindowState(QtCore.Qt.WindowMinimized)

rawDescription: How do I catch a pyqt closeEvent and minimize the dialog instead of exiting?

description: Catch a pyqt closeEvent and minimize the dialog instead of exiting


code:
rb_list = [ rb1, rb2, rb3 ] # where items are your radio buttons
#these can be appended to the list when the objects are created
def rb_check(rbl=rb_list):
    for rb in rbl:
        if rb.isChecked():
            print("RadioButton", rb, "is checked.") # or return value

rawDescription: Binding Variable PyQt Radio Buttons

description: Binding Variable PyQt Radio Buttons


rawDescription: Implementing a Linked List in Python

description: Implementing a Linked List in Python


code:
df= pd.DataFrame({'ACCOUNT':["ACCT1", "ACCT1", "ACCT1", "ACCT2"],
                  'TICKER':["ABC", "MNP", "XYZ", "XYZ"],
                  'val':[1,2,3,4]},
                 index=pd.date_range("2013-06-19 09:30:00", periods=4, freq='5T'))
df = df.set_index(['ACCOUNT', 'TICKER'], append=True)
df.loc[(pd.Timestamp('2013-06-19 09:30:00'), 'ACCT1', 'ABC')]

rawDescription: Groupby and Multi indexing

description: Groupby and Multi indexing


code:
import itk
meshType2D = itk.Mesh.D2Q.New()
meshType3D = itk.Mesh.D3Q.New()

rawDescription: How to create a mesh object in ITK using Python bindings?

description: Create a mesh object in ITK using Python bindings


code:
#coding: utf-8 (there is # dont know how to show it here...)
import tornado.ioloop
import tornado.web

class Abdou(tornado.web.RequestHandler):
    def get(self):
        self.write("hi")

miaw = tornado.web.Application([
(tornado.escape.url_escape(u'/ééé'), Abdou),
])

if __name__ == "__main__":
    miaw.listen(8000)
    tornado.ioloop.IOLoop

rawDescription: Tornado and Unicode

description: Tornado and Unicode


rawDescription: How read bits in 64 bit data put into corresponding bitfields in python


code: subprocess.call('echo hello')

rawDescription: File gets created, but subprocess call says no such file or directory


code:
def fileManipulator():
    infile=browse()
    outfile="C:\\out\\File.kml"
    #code that manipulates the file here
    file.save(outfile)

rawDescription: Execute function when button is pressed, not when script runs


code:
collatz(5)
collatz(17)

rawDescription: Python repeat: Is there a conditional/lambda based repeat method for python?


rawDescription: how to move all non-zero elements in a python list or numpy array to one side?

description: Move all non-zero elements in a python list or numpy array to one side


code:
class crawledScore(scrapy.Item):
    reviewScore = scrapy.Field()
    reviewCount = scrapy.Field()
    reviewURL = scrapy.Field()

rawDescription: Saving Scrapy data to corresponding URL in MySQL


code:
def index(request):
    if request.method=="POST":
        uploaded_file = request.FILES['some_file'] # get the uploaded file
        # do something with the file

rawDescription: Python/Django - using a view method on an upload file


code: map(sum, zip(*vd.values()))

rawDescription: How to add elements from a dictonary of lists in python

description: Add elements from a dictonary of lists in python


code:
AM_PM = line[-6:-4]
second = int(line[-9:-7])
minute = int(line[-12:-10])

rawDescription: Parse timestamps containing different lengths Python


code:
import random
num1 = int(input("Input First number: "))
num2 = int(input("Input Second number: "))
random_numbers = [random.uniform(num1, num2) for i in range(10)]
random_numbers
print(sum(random_numbers)/len(random_numbers))

rawDescription: How to calculate the average number of random numbers generated?

description: Calculate the average number of random numbers generated


code:
class MyForm(forms.Form):
    # For BooleanFields, required=False means that Django's validation
    # will accept a checked or unchecked value, while required=True
    # will validate that the user MUST check the box.
    something_truthy = forms.BooleanField(required=False)

rawDescription: Django check if checkbox is selected

description: Django check if checkbox is selected


code:
import subprocess as s
def killProcess(pid):
    s.Popen('taskkill /F /PID {0}'.format(pid), shell=True)

rawDescription: Terminate a python script from another python script


code:
from twisted.web.client import getPage

cookies = {}
d = getPage(
    "https://example.com/auth",
    method="POST",
    headers={"content-type": "application/x-www-form-urlencoded"},
    postdata=urllib.urlencode(dict(Email="alice@example.com", Password="secret")),
    cookies=cookies)

rawDescription: Login to web page using twisted web

description: Login to web page using twisted web


rawDescription: How to updating dict items inside a list of dicts

description: Updating dict items inside a list of dicts


code:
from numpy.lib.stride_tricks import as_strided

a = np.arange(1, 9) # the starting array
slice_length = 4

rawDescription: Efficient 2d cumsum

description: Efficient 2d cumsum


code:
len(test)
len(train)

rawDescription: How do I create test and train samples from one dataframe with pandas?

description: Create test and train samples from one dataframe with pandas


code: r1 = re.compile(r"\.pdf$")

rawDescription: Regular expression in Python won't match end of a string


rawDescription: Text string into lists

description: Text string into lists


code:
def inf_gen(f):
    while True:
        yield f()

rawDescription: A function-like variable

description: A function-like variable


code:
import pandas as pd
df1 = pd.DataFrame.from_csv("file1.csv", sep=",")
df2 = pd.DataFrame.from_csv("file2.csv", sep=",")
final_df = df1.reset_index().merge(df2.reset_index(), how="outer").set_index('ID')

final_df.to_csv("result.csv", sep=",")

rawDescription: Merge CSVs using Python (or Bash)

description: Merge CSVs using Python (or Bash)


rawDescription: getting the prefix of a number in python

description: Getting the prefix of a number in python


code:
max_value = max(example_list)
total = sum(example_list)

rawDescription: Python number processing trouble

description: Python number processing trouble


rawDescription: How to add a statement that checks for numbers or punctuation in a string

description: Add a statement that checks for numbers or punctuation in a string


code:
min_, max_ = min_max(ll.next) # call once
return min(min_, ll.value), max(max_, ll.value) # use the two values

rawDescription: How to speed up recursive call on Python linked list?

description: Speed up recursive call on Python linked list


code:
[{"param331": value, "param332": value},
 {"param331": value, "param332": value},
 {"param331": value, "param332": value}]

rawDescription: How to assign floats to some fields of json dumps using a for loop

description: Assign floats to some fields of json dumps using a for loop


code:
age.get_group(21)
list(permutations(age.get_group(21).index))
[df.loc[list(p)] for p in permutations(age.get_group(21).index)]

rawDescription: Quick way to find all permutations of a pandas DataFrame that preserves a sort?


rawDescription: Convert a float to a two-digit hex number in Python


rawDescription: Regex match following substring in string python


code:
import struct
a = struct.unpack('cccc', struct.pack('I', 0x12345678))
b = sum([[a[i+1], a[i]] for i in range(0, len(a), 2)], [])
struct.pack('cccc', *b)

rawDescription: How to pack in a certain order with Python

description: Pack in a certain order with Python


rawDescription: Selenium/python - fails to find partial link text


code:
@app.route('/')
@login_required
def index():
    pass

rawDescription: Flask-Login extension, enabling login on modules


rawDescription: Insertion Sort Python

description: Insertion Sort Python


code:
parser._actions
parser.print_help()

rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


code:
tag.find('code').find_all_previous('a')
for i in tag.find('code').find_all_previous('a'):
    i.extract()

tag

rawDescription: How to scrape elements that immediately follows a certain element?

description: Scrape elements that immediately follows a certain element


code:
command = "window.frames['IFrame2'].document.getElementById('elementInFrame2')"
driver.execute_script(command)

rawDescription: Several iFrames in multiple processes?

description: Several iFrames in multiple processes


rawDescription: IPython.parallel client is hanging while waiting for result of map_async


rawDescription: using scipy.integrate.odeint with dictionary [Python]

description: Using scipy.integrate.odeint with dictionary [Python]


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

labels = 'ABCDEFGHIKJLMNOPQRSTUV'
data = np.random.random((len(labels), len(labels)))

fig, ax = plt.subplots()
ax.matshow(data)
ax.set(xticks=np.arange(len(labels)), xticklabels=labels,
       yticks=np.arange(len(labels)), yticklabels=labels)
plt.show()

rawDescription: matplotlib - Large Heatmap

description: Matplotlib - Large Heatmap


rawDescription: compare two dictionaries of different keys in python

description: Compare two dictionaries of different keys in python


code: right_index = max(map(text.rfind, '+-/*'))

rawDescription: Python: Using find function not in order


code:
def func(x):
   return x*x

rawDescription: pass function to function with different number of variables

description: Pass function to function with different number of variables


code: format(addrint, '#04x')

rawDescription: Convert an integer to a 2 byte Hex value in Python


code:
groups = Group.objects.all().annotate(last_response=Max('discussion__discussionresponse__timestamp')).order_by('-last_response')
for group in groups:
    print(group.id, group.last_response)

rawDescription: Django: how to order_by on a related field of a related field


code:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz

def get_timezone_with_different_date(input_timezone_id, now=None):
    """
    input_timezone_id: the tz database id such as 'America/New_York'
    now: a naive datetime object representing time in input_timezone_id
    """
    input_tz = pytz.timezone(input_timezone_id)
    if now is None:
       now = datetime.now(input_tz) # use the current time
    else:
       now = input_tz.localize(now, is_dst=None) # make it timezone-aware

    for tz in map(pytz.timezone, pytz.all_timezones_set):
        if tz.normalize(now.astimezone(tz)).date() != now.date():
             return tz.zone
    assert 0, 'never happens'

rawDescription: Obtaining a Time Zone Locale that is Different from Local Machine


code:
import re
ansi_escape = re.compile(r'\x1b[^m]*m')
sometext = 'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m'
ansi_escape.sub('', sometext)

rawDescription: How can I remove the ANSI escape sequences from a string in python

description: Remove the ANSI escape sequences from a string in python


code:
from itertools import izip_longest

def apply_pairwise(lst, f, loops=1):
    if loops == 0:
        return lst
    new_lst = [f(a,b) for a,b in zip(lst, lst[1:])]
    next_lst = [e for t in izip_longest(lst, new_lst) for e in t if e]
    return apply_pairwise(next_lst, f, loops-1)

rawDescription: Algorithm to generate a series

description: Algorithm to generate a series


code:
m_set=set(M)
any(x in m_set  for x in L)

rawDescription: efficiently knowing if intersection of two list is empty or not, in python

description: Efficiently knowing if intersection of two list is empty or not, in python


code:
def getkey(tup):
    a, b = tup[0].split('_')
    return Reverser(a), b

my_list.sort(key=getkey)

rawDescription: Help sorting: first by this, and then by that


code:
import ldap

# connect to your ldap server

some_dn = '...' # Your base dn
some_lookup = '...' # your lookup attr

result = conn.search_s(some_dn,ldap.SCOPE_SUBTREE,some_lookup)
result[0][1].keys()

rawDescription: How to retrieve all the attributes of LDAP database

description: Retrieve all the attributes of LDAP database


code:
ships = [item['name'] for item in data['ships'].values()]
ships

rawDescription: TypeError: string indices must be integers - Parsing JSON


code:
('!!', None, None, None)
(None, '!!', None, None)
(None, None, '!!', None)
(None, None, None, '!!')

rawDescription: Pass in argument to function by name dynamically


code:
class UserCategoryListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('Department',)

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'department'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        if not request.user.is_superuser:
            return (
                (request.user.customuser.department.name, _(request.user.customuser.department.name)),
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # to decide how to filter the queryset.
        if request.user.is_superuser:
            if self.value() == request.user.customuser.department.name:
                return queryset.filter(
                    department__in=Department.objects.filter(
                        name=request.user.customuser.department.name))
        else:
            return queryset

rawDescription: django1.8 filter list_filter based on login

description: Django1.8 filter list_filter based on login


rawDescription: Calculating average of numbers in a file


rawDescription: Python Special Chars Escape

description: Python Special Chars Escape


code: lst

rawDescription: output is column and want it to be in a row

description: Output is column and want it to be in a row


code:
data = {}
for row in soup.select('#content #table .row'):
    key, value = (cell.text for cell in row.select('.cell'))
    data[key.rstrip(' :')] = value.strip()

rawDescription: extract only a few lines from output

description: Extract only a few lines from output


rawDescription: How to recursively check all combinations of list python

description: Recursively check all combinations of list python


code:
concordance_index = ConcordanceIndex2([x.encode('utf-8') for x in tokens], key=lambda s: s.lower())    # encoded here to match an encoded text
concordance_index.print_concordance(u'\u039a\u0391\u0399\u03a3\u0391\u03a1\u0395\u0399\u0391\u03a3'.encode('utf-8'))

rawDescription: Concordance Unicode characters in Unicode corpus in nltk


code:
class Feline(models.Model):
    objects = models.Manager()

class Cat(models.Model):
    objects = models.Manager()

    name = models.CharField(max_length=255)
    miaow_factor = models.IntegerField()

rawDescription: How to create a superclass (for an existing model) with Django and South

description: Create a superclass (for an existing model) with Django and South


code:
def longitudinal_parity(data, total_bits, word_bits, expected_parity=1):
    """
    Performs longitudinal parity check
    """
    for nbits in (total_bits, word_bits):
        if nbits & (nbits - 1):
            raise ValueError("bit size must be power of two")

    mask = (1 << total_bits) - 1

    while total_bits > word_bits:
        total_bits >>= 1
        data ^= (data >> total_bits)
        mask >>= total_bits
        data &= mask
    return data == (mask if expected_parity else 0)

rawDescription: Python - How to break word into 64bit chunks


code:
grouped = itertools.groupby(map(str.strip, st.splitlines()), bool)
[list(g) for k,g in grouped if k]

rawDescription: Python itertools groupby not grouping as I expect


code:
from itertools import groupby, islice
myList = [True, True, False, False, True, False, True, False, False]
[sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
myList = [True, True, False, False, True, True, True, True, False, True, False, False]
[sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)

rawDescription: find if element appears n times in a row in python list

description: Find if element appears n times in a row in python list


rawDescription: How to extract a common name from multipal filenames and delete something I don't want

description: Extract a common name from multipal filenames and delete something I don't want


code:
# modulec.py
import modulea
import moduleb  # <-- actually this import does not reload the moduleb, since it was already loaded in modulea, and it was cached.

rawDescription: How to import appropriately

description: Import appropriately


code:
import xml.etree.ElementTree as ET
file = ET.parse('a.xml')
root = file.getroot()
for elem in root.findall('.//trigger/external'):
    check_req_elems = elem.find('./action[@name="check_req"]')
    check_elem = elem.find('./action[@name="ckeck"]')
    if check_req_elems is not None and check_elem is not None:
            elem.remove(check_elem)

file.write('b.xml')

rawDescription: How to delete a particular line in xml file based on the condition using python?

description: Delete a particular line in xml file based on the condition using python


rawDescription: Name of a list changing as I go through a loop


code:
class IterRegistry(type):
    def __iter__(cls):
        return iter(cls._registry)

class Person(object):
    __metaclass__ = IterRegistry
    _registry = []

    def __init__(self, name):
        self._registry.append(self)
        self.name = name

rawDescription: Iterating over object instances of a given class in Python


code:
# open file
f = open(log1, 'r')
# for each line of the file
for line1 in f:
    # print the line
    print (line1)

rawDescription: How to print single lines from file

description: Print single lines from file


code:
import myBoostPythonModule
from PySide.QtCore import *
...
x=myBoostPythonModule.X('foo') # Boost.Python knows how to convert C++ X
                               # to Python X.  Python's type system does not.

w=QPointF()                    # Shiboken knows how to convert C++ QPointF to
                               # Python QPointF.  Python's type system does not.
print(w)                       # Shiboken knows how to represent C++ QPointF as
                               # a string.

y=x.getY()                     # Boost.Python knows how to invoke X::getY(),
                               # but only Shiboken knows how to convert C++
                               # QPointF to Python QPointF.  Thus, the TypeError
                               # exception is raised.

rawDescription: import classes from pyside inside of a boost python module?

description: Import classes from pyside inside of a boost python module


code:
import base64
from Crypto.Cipher import AES
from Crypto.Hash import SHA256

PAD = "X"

def key_hash(key):
    return SHA256.new(key.encode()).digest()

def encrypt(text, key):
    while len(text) % 16 != 0:
        text += PAD
    cipher = AES.new(key_hash(key))
    encrypted = cipher.encrypt(text.encode())
    return base64.b64encode(encrypted).decode()

def decrypt(text, key):
    cipher = AES.new(key_hash(key))
    plain = cipher.decrypt(base64.b64decode(text))
    return plain.decode().rstrip(PAD)

if __name__ == '__main__':
    e = encrypt("This is my string.", "password")
    p = decrypt(e, "password")
    print("Encrypted:", e)
    print("Plain:", p)

rawDescription: Why I am not able to decrypt what I encrypted with pycrypto?


rawDescription: How could I convert a contour plot (matplotlib) to FITS format with header?


code:
for word in word_list:
    for res in findall(word, elements):
        print(word, res)

rawDescription: is recursion the solution ?- Python

description: Is recursion the solution ?- Python


code:
new_values = []
for x in range(0, len(allowed)):
    new_values.extend([(x, val) for val in found[x] if val not in allowed[x]])

rawDescription: List comprehension missing some values versus writing loops


code:
self.matches = [s for s in self.options
                   if text in s]

rawDescription: How to code autocompletion in python?

description: Code autocompletion in python


code:
def gobbleExpr(expr):
    if isinstance(expr, Gobbler):
        return expr
    if isinstance(expr, Mul):
        args = list(o if o.is_Atom or isinstance(o, Gobbler)
                    else gobbleExpr(o)
                    for o in expr.args)
        gobbler = prod(t for t in args if isinstance(t, Gobbler))
        others = prod(o for o in args if not isinstance(o, Gobbler))
        if gobbler==1:
            return others
        else:
            return gobbler.__mul__(others)
    if isinstance(expr, Add):
        return sum(gobbleExpr(arg) for arg in expr.args)
    return expr

rawDescription: Force evaluation of Mul(tiplication) in sympy


code:
items = [
    {'label': 'label1',
     'link': 'link1',
     'children': [
         {'label':'label1.1', 'link': 'link1.1'},
         {'label':'label1.2', 'link': 'link1.2'}
         ]
     },
    {'label': 'label2',
     'link': 'link2',
     'children': [
         {'label':'label2.1', 'link': 'link2.1'},
         {'label':'label2.2', 'link': 'link2.2'}
         ]
     },
    # etc
    ]

rawDescription: Handle n menu items in template engine

description: Handle n menu items in template engine


rawDescription: Erase whole array Python

description: Erase whole array Python


code:
import sys
major, minor, micro, releaselevel, serial = sys.version_info
if (major,minor) <= (2,5):
    # provide advice on getting version 2.6 or higher.
    sys.exit(2)
import app
app.main()

rawDescription: Python graceful future feature (__future__) import


code:
def files(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            yield file

rawDescription: List only files in a directory?

description: List only files in a directory


code:
{'Abitibi-Témiscamingue': ['Rouyn-Noranda', 'Témiscamingue', "Val-d'Or"],
 'Agglomération de Longueuil': ['Boucherville',
                                'Brossard',
                                'Greenfield Park',
                                'Longueuil',
                                'Saint-Bruno',
                                'Saint-Hubert',
                                'Saint-Lambert'],
 'Ahuntsic-Cartierville': [],
 'Alma': [],
 'Anjou': [],
 'Baie-Comeau': [],
 'Bas-Saint-Laurent': ['Rimouski', 'Rivière-du-Loup'],
 'Beaconsfield': [],
 'Beloeil': [],
 'Blainville': [],
 'Boisbriand': [],
 'Boucherville': [],
 'Brossard': [],
 'Capitale-Nationale': ['Québec'],
 'Centre-du-Québec': ['Drummondville', 'Victoriaville'],
 'Chambly': [],
 'Chaudière-Appalaches': ['Lévis', 'Saint-Georges', 'Thetford Mines'],
 'Chicoutimi': [],
 'Châteauguay': [],
 'Côte Saint-Luc': [],
 'Côte-Nord': ['Baie-Comeau', 'Sept-Îles'],
 'Côte-des-Neiges—Notre-Dame-de-Grâce': [],
 'Dollard-des-Ormeaux': [],
 'Dorval': [],
 'Drummondville': [],
 'Estrie': ['Magog', 'Sherbrooke'],
 'Gaspé': [],
 'Gaspésie-Îles-de-la-Madeleine': ['Gaspé', 'Îles-de-la-Madeleine'],
 'Gatineau': [],
 'Granby': [],
 'Greenfield Park': [],
 'Joliette': [],
 'Jonquière': [],
 'Kirkland': [],
 "L'Assomption": [],
 'La Baie': [],
 'La Prairie': [],
 'LaSalle': [],
 'Lachine': [],
 'Lanaudière': ['Joliette',
                "L'Assomption",
                'Mascouche',
                'Repentigny',
                'Terrebonne'],
 'Laurentides': ['Blainville',
                 'Boisbriand',
                 'Mirabel',
                 'Sainte-Thérèse',
                 'Saint-Eustache',
                 'Saint-Jérôme'],
 'Laval': [],
 'Le Plateau-Mont-Royal': [],
 'Le Sud-Ouest': [],
 'Longueuil': [],
 'Lévis': [],
 'L’Île-Bizard—Sainte-Geneviève': [],
 'Magog': [],
 'Mascouche': [],
 'Mauricie': ['Shawinigan', 'Trois-Rivières'],
 'Mercier—Hochelaga-Maisonneuve': [],
 'Mirabel': [],
 'Mont-Royal': [],
 'Montréal': ['Ahuntsic-Cartierville',
              'Anjou',
              'Beaconsfield',
              'Côte-des-Neiges—Notre-Dame-de-Grâce',
              'Côte Saint-Luc',
              'Dollard-des-Ormeaux',
              'Dorval',
              'L’Île-Bizard—Sainte-Geneviève',
              'Kirkland',
              'Lachine',
              'LaSalle',
              'Mercier—Hochelaga-Maisonneuve',
              'Montréal-Nord',
              'Mont-Royal',
              'Outremont',
              'Pierrefonds-Roxboro',
              'Le Plateau-Mont-Royal',
              'Pointe-Claire',
              'Rivière-des-Prairies—Pointe-aux-Trembles',
              'Rosemont—La Petite-Patrie',
              'Saint-Laurent',
              'Saint-Léonard',
              'Le Sud-Ouest',
              'Verdun',
              'Ville-Marie',
              'Villeray—Saint-Michel—Parc-Extension',
              'Westmount'],
 'Montréal-Nord': [],
 'Montérégie': ['Beloeil',
                'Chambly',
                'Châteauguay',
                'Granby',
                'La Prairie',
                'Saint-Constant',
                'Sainte-Julie',
                'Saint-Hyacinthe',
                'Saint-Jean-sur-Richelieu',
                'Salaberry-de-Valleyfield',
                'Sorel-Tracy',
                'Varennes',
                'Vaudreuil-Dorion'],
 'Nord-du-Québec': [],
 'Outaouais': ['Gatineau'],
 'Outremont': [],
 'Pierrefonds-Roxboro': [],
 'Pointe-Claire': [],
 'Québec': [],
 'Repentigny': [],
 'Rimouski': [],
 'Rivière-des-Prairies—Pointe-aux-Trembles': [],
 'Rivière-du-Loup': [],
 'Rosemont—La Petite-Patrie': [],
 'Rouyn-Noranda': [],
 'Saguenay-Lac-Saint-Jean': ['Alma', 'Chicoutimi', 'Jonquière', 'La Baie'],
 'Saint-Bruno': [],
 'Saint-Constant': [],
 'Saint-Eustache': [],
 'Saint-Georges': [],
 'Saint-Hubert': [],
 'Saint-Hyacinthe': [],
 'Saint-Jean-sur-Richelieu': [],
 'Saint-Jérôme': [],
 'Saint-Lambert': [],
 'Saint-Laurent': [],
 'Saint-Léonard': [],
 'Sainte-Julie': [],
 'Sainte-Thérèse': [],
 'Salaberry-de-Valleyfield': [],
 'Sept-Îles': [],
 'Shawinigan': [],
 'Sherbrooke': [],
 'Sorel-Tracy': [],
 'Terrebonne': [],
 'Thetford Mines': [],
 'Tout Arrondissement.com': [],
 'Trois-Rivières': [],
 'Témiscamingue': [],
 "Val-d'Or": [],
 'Varennes': [],
 'Vaudreuil-Dorion': [],
 'Verdun': [],
 'Victoriaville': [],
 'Ville-Marie': [],
 'Villeray—Saint-Michel—Parc-Extension': [],
 'Westmount': [],
 'Îles-de-la-Madeleine': []}

rawDescription: Beautiful soup select siblings not working


code: bool([a for a in my_dict.values() if a != []])

rawDescription: One liner to determine if dictionary values are all empty lists or not


rawDescription: Why is hardcoding this list slower than calculating it?


code: Parallel(n_jobs=num_cores)(delayed(parallel)(a) for a in range(0,500,10))

rawDescription: Paralleling without function is possible?


code: all_decisions = [x for x in all_decisions if x[4] != 0]

rawDescription: Removing Line From Python List - All Lines Containing Certain Number


code: TarFile.addfile(tarinfo, fileobj=None)

rawDescription: Archiving (tar and compress) with metadata (user id, and ctime) in Python


code:
import matplotlib.pyplot  as pyplot
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)
line, = ax.plot(w/np.max(w), h_dB, color='blue', lw=2)
ax.set_xscale('log')

show()

rawDescription: IIR response in Python

description: IIR response in Python


code: data = numpy.genfromtxt(t_in, dtype=None, usecols=(0,1), skip_header = minutesOld - 360)

rawDescription: How to read a file from the bottom with numpy.genfromtxt in python

description: Read a file from the bottom with numpy.genfromtxt in python


code:
import dill
import foo

class Foo:
    y = 1
    def bar( self, x ):
        return x + Foo.y

f = Foo()
ff = foo.Foo()

rawDescription: Why dill dumps external classes by reference, no matter what?


rawDescription: Comparing rows elements in python

description: Comparing rows elements in python