rawDescription: Python Pandas Compare 2 Large DataFrames of Text for Similarity


code:
import test_module

def dummy_sleep(*args, **kwargs):
    pass

test_module.time.sleep = dummy_sleep
e = test_module.Example()
e.foo()

rawDescription: Can Python do DI seamlessly without relying on a service locator?


rawDescription: A superfluous but cool dynamic python structure and questions about decorators, comprehensions, syntax


code: (["-".join((a,b) if a < b else (b,a)) for b in shops if b != a] for a in shops)

rawDescription: Fast way of crossing strings in a list

description: Fast way of crossing strings in a list


code: {'type': 'str', 'name': 'yowza!', 'value': 'c:\\test\\3 tests\\test'}

rawDescription: XML to store system paths in Python with lxml


code: m = re.compile(r'\d{%d}:\d{%d}' % (int(var1), int(var2)))

rawDescription: How to use in python regular expression

description: Use in python regular expression


code: first|a|b

rawDescription: How to unpack a list?

description: Unpack a list


code:
# to use the last parameter (border), you have to
# specify which border(s) to use in the flag parameter:
# wx.TOP, wx.BOTTOM, wx.LEFT, wx.RIGHT, a combination
# of them, or wx.ALL
main_sizer2.Add(self.toolBar, 0, wx.EXPAND|wx.BOTTOM, 5)
main_sizer2.Add(self.searchBar, 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
# proportion missing:
main_sizer.Add(main_sizer2, 1, wx.EXPAND)

rawDescription: wxPython Nested Panel and Sizers

description: WxPython Nested Panel and Sizers


code:
namestaj = open("komad_namestaja.txt", "r")
oldNamestaj = namestaj.read()
namestaj.close()

rawDescription: Writing new line in file with unique parameter


rawDescription: Python - Spot it! Cards

description: Python - Spot it! Cards


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

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label

class Example(App):
    def build(self):
        self.root = FloatLayout()
        self.label = Label(text="I'm aligned :)", size_hint=(1.0, 1.0), halign="left", valign="middle")
        self.label.bind(size=self.label.setter('text_size'))
        self.root.add_widget(self.label)
        return self.root

Example().run()

rawDescription: Python Kivy: Align text to the left side of a Label


code:
try:
    xrange
except NameError:  # Python 3
    xrange = range

def grouper(n, sequence):
    for i in xrange(0, len(sequence), n):
        yield sequence[i:i+n]

pairwise = functools.partial(grouper, 2)

rawDescription: Creating a python dictionary from a line of text


code:
from itertools import chain
f = lambda x: x + 2
g = lambda x: x ** 2
list(chain.from_iterable((f(x), g(x)) for x in range(3)))

rawDescription: Python (List Comprehension): Returning two (or more) items for each item


code:
pwd_context=_get_pwd_context(app)

def _get_pwd_context(app):
    ...
    return CryptContext(schemes=schemes, default=pw_hash, deprecated=deprecated)

from passlib.context import CryptContext

rawDescription: Unique Salt per User using Flask-Security


code: frame[frame.duplicated(['key1', 'key2'], take_last=True) | frame.duplicated(['key1', 'key2'])].groupby(('key1', 'key2')).min()

rawDescription: How to analyze all duplicate entries in this Pandas DataFrame?

description: Analyze all duplicate entries in this Pandas DataFrame


code:
from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Extracting two numbers in each loop iteration


code: cs[i] = c

rawDescription: Python: Speeding up a slow for-loop calculation (np.append)


code:
ax.set_title('Wage Variance and Mean Age')
plt.show()

rawDescription: Legend only shows one label when plotting with pandas


code:
data_frames = []
with open("file2.txt") as f:
        for k, v in groupby(islice(f, 3, None),key=lambda x:  x.strip()[0:1].isdigit()):
            val = list(v)
            if k:
                data_frames.append(pd.DataFrame(map(str.split,val)))
            elif val[-1] == 'Top Total\n':
                break
print(data_frames) # three dataframes in a list

rawDescription: Python read numerical blocks (separated by single line of text) from text file into Numpy array or Pandas DataFrame


code:
with open('spiders.txt') as fh:
    words = set(re.split(r'[ \n\r]+', fh.read())) # set of searched words

with open('access.log.13') as file_in, \
     open('hits.txt', 'w') as file_out:
    for line in file_in:
        if any(word in line for word in words): # look for any of the words
            file_out.write(line)

rawDescription: Searching words from a file in another file


rawDescription: Remove list element without mutation

description: Remove list element without mutation


rawDescription: Dihedral/Torsion Angle From Four Points in Cartesian Coordinates in Python


code:
a, *b = foo()
a
b
*a, b = foo()
a
b
a, *b, c = foo()
a
b
c

rawDescription: Is it possible for a python function to return more than 1 value?


code:
filenames = [
    'Report_Test-01-16-2014.09_42-en.zip',
    'Another Report_Test-01-16-2014.09_42-en.zip',
    'Report_Holiday-01-16-2014.09_42-en.zip',
    'Report_Weekday-01-16-2014.09_42-en.zip',
    'Report_Special-01-16-2014.09_42-en.zip',
    'Report_Test-12-16-2013.10_52-en.zip',
    'Another Report_Test-12-16-2013.10_52-en.zip',
    'Report_Holiday-12-16-2013.10_52-en.zip',
    'Report_Weekday-12-16-2013.10_52-en.zip',
    'Report_Special-12-16-2013.10_52-en.zip',
] # Used in place of `os.listdir(....)`

import re
import datetime

date_pattern = re.compile(r'\b(\d{2})-(\d{2})-(\d{4})\b')
def get_date(filename):
    matched = date_pattern.search(filename)
    if not matched:
        return None
    m, d, y = map(int, matched.groups())
    return datetime.date(y, m, d)

dates = (get_date(fn) for fn in filenames)
dates = (d for d in dates if d is not None)
last_date = max(dates)
last_date = last_date.strftime('%m-%d-%Y')
filenames = [fn for fn in filenames if last_date in fn]
for fn in filenames:
    print(fn)

rawDescription: get latest file based on filename python

description: Get latest file based on filename python


rawDescription: numpy: copying value defaults on integer indexing vs boolean indexing

description: Numpy: copying value defaults on integer indexing vs boolean indexing


code:
fmemo = MemoizeJac(f, fprime)
xopt = fmin_cg(fmemo, x0, fmemo.derivative)

rawDescription: How to return cost, grad as tuple for scipy's fmin_cg function

description: Return cost, grad as tuple for scipy's fmin_cg function


code:
import time
from threading import Thread

def noInterrupt(path, obj):
    try:
        file = open(path, 'w')
        dump(obj, file)
    finally:
        file.close()

a = Thread(target=noInterrupt, args=(path,obj))
a.start()
a.join()

rawDescription: How to prevent a block of code from being interrupted by KeyboardInterrupt in Python?

description: Prevent a block of code from being interrupted by KeyboardInterrupt in Python


code:
proj = Projectile(pos=(self._posX + self._projectile_x, self._posY + self._projectile_y), size = (10, 10))

self.add_widget(proj)

animation = Animation(pos=(100, 100))
animation.start(proj)

rawDescription: Animation does't work as expected for Widget object in Kivy


rawDescription: Averaging indexes of peaks if they are close in Python


code:
import subprocess
x = subprocess.Popen('echo $$')
x = subprocess.Popen('echo $$', shell = True); x.wait()

rawDescription: Issues with subprocess.Popen() replacing os.system()


code:
xml_obj.B.attrib['baz'] = 'boo'
xml_obj.B[1].attrib['foo'] = 'blah'

rawDescription: Getting valueless elements in python lxml


code:
from itertools import chain
myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]
list(chain.from_iterable(myarray))

rawDescription: how to add all array's elements to one list in python

description: Add all array's elements to one list in python


code: node.register(make_sum, 20, result)

rawDescription: How to override a function call in Python?

description: Override a function call in Python


code:
def fast_iter(context, func, args=[], kwargs={}):
    # http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
    # Author: Liza Daly
    for event, elem in context:
        func(elem, *args, **kwargs)
        elem.clear()
        while elem.getprevious() is not None:
            del elem.getparent()[0]
    del context

rawDescription: Parsing large XML using iterparse() consumes too much memory. Any alternative?


code:
data = pd.read_csv('/home/Desktop/dataset.txt')
for i in np.arange(0,l00):
     if data[i,0]==5:
         i=i*5
     elif data[i,0]==10:
         i=i*10
     else:
         i=i*20

rawDescription: Steps for "for loop" in python

description: Steps for "for loop" in python


code:
idx = df.groupby(['Mt'])['count'].transform(max) == df['count']
df[idx]

rawDescription: Python : Getting the Row which has the max value in groups using groupby


code:
qs = QuestionAnswer.objects.filter(pk=12345)
qa = qs[0]
qa.graded
qa.graded = 1
qa.save()
qa = QuestionAnswer.objects.filter(pk=12345)
qa[0].graded

rawDescription: Django objects.filter is not updating field but objects.get is


code: from MyModule import *

rawDescription: Python - Changing global variable in a function


code:
@asyncio.coroutine
def consumer(queue):
    while True:
        message = yield from queue.get()
        yield from handle(message)

@asyncio.coroutine
def listener(queue):
    for i in range(5):
         asyncio.ensure_future(consumer(queue))
    while True:
        message = yield from websocket.recieve_message()
        if message:
            yield from q.put(message)

q = asyncio.Queue()
loop = asyncio.get_event_loop()
loop.run_until_complete(listener(q))

rawDescription: Asyncio and infinite loop

description: Asyncio and infinite loop


code:
def gen_strings(max_length, state="A", str="", result=None):
    if len(str) > max_length:
        return
    if state == "A":
        gen_strings(max_length, "B", str + "0", result)
        gen_strings(max_length, "C", str + "1", result)
    # etc.

rawDescription: Return a set from a recursive function

description: Return a set from a recursive function


code:
from itertools import islice
from fileinput import input as inp
import sys

with open("in.txt") as f:
    sli = None
    for line in f:
        if line.rstrip() == 'Phrase/String that I am looking for':
            f.seek(0) # reset pointer
            sli = islice(f, 2, 5) # get lines 3-5, o based indexing
            break
    if sli is not None:
        for ind, line in enumerate(inp("other.txt",inplace=True)):
            if ind in {8,9,10}: # if current line is line 9 10 or 11 write the next line from sli
                sys.stdout.write(next(sli))
            else: # else just write the other lines
                sys.stdout.write(line)

rawDescription: Copying specific lines after a string match and using them to replace other lines in another file


code:
from subprocess import Popen, PIPE, STDOUT

shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE,
           stderr=STDOUT)
out = Popen(["tail", "-n", "1"], stdin=event.stdout, stdout=PIPE)

output = out.communicate()
print(output[0])

rawDescription: Run shell builtin command in Python

description: Run shell builtin command in Python


code:
def can_be_int(obj):
    try:
        int(obj)
    except (TypeError, ValueError):
        return False
    return True

headers = [header for header in tmp_dict.keys() if not can_be_int(header)]

rawDescription: Skip keys without Type checking in Python (pymssql)


code:
class bitwise(int):

    def get(self, num):
        return self >> (num - 1) & 1

    def len(self):
        return len(bin(self)[2:])

a = bitwise(ord('f'))

print(a, bin(a))

for x in range(1, a.len()+1):
    print(a.get(x))

rawDescription: How to get value of chosen bit position from byte word

description: Get value of chosen bit position from byte word


code:
LABEL_COLOR_MAP = {0 : 'red',
                   1 : 'blue',
                   2 : 'green',
                   3 : 'purple',
                   4 : 'yellow'}

existing_df_2d.plot(
        kind='scatter',
        x='PC2',y='PC1',
        c=existing_df_2d.cluster.map(LABEL_COLOR_MAP),
        figsize=(16,8))

rawDescription: Assigning custom colors to clusters using numpy


code: fh = open(fname, 'r')

rawDescription: Python 2.7.1, codecs, and MySQLdb; why is setting file encoding not needed


rawDescription: Sort a list based on a given distribution


code:
items = [["First Element of List {0}".format(i)] for i in range(int(input("How Many?")))]
items[1].append("Second Element of List 1")
items

rawDescription: Make a for-loop that makes "n" lists (i.e. 5 lists when n= 5 or 10 lists when n=10)


code:
class PostHandler(BaseHandler):
    ''' Handler for viewing blog posts. '''
    def get(self, id):
        blog_post = models.BlogPost.get_by_id(int(id))

rawDescription: Is it possible to retrieve an uri chunk on AppEngine?


rawDescription: Determine sequential numbers in a list (Python)


code:
# main file, call it main.py
lock = None
if __name__ == '__main__':
    lock = threading.Lock()
    # launch threads without passing lock

rawDescription: Passing locks in python

description: Passing locks in python


code: d = Decimal(stamp)

rawDescription: Need a timestamp with microseconds as Decimal


code:
import numpy as np
x = np.linspace(1, 3.5, 6)
y = np.linspace(1, 3, 5)
X, Y = np.meshgrid(x, y)

rawDescription: Python show a two-dimensional PDF function


rawDescription: return the position with specific word

description: Return the position with specific word


rawDescription: for looping through arrays in python- from matlab

description: For looping through arrays in python- from matlab


code:
import numpy
a = numpy.empty((3,3,))
a[:] = numpy.NaN
a
b=a[:]
b
b[numpy.isnan(b)]=1
a
b
a[:] = numpy.NaN
a
b

rawDescription: Python array assignments

description: Python array assignments


code:
fd = pickle.load(open("data/fd.txt", 'rb'))

def compute_ave_freq(word_forms):
    try:
        return sum([fd.freq(form) for form in word_forms]) / len(word_forms)
    except ZeroDivisionError:
        return 0

rawDescription: Faster way to store a NLTK FreqDict?

description: Faster way to store a NLTK FreqDict


code:
# Required imports
import cgi
from django.core.files.uploadedfile import SimpleUploadedFile

def get_uploaded_files(self):
    """Gets a dictionary mapping field names to SimpleUploadedFile objects
    for each uploaded file in the given params.  Suitable for passing to a
    Django form as the `files` argument."""
    return dict((k, SimpleUploadedFile(v.filename, v.file.read()))
                for k, v in self.request.params.items()
                if isinstance(v, cgi.FieldStorage) and v.file)

rawDescription: Uploading files to App Engine using webapp and Django forms


rawDescription: Generating overlapping sequences

description: Generating overlapping sequences


rawDescription: How to solve non-linear sets of equations

description: Solve non-linear sets of equations


code: func = lambda x: {k:v for k,v in x.iteritems() if k != 'code'}

rawDescription: group dictionary by values in a new nested one

description: Group dictionary by values in a new nested one


code:
from mock import Mock
db = Mock()
db.exists.return_value = True
db.exists()

rawDescription: Can I make test dummies for every kind of service for an integrated app?

description: Make test dummies for every kind of service for an integrated app


code:
only_positive_words
only_negative_words

rawDescription: Separating nltk.FreqDist words into two lists?


code:
def moving_averages(values, size):
    for _ in range(size - 1):
        yield None
    for selection in window(values, size):
        yield sum(selection) / size

rawDescription: How to calculate moving average in Python 3?

description: Calculate moving average in Python 3


code:
df_fec = df['id.fec'].apply(pd.Series)

print(df_fec.head())

rawDescription: Retrieving data from a yaml file based on a Python list


code: a[:, np.apply_along_axis(np.count_nonzero, 0, a) >= 5]

rawDescription: Delete columns of a matrix that are mostly zero


code:
class BlogDetail(BetterAPIView):
    model = Post

    def get(self, request, pk, format=None):
        post = self.get_object(pk)

rawDescription: Is there a way to specify abstract functions which take in values for __init__


code: s = s.split()

rawDescription: Split a string into a list, leaving accented chars and emoticons but removing punctuation


rawDescription: pythonic way to aggregate arrays (numpy or not)

description: Pythonic way to aggregate arrays (numpy or not)


code:
b = df2.set_index("index")
b

rawDescription: Fill a Pandas dataframe using information from another Pandas dataframe


code: strasse

rawDescription: Python locale-aware string comparison

description: Python locale-aware string comparison


code:
#!/usr/bin/python

def commit(message, cwd):
    __salt__['cmd.run']("git add . && git commit -am '{}'".format(message),
                        cwd=cwd)

def push(cwd):
    __salt__['cmd.run']("git push origin master",
                        cwd=cwd)

def prepare(message, cwd):
    commit(message=message, cwd=cwd)
    push(cwd=cwd)

rawDescription: Can saltstack do something similar to Fabric?


code: list_1 = [v - 5 if v > 20 else v for v in list_1]

rawDescription: How do you compare a list with an integer in an 'if' statement? Python

description: Compare a list with an integer in an 'if' statement? Python


code: masked_b = ma.masked_array(*np.broadcast(b, ext_mask))

rawDescription: Extending numpy mask

description: Extending numpy mask


code:
value1 = sympify(ls[0])
value2 = sympify(ls[1])
value3 = sympify(ls[3])

rawDescription: Efficiently evaluate polynomial of 80 variables with 80,000 terms


code:
with open("HORSES.csv") as f:
    for row in csv.reader(f):
        # Number of pages plus one
        for horse in row:
            url = "http://www.pedigreequery.com/{}".format(horse)
            r = requests.get(url)
            soup = BeautifulSoup(r.content)
            letters = soup.find_all("a", class_="horseName")
            print(letters)

rawDescription: Looping through a list of urls for web scraping with BeautifulSoup


code:
x = 3
y = 4
def f(x): return (x<4)

rawDescription: load python code at runtime

description: Load python code at runtime


code: temp = guess[:]

rawDescription: Python overwriting my original list

description: Python overwriting my original list


code:
for month in range(0, 12):
    Balance = (StartBalance-Payment)/10*(1+MonthlyRate)

rawDescription: Python Bisection search overshoots target


code:
class CastSpell(Wand):
    def __init__(self, spell, thing, length, wandtype):
        self.spell = spell
        self.thing = thing
        super(CastSpell, self).__init__(length, wandtype)

rawDescription: Python Class Inheritance AttributeError - why? how to fix?


code: np.where((df.iloc[0]) & (df.iloc[1]))

rawDescription: Finding the common columns when comparing two rows in a datafame in python


code:
x = 1.5
y = 1.5
items = [x-1, x, x+1]
items = [[a, b] for a in items for b in items if x != a or y != b]
items

rawDescription: Creating a list with two different numbers


code:
def numpy_binary_closing(mask,threshold):

    # Define kernel
    K = np.ones(threshold)

    # Perform dilation and threshold at 1
    dil = np.convolve(mask,K,mode='same')>=1

    # Perform erosion on the dilated mask array and threshold at given threshold
    dil_erd = np.convolve(dil,K,mode='same')>= threshold
    return dil_erd

rawDescription: Find consecutive unmasked values

description: Find consecutive unmasked values


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(123456)
import pandas as pd

def align_labels(labels):
    for text in labels:
        x, y = text.get_position()
        h_align = 'left' if x > 0 else 'right'
        v_align = 'bottom' if y > 0 else 'top'
        text.set(ha=h_align, va=v_align)

df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                  columns=['x', 'y','z','w'])

plt.style.use('ggplot')
colors = plt.rcParams['axes.color_cycle']

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, col in zip(axes.flat, df.columns):
    artists = ax.pie(df[col], autopct='%.2f', pctdistance=1.05, colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')
    align_labels(artists[-1])

fig.legend(artists[0], df.index, loc='center')

plt.show()

rawDescription: How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib

description: Make MxN piechart plots with one legend and removed y-axis titles in Matplotlib


code:
class Archive(models.Model):
    pub_date = models.DateField()

    def __unicode__(self):
        return "Archive: %s" % self.pub_date

class ArchiveB(Archive):
    def __unicode__(self):
        return "ArchiveB: %s" % self.pub_date

rawDescription: Distinguishing parent model's children with Django inheritance


code: KOAK.columns = ['KOAK-' + x if 4 <= i <= 38 else x for i, x in enumerate(KOAK.columns, 1)]

rawDescription: How to rename a specific range of columns in Python (Pandas)

description: Rename a specific range of columns in Python (Pandas)


code:
from enum import Enum
class Suits(Enum):
    HEARTS = 0
    SPADES = 1
    DIAMONDS = 2
    CLUBS = 3

class Card:
    def __init__(self, suit):
        assert(type(suit) is Suits)
        self.suit = suit

snurz = Card(Suits.CLUBS)

rawDescription: How to get a retrieve a string from a tuple directly?

description: Get a retrieve a string from a tuple directly


code: some_dict[k] = new_val if some_dict.get(k, 0) < new_val else some_dict.get(k)

rawDescription: Fastest way to set a dictionary value in python when greater than current key value


code:
with open('InputList.csv') as l:
    inputList = csv.reader(l)
    for item in inputList:
        print('At {} {} the ID is {}'.format(*item.split()))

rawDescription: Build string by selecting column in csv

description: Build string by selecting column in csv


code:
def register(request):
    profiles = TProfiles.objects.all()

    return render_to_response("register.html", {
        "form": form, "profiles": profiles,
    }, RequestContext(request))

rawDescription: Join two models together using a common column


rawDescription: how to get the items with maximal score in a list

description: Get the items with maximal score in a list


code:
def RandomSub():
    var1 = "something"
    var2 = "something"
    var3 = "something"
    return var1,var2,var3

def Button1_Click(param1, param2):
    rndstring1,rndstring2,rndstring3 = RandomSub()
    # use rndstrings here

rawDescription: Subs from VB.Net in Python

description: Subs from VB.Net in Python


code: data[data[data > 10].count(axis=1) > 5]

rawDescription: pandas: How do I select rows based on if X number of columns is greater than a number?

description: Pandas: How do I select rows based on if X number of columns is greater than a number


code:
s = set((1, 2, 3))
map(set, itertools.combinations(s, 2))

rawDescription: Generate all subsets of size k (containing k elements) in Python


code: np.savetxt('eventResults.csv', na_csv_output, fmt='%f, %f, %f, string= %s %s, last number = %f', delimiter=",")

rawDescription: Making a numpy array with mixed types and writing it as csv


rawDescription: plotting a graph with matplotlib plot function takes sometimes minutes

description: Plotting a graph with matplotlib plot function takes sometimes minutes


code:
def upload_path_handler(instance, filename):
    import os.path
    fn, ext = os.path.splitext(filename)
    return "site_media/images/gallery/{id}{ext}".format(id=instance.pk, ext=ext)

rawDescription: Django admin file upload with current model id


code:
#forms.py
class StatusForm(ModelForm):
    STATUS_CHOICES = (
        ('0', 'New'),
        ('1', 'Not approved'),
        ('2', 'Approved')
    )
    status = forms.ChoiceField(required=False, widget=forms.RadioSelect(attrs={'class': ''}), choices=STATUS_CHOICES)

    class Meta:
        model = CandidateToJob
        exclude = ['candidate', 'job']

class HairColorForm(ModelForm):
    HAIRCOLOR_CHOICES = (
        ('1', 'Black'),
        ('2', 'Brown'),
        ('3', 'Blonde'),
        ('4', 'Red')
    )
    status = forms.ChoiceField(required=False, widget=forms.RadioSelect(attrs={'class': ''}), choices=HAIRCOLOR_CHOICES)

    class Meta:
        model = CandidateLook

class ScreeningForm(forms.Form):
    haircolor = forms.ChoiceField(choices=CandidateLook.HAIRCOLOR_CHOICES, required=False)
    status = forms.ChoiceField(choices=CandidateToJob.STATUS_CHOICES, required=False)

    def filter_job_candidates(self, job):
        assert self.is_valid()

        job_candidates = job.applied_to.all().order_by('candidate')

        if self.cleaned_data['haircolor']:
            job_candidates = job_candidates.filter(candidate__candidatelook__haircolor=self.cleaned_data['haircolor'])

        if self.cleaned_data['status']:
            job_candidates = job_candidates.filter(status=self.cleaned_data['status'])

        return job_candidates

rawDescription: How to filter results using forms in Django (best approach)

description: Filter results using forms in Django (best approach)


code:
l = ['I have a text like that', 'Or like that']
['<tag1>{0}</tag1>'.format(s) for s in l]

rawDescription: How to Insert tags in texts

description: Insert tags in texts


code: data = data[1] + data[0]

rawDescription: flip bytes using Python's struct module

description: Flip bytes using Python's struct module


code:
import json
import urllib.request
import csv

def fetch_currencies():
    f = urllib.request.urlopen('http://openexchangerates.org/api/currencies.json')
    charset = f.info().get_param('charset', 'utf8')
    data = f.read()
    decoded = json.loads(data.decode(charset))
    return decoded

def save_currencies(currencies, filename):
    sorted_currencies = sorted(currencies.items())
    with open(filename, 'w') as my_csv:
        csv_writer = csv.writer(my_csv, delimiter=',')
        csv_writer.wrtiterows(sorted_currencies)

save_currencies(fetch_currencies(), 'currencies.csv')

rawDescription: Saving a dictionary as a file with columns which i can continously add to


code:
class Classroom(models.Model):
    name = models.CharField()

    def __str__(self):
        return self.name

class Student(models.Model):
    name = models.CharField()
    classroom = models.ForeignKey('Classroom')

    def __str__(self):
        return self.name

rawDescription: Create data by combining query results in Django


code:
result = getPixel(0,123);
print(result);

rawDescription: How to output the intensity of every point using imageJ?

description: Output the intensity of every point using imageJ


code: alldec = lambda l, upperlimit: len({x // 10 for x in l}) == upperlimit // 10

rawDescription: How to check if a group of numbers are represented from each decile?

description: Check if a group of numbers are represented from each decile


rawDescription: Django settings based on IP or hostname

description: Django settings based on IP or hostname


code:
import os
import itertools

root = "C:\\test\\"
for path, subdirs, files in itertools.islice(os.walk(root), 1, None):
    if files:
        print(os.path.join(path, min(files)))

rawDescription: Listing a single file in multiple directories with python


code: ACCOUNT_FORMS = { 'signup': 'path.to.forms.AllauthSignupForm'}

rawDescription: Django All-Auth - Validate against linked object on account creation?


rawDescription: Python custom datetime(?) format handling


code:
import math

# pascals_tri_formula = [] # don't collect in a global variable.

def combination(n, r): # correct calculation of combinations, n choose k
    return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r)))

def for_test(x, y): # don't see where this is being used...
    for y in range(x):
        return combination(x, y)

def pascals_triangle(rows):
    result = [] # need something to collect our results in
    # count = 0 # avoidable! better to use a for loop,
    # while count <= rows: # can avoid initializing and incrementing
    for count in range(rows): # start at 0, up to but not including rows number.
        # this is really where you went wrong:
        row = [] # need a row element to collect the row in
        for element in range(count + 1):
            # putting this in a list doesn't do anything.
            # [pascals_tri_formula.append(combination(count, element))]
            row.append(combination(count, element))
        result.append(row)
        # count += 1 # avoidable
    return result

# now we can print a result:
for row in pascals_triangle(3):
    print(row)

rawDescription: Pascal's Triangle for Python

description: Pascal's Triangle for Python


code: data1.append(tuple([last, first + ' ' + des1 + ' ' + des2, number, position, salary]))

rawDescription: List position changing

description: List position changing


code:
def fib(n):
    a, b = 0, 1
    while a <= n:
        a, b = b, a + b
        if not b & 1:
            yield b

print(sum(fib(4000000)))

rawDescription: Sum of Even Fibonacci Numbers < X

description: Sum of Even Fibonacci Numbers < X


code:
def convert(capital):
    index = 0
    while index < len(capital) and not capital[index].isalpha():
        index += 1
    return capital[:index] + capital[index:].capitalize()

rawDescription: python function capitalize first letter only

description: Python function capitalize first letter only


code:
def fib(n):
    #TODO: handle invalid case(negative or non-int) and return

    if(n == 0):
        print(0)
        return

    if(n == 1):
        print(1)
        return

    a, b = 0, 1
    i = 2
    #this will go up to the n-th number
    while i<=n:
        a,b = b, a+b
        i+=1

    print (b)

rawDescription: Fibonacci numbers integer taken

description: Fibonacci numbers integer taken


code:
import re
from bs4 import BeautifulSoup

html_doc = """

here is a lot of text that i don't need
this is the span i need because it contains 04/18/13 7:29pm
04/19/13 7:30pm
Posted on 04/20/13 10:31pm

"""

# parse the html
soup = BeautifulSoup(html_doc)

# find a list of all span elements
spans = soup.find_all('span', {'class' : 'blue'})

# create a list of lines corresponding to element texts
lines = [span.get_text() for span in spans]

# collect the dates from the list of lines using regex matching groups
found_dates = []
for line in lines:
    m = re.search(r'(\d{2}/\d{2}/\d{2} \d+:\d+[a|p]m)', line)
    if m:
        found_dates.append(m.group(1))

# print the dates we collected
for date in found_dates:
    print(date)

rawDescription: How to find spans with a specific class containing specific text using beautiful soup and re?

description: Find spans with a specific class containing specific text using beautiful soup and re


code:
@register.filter_function
def split(text, split_by):
    return split_by.join(text.split(split_by)[1:])

rawDescription: How can I make this custom filter work in django?

description: Make this custom filter work in django


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

def plot_s(data, x, y, xlist, ylist):
    ax = plt.gca()

    ###########  create your uniform meshgrid.....   ############
    X, Y = np.meshgrid(x, y)
    CS = ax.contour(X, Y, data, colors='k')

    ###### ... and let ticks indicate that your new space is not linear
    # assign tick positions according to the regular array
    ax.set_yticks(y)
    # Assign the label to reflect your original nodes position
    ax.set_yticklabels(ylist)

    # and same for x
    ax.set_xticks(x)
    ax.set_xticklabels(xlist)
    #############################################################

    ###########    GET MAXIMUM AND MARK IT WITH A POINT  ########
    # get maximum value in your data
    max_value = np.max(data)
    # get position index of this calue in your data array
    local_max_index = np.where(data==max_value)

    ## retrieve position of your
    max_x = X[local_max_index[0], local_max_index[1]]
    max_y = Y[local_max_index[0], local_max_index[1]]

    # plot one marker on this position
    plt.plot(max_x, max_y, color="red", marker = "o", zorder = 10,
                                       markersize=15, clip_on=False)
    ##############################################################

    plt.title('Contour plot')
    plt.show()

def main():
    # Your data: 4 x 10 array
    data = np.array([[ 0.56555019,  0.57933922,  0.58266252,  0.58067285, 0.57660236,
                       0.57185625,  0.56711252,  0.55557035,  0.55027705,  0.54480605],
                     [ 0.55486559,  0.57349717,  0.57940478,  0.57843897,  0.57463271,
                       0.56963449,  0.5643922 ,  0.55095598,  0.54452534,  0.53762606],
                     [ 0.53529358,  0.56254991,  0.57328105,  0.57409218,  0.57066168,
                       0.5654082 ,  0.55956853,  0.5432474 ,  0.53501127,  0.52601203],
                     [ 0.50110483,  0.54004071,  0.55800178,  0.56173719,  0.55894846,
                       0.55328279,  0.54642887,  0.52598388,  0.51533094,  0.50354147]])
    # create a list values with regular interval for the mesh grid
    x = np.array([10 + i * (150.-10.)/9 for i in range(10)])
    y = np.array([50 + i * (100.-50.)/4 for i in range(4)])

    # create arrays with values to be displayed as ticks
    xlist =  np.array([10., 20., 30., 40., 50., 60., 70., 100., 120., 150.])
    ylist =  np.array([50, 70, 90, 100])

    plot_s(data, x, y, xlist, ylist)

if __name__ == '__main__':
    main()

rawDescription: Render non-uniform grid and mark maximum value's location in contour plot


code:
from itertools import zip_longest

[tup[0] for tup in zip_longest(mylist,mylist[1:]) if len(set(tup)) == 2]
Out[11]: [1, 2, 3, 6, 7, 9, 11]

rawDescription: Python: list filtering using list comprehension


code:
mvt = requestHandler(request, zoom, x, y)
datasource = mapnik.Python(factory='Datasource', mvt=mvt)

rawDescription: How to pass a variable to a mapnik datasource class?

description: Pass a variable to a mapnik datasource class


code:
from math import *
from numpy import *
from time import *

rawDescription: Python import modules in another file

description: Python import modules in another file


rawDescription: Retrieve DNS Flags information (in Hexadecimal format)


rawDescription: Confused about Python’s id()

description: Confused about Python’s id()


code:
repr(myarr[1])
repr(6.65)

rawDescription: numpy arange and where

description: Numpy arange and where


rawDescription: how to sort a dictionary val along with the key in python

description: Sort a dictionary val along with the key in python


code:
import demjson
demjson.decode('''\
{ about: 'RRDtool xport JSON output',
  meta: {
    start: 1401778440,
    step: 60,
    end: 1401778440,
    legend: [
      'rta_MIN',
      'rta_MAX',
      'rta_AVERAGE'
          ]
     },
  data: [
    [ null, null, null ],
    [ null, null, null ],
    [ null, null, null ],
    [ null, null, null ],
    [ null, null, null ],
    [ null, null, null  ]
  ]
}''')

rawDescription: Converting str to dict in python

description: Converting str to dict in python


code: ''.join(format(x, '08b') for x in c)

rawDescription: What is the equivalent of the '^' operator when working with String of binaries in python?


code:
result = []
groups = itertools.groupby(enumerate(a), key=lambda x: x[1] - x[0])
for _, values in groups:
    result.append([v[1] for v in values])

rawDescription: Make a list of a list from a list with consecutive numbers


code:
from tifffile import imread, imsave
im = imread('tiger-rgb-strip-contig-16.tif')
imsave("tiger-rgb-strip-contig-16-zip.tif", im, compress=6)

rawDescription: How convert image into 16bit zip (deflate) compressed TIF in python?


rawDescription: how to use python re to match a sting only with several specific charaters?

description: Use python re to match a sting only with several specific charaters


code:
import requests
import csv

url = 'https://maps.googleapis.com/maps/api/directions/json'
apikey = '*key*'

with open('csv_filename', 'r', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    coords = ['{X},{Y}'.format(**row) for row in reader]
    start, waypoints, end = coords[0], coords[1:-1], coords[-1]
    params = {'origin': start,
              'waypoints': '|'.join(waypoints),
              'destination': end,
              'key': apikey}
    directions = requests.get(url, params=params).json()

rawDescription: Using various input files for fields in Python Requests


code:
from collections import OrderedDict as dord

class FirstClass(object):
    @staticmethod
    def changeIt(d):
        d['b'] = 'b'

class SecondClass(object):
    def __init__(self):
        pass
    def test(self, d):
        d = dord((k.upper(), v.upper()) for k, v in d.items())
        FirstClass.changeIt(d)

if __name__ == "__main__":

    d = dord({'a':'a'})
    t = SecondClass()
    t.test(d)
    print(d)

rawDescription: Mutable object is not changed by a function. How to debug it?


code: entries, bin_edges, patches = plt.hist(N, bins=b, weights=w, normed=True)

rawDescription: Compare Histogram to Poisson Distribution and Gauss-Curve


code:
from pyramid.config import Configurator

from pyramid.view import view_config
from pyramid.response import Response

from pyramid.authentication import CallbackAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy

from pyramid.security import (
    Allow, Deny,
    Everyone, Authenticated,
)

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)

    #config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view(name='static', path='issueapp:static')
    config.add_route('home', '/')

    config.set_root_factory(RootFactory)
    config.set_authentication_policy(DummyAuthPolicy())
    config.set_authorization_policy(ACLAuthorizationPolicy())

    config.scan()
    return config.make_wsgi_app()

@view_config(route_name='home')
def home_view(request):
    src = request.static_url('issueapp:static/pyramid.png')
    return Response('<img src='+ src + '>')

class RootFactory:
    __acl__ = [
        (Allow, Authenticated, 'edit'),
        (Deny, Authenticated, 'login'),
        (Allow, Everyone, 'login'),
    ]

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

class DummyAuthPolicy(CallbackAuthenticationPolicy):
    def __init__(self, callback=None, debug=False):
        self.callback = callback
        self.debug = debug

    def remember(self, request, principal, **kw):
        return []

    def forget(self, request):
        return []

    def unauthenticated_userid(self, request):
        # this will print the request url
        # so we can know which request is causing auth code to be called
        print('[auth]: ' + request.url)

        # this means the user is authenticated
        return "user"

rawDescription: Pyramid: sessions and static assets

description: Pyramid: sessions and static assets


code: fig.set_size_inches(5, 8)

rawDescription: matplotlib savefig image size with bbox_inches='tight'

description: Matplotlib savefig image size with bbox_inches='tight'


code:
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),

rawDescription: Django User Logout Fails to Redirect Homepage


rawDescription: comparing two different lists

description: Comparing two different lists


code: listOfIds = [id1,id2,id3]

rawDescription: Finding particular value from a list by matching in Python


code: Ford

rawDescription: Fetching nested value given dot notation


code: ARTICLE_ORDER_BY = lambda x:os.path.basename(x.source_path or '')

rawDescription: How to sort articles by filename in pelican?

description: Sort articles by filename in pelican


code:
global packet_log
packet_log = []
logging.basicConfig(level=logging.DEBUG)

for pkt in ThinkGearProtocol('/dev/rfcomm9').get_packets():
    packet_log.append(pkt)

rawDescription: Python Mindwave Graphs

description: Python Mindwave Graphs


code:
def sq(n):
    """Returns the square of n."""
    return n * n

rawDescription: What is the standard Python docstring format?


code:
# COMMENT: We dont want arrays in SOAP-XML so I commented out the following lines
# if typed:
#    self.out.append(
#        '<%s %sarrayType="%s[%d]" %stype="%sArray"%s%s%s%s%s%s>\n' %
#        (tag, ens, t, len(data), ins, ens, ndecl, edecl, idecl,
#         self.genroot(ns_map), id, a))

#if typed:
#    try: elemsname = obj._elemsname
#    except: elemsname = "item"
#else:
elemsname = tag

for i in data:
    self.dump(i, elemsname, not same_type, ns_map)

#if typed: self.out.append('</%s>\n' % tag)

rawDescription: How do I pass a list parameter as multiple link-named elements instead of as an array in SOAPpy?

description: Pass a list parameter as multiple link-named elements instead of as an array in SOAPpy


code:
from subprocess import Popen, STDOUT, PIPE
from time import sleep
audio_file = "/tmp/music.wav"

x = Popen('afplay ' + audio_file, shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
while x.poll() == None:
    output = x.stdout.readline() # You need this!
    # Otherwise the output buffer will get full and hang your application.
    # Or just remove stdout=PIPE, stdin=PIPE, stderr=STDOUT from the Popen() call
    # if you're not interested in the output of the application.
    sleep(0.025)
print('Music stoped')

rawDescription: Pygame won't work on Mac mini with no monitor connected


code:
A=np.array(a)
A[:(A<np.percentile(a, 90)).argmin()].sum() #461

rawDescription: Cumulative sum of variable till a given percentile


code:
div = soup.find('div', class_="crBlock ")
print(div.find_all(text='foobar'))

rawDescription: Using BeautifulSoup to select div blocks within HTML


code:
class NoProps(object):
    def __init__(self, spam=None):
        if spam is None:
            spam = 0  # Pick a sensible default
        self.spam = spam

class Props(NoProps):
    @property
    def spam(self):
        """Docstring for the spam property"""
        return self._spam

    @spam.setter
    def spam(self, value):
        # Do whatever calculations are needed here
        import random
        self._spam = value + random.randint(0,20)

    @spam.deleter
    def spam(self):
        del self._spam

rawDescription: Turning an attribute into a property on an object-by-object basis?


code: users_with_invites_ids_set = set(tuple(x) for x in users_with_invites_ids_list)

rawDescription: how to convert list of lists to a set in python so I can compare to other sets?

description: Convert list of lists to a set in python so I can compare to other sets


code:
matrix = getMatrix()
printMatrix(matrix)

rawDescription: Python 3- matrix input

description: Python 3- matrix input


code:
for base, argtype, *args in data:
    print(base, argtype, args)

rawDescription: How can I easily unpack extra elements of array into single variable?

description: Easily unpack extra elements of array into single variable


code:
with open('data.txt') as f1,open('data1.txt') as f2,open('sudentlist.txt') as f3:

    line=f1.readline().strip()             #read the first line of names file
    names=map(str.strip,line.split(','))   #split the line by "," and then apply strip()

    line=f2.readline().strip()             #read the first line of ID file
    ids=map(str.strip,line.split(','))     #split the line by "," and then apply strip()

    f3.write("{0:25}{1}\m".format("Student_Name","Student_Id"))

    for name,i in zip(names,ids):          #use zip() to fetch data from both lists
        f3.write("{0:25}|{1}\n".format(name,i)) #use write() instead of print to write it to a file

rawDescription: Python: Formatting a merged txt file

description: Python: Formatting a merged txt file


code:
from __future__ import division

import numpy as np

def sample_hollow_lamina(size, outer_width, outer_height, a, b, inner_width, inner_height):
    """
    (a, b) is the lower-left corner of the "hollow".
    """
    llcorners = np.array([[0, 0], [a, 0], [a+inner_width, 0],
                          [0, b], [a+inner_width, b],
                          [0, b+inner_height], [a, b+inner_height], [a+inner_width, b+inner_height]])
    top_height = outer_height - (b + inner_height)
    right_width = outer_width - (a + inner_width)
    widths = np.array([a, inner_width, right_width, a, right_width, a, inner_width, right_width])
    heights = np.array([b, b, b, inner_height, inner_height, top_height, top_height, top_height])
    areas = widths * heights
    shapes = np.column_stack((widths, heights))

    regions = np.random.multinomial(size, areas/areas.sum())
    indices = np.repeat(range(8), regions)
    unit_coords = np.random.random(size=(size, 2))
    pts = unit_coords * shapes[indices] + llcorners[indices]

    return pts

rawDescription: Pythonic way to generate random uniformly distributed points withing hollow square lamina


code: {'name': {'first': 'John', 'last': 'Doe'}}

rawDescription: Combination of two fields to be unique in Python Eve


code:
import re
from itertools import combinations

def get_mp3_info(groups, pattern, title):
    match = re.match(pattern, title)
    if not match:
        return []
    result = [{}]
    for i, v in enumerate(groups):
        if v[1] is None:
            for r in result:
                r[v[0]] = match.group(i+1)
        else:
            splits = match.group(i+1).split(v[1])
            before = [d.copy() for d in result]
            for comb in combinations(range(1, len(splits)), len(v[0])-1):
                temp = [d.copy() for d in before]
                comb = (None,) + comb + (None,)
                for j, split in enumerate(zip(comb, comb[1:])):
                    for t in temp:
                        t[v[0][j]] = v[1].join(splits[split[0]:split[1]])

                if v[0][0] in result[0]:
                    result.extend(temp)
                else:
                    result = temp
    return result

rawDescription: How to match regex with multiple overlapping patterns?

description: Match regex with multiple overlapping patterns


code:
mysocket.setblocking(0)
ACK, address = mysocket.recvfrom(1024)

rawDescription: Python implementation for Stop and Wait Algorithm


code:
type(data1)
type(data1[()])   #get element out of 0-dim array
data1[0]
data1[()][0]
data1.ndim
data1[()].ndim

rawDescription: Equivalent of named tuple in NumPy?

description: Equivalent of named tuple in NumPy


code:
d = []
while True:
    try:
        filename = 'foo.txt'
        with open(filename, "r") as f:
            for line in f:
                d.append(list(line.strip()))
            break

    except FileNotFoundError:
        print("File name does not exist; please try again")

print(d)

for line in d:
    print(''.join(line))

rawDescription: Looping in a dictionary

description: Looping in a dictionary


code:
titles = {
    'Title1': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name'},
    'Title2': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name2'},
}

rawDescription: How to find dict value by Key in list

description: Find dict value by Key in list


code:
from collections import Counter
sets = [{randint(1, 100) for _ in range(100)} for i in range(100)]

from itertools import chain

cn = Counter(chain.from_iterable(sets))
unique = [k for k, v in cn.items() if v == 1] # use {} to get  a set
print(unique)

rawDescription: Looking for unique numbers in a list of sets


code: [random.choice(lst) for _ in range(len(lst))]

rawDescription: shuffle a python array WITH replacement

description: Shuffle a python array WITH replacement


code: fig = map.imshow(IR)

rawDescription: overplot array on a world map in python

description: Overplot array on a world map in python


code:
data = numpy.loadtxt(open('FF-data.csv', 'rb'), delimiter = ',', skiprows = 1)#Load
numpy.random.shuffle(data)

features = data[:,0:11]
nfeatures = (features-features.mean(axis=0))/features.std(axis=0)
targets = numpy.matrix(data[:, 12]).T

n = NN([11, 50, 1])

n.train(nfeatures, targets, 0.07, 0.0, 2000)

import matplotlib.pyplot
matplotlib.pyplot.subplot(221)
matplotlib.pyplot.plot(n.cost)
matplotlib.pyplot.title('Cost vs. Iteration')

matplotlib.pyplot.subplot(222)
matplotlib.pyplot.scatter(n.predict(nfeatures).tolist(), targets.tolist())
matplotlib.pyplot.plot(targets.tolist(), targets.tolist(), c = 'r')
matplotlib.pyplot.title('Data vs. Predicted')

matplotlib.pyplot.savefig('Report.png', format = 'png')
matplotlib.pyplot.close()

rawDescription: Trying to write my own Neural Network in Python


code: { k[0]: k[1:] for k in lst }

rawDescription: How to Convert Nested List into dictionary in Python where lst[0][0] is the key


code:
output = list()
for rownum in xrange(sh1.nrows):
    output.extend(sh1.row_values(rownum))
wr.writerow(output)

rawDescription: Python - Using csv and xlrd module to write multi-row excel file to one row csv file


code:
import boto.support
conn = boto.support.connect_to_region('us-east-1', aws_access_key_id="<access key>", aws_secret_access_key="<secret key>")

rawDescription: Using Python Boto with AWS Support API

description: Using Python Boto with AWS Support API


code:
def randvector(n):
    theta = 2 * np.pi * np.random.random_sample((n))
    return np.vstack((np.cos(theta), np.sin(theta))).T

rawDescription: Most efficient way to create an array of cos and sin in Numpy


rawDescription: Django SUM Query?

description: Django SUM Query


code:
from cStringIO import StringIO
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import ResponseDone
from twisted.web.client import FileBodyProducer

class GetPageProtocol(Protocol):
    def __init__(self):
        self.deferred = Deferred()
        self.data = []

    def dataReceived(self, data):
        self.data.append(data)

    def connectionLost(self, reason):
        reason.trap(ResponseDone)
        data = ''.join(self.data)
        del self.data
        self.deferred.callback(data)

def agentGetPage(agent, url,
                 method="GET",
                 headers=None,
                 postdata=None):
    if postdata is not None:
        bodyProducer = FileBodyProducer(StringIO(postdata))
    else:
        bodyProducer = None

    def _getPageResponded(response):
        if response.length != 0:
            proto = GetPageProtocol()
            response.deliverBody(proto)
            return proto.deferred
        else:
            return None

    d = agent.request(method, url, headers, bodyProducer)
    d.addCallback(_getPageResponded)
    return d

rawDescription: Twisted / perform asynchronous http requests


code:
from your_app import utils
def run():
    if option == 'help':
        utils.help()
if __name__ == "__main__":
    run()

rawDescription: Python, globally accessable function

description: Python, globally accessable function


code:
CELERY_TIMEZONE = TIME_ZONE
CELERY_ACCEPT_CONTENT = ['json', 'pickle']
CELERYD_CONCURRENCY = 2
CELERYD_MAX_TASKS_PER_CHILD = 4
CELERYD_PREFETCH_MULTIPLIER = 1

# celery queues setup
CELERY_DEFAULT_QUEUE = 'default'
CELERY_DEFAULT_EXCHANGE_TYPE = 'topic'
CELERY_DEFAULT_ROUTING_KEY = 'default'
CELERY_QUEUES = (
    Queue('default', Exchange('default'), routing_key='default'),
    Queue('feeds', Exchange('feeds'), routing_key='long_tasks'),
)
CELERY_ROUTES = {
    'arena.social.tasks.Update': {
        'queue': 'feeds',
        'routing_key': 'long_tasks',
    },
}

rawDescription: Django/Celery multiple queues on localhost - routing not working


code:
import re
import numpy as np
import matplotlib.pyplot as pytl
from matplotlib import rc

rc('font', **{'family':'sans-serif', 'sans-serif':['Helvetica']})
rc('text', usetex = True)
recdt = np.dtype([('compound', str, 4), ('H_v', 'f4'), ('B_o', 'f4')]);
gat =  np.loadtxt('tra', dtype = object, usecols = (0, 1, 2), unpack = True);
gct, ght, gbt = [], [], []
for c, h, b in np.transpose(gat):
    c = r'$\tt{{{c}}}$'.format(c = re.sub(r'(\d+)', r'_{\1}', c))
    gct = np.append(gct, c)
    ght = np.append(ght, h)
    gbt = np.append(gbt, b)
ght = ght.astype(np.float)
gbt = gbt.astype(np.float)
hard = pytl
four = hard   #####
four.scatter(gbt, ght)
hard.title( 'physical stuff' )
hard.xlabel('physical prop 1')
hard.ylabel('physical prop2 ')
for l, x1, y2 in zip ( gct, gbt, ght):
    print(l, x1, y2)
    hard.annotate(
        l, xy = (x1, y2), xytext = (-24, 12), textcoords = 'offset points',
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'),
        rotation = 0 )
hard.ylim([0, 10])
hard.savefig('hardcomp.png')
hard.show()

rawDescription: How do i annotate with a subscripted text in matplotlib?

description: Annotate with a subscripted text in matplotlib


code:
from itertools import izip_longest
d = {'key2': [3, 4, 5, 6], 'key1': [1, 2]}
map(lambda a: dict(filter(None, a)), izip_longest(*[[(k, v) for v in value] for k, value in d.items()]))

rawDescription: Split dictionary of lists into list of dictionaries


code:
import networkx as nx

G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4), (3, 5), (4, 6), (5, 6), (3, 7), (7, 6), (6, 8), (8, 9)])

paths_between_generator = nx.all_simple_paths(G,source=3,target=6)
nodes_between_set = {node for path in paths_between_generator for node in path}
SG = G.subgraph(nodes_between_set)

rawDescription: Getting subgraph of nodes between two nodes?


code:
def weightedSum(listToSum):
    ws = 0
    weight = len(listToSum)
    for i in listToSum:
        ws += i * weight
        weight -= 1
    return ws

weightedSum([1, 2, 3])
1 * 3 + 2 * 2 + 3 * 1
pop
pop.sort(key=weightedSum)
pop
pop += [[1, 3, 8]]
pop.sort(key=weightedSum)
pop

rawDescription: sort 2-D list python

description: Sort 2-D list python


rawDescription: Inverse lookup in pandas

description: Inverse lookup in pandas


rawDescription: How to save file automatically after a new window opens in Selenium

description: Save file automatically after a new window opens in Selenium


code:
# name1 and name2 will be available in calling module's namespace
# when using "from package import *" syntax
__all__ = ['name1', 'name2']

rawDescription: Organising my Python project

description: Organising my Python project


code:
def main():
    app = QtGui.QApplication(sys.argv)

    w = QtGui.QWidget()
    trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), w)
    menu = QtGui.QMenu(parent)
    exitAction = menu.addAction("Foo")
    trayIcon.setContextMenu(menu)

    trayIcon.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: Menubar/ System tray app with Qt

description: Menubar/ System tray app with Qt


code:
def helper(*args):
    return args[0](*args[1:])

rawDescription: Parallelize calling of object methods

description: Parallelize calling of object methods


code:
mystr = '\xde\x05\xd7\x05\xe9\x05\xd1\x05'
mystr.decode('utf-16-le')

rawDescription: A string that represents encoded characters


code:
# -*- coding: utf-8 -*-

import pygame
import sys

unistr = "♛"
pygame.font.init()
srf = pygame.display.set_mode((500,500))
f = pygame.font.Font("segoe-ui-symbol.ttf",64)
srf.blit(f.render(unistr,True,(255,0,0)),(0,0))
pygame.display.flip()

while True:
    srf.blit(f.render(unistr,True,(255,255,255)),(0,0))
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

rawDescription: Rendering unicode in pygame

description: Rendering unicode in pygame


code:
for i in range(1, -1, -1):
    try:
        string[i] = int(string[i])
    except ValueError:
        pass
    else:
        break
else:
    print('Was in neither form')

rawDescription: Two try statements with the same except clause


rawDescription: Removing columns in python

description: Removing columns in python


code:
plt.figure()
plt.pcolor((H_1+H_2).T)

rawDescription: matplotlib: plot hist2d piecewise

description: Matplotlib: plot hist2d piecewise


code:
df
#  ID NormalResponse       MultipleCheckboxResponse
#0  1        Answer3                      Response3
#1  2        Answer1            Response1|Response7
#2  3        Answer2  Response2|Response4|Response7
#3  4        Answer2            Response2|Response3

rawDescription: Pandas- Create new columns by splitting cells on | n times


code: [list(zip(*paired)) for paired in zip(m1, m2)]

rawDescription: Zipping two list of lists

description: Zipping two list of lists


rawDescription: The best way to invoke methods in Python class declarations?

description: Invoke methods in Python class declarations


code:
from itertools import groupby
[t + ds[0] for ds, ts in zip(*[(list(g) for _, g in groupby(l, len))] * 2) for t in ts]

rawDescription: Joining specific tuples within a list

description: Joining specific tuples within a list


code:
with open('userID.txt', 'r') as f_input, open('emails.txt', 'w') as f_output:
    emails = ["{}@wherever.com".format(line.strip()) for line in f_input]
    f_output.write(", ".join(emails))

rawDescription: appending a single string to each element of a list in python

description: Appending a single string to each element of a list in python


code:
stockdict = dict(pairs)
stockdict
histodict = dict()
histodict[date] = stockdict

rawDescription: How to sort a structured list of stock data for later access in Python?

description: Sort a structured list of stock data for later access in Python


code: any(item[2] == 0 for item in items)

rawDescription: How to check if all elements of a list matches a condition?

description: Check if all elements of a list matches a condition


code:
with open("in.txt") as f:
    col_1 = f.next().split()[0] # get first column number
    lines = set(x.split()[1] for x in f) # get all second column nums
    lines.add(col_1) # add first column num
    with open("in.txt","w") as f1:
        f1.writelines("\n".join(lines))

rawDescription: Merge Columns and Remove Duplication

description: Merge Columns and Remove Duplication


rawDescription: Numpy tensor: Dot product along third axis


code: QTimer.singleShot(msecs, callback);

rawDescription: How to add a function to the Qt Mainloop

description: Add a function to the Qt Mainloop


code: db.command('aggregate', 'collection', pipeline=[{"$group": {"_id": "$_country_code", "count": {"$sum": 1}}}])

rawDescription: PyMongo statistics

description: PyMongo statistics


code:
if loop == "do":
    outfile.write(" label 1; label 2;\n")
    for count, word in enumerate(words(infile)):
        varList[count] = var

rawDescription: Anyway to input next string from a file in python


code:
from collections import OrderedDict
dct = OrderedDict([(73, 'Mocha My Day'), (77, 'Coffee Cafe'), (83, 'Flavour Fusion'), (85, 'Mexican Grill')])
dct.items()

rawDescription: Convert from OrderedDict to list

description: Convert from OrderedDict to list


code: box = blah

rawDescription: Broadcasting into views of Numpy arrays

description: Broadcasting into views of Numpy arrays


code:
df.loc[ df['ID'] == df['ID'].shift(), 'first'] = df['Name']
df.loc[ df['ID'] == df['ID'].shift(-1), 'last'] = df['Name']

rawDescription: Modify pandas dataframe in python based on multiple rows


rawDescription: Best Pythonic way to replace any non-A-Z, non numbers, with a dash


code:
c1
c2

rawDescription: Python XML Pull Parser

description: Python XML Pull Parser


code:
from datetime import datetime as d, timedelta, time
import datetime as o_d

time_open = '08:00:00'
time_close = '17:00:00'
times = []
for i in range(0, 24 * 4):
    date = (d.combine(o_d.date.today(), time()) + timedelta(minutes=15) * i).time()
    date_str = date.strftime("%H:%M:%S")
    if time_open <= date_str <= time_close:
        times.append(date_str)
        #times.append(date)
print(times)

rawDescription: Python Remove From List of Times Based on Business Hours


code:
f = open('bar.text', 'w')
f.write(unicode_object.encode('utf8'))

rawDescription: Print to UTF-8 encoded file, with platform-dependent newlines?


code: df.apply(bar, args=(1,), axis=1)

rawDescription: Apply function over relative rows in Pandas


code:
from unittest.case import TestCase

class MyTestCase(TestCase):
    def setUp(self):
        self.spider = MySpider()

    def test_parse(self):
        response = fake_response('input.html')
        item = self.spider.parse(response)
        self.assertEqual(item['title'], 'My Title')
        # ...

rawDescription: How can I start to write Unit test in web Scrapy using python?

description: Start to write Unit test in web Scrapy using python


code:
for v2 in s2 :
    if v2 in vowels:
        if v2 in d2:
            d2[v2] += 1
        else:
            d2[v2] = 1

rawDescription: Python- Using dictionaries to compare two lists


code: [c in range(k[0], k[1]+1) for c in a for k in b]

rawDescription: Python - Apply an conditional function (intersection) to every element of a list


rawDescription: how to sort a list of string by every element's numeric value

description: Sort a list of string by every element's numeric value


code:
try:
    # pick an available direction at random
    random.choice(directions)()
except IndexError:
    # no directions available
    stop()

rawDescription: Python if-elif statements order

description: Python if-elif statements order


code:
@coroutine
def create_someobj():
   s = SomeObj()
   yield s.slow_init()
   return s

rawDescription: Python coroutines on builtin functions

description: Python coroutines on builtin functions


code:
import unittest

class TestMyCode(unittest.TestCase):

    def test_code(self):
        self.assertTrue(True)

    @classmethod
    def run_tests(cls):
        test = unittest.defaultTestLoader.loadTestsFromTestCase(cls)
        unittest.TextTestRunner().run(test)

rawDescription: Invoking Test Methods with a Method for a unittest.TestCase Subclass Python


code: sorted(list_of_objects, key=lambda x: x.id)

rawDescription: Function to compare lists: no __cmp__

description: Function to compare lists: no __cmp__


code: i = __import__('matplotlib.text', fromlist=[''])

rawDescription: import module from string variable

description: Import module from string variable


code:
class_name(argument1="some value")

def __init__(self, **options):
    for name,val in options.iteritems():
        self.__dict__[name] = val

rawDescription: Receiving Arguments via Pointers in Python


code:
def main():
  #initialization
  import access_tool
  con = database_connection()
  servers = query_database_for_servers()

  for server in servers:
    #assume server is a dict of values
    access_tool.add_user ( **server )

rawDescription: Classes with different files and passing vars between functions


code:
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
locale.format("%d", 1255000, grouping=True)

rawDescription: How to print number with commas as thousands separators?

description: Print number with commas as thousands separators


code:
def wrapper(x, y):
    return aux_functions.final_potential(complex(x, y), element_list)

a = np.vectorize(wrapper)(X, Y)

rawDescription: List comprehension for two variable loop in Python and numpy


code: max(0, min(b,z - c) - max(a, z - d) + 1)

rawDescription: Sum of 2 elements from 2 ranges that will be one given number


code:
import ast
from collections import OrderedDict
d=OrderedDict()
...
# the same code

rawDescription: How do I remove duplicate terms with scores from a text file?

description: Remove duplicate terms with scores from a text file


code:
df = pd.read_csv('data', sep=';',
                 names=['time','flare','praia','spot','ruido'], header=1,
                 index_col=0, parse_dates=[0])

rawDescription: Pandas: read_csv with only HH:MM:SS in the index


code:
import pandas as pd

df = pd.read_csv("file.csv", usecols=[1])

rawDescription: Loop through csv with Pandas, specific column


code:
import re
match = re.search('(\d+) ooo(\w+)', '12 ooops')
match.group(1), match.group(2)

rawDescription: Parsing from format in Python

description: Parsing from format in Python


code: dict_all = dict(dict_all.items())

rawDescription: Differentiate lists according to translations


code:
for row in x:
    print('%i %.2f   %s'%tuple(row))

rawDescription: Writing row from structured numpy array with varying delimiter


code:
import sys

class Log(object):
    def __init__(self):
        self.orgstdout = sys.stdout
        self.log = open("log.txt", "a")

    def write(self, msg):
        self.orgstdout.write(msg)
        self.log.write(msg)

sys.stdout = Log()
print('Hello World')

rawDescription: Get current console output in python

description: Get current console output in python


code: #! ipython

rawDescription: Executing Ipython Script from System Shell


rawDescription: Python - Returning max number in an array. Errors


code:
import timeit
it = lambda: list(chain(*tupleOfTuples))
timeit.timeit(it)
lc = lambda: [element for tupl in tupleOfTuples for element in tupl]
timeit.timeit(lc)

rawDescription: How do I convert a tuple of tuples to a one-dimensional list using list comprehension?

description: Convert a tuple of tuples to a one-dimensional list using list comprehension


code:
statutes={}
for block in txt.split('\n\n'):
    m=re.search(r'^.*(Superseded|Repealed|Transferred|Obsolete|Reserved|Rejected|Omitted|Not|Executed)', block)
    if m:
        statutes.setdefault(m.group(1), []).append(block)
    else:
        statutes.setdefault('Enacted', []).append(block)
# etc

rawDescription: At a standstill parsing some statutes with regex


code:
import numpy as np
grid_shape = (4,5)
N = np.prod(grid_shape)

y = np.add.outer(np.arange(grid_shape[0]),np.arange(grid_shape[1]))
print(y)

# [[0 1 2 3 4]
#  [1 2 3 4 5]
#  [2 3 4 5 6]
#  [3 4 5 6 7]]

rawDescription: More numpy way of iterating through the 'orthogonal' diagonals of a 2D array


code:
from my_cgi import this_func, that_func
def my_cgi( environ, start_response ):

    result= this_func( some_args )
    page_text= that_func( result, some_other_args )

    status = '200 OK' # HTTP Status
    headers = [('Content-type', 'text/html')] # HTTP Headers
    start_response(status, headers)
    return page_text

rawDescription: Python cgi performance

description: Python cgi performance


rawDescription: Python Extracting a substring of variable length


rawDescription: Django: Accessing method on child different child classes through common name


rawDescription: Infinite Sequence. Cannot process answer in 1 second


code: age + (height - (weight * (iq / 2)))

rawDescription: Learn Python The Hard Way Exercise 21 Extra Credit


code: df.loc[:, 'values'] = np.sum([df['values'].where(df['labels'].isin([v])).div(df['values'].where(df['labels'].isin([v])).sum().sum()).fillna(0).values for v in np.unique(df['labels'])], axis=0)

rawDescription: groupby and normalize over two arrays

description: Groupby and normalize over two arrays


code:
fig, ax = plt.subplots(1,1)

ax.hist(dfjoined.a_gt, bins=10,range=(0,1), color='r')
ax.hist(dfjoined.a_lt, bins=10,range=(0,1), color='b')

rawDescription: Split single column via a condition creating a new pandas DataFrame with two columns


code: json_c = [{k: v for k, v in d.iteritems() if v is not None} for d in json_c]

rawDescription: Adding tuple to dictionary only if condition is true


code:
df
pd.isnull(df).sum() > 0

rawDescription: How to find which columns contain any NaN value in Pandas dataframe (python)

description: Find which columns contain any NaN value in Pandas dataframe (python)


code:
import numpy
a = numpy.array([10,7,2,0])
b = numpy.array([10,9,8,7,6,5,4,3,2,1])
indices = [numpy.where(a<=x)[0][0] for x in b]
numpy.digitize(b,a)

rawDescription: Comparing two numpy arrays of different length


code: buttons_dict[COORDS_LIST[-1]] = ttk.Button(board_frame, text="O", width="2", command=lambda x=c, y=r: fire_here(x, y))

rawDescription: tkinter >> how to get button references?

description: Tkinter >> how to get button references


rawDescription: How can I remove text within parentheses with a regex?

description: Remove text within parentheses with a regex


code:
df
df.index = pd.Series(df.index).fillna(method='ffill')
df

rawDescription: Pandas: Reading Excel with merged cells

description: Pandas: Reading Excel with merged cells


code:
def mioGhostscript(tile, size, fp):
    """Render an image using Ghostscript (Unix only)"""

    # Unpack decoder tile
    decoder, tile, offset, data = tile[0]
    length, bbox = data

    import tempfile, os

    file = tempfile.mktemp()

    # Build ghostscript command
    command = ["gs",
        "-q",                    # quite mode
        "-g%dx%d" % size,        # set output geometry (pixels)
        "-dNOPAUSE -dSAFER",     # don't pause between pages, safe mode
        "-sDEVICE=ppmraw",       # ppm driver
        "-sOutputFile=%s" % file,# output file
        "-"
    ]

    #command = shlex.split(string.join(command))
    # push data through ghostscript

    try:
        #gs = os.popen(command, "w")

        args = command#['gs','-dSAFER','-dNOPAUSE','-dBATCH','-sDEVICE=jpeg','-sOutputFile=/home/user/output2.jpg /home/user/downloads/test.pdf']
        gs = subprocess.Popen( args, stdout = PIPE, stderr = STDOUT, stdin=PIPE )
        # adjust for image origin
        if bbox[0] != 0 or bbox[1] != 0:
            #gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
            gs.stdin.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
        fp.seek(offset)
        while length > 0:
            s = fp.read(8192)
            if not s:
                break
            length = length - len(s)
            gs.stdin.write(s)
        gs.communicate()[0]
        status = gs.stdin.close()
        #status = gs.close()
        #if status:
        #   raise IOError("gs failed (status %d)" % status)
        im = Image.core.open_ppm(file)
    finally:
        try: os.unlink(file)
        except: pass

    return im

import PIL.EpsImagePlugin
PIL.EpsImagePlugin.Ghostscript = mioGhostscript

rawDescription: convert Ghostscript from os.popen to subsession.popen python

description: Convert Ghostscript from os.popen to subsession.popen python


code:
def test_that_two_calls_to_my_method_with_same_params_fails(self):
    var1 = 1
    varg = 1
    assert myMethod(var1, varg)
    assert myMethod(var1, varg) == False

rawDescription: Python & nose: what is the variable scope in the "test class"?


code: deleted_column = [i.pop(which_column) for i in triangle]

rawDescription: Python - Delete column from a matrix without numPy


code:
reading
upvote
unlikely

rawDescription: Stemming of words using python

description: Stemming of words using python


rawDescription: Invoking top-level function by name in Python


code:
def interruptable_get(self):
    while True:
        try:
            return self.get(timeout=1000)
        except Queue.Empty:
            pass
Queue.interruptable_get = interruptable_get

rawDescription: Keyboard interruptable blocking queue in Python


code: poisci_pare("Hello world. This is great.")

rawDescription: Python how to split a string inside a list


code: lines = [seg.split("\n") for seg in segments]

rawDescription: Getting specific lines in a text file and pass it to an array


code:
for _ in id_generator(some_json_dict):
     print(_)

rawDescription: recursive iteration through nested json for specific key in python

description: Recursive iteration through nested json for specific key in python


code:
import os

def gather_files(folder, ending):
    contents = os.walk(folder)
    files = []
    for (dirpath, dirnames, filenames) in contents:
        files += ([file.splitext()[0] for file in filenames if file.lower().endswith(ending)])
    return files

def main():
    f = gather_files("test", ".pdf")
    if not f:
        f = gather_files("test", ".tif")

    if not f:
        print("No .pdf or .tif files found in the given directory.")
    else:
        with open("test_out.txt", "w", encoding="utf-8") as output:
            output.write("\n".join(f) + "\n")

if __name__ == "__main__":
    main()

rawDescription: How to sequentially search for files and save them?

description: Sequentially search for files and save them


code:
sets = [ frozenset(x) for x in myList ]
filtered = [ myList[i] for i in range(len(myList)) if set(myList[i]) not in sets[:i] ]
filtered

rawDescription: Removing Python List Items that Contain 2 of the Same Elements


code:
s = 'track-12-29\ntrack-1-210\ntrack-56-1'
results = [x.split('-')[1:] for x in s.splitlines()]

rawDescription: Python Regex capture multiple sections within string


rawDescription: vectorization of date range function for transformation of pandas dataframe

description: Vectorization of date range function for transformation of pandas dataframe


rawDescription: Sending hand-crafted BPDU (Spanning Tree Protocol packet) with Python


code:
from traits.api import HasTraits, Instance, Str, List
from traitsui.api import View, Item, CheckListEditor

class Bclass(HasTraits):
    options = List(['one', 'two'])

class Aclass(HasTraits):
    bclass = Instance(Bclass)
    abc = Str

    traits_view = View(
        Item(name='abc', editor=CheckListEditor(name='object.bclass.options')),
    )

b = Bclass()
a = Aclass(bclass=b)
a.configure_traits()

rawDescription: enthought traits UI, add values dynamically to 'values' trait of CheckListEditor

description: Enthought traits UI, add values dynamically to 'values' trait of CheckListEditor


code:
left = x.find("{")
right = x.find("}")
y = x[left+1:right]

rawDescription: How to convert JavaScript dictionary into Python syntax

description: Convert JavaScript dictionary into Python syntax


rawDescription: Python IDLE shell keystroke to signal end of statement and return to prompt


code:
while p >= 0:

    #Here is a bunch of code
    list_of_shapes.append(("c", circle)) # appends the data for the circles
while p2 >= 0:
    #bunch of code
    list_of_shapes.append(("r", rect)) # appends the data for the rectangle
while p3 >= 0:
    #code
    list_of_shapes.append(("p", poly)) # appends the data for the polygon

    return list_of_shapes

rawDescription: How to add strings to a list in Python?

description: Add strings to a list in Python


rawDescription: Pandas read multiindexed csv with blanks


code: nbr_list = []

rawDescription: I can't seem to get this function to add the list together


code:
from state import _state
def get_authenticated_user():
    user = _state.user
    if not user:
        raise AuthenticationError()
    return user

rawDescription: Store objects at "request scope" in google app engine


code:
class Foo(object):
    @counted
    def do_something(self): pass

rawDescription: Decorate methods per instance in Python

description: Decorate methods per instance in Python


code: M.reshape(-1, 2, 2).sum(axis=0)

rawDescription: Python - Sum 4D Array

description: Python - Sum 4D Array


code:
var = 0

def foo():
    global var
    #use var here

rawDescription: how to define a global variable to be used in a function of an imported file?

description: Define a global variable to be used in a function of an imported file


code:
import random
import pprint

class Graph:
    nodes = []
    edges = []
    removed_edges = []
    def remove_edge(self,x,y):
        e = (x,y)
        try:
            self.edges.remove(e)
            print("Removed edge %s" % str(e))
            self.removed_edges.append(e)
        except:
            print("Attempted to remove edge %s, but it wasn't there" % str(e))

    def Nodes(self):
        return self.nodes

    # Sample data
    def __init__(self):
        self.nodes = [1,2,3,4,5]
        self.edges = [
            (1,2),
            (1,3),
            (1,4),
            (1,5),
            (2,4),
            (3,4),
            (3,5),
            (4,5),
        ]

G = Graph()
N = G.Nodes()
for  x in N:
   for y in N:
      for z in N:
         #print("(%d,%d,%d)" % (x,y,z))
         if (x,y) != (y,z) and (x,y) != (x,z):
            if (x,y) in G.edges and (y,z) in G.edges:
                G.remove_edge(x,z)

print("Removed edges:")
pprint.pprint(G.removed_edges)
print("Remaining edges:")
pprint.pprint(G.edges)

rawDescription: I'm trying to perform the transitive reduction of directed graph in Python


code:
def calls(n):
    index = 0
    step = 1
    call = 0
    while index < n:
        index += step
        step += 1
        call += 1
    return call

UPTO = 500
for i in range(1, UPTO):
    print("{:>4}: {}".format(i, calls(i)))

rawDescription: Number of iterations of while loop with increasing step


code:
items = ['1 (UID 3234 FLAGS (seen \\Seen))', '2 (UID 3235 FLAGS (\\Seen))', '3 (UID 3236 FLAGS (\\Deleted))', '4 (UID 3237 FLAGS (-FLAGS \\Seen +FLAGS))', '5 (UID 3241 FLAGS (-FLAGS \\Seen +FLAGS))', '6 (UID 3242 FLAGS (\\Seen))',  '7 (UID 3243 FLAGS (\\Seen))', '8 (UID 3244 FLAGS (\\Seen))',  '9 (UID 3245 FLAGS (\\Seen))', '10 (UID 3247 FLAGS (\\Seen))', '11 (UID 3252 FLAGS (\\Seen))', '12 (UID 3253 FLAGS (\\Deleted))', '13 (UID 3254 FLAGS ())', '14 (UID 3256 FLAGS (\\Seen))', '15 (UID 3304 FLAGS ())', '16 (UID 3318 FLAGS (\\Seen))', '17 (UID 3430 FLAGS (\\Seen))', '18 (UID 3431 FLAGS ())', '19 (UID 3434 FLAGS (\\Seen))', '20 (UID 3447 FLAGS (-FLAGS \\Seen +FLAGS))', '21 (UID 3478 FLAGS ())', '22 (UID 3479 FLAGS ())', '23 (UID 3480 FLAGS ())', '24 (UID 3481 FLAGS ())']

import re
pattern = re.compile(r"\d+ \(UID (\d+) FLAGS \(([^)]*)\)\)")
values = dict(pattern.match(item).groups() for item in items)

rawDescription: pythonic way to optimize the logic to filter/extract data from list

description: Pythonic way to optimize the logic to filter/extract data from list


code:
from builtins import zip
zip([1,2,3,4])
from builtins import zip
zip([1,2,3,4])

rawDescription: zip in IronPython 2.7 and Python3.5

description: Zip in IronPython 2.7 and Python3.5


rawDescription: How can I give parameters to a function of a python script through the command-line?

description: Give parameters to a function of a python script through the command-line


rawDescription: Creating a matrix of options using itertools


code:
def total_seconds(td):
    return td.days * 60 * 60 * 24 + td.seconds

rawDescription: Use database to store session instead of Cookie with Flask


code:
x.tolist()
list(map(int,x.tolist()))

rawDescription: How convert [x] into x?

description: How convert [x] into x


rawDescription: Get keyboard code of a keypress in Python


code:
orig_indices = xs.argsort()
ndx = orig_indices[numpy.searchsorted(xs[orig_indices], ys)]

rawDescription: Find multiple values within a Numpy array


code: d = dict(iter(g))

rawDescription: Create multiple dataframe using for loop in python 2.7


rawDescription: allowing urls as parameters

description: Allowing urls as parameters


code: df.groupby('id', sort = False, as_index = False).max()

rawDescription: efficiently find maxes of one column over id in a Pandas dataframe

description: Efficiently find maxes of one column over id in a Pandas dataframe


code:
ItemList = [(1,7),(2,1),(1,5),(1,1)]
sorted(ItemList, key=lambda item: (-item[0], item[1]))

rawDescription: Difficulty Sorting Tuples with itemgetter


code:
#spell cooldown timer
self.timers['cooldown'] = max(0, self.timers['cooldown']-1)

rawDescription: Python too slow - Can I rewrite engine in lower level and cp scripts?


rawDescription: Not sure how to parse this

description: Not sure how to parse this


code:
#python3.x
allowed=vars(__builtins__).copy()
allowed['__import__']=None
exec("import os",{'__builtins__':None},allowed)  #raises ImportError
exec("print(abs(-4))",{'__builtins__':None},allowed) #prints 4 as you'd expect.

rawDescription: Python: have a user-defined function as an input while keeping the source-code inaccessible?


rawDescription: Multiple instances of JQueryUI Autocomplete on same Pyramid page


code:
self.class_logg(('http://example.com/api/?'
                 'option=ajax&nologin=1&a=vmware_migrate_2&'
                 'original_server_ip=%s&target_server_ip=%s&'
                 'vmware_name=%s' % (self.ip, dest_node.ip, machine.name)))

rawDescription: python log unexpectedly prints the indentation

description: Python log unexpectedly prints the indentation


code:
from numbers import Integral

def is_sort_of_integer(value):
    if isinstance(value, Integral):
        return True

    try:
        return value.is_integer()

    except AttributeError:
        return False

rawDescription: How to check if value is logically integer?

description: Check if value is logically integer


rawDescription: Append list elements to a list of tuples


code:
api.add_resource(CuteKitty, '/kitty/<int:kitty_id>/')
api.add_resource(DrinkingKitty, '/kitty/<int:kitty_id>/drink/<what>')
api.add_resource(MeowingKitty, '/kitty/<int:kitty_id>/meow/')

rawDescription: Flask-RESTful custom routes other than GET,PUT,POST,DELETE


code: { k:[d[k] for d in dicts] for k in dicts[0] }

rawDescription: How can I combine dictionaries with the same keys in python?

description: Combine dictionaries with the same keys in python


code: merged = pd.merge(tidysd, tidypos, how='left'); merged

rawDescription: Pandas Create Columns From Rows in Other Data Frame with Criteria


code:
{'Action': 'Click',
 'Campaign ID': '167713',
 'Creative ID': '113961',
 'Creative Type': 'Alert',
 'Schema Version - Client': '3',
 'Schema Version - Server': '1',
 'android_id': 'ds cgethcvwrzvbjezrzve',
 'app': 'hndbfhjdfhf bnmhjknuihklmmkbghjbtfgjnkluilnkkfbnjtkjzn',
 'app_ver': '10.0.1_0',
 'at': '2016-02-02 23:59:47',
 'birth_date': 1447896843,
 'browser': 'Android 4',
 'carrier': 'Comcast Cable',
 'city_name': 'Jacksonville',
 'country': 'us',
 'customer_id': '1234587612545464525441540341414',
 'data_conn': 'android_network_type_3',
 'device_new': False}

rawDescription: How to Access nested dictionary keys to make a Pandas DataFrame


code: df2 = df.set_index(['firstname','lastname','weight', 'vehicle'])

rawDescription: Pivoting pandas DataFrame -- AssertionError: Index length did not match values


rawDescription: Mysql named placeholders in python used in the IN clause


code:
def convertDL(val):
    if isinstance(val, dict):
        return [[k] + v for k, v in val.iteritems()]
    return {v[0]: v[1:] for v in val}

convertDL({'a':[1,2], 'b':[3], 'c':[4,5]})
convertDL([['a', 1, 2], ['c', 4, 5], ['b', 3]])

rawDescription: Function to convert List to Dictionary and viceversa using Python


code:
import numpy as np
from scipy import interpolate
data = np.array([[0, 2, 4, 6, 8], [1, 179, 211, 359, 1]])
complement360 = np.rad2deg(np.unwrap(np.deg2rad(data[1])))
complement360
f = interpolate.interp1d(data[0], complement360, kind='linear', bounds_error=False, fill_value=None)
f(np.arange(9))
f(np.arange(9))%360

rawDescription: bounded circular interpolation in python

description: Bounded circular interpolation in python


code:
data = [8,8,6,6,3,8]
from itertools import count
from collections import defaultdict
counter = defaultdict(lambda x=count(): next(x))
print([counter[item] for item in data])
# [0, 0, 1, 1, 2, 0]

rawDescription: Shortest way to linearize a list in Python


code:
import logging

class UserIDFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.
    """
    from myapp.core import authenticationManager

    def filter(self, record):
        user_id = authenticationManager.current_user_id_if_authenticated()
        user_id = "unknown" if user_id is None else str(user_id)
        record.user_id = user_id
        return True

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)-15s %(name)-5s %(levelname)-8s user_id %(user_id)-15s: %(message)s')

logger = logging.getLogger(__name__)
filt = UserIDFilter()
logger.addFilter(filt)

rawDescription: Python Logging : how to add a custom field to LogRecord, and register a global callback to sets it's value


code:
df2 = df.filter(regex='spike')
print(df2)

rawDescription: Pandas: find column whose name contains a specific string


code:
pd.DataFrame({
    'a': data.a2 / data.a1,
    'c': data.b2 / data.b1,
    'd': data.c2 / data.c1})

rawDescription: Pandas filter and combine

description: Pandas filter and combine


code:
summary = {'df': df.to_dict(orient = 'records'), 'df_metric': df.sum() / df.min()}
summary['df_metric']
pd.io.json.dumps(summary)

rawDescription: Pandas to_dict modifying numbers

description: Pandas to_dict modifying numbers


rawDescription: AttributeError in dictionary

description: AttributeError in dictionary


code:
class topList():
    __slots__ = ( "name", "gender", "occurences" )

    def __repr__(self):
        return 'topList({s.name!r}, {s.gender!r}, {s.occurences!r})'.format(s=self)

    def __str__(self):
        return '{s.name} ({s.gender}): {s.occurences!r})'.format(s=self)

rawDescription: Object Locations with Classes (Python)

description: Object Locations with Classes (Python)


code:
import numpy as np

nRings = 3
nn = [[nRings+1-n] * n for n in range(nRings+1)]
RING = reduce(lambda x, y: x+y, nn)
ID = range(1,len(RING)+1)
X = np.array([ID, RING])

dt = {'names':['ID', 'Ring'], 'formats':[np.int, np.int]}
Y = np.zeros(len(RING), dtype=dt)
Y['ID'] = X[0]
Y['Ring'] = X[1]

rawDescription: How to add names to a numpy array without changing its dimension?

description: Add names to a numpy array without changing its dimension


code: session.autoflush = False

rawDescription: Disable autosave on update in SQLAlchemy


code:
if __name__ == "__main__":
    instance = PerformConnectionTCP('admin', 'admin')
    instance.perform()

rawDescription: Python decorate function with class and access class instance


code:
acc = None
for idx, ch in enumerate(input):
    if ch in '1234567890':
        if acc is None: acc = 0
        acc = 10 * acc + int(ch)
        continue
    if acc != None:
        yield acc
        acc = None
    if ch in '+-=x':
        yield ch
    elif ch == ' ':
        pass
    else:
        raise ValueError('illegal character "%s" at %d' % (ch, idx))

rawDescription: Solving a linear equation in one variable


rawDescription: Splitting using regex is giving unwanted empty strings


code:
from collections import defaultdict
l=['AB4', 'AB3','AC3', 'BC4', 'BC5']
result=defaultdict(list)
for item in l:
    #If you want numbers to be numbers and not strings replace item[2:] with int(item[2:])
    result[item[:2]].append(item[2:])
    result[item[2:]].append(item[:2])

rawDescription: How to create lists from every item of an existing list in python 2.7.11?

description: Create lists from every item of an existing list in python 2.7.11


rawDescription: Minimum lenght of string that match a regex


rawDescription: Python dictionary class, 'KeyError'

description: Python dictionary class, 'KeyError'


rawDescription: modelling crowd movement with matplotlib

description: Modelling crowd movement with matplotlib


code:
def load_file(filename):
    with open(filename, 'Ur') as f:
        return list(f)

rawDescription: Python, adding a file into another file

description: Python, adding a file into another file


code:
var1 = 'network1'
print(re.search(r'.*(\s+'+ var1 + r':)', line).group(1))

rawDescription: Python regex: How to match a string at the end of a line in a file?


code:
#!/bin/env python

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder (opts[1] is a list (possibly empty) of all remaining args)
if opts[1]: print('You passed the strings %s' % opts[1])

rawDescription: python - Using argparse, pass an arbitrary string as an argument to be used in the script

description: Python - Using argparse, pass an arbitrary string as an argument to be used in the script


rawDescription: How to compare values in tuples in a list

description: Compare values in tuples in a list


rawDescription: Numpy.unique - getting output with consistent depth


rawDescription: Receive a string with values and return a list


code:
with open( "some file", "r" ) as source:
    for line in source:
        process( line )

rawDescription: What is the best file parsing solution for converting files?


code:
radio = driver.find_element_by_id("ContentPlaceHolder1_HitterRadioButton")
radio.click()

rawDescription: How to select radio button with Selenium and Python

description: Select radio button with Selenium and Python


code:
import random

input1 = list(range(1000))
input2 = [
    ([random.randint(0, 1000) for _ in range(100)], random.choice("ABCDE"))
    for _ in range(10000)
]

rawDescription: Python nested loop comparing two lists and updating a dictionary


rawDescription: scrapy crawlspider output

description: Scrapy crawlspider output


code:
dummy = dict()

alphabet = ["aaa", "bbb", "ccc"]

for i in alphabet:
    dummy.setdefault(i,[]).append((1,2,3)) # <-- better initialization?

rawDescription: List of Lists in Dict weird initialization syntax


code:
class Test:
    def __init__(self, a=0, b=2):
        self.a = a
        self.b = b

test = Test(2, 2)
from sys import getrefcount
count = getrefcount(test)
import example
store = example.Var()
store.Test_1 = test
assert(store.Test_1 is test)
assert(count + 1 == getrefcount(test))
assert(store.Test_1.a == 2)
store.Test_1.a = 42
assert(test.a == 42)
store.Test_2 = test
assert(store.Test_2 is test)
assert(count + 2 == getrefcount(test))
assert(count + 2 == getrefcount(store.Test_2))
store.Test_2 = None
assert(count + 1 == getrefcount(test))
store = None
assert(count == getrefcount(test))

rawDescription: How can i declare a Boost.Python C++ Class with PyObjects

description: Declare a Boost.Python C++ Class with PyObjects


code:
import struct
...
f2.write(struct.pack('b', int(byte,2))) # signed 8 bit int

rawDescription: python literal binary to hex conversion

description: Python literal binary to hex conversion


code:
bin(3)
format(3, 'b')
format(3, '08b')

rawDescription: Interpreting bytes received through serial port


code: SeriouslyDont[1, 2]

rawDescription: How to have multiple ways to construct an object of same class in python?

description: Have multiple ways to construct an object of same class in python


code:
if all(x > 3 for x in lst):
    do_stuff()

rawDescription: How to do "if-for" statement in python?

description: Do "if-for" statement in python


rawDescription: Python Data Types and set, bool, hex

description: Python Data Types and set, bool, hex


code:
import os
open_files = [open(f) for f in os.listdir(some_path)]

rawDescription: Python - Opening successive Files without physically opening every one


rawDescription: Possible to output dir() in python as a vertical list?


code:
summary = []
for key, (column, op) in sumdict.items():
    if column is None:
        res = p.agg(op).max(axis=1)
    elif column not in df:
        continue
    else:
        res = p[column].agg(op)  # just use the string (or it could be a func)
    summary.append(pd.DataFrame({key: res}))
summary = pd.concat(summary, axis=1)

rawDescription: Summarizing Dataframes with ambiguous columns with apply function


code: screen -R [sessionname]

rawDescription: print in new terminal window

description: Print in new terminal window


code: {item for item in iterable if condition}

rawDescription: What is an expression such as [d[k] for k in d] called?


code:
a = np.arange(16)
windowed_view(a, 4, 2)
windowed_view(a, 4, 1)

rawDescription: Window overlap in Pandas

description: Window overlap in Pandas


rawDescription: Convert Python dict into an interactive table in HTML


code:
lst = [1,2,3,4]
all(x <= y for x,y in zip(lst, lst[1:]))
lst = [1,2,4,3]
all(x <= y for x,y in zip(lst, lst[1:]))

rawDescription: How do I tell if a list is in ascending order? Just needs to return True or False

description: Tell if a list is in ascending order? Just needs to return True or False


rawDescription: Python PyQt4 update data on widget every 1 min


code:
if sort == True:
    return my_sort(array_to_sort)

rawDescription: Lite empty on return from function in python


code: os.path.join(dir_name, base_filename + "." + filename_suffix)

rawDescription: building full path filename in python,

description: Building full path filename in python,


code:
@patch("server.subprocess.Popen")
@patch('server.__builtin__.open')
def test_stop_when_running(self, mock_open, mock_subprocess):
    server = Server()
    server.start()
    server.stop()
    mock_subprocess.terminate.assert_called_once_with()

rawDescription: mocking subprocess Process terminate

description: Mocking subprocess Process terminate


code:
def process_spider_output(self, response, result, spider):
    def _filter(request):
        if isinstance(request, Request):
            depth = response.meta['depth'] + 1
            ...

rawDescription: Overriding parse_start_url() in Scrapy and limiting crawl depth to 1


rawDescription: Getting stats about each row and putting them into a new column. Pandas


code:
st = set()

t[:] = (st.add(tuple(sub)) or sub for sub in t if tuple(sub) not in st)

print(t)

rawDescription: Removing duplicate lists within another list


rawDescription: python convert to binary and keep leading zeros

description: Python convert to binary and keep leading zeros


code:
lambda m: replacement_dict.get(m.group(), m.group())
# fallback to just leaving the word there if we don't have a replacement

rawDescription: Python Regex Sub - Use Match as Dict Key in Substitution


code:
import math
import wave
import struct

if __name__ == '__main__':
    # http://stackoverflow.com/questions/3637350/how-to-write-stereo-wav-files-in-python
    # http://www.sonicspot.com/guide/wavefiles.html
    freq = 440.0
    data_size = 40000
    fname = "test.wav"
    frate = 11025.0
    amp = 64000.0
    nchannels = 1
    sampwidth = 2
    framerate = int(frate)
    nframes = data_size
    comptype = "NONE"
    compname = "not compressed"
    data = [math.sin(2 * math.pi * freq * (x / frate))
            for x in range(data_size)]
    wav_file = wave.open(fname, 'w')
    wav_file.setparams(
        (nchannels, sampwidth, framerate, nframes, comptype, compname))
    for v in data:
        wav_file.writeframes(struct.pack('h', int(v * amp / 2)))
    wav_file.close()

rawDescription: how to extract frequency associated with fft values in python

description: Extract frequency associated with fft values in python


code:
def check_files(zipfilename):
    """ Check and see if all members of a .zip archive can be opened.
        Beware of vacuous truth - all members of an empty archive can be opened
    """
    def can_open(archive, membername):
        try:
            archive.open(membername, 'r')  # return value ignored
        except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile):
            return False
        return True

    with zipfile.ZipFile(zipfilename, 'r') as archive:
        return all(can_open(archive, membername)
                    for membername in (
                        name for name in archive.namelist() if name[-1] != '/'))

rawDescription: Selective extracting and opening for zipfile in python


code:
soup2 = [option.get('value') for option in soup.findAll('option')]
soup2

rawDescription: Get value attribute for each tag found using Tag.find_all()


code:
for line in old_file:
    line = line.strip()     # remove newline/whitespace from begin and end of line
    line = line.split(',')  # get comma-separated values
    line = " & ".join(line) # make it ampersand-separated values
    line += r" \\"          # add latex line break
    line += "\n"            # add file line break
    new_file.write(line)

rawDescription: Concatenating strings inside file.write() in Python?


code:
d/app/testingA.py
d/config.py
d/run.py

rawDescription: Python creating a module

description: Python creating a module


code: [list(g) for k,g in groupby(l, bool) if k]

rawDescription: subsequences of an array that are not zero

description: Subsequences of an array that are not zero


code: grouped = df.groupby(['code', 'colour'])['size'].agg([np.sum, np.average, np.size, np.argmax]).reset_index()

rawDescription: Pandas Dataframe GroupBy - Displaying Group Statistics


code:
class Pathology(models.Model):
    pathology = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

class Publication(models.Model):
    pubtitle = models.TextField()

rawDescription: python code for django view

description: Python code for django view


rawDescription: How to combine two dicts by key in python?

description: Combine two dicts by key in python


rawDescription: python while and if with pairs of conditions

description: Python while and if with pairs of conditions


code:
class ImageUploadHandler(webapp2.RequestHandler):
    def post(self):
        chunk_number = int(self.request.params.get('flowChunkNumber'))
        chunk_size = int(self.request.params.get('flowChunkSize'))
        current_chunk_size = int(self.request.params.get('flowCurrentChunkSize'))
        total_size = int(self.request.params.get('flowTotalSize'))
        total_chunks = int(self.request.params.get('flowTotalChunks'))
        identifier = str(self.request.params.get('flowIdentifier'))
        filename = str(self.request.params.get('flowFilename'))
        data = self.request.params.get('file')

        f = ImageFile(filename, identifier, total_chunks, chunk_size, total_size)
        f.write_chunk(chunk_number, current_chunk_size, data)

        if f.ready_to_build():
            info = f.build()
            if info:
                self.response.headers['Content-Type'] = 'application/json'
                self.response.out.write(json.dumps(info.as_dict()))
            else:
                self.error(500)
        else:
            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write(json.dumps({
                'chunkNumber': chunk_number,
                'chunkSize': chunk_size,
                'message': 'Chunk ' + str(chunk_number) + ' written'
            }))

rawDescription: Files uploaded using ng-flow to upload to gae blobstore always named 'blob'


code:
for item in list: # 2.
    if item not in list_b: # 3.
        new_list.append(item) # 1.

rawDescription: understanding "item for item in list_a if ..." PYTHON

description: Understanding "item for item in list_a if ..." PYTHON


code: get_common_words = lambda places: [word for word in places[0] if all(word in place for place in places[1:])]

rawDescription: Dictionaries in Python

description: Dictionaries in Python


code:
indexer = (StringIndexer()
  .setInputCol("type")
  .setOutputCol("type_idx")
  .fit(training))

rawDescription: Spark: Use same OneHotEncoder on multiple dataframes