code:
import datetime as dt
from itertools import groupby
from math import ceil

def _unique_subsets_which_sum_to(target, value_counts, max_sums, index):
    value, count = value_counts[index]
    if index:
        # more values to be considered; solve recursively
        index -= 1
        rem = max_sums[index]

        # find the minimum amount that this value must provide,
        # and the minimum occurrences that will satisfy that value
        if target <= rem:
            min_k = 0
        else:
            min_k = (target - rem + value - 1) // value  # rounded up to next int

        # find the maximum occurrences of this value
        # which result in <= target
        max_k = min(count, target // value)

        # iterate across min..max occurrences
        for k in range(min_k, max_k+1):
            new_target = target - k*value
            if new_target:
                # recurse
                for solution in _unique_subsets_which_sum_to(new_target, value_counts, max_sums, index):
                    yield ((solution + [(value, k)]) if k else solution)
            else:
                # perfect solution, no need to recurse further
                yield [(value, k)]
    else:
        # this must finish the solution
        if target % value == 0:
            yield [(value, target // value)]

def find_subsets_which_sum_to(target, values):
    """
    Find all unique subsets of values which sum to target

        target   integer >= 0, total to be summed to
        values   sequence of integer > 0, possible components of sum
    """
    # this function is basically a shell which prepares
    #  the input values for the recursive solution

    # turn sequence into sorted list
    values = sorted(values)
    value_sum = sum(values)

    if value_sum >= target:
        # count how many times each value appears
        value_counts = [(value, len(list(it))) for value,it in groupby(values)]

        # running total to each position
        total = 0
        max_sums = [0]
        for val,num in value_counts:
            total += val * num
            max_sums.append(total)

        start = dt.datetime.utcnow()
        for sol in _unique_subsets_which_sum_to(target, value_counts, max_sums, len(value_counts) - 1):
            yield sol
        end = dt.datetime.utcnow()
        elapsed = end - start
        seconds = elapsed.days * 86400 + elapsed.seconds + elapsed.microseconds * 0.000001
        print("  -> took {:0.1f} seconds.".format(seconds))

# I multiplied each value by 100 so that we can operate on integers
# instead of floating-point; this will eliminate any rounding errors.
values = [
    9856, 9856, 9856, 12944, 16000, 24219, 28687, 29000, 35101, 66500,
    67500, 67500, 67745, 67745, 69500, 69500, 69500, 69500, 71500, 72000,
    72500, 73000, 74500, 74500, 75000, 75000, 75000, 75000, 75893, 75893,
    76385, 76500, 78000, 78134, 78170, 81379, 82497, 82705, 85628, 87408,
    87444, 149811, 158000, 160000, 160000
]
sum_to = [
    298811,
    688441,
    850160  #,
            # 1438214
]

def main():
    subset_sums_to = []
    for target in sum_to:
        print("\nSolutions which sum to {}".format(target))
        res = list(find_subsets_which_sum_to(target, values))
        print("  {} solutions found".format(len(res)))
        subset_sums_to.append(res)
    return subset_sums_to

if __name__=="__main__":
    subsetsA, subsetsB, subsetsC = main()

rawDescription: Determine which numbers in list add up to specified value


code:
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

rawDescription: sort a column with setCellWidget in QTableWidget

description: Sort a column with setCellWidget in QTableWidget


code:
from pyramid.view import view_config

def ProductLengthPredicate(length):
    def check_length(context, request):
        return len(context.products) == length
    return check_length

@view_config(context='app.models.ProductFinder', renderer='oneproduct.mako',
             custom_predicates=(ProductLengthPredicate(1),))
@view_config(context='app.models.ProductFinder', renderer='twoproducts.mako',
             custom_predicates=(ProductLengthPredicate(2),))
@view_config(context='app.models.ProductFinder', renderer='manyproducts.mako')
def products(context, request):
    return dict(page=context)

rawDescription: In Pyramid, how can I use a different renderer based on contents of context?


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:
bb, mb = np.broadcast(b, ext_mask)
print(mb.shape)       # (3, 9, 31, 2, 5) - same shape as b
print(mb.base.shape)  # (3, 9, 31, 2) - the shape of the original mask
print(mb.strides)     # (558, 62, 2, 1, 0) - that's how it works: 0 stride

rawDescription: Extending numpy mask

description: Extending numpy mask


code:
import requests
from bs4 import BeautifulSoup

with open("HORSES.csv") as f:
    for horse in map(str.strip,f):      # Number of pages plus one
        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:
translate_text = [string.text for text in translate_root.getiterator(
                      '{0}TranslateArrayResponse'.format(namespace))
                      for string in text.getiterator(
                      '{0}TranslatedText'.format(namespace))]

rawDescription: Matching the XML Req and Res

description: Matching the XML Req and Res


code:
class ClassView(View):
    def get(self, request):
        return HttpResponse("test")

    def post(self, request):
        # do something
        return redirect(test_view)

test_view = ClassView.as_view()

rawDescription: Django class based generic view redirect


code:
 # custom_storages.py
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

class StaticStorage(S3BotoStorage):
    location = settings.STATICFILES_LOCATION

class MediaStorage(S3BotoStorage):
    location = settings.MEDIAFILES_LOCATION

rawDescription: Using S3 as media storage for Django on python 3.3 hosting Openshift


code:
[{'currency_name': 'U.S. dollar ',
  'observation_data': '1.2598',
  'observation_data_reciprocal': '0.7938',
  'observation_date': '2015-03-09',
  'observation_iso4217': 'USD'},
 {'currency_name': 'U.S. dollar ',
  'observation_data': '1.2764',
  'observation_data_reciprocal': '0.7835',
  'observation_date': '2015-03-11',
  'observation_iso4217': 'USD'},
 {'currency_name': 'Argentine peso',
  'observation_data': '0.1438',
  'observation_data_reciprocal': '6.9541',
  'observation_date': '2015-03-09',
  'observation_iso4217': 'ARS'},
 {'currency_name': 'Argentine peso',
  'observation_data': '0.1440',
  'observation_data_reciprocal': '6.9444',
  'observation_date': '2015-03-10',
  'observation_iso4217': 'ARS'}]

rawDescription: HTML Parser on XML page, getting a dictionary of data


code:
Balance = StartBalance
for month in range(0, 12):
    Balance = (Balance-Payment) * (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
        self.length = length
        self.wandtype = wandtype

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


code:
df = pd.read_csv('data', sep=r',| - ', skiprows=1, header=None,
                 names=['Day','rossmann'], usecols=[0,2])

rawDescription: Pandas date range to single dates

description: Pandas date range to single dates


code:
mask
threshold = 3
mask_ext = np.pad(mask,1,'constant',constant_values=(1))
out

rawDescription: Find consecutive unmasked values

description: Find consecutive unmasked values


rawDescription: Interpolating an array within an astropy table column


code:
import pandas as pd

order=['mix', 'meow']
D = {'foo':{'meow':1.23,'mix':2.34}, 'bar':{'meow':4.56, 'mix':None}, 'baz':{'meow':None,'mix':None}}

df = pd.DataFrame(D).T.reindex(columns=order)

df.to_csv('./foo.txt', sep='\t', na_rep="none")

rawDescription: Python: Write dictionary to text file with ordered columns


code:
df = pd.read_fwf(StringIO(data),widths=[9,13],parse_dates=True,index_col=0,names=['sample'],header=None,skiprows=1)
df

rawDescription: Pandas Read CSV with dates as DD-MMM-YY

description: Pandas Read CSV with dates as DD-MMM-YY


code:
import re
text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"
re.sub(r'\s([?.!"](?:\s|$))', r'\1', text)

rawDescription: How to strip whitespace from before but not after punctuation in python

description: Strip whitespace from before but not after punctuation in python


code:
input_data = [{ 'cust_no':126, 'lastname': 'smith', 'firstname':'john'}, {'cust_no':127, 'lastname':'smoth', 'firstname':'bob'}]
from collections import defaultdict
output_data = defaultdict(list)
for a_dict in input_data:
    for k, v in a_dict.items():
            output_data[k].append(v)
output_data

rawDescription: list of dictionaries to dictionary of lists

description: List of dictionaries to dictionary of lists


code:
KOAK = pd.DataFrame(dict.fromkeys('ABCDEFG', [12]))
KOAK.columns = ['KOAK-' + x if 2 <= i <= 4 else x
                for i, x in enumerate(KOAK.columns, 1)]
print(KOAK)

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

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


rawDescription: Unable to find the correct regex in python


rawDescription: How to stop a loop?

description: Stop a loop


code: list(itertools.combinations((1, 2, 3), 2))

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


code:
from itertools import ifilterfalse

...

keywords_without_stopwords = ifilterfalse(stopwords.__contains__, keywords)

return list(keywords_without_stopwords + set(tags))  # Can you cache `set(tags`)?

rawDescription: How to stop memory memory leak from Flask and NLTK

description: Stop memory memory leak from Flask and NLTK


code:
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

_UNSAVED_FILEFIELD = 'unsaved_filefield'

@receiver(pre_save, sender=Image)
def skip_saving_file(sender, instance, **kwargs):
    if not instance.pk and not hasattr(instance, _UNSAVED_FILEFIELD):
        setattr(instance, _UNSAVED_FILEFIELD, instance.image)
        instance.image = None

@receiver(post_save, sender=Image)
def save_file(sender, instance, created, **kwargs):
    if created and hasattr(instance, _UNSAVED_FILEFIELD):
        instance.image = getattr(instance, _UNSAVED_FILEFIELD)
        instance.save()
        # delete it if you feel uncomfortable...
        # instance.__dict__.pop(_UNSAVED_FILEFIELD)

rawDescription: Django admin file upload with current model id


code: reduce(lambda x,y: x+[y] if not y in x else x, your_list,[])

rawDescription: Make Python List Unique in Functional way (map/reduce/filter)


code:
while alive:
    ...

rawDescription: Python random variable not working

description: Python random variable not working


code: newlst = [x+y for x,y in zip(lstA, lstB)]

rawDescription: Python: Concatenating sublists between different lists


code:
def __repr__(self):
   # remove the Agent( so you can add the commission at the *front*
   s = super(Agent,self).__str__()
   return self.__name__ + "('" + self.commission + "'," + \
          s[len(self.__name__ + 1):]

rawDescription: Python inheritance woes

description: Python inheritance woes


rawDescription: make a tree based on the key of each element in list

description: Make a tree based on the key of each element in list


code: '<tag1>{0}</tag1>'.format('I have a text like that')

rawDescription: How to Insert tags in texts

description: Insert tags in texts


rawDescription: Why the various JPEG Extensions?

description: Why the various JPEG Extensions


rawDescription: What is the preferred way to import pylab at a function level in Python 2.7?


code:
# create a list with sheet numbers you want to process
sheets = map(str,range(1,6))

# convert each sheet to csv and then read it using read_csv
df={}
from subprocess import call
excel='C:\\Users\\rsignell\\OTT_Data_All_stations.xlsx'
for sheet in sheets:
    csv = 'C:\\Users\\rsignell\\test' + sheet + '.csv'
    call(['cscript.exe', 'C:\\Users\\rsignell\\ExcelToCsv.vbs', excel, csv, sheet])
    df[sheet]=pd.read_csv(csv)

rawDescription: Faster way to read Excel files to pandas dataframe


code:
wrapped_function = makeIncrease(2)
wrapped_function
total = applyIncrease(wrapped_function, 3)
total

rawDescription: How to define a function that output another function?

description: Define a function that output another function


code:
class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        # Calling custom encode function:
        jsonString = HelperFunctions.jsonEncodeHandler(obj)
        if (jsonString != obj):  # Encode function has done something
            return jsonString  # Return that
        return JSONEncoder.default(self, obj)  # else let the base class do the work

rawDescription: Proper overloading of json encoding and decoding with Flask


rawDescription: Pascal's Triangle for Python

description: Pascal's Triangle for Python


rawDescription: List position changing

description: List position changing


code:
['First paragraph of the abstract', 'Second paragraph of the abstract']
['First keyword', 'Second keyword', 'Third keyword']

rawDescription: Handling nested elements with Python lxml


code:
epsillon = 0.0001
levels = np.arange(max_value - epsillon, max_value + epsillon)
CS2 = plt.contour(X,Y,data, levels,
             origin='lower',
             linewidths=2,
             extent=(-3,3,-2,2))

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


code:
years = range(1996, 2015)
numbers = range(0,200)
zip(years,numbers)
result = ""
for y, n in zip(years,numbers):
    result += "%d:%d, "%(y, n)

result

rawDescription: Python: Create two ranges and join to one expression


code: afc = {'Baltimore Ravens': (10,3), 'Pb Steelers': (3,4)}

rawDescription: Can a value in a Python Dictionary have two values?


code:
for post in Post.objects.values('id', 'name', 'author__username'):
    ...

rawDescription: Is there a way to choose a specific representation when serializing a `ForeignKey`?


code:
docmessage = 'Here I am.'
def load_this(dt):
    pass
load_this.__doc__ = docmessage

rawDescription: Python docstring repeated param text

description: Python docstring repeated param text


code:
@app.route('/tracking/resumes/<document_name>')
def tracking_resume_view(document_name):
    addUserToView(session['user'], document_name)
    redirect(url_for('static', filename='resume/{document_name}'.format(document_name)))

rawDescription: How to track a user clicking on a link to a document

description: Track a user clicking on a link to a document


code:
# unlike the one before, this sample doesn't rely on the dictionary containing every vertice twice
matrix=[[None]*size for row in range(size)]
for node, vertices in hubs:
    for vertice, weight in vertices.items():
        matrix[vertice][size-node-1] = weight

rawDescription: Creating Adjacency Lists from Dicts in Python


code:
import os
def isresponding(name):
    os.system('tasklist /FI "IMAGENAME eq %s" /FI "STATUS eq running" > tmp.txt' % name)
    tmp = open('tmp.txt', 'r')
    a = tmp.readlines()
    tmp.close()
    if a[-1].split()[0] == name:
        return True
    else:
        return False

rawDescription: How to tell if process is responding in Python on Windows

description: Tell if process is responding in Python on Windows


code:
df['C'] = df.groupby(['PplNum','RoomNum']).cumcount() + 1
df

rawDescription: Python Pandas Identify Duplicated rows with Additional Column


code:
import re
import json

yourtext = re.sub(r'(?:^|(?<={))\s*(\w+)(?=:)', r' "\1"', yourtext, flags=re.M)
yourtext = re.sub(r"'", r'"', yourtext)
data = json.loads(yourtext)

rawDescription: Converting str to dict in python

description: Converting str to dict in python


code: x.reshape(2, -1)

rawDescription: calculating distance between two numpy arrays

description: Calculating distance between two numpy arrays


code:
a, b = b'abc', b'def'
c = bytes(x^y for x,y in zip(a, b))
c
bytes(x^y for x,y in zip(a, c))
bytes(x^y for x,y in zip(b, c))

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


code:
import cherrypy
from redis import Redis
from rq import Queue
from mytask import long_running_task

class BackgroundTasksWeb(object):

    def __init__(self):
        self.queue = Queue(connection=Redis())
        self.jobs = []

    @cherrypy.expose
    def index(self):
        html =  ['', '']
        html += ['<form action="job">', '<input name="q" type="text" />', '<input type="submit" />', "</form>"]
        html += ['']
        html += ['', '']
        return '\n'.join(html)

    @cherrypy.expose
    def results(self):
        html = ['', '', '<meta http-equiv="refresh" content="2" >', '', '']
        html += ['
']
        html += ['
job:{} status:{} result:{} input:{}
'.format(j.get_id(), j.get_status(), j.result, j.args[0]) for j in self.jobs]
        html += ['
']
        html += ['', '']
        return '\n'.join(html)

    @cherrypy.expose
    def job(self, q):
        job = self.queue.enqueue(long_running_task, q)
        self.jobs.append(job)
        raise cherrypy.HTTPRedirect("/")

cherrypy.quickstart(BackgroundTasksWeb())

rawDescription: How to return data from a CherryPy BackgroundTask running as fast as possible

description: Return data from a CherryPy BackgroundTask running as fast as possible


code:
import dis
def foo():
    parent = ('    ' if comment['parent'] == cid-1 else commit['parent']) if 'parent' in commit else '<no parent>'

dis.dis(foo)

rawDescription: nested if-else as one-liners

description: Nested if-else as one-liners


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

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


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):
        #save the temporary result
        temp = dord((k.upper(), v.upper()) for k, v in d.items())
        #empty the old one
        d.clear()
        #update with the new data
        d.update(temp)
        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:
def poisson(x, lamb):
    from scipy.stats import poisson as _poisson
    return _poisson.pmf(x,lamb)

parameters, cov_matrx = curve_fit(poisson, bin_middles, entries, p0=6000)

rawDescription: Compare Histogram to Poisson Distribution and Gauss-Curve


code:
from collections import defaultdict
import re

# Only process words at least a minimum number of letters long.
MIN_WORD_LEN = 3
WORD_RE = re.compile('[a-zA-Z]{%s,}' % MIN_WORD_LEN)

def make_index(input_file):
    index = defaultdict(set)

    for line_num, line in enumerate(input_file, start=1):
        for word in re.findall(WORD_RE, line.lower()):
            index[word].add(line_num)  # Make sure line number is in word's set.

    # Convert result into a regular dictionary of simple sequence values.
    return {word:tuple(line_nums) for word, line_nums in index.iteritems()}

rawDescription: Check Values of A Dictionary for Repeating Numbers


code: "You have 10 cheeses!"

rawDescription: Explain why variables in my function are not related to variables in my script in Python 2


code:
return HttpResponse(data, mimetype='application/json', status=200)
return list

rawDescription: How can i change the values returned by parent class function in python

description: Change the values returned by parent class function in python


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

rawDescription: Django User Logout Fails to Redirect Homepage


code: map(list, permutations([2, 3, 4]))

rawDescription: How to find all possible sequences of elements in a list?

description: Find all possible sequences of elements in a list


code:
if counter == FRAMERATE:
    counter=0
    not_pressed=True

rawDescription: How to only get a key entry once per second? (or delay the time in between two keyboard entry)

description: Only get a key entry once per second? (or delay the time in between two keyboard entry)


rawDescription: How to speed up Poisson pmf function?

description: Speed up Poisson pmf function


code:
data2=np.array([[1,2],[3,4],[5,6]])
c = zip('a'*len(data2),data2[:,0],data2[:,1])
c
d = np.array(c,dtype=[('A', 'a1'),('Odd Numbers',int),('Even Numbers',int)])
d
d['Odd Numbers']

rawDescription: How can I quickly convert to a list of lists, insert a string at the start of each element?

description: Quickly convert to a list of lists, insert a string at the start of each element


code:
def PacketHandler(packet):
    # Send an event out to objects
    for obj in listeners:
        obj.packet_callback(packet)

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

rawDescription: Python Mindwave Graphs

description: Python Mindwave Graphs


code:
for f in files:
    parse_pdf(f)

rawDescription: How do I apply my python code to all of the files in a folder at once, and how do I create a new name for each subsequent output file?

description: Apply my python code to all of the files in a folder at once, and how do I create a new name for each subsequent output file


code:
import pyaudio
import wave
import sys

CHUNK = 1024

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

data = wf.readframes(CHUNK)

while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()

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


code:
class MyDecorator(object):
    def __init__(self, func):
        self.func = func
    def __call__(self, instance, *args, **kwargs):
        instance.someProperty = "New value"
        return self.func(instance, *args, **kwargs)
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return self.__call__.__class__(self, instance)

class ABC(object):
    def __init__(self):
        self.someProperty = "Initial value"
    @MyDecorator
    def someFunction(self):
        print("Hello world")

rawDescription: Set the property of a class using decorators on a class method in python


code:
class ObjectId(object):
  def __init__(self, v):
    self.v = v

list_of_lists = [[ObjectId('55119e14bf2e4e010d8b48f2')], [ObjectId('54624128bf2e4e5e558b5a52')], [ObjectId('53a6e7bc763f4aa0308b4569')], [ObjectId('55241823bf2e4e59508b494c')]]
set(tuple(x) for x in list_of_lists)

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:
import operator
unpacker = operator.itemgetter(0,1,slice(2,None,None))
for base, argtype, args in map(unpacker, 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


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


code:
{
    'name': {
        'type':'dict',
        'required': True,
        'unique': True,
        'schema': {
            'first': {'type': 'string'},
            'last': {'type': 'string'}
        }
    }
}

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


code:
def f():
    a = 2

rawDescription: Why can't Python access a subfunction from outside?


code:
if display_graph:
    init_something()

all_functions = [
    (show_timer, do_something),
    (other_option, do_other_thing),
]

functions_to_call = [function for (flag, function) in all_functions if flag]

while True:
    for function in functions_to_call:
        function()

rawDescription: Python code readablity for boolean variable driven code


code:
links = []
for row in reader2:
    edited_link = row[0].replace("http://", "", 1) if row[0].startswith("http://") else row[0]
    edited_link = edited_link.replace("https://", "", 1) if edited_link.startswith("https://") else edited_link
    edited_link = edited_link.replace("www.", "", 1) if edited_link.startswith("www.") else edited_link
    links.append(edited_link)

rawDescription: Getting urls with csv reader and putting them into a list


code:
from random import randint
from collections import Counter
from itertools import chain
sets = [{randint(1, 100) for _ in range(100)} for i in range(0, 100)]+ [{1, 2, 102},{3,4,103}]
cn = Counter(chain.from_iterable(sets))
unique = [k for k, v in cn.items() if v == 1]
print(unique)

rawDescription: Looking for unique numbers in a list of sets


code: df['bool'] = df['bool'].replace({'n': False, 'y': True})

rawDescription: How can I use transform to extract a feature based on multiple conditions, using pandas

description: Use transform to extract a feature based on multiple conditions, using pandas


rawDescription: Begineer's sorting with tuples

description: Begineer's sorting with tuples


code:
import timeit
timeit.timeit('list', number=10**7)
timeit.timeit('dict', number=10**7)

rawDescription: Why is [] faster than list()?

description: Why is [] faster than list()


code: self.regex_pattern = re.compile(r'\b[a-z]*?([a-z]{2,}?)\1+[a-z]*?\b', re.IGNORECASE)

rawDescription: Regex to match repeated (unknown) substrings


rawDescription: Bizarre issue with pandas' .groupby function, when function applied to rows


code:
horizontal = Gallery.objects.filter(type=True).order_by('?')[:7]
vertical = Gallery.objects.filter(type=False).order_by('?')[:5]

rawDescription: Custom filter for Django querysets

description: Custom filter for Django querysets


code:
import boto.support
conn = boto.support.connect_to_region('us-east-1')

rawDescription: Using Python Boto with AWS Support API

description: Using Python Boto with AWS Support API


code:
freqDict = {}
...
if word not in freqDict:
    freqDict[word] = 1
else:
    freqDict[word] += 1

rawDescription: Converting a Doc object into a string in python


code:
M = 10000
N = 10000

def thegoodone():
   for x in xrange(N):
       for y in xrange(M):
           pass

def thebadone():
    x = 0
    while x < N:
        y = 0
        while y < M:
            y += 1
        x += 1

rawDescription: Rationale behind Python's preferred for syntax


code: [tbl._cells[row, -1]._text.set_color('white') for row in range(1, len(colors)+1)]

rawDescription: Conditionally change background color of specific cells


code:
def help():
    ret = "calculating stuff to return"
    return ret

rawDescription: Python, globally accessable function

description: Python, globally accessable function


code:
from ctypes import *
from ctypes.wintypes import *

wininet = WinDLL('wininet', use_last_error=True)

class URL_COMPONENTS(Structure):
    _fields_ = (("dwStructSize", DWORD),
                ("lpszScheme", LPWSTR),
                ("dwSchemeLength", DWORD),
                ("nScheme", INT),
                ("lpszHostName", LPWSTR),
                ("dwHostNameLength", DWORD),
                ("nPort", INT),
                ("lpszUserName", LPWSTR),
                ("dwUserNameLength", DWORD),
                ("lpszPassword", LPWSTR),
                ("dwPasswordLength", DWORD),
                ("lpszUrlPath", LPWSTR),
                ("dwUrlPathLength", DWORD),
                ("lpszExtraInfo", LPWSTR),
                ("dwExtraInfoLength", DWORD))
    def __init__(self, bufsize=512):
        self.dwStructSize = sizeof(self)
        fields = iter(self._fields_)
        for name, dtype in fields:
            if dtype == LPWSTR:
                buf = (c_wchar * bufsize)()
                setattr(self, name, cast(buf, LPWSTR))
                name, dtype = next(fields)
                setattr(self, name, bufsize)

rawDescription: InternetCrackUrlW does not fill the values of strings behind pointers in structured class


code: sorted(range(len(a)), key=lambda i: a[i])[-2:]

rawDescription: Get index of the top n values of a list in python


code:
import re
s = 'start TT end'
callback = lambda pat: pat.group(1).lower()
re.sub(r'([A-Z]){2}', callback, s)

rawDescription: Using a regular expression to replace upper case repeated letters in python with a single lowercase letter


code: ser.write(b'5') # prefix b is required for Python 3.x, optional for Python 2.x

rawDescription: How can I interface python with the serial output from an Arduino Uno on a Mac?

description: Interface python with the serial output from an Arduino Uno on a Mac


rawDescription: Python/Numpy compress methode issue

description: Python/Numpy compress methode issue


rawDescription: Inverse lookup in pandas

description: Inverse lookup in pandas


code:
def change_vol(_=None):
    sounds.music.set_volume(vol.get())

rawDescription: Creating a volume slider in tkinter

description: Creating a volume slider in tkinter


code:
processed = 0
for filename in os.listdir(filepath):
    if not filename.endswith('.txt') or filename in synched:
        continue
    # process
    processed += 1
    if processed >= synclimit:
        break  # done for today.

rawDescription: FOR loop range to process certain number of files at a time


code:
def _get_pk_val(self, meta=None):
    if not meta:
        meta = self._meta
    return getattr(self, meta.pk.attname)

rawDescription: Django custom save not working

description: Django custom save not working


code:
import sys
from PyQt4 import QtGui

class Example(QtGui.QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(QtGui.qApp.quit)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Menubar')
        self.show()

def main():

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

if __name__ == '__main__':
    main()

rawDescription: Menubar/ System tray app with Qt

description: Menubar/ System tray app with Qt


rawDescription: Python, using BeautifulSoup parsing values from a table


code:
import re

valid_pattern = re.compile('^(?:\d[A-Z]|[A-Z]\d)$')
def is_valid(string):
    return valid_pattern.match(string) is not None

rawDescription: Two try statements with the same except clause


code: df['a'] = df['a'].str.lower()

rawDescription: How to correct typos in pandas dataframe

description: Correct typos in pandas dataframe


code:
import datetime

def get_start_of_previous_month(dt):
    '''
    Return the datetime corresponding to the start of the month
    before the provided datetime.
    '''
    previous = dt.date().replace(day=1) - datetime.timedelta(days=1)
    return datetime.datetime.combine(previous.replace(day=1), datetime.time.min)

rawDescription: Handling months in python datetimes

description: Handling months in python datetimes


code:
import subprocess
def make_shells(n):
    for i in range(n):
         subprocess.Popen(["cmd.exe"])

rawDescription: How to create 3 instances of command prompt in Windows and pass commands to each prompt in parallel using python

description: Create 3 instances of command prompt in Windows and pass commands to each prompt in parallel using python


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

rawDescription: Zipping two list of lists

description: Zipping two list of lists


code:
for shape_type, shape in list_of_shapes:
    print("{} {}".format(shape_type, ",".join(str(item) for item in shapes)))

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

description: Add strings to a list in Python


code:
def algorithm(houses, L):
    def revenue(i):
        return sum(pop * min((i-j)%(4*L), 4*L - (i-j)%(4*L)) for j,pop in houses)

    slope_changes = sorted(
            [(x, 2*pop) for x,pop in houses] +
            [((x+2*L)%(4*L), -2*pop) for x,pop in houses])

    current_x = 0
    current_revenue = revenue(0)
    current_slope = current_revenue - revenue(4*L-1)
    best_revenue = current_revenue

    for x, slope_delta in slope_changes:
        current_revenue += (x-current_x) * current_slope
        current_slope += slope_delta
        current_x = x
        best_revenue = max(best_revenue, current_revenue)

    return best_revenue

rawDescription: Algorithm (prob. solving) achieving fastest runtime


code:
def littery(*lst):
    return ''.join(lst[:-1] + [lst[-1][:-1]])

rawDescription: How do I join a list and then delete the last character?

description: Join a list and then delete the last character


code:
import math

class Ship:
    def centroid(self):
        return 1 / 3 * (self.x0 + self.x1 + self.x2), 1 / 3 * (self.y0 + self.y1 + self.y2)

    def __init__(self, canvas, x, y, width, height, turnspeed, acceleration=1):
        self._d = {'Up':1, 'Down':-1, 'Left':1, 'Right':-1}

        self.canvas = canvas
        self.width = width
        self.height = height
        self.speed = 0
        self.turnspeed = turnspeed
        self.acceleration = acceleration

        self.x0, self.y0 = x, y

        self.bearing = -math.pi / 2

        self.x1 = self.x0 + self.width / 2
        self.y1 = self.y0 - self.height

        self.x2 = self.x0 + self.width
        self.y2 = self.y0

        self.x, self.y = self.centroid()

        self.ship = self.canvas.create_polygon((self.x0, self.y0, self.x1, self.y1, self.x2, self.y2), outline="white", width=3)

    def changeCoords(self):
        self.canvas.coords(self.ship,self.x0, self.y0, self.x1, self.y1, self.x2, self.y2)

    def rotate(self, event=None):
        t = self._d[event.keysym] * self.turnspeed * math.pi / 180 # the trig functions generally take radians as their arguments rather than degrees; pi/180 radians is equal to 1 degree

        self.bearing -= t

        def _rot(x, y):
            #note: the rotation is done in the opposite fashion from for a right-handed coordinate system due to the left-handedness of computer coordinates
            x -= self.x
            y -= self.y
            _x = x * math.cos(t) + y * math.sin(t)
            _y = -x * math.sin(t) + y * math.cos(t)
            return _x + self.x, _y + self.y

        self.x0, self.y0 = _rot(self.x0, self.y0)
        self.x1, self.y1 = _rot(self.x1, self.y1)
        self.x2, self.y2 = _rot(self.x2, self.y2)
        self.x, self.y = self.centroid()

        self.changeCoords()

    def accel(self, event=None):
        mh = int(self.canvas['height'])
        mw = int(self.canvas['width'])
        self.speed += self.acceleration * self._d[event.keysym]

        self.x0 += self.speed * math.cos(self.bearing)
        self.x1 += self.speed * math.cos(self.bearing)
        self.x2 += self.speed * math.cos(self.bearing)

        self.y0 += self.speed * math.sin(self.bearing)
        self.y1 += self.speed * math.sin(self.bearing)
        self.y2 += self.speed * math.sin(self.bearing)

        self.x, self.y = self.centroid()

        if self.y < - self.height / 2:
            self.y0 += mh
            self.y1 += mh
            self.y2 += mh
        elif self.y > mh + self.height / 2:
            self.y0 += mh
            self.y1 += mh
            self.y2 += mh

        if self.x < -self.width / 2:
            self.x0 += mw
            self.x1 += mw
            self.x2 += mw
        elif self.x > mw + self.width / 2:
            self.x0 -= mw
            self.x1 -= mw
            self.x2 -= mw

        self.x, self.y = self.centroid()

        self.changeCoords()

rawDescription: How do I rotate a polygon in python on a Tkinter Canvas?

description: Rotate a polygon in python on a Tkinter Canvas


code:
output_string = " ".join(nwords)
print(output_string)

rawDescription: How to preserve and reverse a string?

description: Preserve and reverse a string


code:
keys = ['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos']
histodict = dict()
for item in history:
    date = item[0]
    values = item[1:]
    histodict[date] = dict(zip(keys, values))

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:
class TypedProperty2(object):
    def __init__(self, val, typ):
        if not isinstance(val, typ):
            raise TypeError()
        self.value = val
        self.typ = typ

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, val):
        if not isinstance(val, self.typ):
            raise TypeError()
        self.value = val

class Foo(object):
    name = TypedProperty2("name", str)

f1 = Foo()
f1.name = 'blah'

f2 = Foo()
print(f2.name)
f2.name = 'bar'

print(f1.name)

rawDescription: understanding a python descriptors example (TypedProperty)

description: Understanding a python descriptors example (TypedProperty)


code: x = ['Hello, I\'m bob', 'Hello, I\'m Gabe']

rawDescription: How do I check if a sub string exist in a list nested in a dictionary?

description: Check if a sub string exist in a list nested in a dictionary


rawDescription: Numpy tensor: Dot product along third axis


code:
timer = QTimer()
timer.timeout.connect(callback)
timer.start(msecs)

rawDescription: How to add a function to the Qt Mainloop

description: Add a function to the Qt Mainloop


code:
def update_html_on_client(request):
    language = request.GET.get('language', None)
    #for selected language do something
    cal_1 = ...
    return render_to_response('my_template.html', {'cal':cal_1}, content_instance = template.RequestContent(request))

rawDescription: Pass ajax response to django template

description: Pass ajax response to django template


code: import pdbtools

rawDescription: How do I call write a python function without opening the file beforehand?

description: Call write a python function without opening the file beforehand


code:
def check_ellipse(ellipse):
  h = ellipse[1][0]
  w = ellipse[1][1]
  #make sure it's not too large, or too circular
  if abs(h-w) < 2 or h > 30 or w > 30:
    return False
  return True

rawDescription: Uniquely identifying clustered ellipses which are about the same shape, but different sizes


code: lis=[(item[3],item[5]) for item in msg if item .startwith('$') ]

rawDescription: How to retrieve a specific field whith a special character in a list

description: Retrieve a specific field whith a special character in a list


rawDescription: pandas dataframe by index and integer

description: Pandas dataframe by index and integer


code: box[:] = blah

rawDescription: Broadcasting into views of Numpy arrays

description: Broadcasting into views of Numpy arrays


code:
dict2 = {}
for word in all_words:
    # Iterate over the dict1's items
    for key, sublist in dict1.items():
        # If the word is found in the sublist
        if word in sublist:
            # If the current word is found in dict2's keys
            if word in dict2:
                # Append the current key as a one element tuple
                dict2[word] += (key,)
            else:
                # Create a one element tuple and assign it to the word
                dict2[word] = (key,)

dict2

rawDescription: python- searching dictionary sublists; converting dictionary keys to values

description: Python- searching dictionary sublists; converting dictionary keys to values


code:
import re
m = re.sub(r'10', r'20', "hello number 10, Agosto 19")
m

rawDescription: python re.sub : replace substring with string

description: Python re.sub : replace substring with string


code: f = codecs.open('bar.txt', 'wt', encoding='utf8')

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


code:
import working_code
import mock

def test_my_fn():
    mock_simplejson = mock.Mock()
    working_code.simplejson = mock_simplejson
    working_code.my_fn('test-args')
    mock_simplejson.dumps.assert_called_with({'args': 'test-args'})

rawDescription: Python mocking- understand the concept and necessity


code:
pd.set_option('display.float_format', lambda x: '%.3f' % x)
Series(np.random.randn(3))*1000000000

rawDescription: Format / Suppress Scientific Notation from Python Pandas Aggregation Results


code:
@app.route('/test/<string:hashid>')
def test(hashid):
    hashids = Hashids()
    intid = hashids.decode(hashid)

    return url_for('test', hashid=hashids.encode(intid))

rawDescription: How to use encrypted parameters in url python flask?

description: Use encrypted parameters in url python flask


code:
def fake_response(file_name=None, url=None):
    """Create a Scrapy fake HTTP response from a HTML file"""
    if not url:
        url = 'http://www.example.com'

    request = Request(url=url)
    if file_name:
        if not file_name[0] == '/':
            responses_dir = os.path.dirname(os.path.realpath(__file__))
            file_path = os.path.join(responses_dir, file_name)
        else:
            file_path = file_name

        file_content = open(file_path, 'r').read()
    else:
        file_content = ''

    response = TextResponse(url=url, request=request, body=file_content,
                            encoding='utf-8')
    return response

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:
list1 = [
    self.tr('First Item'),
    self.tr('Second Item'),
    self.tr('Third Item'),
    ]

rawDescription: In pyqt how do I add items in a combobox?


code:
from os import system, environ
import win32con
from win32gui import SendMessage
from _winreg import (
    CloseKey, OpenKey, QueryValueEx, SetValueEx,
    HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE,
    KEY_ALL_ACCESS, KEY_READ, REG_EXPAND_SZ, REG_SZ
)

def env_keys(user=True):
    if user:
        root = HKEY_CURRENT_USER
        subkey = 'Environment'
    else:
        root = HKEY_LOCAL_MACHINE
        subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
    return root, subkey

def get_env(name, user=True):
    root, subkey = env_keys(user)
    key = OpenKey(root, subkey, 0, KEY_READ)
    try:
        value, _ = QueryValueEx(key, name)
    except WindowsError:
        return ''
    return value

def set_env(name, value):
    key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)
    SetValueEx(key, name, 0, REG_EXPAND_SZ, value)
    CloseKey(key)
    SendMessage(
        win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')

def remove(paths, value):
    while value in paths:
        paths.remove(value)

def unique(paths):
    unique = []
    for value in paths:
        if value not in unique:
            unique.append(value)
    return unique

def prepend_env(name, values):
    for value in values:
        paths = get_env(name).split(';')
        remove(paths, '')
        paths = unique(paths)
        remove(paths, value)
        paths.insert(0, value)
        set_env(name, ';'.join(paths))

def prepend_env_pathext(values):
    prepend_env('PathExt_User', values)
    pathext = ';'.join([
        get_env('PathExt_User'),
        get_env('PathExt', user=False)
    ])
    set_env('PathExt', pathext)

set_env('Home', '%HomeDrive%%HomePath%')
set_env('Docs', '%HomeDrive%%HomePath%\docs')
set_env('Prompt', '$P$_$G$S')

prepend_env('Path', [
    r'%SystemDrive%\cygwin\bin', # Add cygwin binaries to path
    r'%HomeDrive%%HomePath%\bin', # shortcuts and 'pass-through' bat files
    r'%HomeDrive%%HomePath%\docs\bin\mswin', # copies of standalone executables
])

# allow running of these filetypes without having to type the extension
prepend_env_pathext(['.lnk', '.exe.lnk', '.py'])

rawDescription: Interface for modifying Windows environment variables from Python


code:
for x in t[1].values():
    setattr(x, 'test', 'wow')

rawDescription: Dynamically set object attribute with map and setattr function


rawDescription: How to iterate a multilevel dict in python

description: Iterate a multilevel dict in python


code: type(f).__str__ is not object.__str__

rawDescription: How to check if __str__ is implemented by an object

description: Check if __str__ is implemented by an object


code:
from time import time
current_time = time.strftime(r"%d.%m.%Y %H:%M:%S", time.localtime())
import time
current_time = time.strftime(r"%d.%m.%Y %H:%M:%S", time.localtime())
current_time

rawDescription: Python: Generate a date time string that I can use in for MySQL


code:
def print_param(param):
    print('Values passed via parameter: {}'.format(param))

rawDescription: Passing private variables from class isntance into method outside class?


code:
def fun(**args):
  param1 = args.get('param1', 'default_value')
  param2 = ... # etc

fun(param1='val1', param2 = 'val2')

rawDescription: Classes with different files and passing vars between functions


code: ['$25', 'Sep', '5', 'Porcelain', 'Baby', 'Deer', '$25', '(sunnyvale)', 'pic', 'household', 'items', '-', 'by', 'owner']

rawDescription: Python Web Scrape Write Output to File

description: Python Web Scrape Write Output to File


code: dates = [v[1] for v in E.itervalues()]

rawDescription: Dictionary conversion to list in Python

description: Dictionary conversion to list in Python


rawDescription: How to get ctypes type object from an ctypes array

description: Get ctypes type object from an ctypes array


code:
import pandas as pd
df = pd.read_csv('citydat.csv', header=None,
     names=['code','sur','name','date','city','post','sex','email'])
df.set_index('code', inplace=True, drop=True)
cities = df.city.unique()
while True:
    city = input('enter city: ').title()
    if city in cities:
        print(df[df.city==city])
    elif city == '':
        break
    else:
        print(city,'not in database')

rawDescription: Display array values based on user input in Python


code:
import pyodbc
import win32com.client
import urllib2

class CacheOdbcClient:

    connectionString="DSN=MYCACHEDSN"

    def __init__(self):
        pass

    def getGlobalAsOverlyLargeList(self):
        connection=pyodbc.connect(self.connectionString)
        cursor=connection.cursor()
        cursor.execute("call MyPackageName.MyClassName_OneGlobal ?","MYGLOBAL")
        list=[]
        for row in cursor :
            list.append((row.NodeValue,row.Sub1,row.Sub2,row.Sub3,row.Sub4,row.Sub5,row.Sub6,row.Sub7,row.Sub8,row.Sub9))
        return list

rawDescription: Intersystems Cache - Can Python be used to directly access a global or only classes exposed as sql tables?


code: dfts.groupby(lambda x : x.year).std()

rawDescription: Group by multiple time units in pandas data frame


code:
import header as h
h.module1.method()

rawDescription: Python "header.py" module

description: Python "header.py" module


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


code:
def flat(l):
    def _flat(l, r):
        if type(l) is not list:
            r.append(l)
        else:
            for i in l:
                r = r + flat(i)
        return r
    return _flat(l, [])

rawDescription: python: how can I achieve a cartesian product of all the lists in a list?

description: Python: how can I achieve a cartesian product of all the lists in a list


code:
wins = df.groupby('Winner').size()
losses = df.groupby('Loser').size()

scores = pd.DataFrame({'Wins' : wins, 'Losses' : losses}).fillna(0)

rawDescription: pandas dataframe aggregate calculation

description: Pandas dataframe aggregate calculation


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


rawDescription: How to get DataFrame indices for multiple rows configurations using Pandas in Python?

description: Get DataFrame indices for multiple rows configurations using Pandas in Python


rawDescription: How should I convert a string containing unicode characters to unicode?


rawDescription: Infinite Sequence. Cannot process answer in 1 second


code: meth = getattr(obj, func.__name__)

rawDescription: Can I weak reference methods?

description: Weak reference methods


code:
safe_builtins = dict(
    __builtins__ = None,
    float = float,
    sum = sum,
    custom_func = ...
)

loaded_func = eval("lambda x: ...", safe_builtins)

rawDescription: Is there a recommended way to load arbitrary functions from text (json) files?


code:
new_values = pd.DataFrame(data=np.zeros(df['values'].shape))
for v in np.unique(df['labels']):
    mask = df['values'].where(df['labels'].isin([v]))
    new_values += mask.div(mask.sum().sum()).fillna(0)
df.loc[:, 'values'] = new_values.values

rawDescription: groupby and normalize over two arrays

description: Groupby and normalize over two arrays


code:
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'C:/users/you/myproject/my.db'

rawDescription: Trouble setting up sqlite3 with django! :/


code:
def serialize_place(place):
    res = dict(id=place.id, address=place.address, city=place.city)
    lat, lng = place.lat(), place.lng()
    if lat is not None:
        res['lat'] = lat
    if lng is not None:
        res['lng'] = lng
    return res

json_c = [serialize_place(place) for place in dataset.places.all()]

rawDescription: Adding tuple to dictionary only if condition is true


code:
import re

number_regex = r'#define\s+VERSION_M[AJIN]+OR\s+(\d+)'

with open("guidefs.h") as f:
    your_text = f.read()
    all_numbers = re.findall(number_regex, your_text)
    # This will return ['2', '1']

rawDescription: Read a number in a word from a file in python


code:
pd.isnull(df).any()
df.columns[pd.isnull(df).sum() > 0].tolist()
df.columns[pd.isnull(df).any()].tolist()

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: wcounts, xedges, yedges = np.histogram2d(x, y, weights=w)

rawDescription: Generate Weight Map in Color with MatPlotLib?


code:
#spawn by path + return immediately  and get pid
pid = os.spawnl(os.P_NOWAIT, "./home/tim/bin/dalitest")

rawDescription: Call a shell script on a button press & kill it after pressed again


code:
test_name = 'John'
test_code = 1234

rawDescription: Searching and sorting in text files

description: Searching and sorting in text files


rawDescription: return an array instead of a tuple from a NumPy function

description: Return an array instead of a tuple from a NumPy function


code:
class BaseRequestHandler(webapp.RequestHandler):
    def __init__(self):
        self.user = None

    def get(self):
        self.user = users.get_current_user()
        if not self.user:
          self.redirect(users.create_login_url(request.uri))
          return
        self.doGet()

    def doGet(self):
        raise Exception("doGet() needs to be implemented by a subclass.")

class AnswerHandler(BaseRequestHandler):
    def doGet(self):
        answer = Answer.next_answer_by_user(self.user)
        self.write_template({"answer" : answer})

rawDescription: How to stop execution after self.redirect

description: Stop execution after self.redirect


code: X, Y, Z = np.meshgrid(x, y, z, sparse=True)

rawDescription: faster way to make a 3D blob with python?

description: Faster way to make a 3D blob with python


code: sum(i.pop(which_column) for i in triangle)

rawDescription: Python - Delete column from a matrix without numPy


code:
import os
os.execlp('ssh', 'ssh', 'user@server')

rawDescription: Python script ending in SSHing the terminal into a remote server


code:
def my_side_effect(email):
    return email == '1'

rawDescription: Python patch object with a side_effect

description: Python patch object with a side_effect


code: my_value = conditions[my_key]

rawDescription: Is there any way to compress test cases?

description: Is there any way to compress test cases


rawDescription: Counting occurence of words in CSV column and writing to another CSV?


code:
with open("test_out.txt", "w", encoding="utf-8") as output:
    output.write("\n".join(text) + "\n")

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

description: Sequentially search for files and save them


code:
from francesco import main

def test_this():
    main()
    print("All seems fine to me")
    assert True

rawDescription: python setup.py sdist and custom setup keywords don't play together

description: Python setup.py sdist and custom setup keywords don't play together


code:
import numpy as np
d = np.random.random((10, 2)).reshape((-1,4))
d
e = np.array([4-np.argsort(r) for r in d])
e

rawDescription: What is the best way to create a moving window in 2D array ond order pixels


code: ', '.join([row[x] for x in range(1, len(row) - 1)])

rawDescription: A single CSV column includes commas - Python


code: df['number_of_days'] = [np.sum(np.exp(-0.001 * (np.arange(d) + s))) for d, s in zip(delta.values, shift.values)]

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

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


code: z

rawDescription: How to convert JavaScript dictionary into Python syntax

description: Convert JavaScript dictionary into Python syntax


code:
d = {1: 'a', 3: 'a'}
from collections import OrderedDict
sorted_d = OrderedDict((k, d[k]) for k in sorted(d))

rawDescription: Should dict store key in order by inc?

description: Should dict store key in order by inc


code:
def something():
    x =0

    return x

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


code:
min(a.itervalues(),
    key=lambda v: v if isinstance(v, datetime) else datetime.max)

rawDescription: How to get the item with max date value in a python dictionary?

description: Get the item with max date value in a python dictionary


code:
A = [set([1,2]),set([1,2]), set([1])]
set(frozenset(s) for s in A)

rawDescription: Convert a list of sets to a set of sets (to find the unique elements)


code:
Ellipsis.__doc__ is None
NotImplemented.__doc__ is None
type(Ellipsis)()
type(NotImplemented)()

rawDescription: Why does None lack a docstring?

description: Why does None lack a docstring


code:
df2 = pd.DataFrame([[1,.2],[4,3]], dtype='object')
df2[1].dtype
map(type,df2[1])

rawDescription: Mixed types of elements in DataFrame's column


code: weight, l, n, dn = get_element(dim, vertices, quadrature_degree, polynomial_degree)

rawDescription: Wrap C struct with array member for access in python: SWIG? cython? ctypes?


code: np.einsum('ijkl->kl', M)

rawDescription: Python - Sum 4D Array

description: Python - Sum 4D Array


code:
pd.to_numeric(df.A, errors='coerce').notnull() & (df.A > 0)
df.A.apply(np.isreal) & (df.A > 0)

rawDescription: how to create dummy variables in Pandas when columns can have mixed types?

description: Create dummy variables in Pandas when columns can have mixed types


code:
import json

with open('grocery_stock.txt', 'r') as file:
    grocery_stock = json.load(file)

...

with open('grocery_stock.txt', 'w') as file:
    json.dump(grocery_stock, file, indent=4)

rawDescription: Adding a '\n' to the end of my dictionary when writing it to file


code: "he is a good man, and a good husband".replace('good', '[[ good ]]', 1)

rawDescription: replacing certain expressions in file but only one time

description: Replacing certain expressions in file but only one time


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


rawDescription: using Python reduce over a list of pairs

description: Using Python reduce over a list of pairs


code: from builtins import zip

rawDescription: zip in IronPython 2.7 and Python3.5

description: Zip in IronPython 2.7 and Python3.5


rawDescription: Parse resulting webpage Python Selenium

description: Parse resulting webpage Python Selenium


code:
fig1 = plt.figure(1)
plt.plot(tbdata['g0-r0'], tbdata['g0'], 'r.', label=u'Etoiles du champ')
plt.plot(Blue_stars['g0-r0'], Blue_stars['g0'], 'b.', label =u'Etoiles bleues')
plt.title('Diagramme Couleur-Magnitude')
plt.xlabel('(g0-r0)')
plt.ylabel('g0')
plt.xlim(-1.5,2.5)
plt.ylim(14,28)
plt.legend(loc='upper left')
plt.gca().invert_yaxis()

plt.show()
#fig.savefig('CMD.png')

rawDescription: Conditions with Numpy

description: Conditions with Numpy


code:
app = Flask(__name__)
app.session_interface = RedisSessionInterface()

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


code:
import re
from itertools import chain

lis = ['plu;ean;price;quantity'*1000, 'plu1;ean1;price1;quantity1'*100]*1000

matcher = re.compile('^(?:plu(?:;|$)|[^;]*;ean(?:;|$))').match
[l.split(';') for l in lis if matcher(l)]

rawDescription: Fastest possible way to iterate through specific list in python


code:
int(x)
x[0]
x.item()

rawDescription: How convert [x] into x?

description: How convert [x] into x


rawDescription: Transportation Algorithm in Python

description: Transportation Algorithm in Python


code:
xs.sort()
ndx = numpy.searchsorted(xs, ys)

rawDescription: Find multiple values within a Numpy array


code:
d = {'data1': {'yes': 'abc'}, 'data2': {'yes': 'xyz'}}
for nested_d in d.values():
    nested_d['no'] = nested_d.pop('yes')
d

rawDescription: How to change the key of a nested dictionary

description: Change the key of a nested dictionary


code: {{ instance.fieldname|linebreaksbr }}

rawDescription: django + mysql text field format with breakline

description: Django + mysql text field format with breakline


code:
import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

rawDescription: Parsing a YAML file in Python, and accessing the data?


rawDescription: Update selected columns in 2D numpy array with 1D array


code:
for spell_timer in self.spellTimers.itervalues():
            spell_timer['tick'] += 1

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


code:
def hidePasswords(L, password):
    return ['*'*len(password) if elem==password else elem for elem in L]

rawDescription: List as a function argument - modifications discarded


code:
def run_user(S):
    #S is the user's function as a string.
    lvars=None #make sure the name is in locals()
    lvars=set(locals())
    exec(S)  #exec isn't usually a good idea -- but I guess you're a very trusting person.
    usr_namespace=list(set(locals())-lvars)
    usr_func_name=usr_namespace[0]
    if(len(usr_namespace)>1):
        raise ValueError("User input too much into the namespace!")

    usr_func=locals()[usr_func_name]
    usr_func()  #comment this out if you don't want to run the function immediately
    return usr_func

usr_string="""
def foo():
     a="Blah"
     print "Hello World! "+a
"""

func_handle=run_user(usr_string)  #prints "Hello World! Blah"
#and to demonstrate that we can pass a handle to the function around:...
func_handle() #prints "Hello World! Blah" again.

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


code:
import logging
import getpass

FORMAT = "DATE : %(asctime)-15s USER :  %(message)s FILE : %(filename)s"

logging.basicConfig(level=logging.DEBUG,
                    format=FORMAT,
                    filename='users.log',
                    filemode='a')

logging.debug(getpass.getuser())

rawDescription: python: Python script knows user that started this script last time?

description: Python: Python script knows user that started this script last time


code:
[var[0] for var in x]
[var[2] for var in x]

rawDescription: Create list out of a particular element of sublists


code:
preds = {0: lambda x: abs(x) > 5,
         1: lambda x: x % 2}
def splitList(myList, option):
    return filter(preds[option], myList)

rawDescription: Trying to return numbers in a list

description: Trying to return numbers in a list


code: EC.presence_of_element_located((By.XPATH, '//*[@id="myElem" and text() != ""]'))

rawDescription: How to verify an element contains ANY text?

description: Verify an element contains ANY text


code:
A = [{u'CI': {u'RP': 1}}, {u'CI': {u'RP': 1}},  {u'JI': {u'RP': 1}}]
B = defaultdict(lambda: defaultdict(int))
for d in A:
    for (key,d2) in d.iteritems():
        for (key2, value) in d2.iteritems():
            B[key][key2] += value

B.items()

rawDescription: Aggregate items in dict

description: Aggregate items in dict


code:
from numbers import Number, Integral

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

    if isinstance(value, Number):
        try:
            return not value % 1
        except TypeError:
            return False

    return False

rawDescription: How to check if value is logically integer?

description: Check if value is logically integer


code:
import sys
sys.path

rawDescription: python path django

description: Python path django


code:
cs1110
opython
nested
recursion
test

rawDescription: Recursive means of printing elements in a list in new lines


code:
wav = 'myfile.wav'
cmd = 'lame --preset insane %s' % wav
subprocess.call(cmd, shell=True)

rawDescription: Python convert wav to mp3

description: Python convert wav to mp3


code: ln -s /Users/Ben/Documents/Python/chaos.py /usr/local/bin/chaos.py

rawDescription: Trying use a .pth file to add a path in documents folder on Mac


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

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

description: Combine dictionaries with the same keys in python


code:
data = []
for idx, row in df.iterrows():
    data.append((row['country'], row['year'], row[row['year']]))
result = pd.DataFrame(data, columns=['country', 'year', 'value'])
print(result)

rawDescription: iterate through df column and return value in dataframe based on row index, column reference

description: Iterate through df column and return value in dataframe based on row index, column reference


code:
def add(x, y):
    return x + y

# Flatten the second list
second_flattened = list(chain(*(chain(*second))))

# There is probably a better way to achieve this
foo = [add(x, y) for x, y in zip(first, second_flattened)]

# If second is longer we should append unprocessed values
if len(second_flattened) > len(first):
    foo += second_flattened[len(foo): ]

bar = [foo[i:i+3] for i in range(0, len(foo), 3)]
second = [bar[i:i+2]  for i in range(0, len(foo) / 3, 2)]

rawDescription: Iterating over multiple lists simultaneously in Python


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}

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


rawDescription: How to create a pandas Timestamp object?

description: Create a pandas Timestamp object


code: list(map(lambda i, c=defaultdict(lambda c=count(): next(c)): c[i], data))

rawDescription: Shortest way to linearize a list in Python


code:
import matplotlib.pyplot as plt

plt.plot(range(10))
plt.axvspan(3, 6, color='red', alpha=0.5)
plt.show()

rawDescription: In a matplotlib plot, can I highlight specific x-value ranges?


code:
['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']

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


rawDescription: Pandas to_dict modifying numbers

description: Pandas to_dict modifying numbers


code:
def remove_checkbuttons():
    # Remove the checkbuttons you want
    for chk_bx in checkbuttons:
        chk_bx.destroy()

def create_checkbutton(name):
    return Checkbutton(root, text=name, command=lambda: box_select(name),
                       onvalue=1, offvalue=0, height=1, width=20)

#...
checkbuttons = [create_checkbutton(name) for name in test_name]

rawDescription: checkbox box with tkinter

description: Checkbox box with tkinter


rawDescription: Fit a curve to a histogram in Python

description: Fit a curve to a histogram in Python


code:
c = [1,2,3]
def multiply(*n):
    return reduce(lambda x, y: x * y, n)
def add(*n):
    return sum(n)
my_math = { "+":add,
            "*":multiply}
print(str(my_math["+"](*c)))
print(str(my_math["*"](*c)))

rawDescription: About functions dispatch in python3

description: About functions dispatch in python3


code:
class topList():
    __slots__ = ( "name", "gender", "occurences" )
    def __str__(self):
        return 'topList({s.name!r}, {s.gender!r}, {s.occurences!r})'.format(s=self)

tl = topList()
tl.name = 'FooBar'
tl.gender = 'm'
tl.occurences = 42
print(tl)
tl

rawDescription: Object Locations with Classes (Python)

description: Object Locations with Classes (Python)


rawDescription: write formated file

description: Write formated file


code: result = var1 if var1 is not None else var2

rawDescription: When zero is not None or not False but digit 0


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--l1', type=str)
parser.add_argument('--l2', type=str)
args = parser.parse_args()
l1_list = args.l1.split(',') # ['1','2','3','4']

rawDescription: Passing integer lists to python

description: Passing integer lists to python


code:
import binascii
binascii.hexlify('\x03\x2F\x00\x00\x02\x12\x01\x47')
' '.join(binascii.hexlify(ch) for ch in '\x03\x2F\x00\x00\x02\x12\x01\x47')

rawDescription: calculate hex checksum in python

description: Calculate hex checksum in python


code: unused_chars = all_chars - set(mystring)

rawDescription: Get all chars not in string python

description: Get all chars not in string python


code:
class PerformConnection():
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def perform(self):
        raise NotImplementedError

class PerformConnectionTCP(PerformConnection):
    def perform(self):
        # do what you got to do here...
        return results

rawDescription: Python decorate function with class and access class instance


code: {k: v for k, *v in zip(*ll)}

rawDescription: Creating dictionary with key/values coming from a list of lists


code:
import pprint
pp = pprint.PrettyPrinter()
pp.pprint(result)

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


code:
from datetime import datetime

l =  ['1','2','01/02/2015','3','4','1-05-2015','5','Another Ex/ample','6']

out = []

for ele in l:
    try:
        out.append(datetime.strptime(ele,"%d/%m/%Y").strftime("%Y-%m-%d"))
    except ValueError:
        out.append(ele)

print(out)

rawDescription: Python - Regular Expression to find dates in list


code:
# Could also check whether session.logged_in_user exists in DB, but probably not needed
# If so though, should be renamed zAuth or something to come after db.py file
if not session or not session.logged_in_user:
  redirect(URL('default','login', vars={'next':request.vars.url}))

rawDescription: Web2Py minimal User authentication (username only)


rawDescription: Find the start and the end of Programming Code in a whole Text


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

# size of the crowd
N = 100

def gen_data():
    """ init position and speed of each people """
    x = y = np.zeros(N)
    theta = np.random.random(N) * 360 / (2 * np.pi)
    v0 = 0.1
    vx, vy = v0 * np.cos(theta), v0 * np.sin(theta)
    return np.column_stack([x, y, vx, vy])

def init():
    pathcol.set_offsets([[], []])
    return pathcol,

def update(i, pathcol, data):
    data[:, 0:2] += data[:, 2:4]
    data[:, 2] = np.where(np.abs(data[:, 0]) > 5, -data[:, 2], data[:, 2])
    data[:, 3] = np.where(np.abs(data[:, 1]) > 5, -data[:, 3], data[:, 3])
    pathcol.set_offsets(data[:, 0:2])
    return [pathcol]

fig = plt.figure()
ax = plt.axes(xlim=(-5, 5), ylim=(-5, 5))
pathcol = plt.scatter([], [])
data = gen_data()
anim = animation.FuncAnimation(fig, update, init_func=init,
                               fargs=(pathcol, data), interval=0, blit=True)
plt.show()

rawDescription: modelling crowd movement with matplotlib

description: Modelling crowd movement with matplotlib


code:
class classproperty(object):
    def __init__(self, getter):
        self.getter = getter

    def __get__(self, instance, cls):
        return self.getter(cls)

class MyClass(object):
    def __init__(f):
        self._f = f

    @classproperty
    def f(cls):
        return cls._f

rawDescription: Idiom to define a class property

description: Idiom to define a class property


code:
def load_file(filename):
    lines = []
    with open(filename, 'Ur') as f:
        for line in f:
            lines.append(line)
    return lines

rawDescription: Python, adding a file into another file

description: Python, adding a file into another file


code:
def page_parser(self, response):
      sites = hxs.select('//div[@class="row"]')
      items = []
      request =  Request("http://www.example.com/lin1.cpp",  callback =self.parseDescription1)
      request.meta['item'] = item

      request =  Request("http://www.example.com/lin1.cpp",  callback =self.parseDescription2)
      request.meta['item'] = item

      request =  Request("http://www.example.com/lin1.cpp",  callback =self.parseDescription2)
      request.meta['item'] = item

      return request

def parseDescription1(self,response):
            item = response.meta['item']
            item['desc1'] = "test"
            return item

def parseDescription2(self,response):
            item = response.meta['item']
            item['desc2'] = "test2"
            return item

def parseDescription3(self,response):
            item = response.meta['item']
            item['desc3'] = "test3"
            return item

rawDescription: How can i use multiple requests and pass items in between them in scrapy python

description: Use multiple requests and pass items in between them in scrapy python


code:
import re
s = 'foo network1: network1:'
var1 = 'network1'
print(re.search(r'.*(\s+'+ var1 + r':)', s).group(1))
print(re.search(r'.*(..\s+'+ var1 + r':)', s).group(1)) # to check whether it fetches the last string or not.

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


code:
start_number = 0
# OR
start_number = 1

rawDescription: request url with number increase

description: Request url with number increase


rawDescription: How to convert a pymongo.cursor.Cursor into a dict?

description: Convert a pymongo.cursor.Cursor into a dict


code:
s = "Hello(There|World!!Hi[There]"
re.split(r'[(|!\[\]]+', s)

rawDescription: How can I use re's special characters when splitting a string?

description: Use re's special characters when splitting a string


code: np.multiply.outer(x, x)

rawDescription: performing outer addition with numpy

description: Performing outer addition with numpy


code:
from collections import Counter
with open('customers.txt') as customers:
    c = Counter(line.split(";")[0] for line in customers )
    print(c.most_common())

rawDescription: Assign values to dictionary by order they were added


code:
df = pd.DataFrame.from_dict({ k: dict(v) for k,v in d.items() },
                            orient="index").fillna(0)

rawDescription: Building a dataframe in an efficient way from dictionary


rawDescription: Get java version number from python

description: Get java version number from python


code: f1 = dict["file1"]

rawDescription: setting variables in a for loop python

description: Setting variables in a for loop python


code:
import pandas as pd
df = pd.DataFrame([{'third':'B','first':'A','second':'C'},
                   {'third':'B','first':None,'second':'C'},
                   {'third':'B','first':None,'second':None},
                   {'third':None,'first':None,'second':None},
                   {'third':'B','first':'A','second':None}])

mask = pd.isnull(df).values
df['combo1'] = df.values[np.arange(len(df)), np.argmin(mask, axis=1)]
order = np.array([1,2,0])
mask = mask[:, order]
df['combo2'] = df.values[np.arange(len(df)), order[np.argmin(mask, axis=1)]]

rawDescription: Is there a better more readable way to coalese columns in pandas


code:
int       # "type"
class X(object): pass

X         # "class"

rawDescription: In python at runtime determine if an object is a class (old and new type) instance


rawDescription: List of Lists in Dict weird initialization syntax


code:
# models.py:
from django.db import models

class ImageTest(models.Model):
    photo = models.ImageField(upload_to='photos')

# settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'

rawDescription: image.url returns local full path in view.py Django 1.6

description: Image.url returns local full path in view.py Django 1.6


code:
need_to_check_duplicate = True

while need_to_check_duplicate:
    need_to_check_duplicate = False
    min_index_map = {key: sorted_index_map[key][i] for key, i in index_of_min_index_map.iteritems()}
    index_set = list(min_index_map.itervalues())
    for key, index in min_index_map.iteritems():
        if index_set.count(index) == 1:
            continue
        else:
            for key_to_check, index_to_check in min_index_map.iteritems():
                if key != key_to_check and index == index_to_check:
                    if test[key][index] > test[key_to_check][index_to_check]:
                        index_of_min_index_map[key] += 1
                        need_to_check_duplicate = True
                        break

rawDescription: python find minimum value in dictionary iteratively

description: Python find minimum value in dictionary iteratively


code:
from collections import defaultdict
d = defaultdict(float)
from itertools import groupby, imap

with open("doc1") as f,open("doc2") as f2:
    values = imap(float, f2.read().split())
    # lambda x: not(x.strip()) will split into groups on the empty lines
    for ind, (k, v) in enumerate(groupby(f, key=lambda x: not(x.strip()))):
        if not k:
            topic = next(v)
            #  get matching float from values
            f = next(values)
            # iterate over the group
            for s in v:
                name, val = s.split()
                d[name] += (float(val) * f)
for k,v in d.iteritems():
    print("Prob for {} is {}".format(k,v))

rawDescription: How to determine probability of words?

description: Determine probability of words


code:
# Open 'new1.txt' as f1, 'new2.txt' as f2 and 'diff.txt' as outf
with open('new1.txt') as f1, open('new2.txt') as f2, open('diff.txt', 'w') as outf:

    # Read the lines from 'new2.txt' and store them into a python set
    lines = set(f2.readlines())

    # Loop through each line in 'new1.txt'
    for line in f1:

        # If the line was not in 'new2.txt'
        if line not in lines:

            # Write the line to the output file
            outf.write(line)

rawDescription: How to compare 2 txt files in Python

description: Compare 2 txt files in Python


code:
class ListWrapper:
    _allowed_attrs = set(['append', 'extend'])
    def __init__(self, value=None):
        self._wrapped = list(value) if value is not None else []
    def __getattr__(self, name):
        if name in self._allowed_attrs:
            return getattr(self._wrapped, name)
        else:
            raise AttributeError('No attribute {}.'.format(name))
    def __repr__(self):
        return repr(self._wrapped)

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


rawDescription: Using for loop for downloading results from blast


code: converters = {'ID': int, 'Data1': float, 'Data2': float, 'Data3': float, 'Data4': int}

rawDescription: Parsing data from text file

description: Parsing data from text file


code:
1 == True
0 == False
issubclass(bool, int)

rawDescription: Python Data Types and set, bool, hex

description: Python Data Types and set, bool, hex


code:
list_of_filenames = ['/foo/bar', '/baz', '/tmp/foo']
open_files = [open(f) for f in list_of_filenames]

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


code:
for spiderConfig in spiderConfigs:
    spiderConfig = spiderConfig.copy() # a dictionary similar to the one with global settings above
    spiderName = spiderConfig.pop('name') # name of the spider is in the configs - i can use the same spider in several instances - giving them different names
    spiderModuleName = spiderConfig.pop('spiderClass') # module with the spider is in the settings
    spiderModule = __import__(spiderModuleName, {}, {}, ['']) # import that module
    SpiderClass = spiderModule.Spider # spider class is named 'Spider'
    spider = SpiderClass(name = spiderName, **spiderConfig) # create the spider with given particular settings
    crawlerProcess.queue.append_spider(spider) # add the spider to spider pool

rawDescription: Running Scrapy from a script - Hangs

description: Running Scrapy from a script - Hangs


code:
country_name = ['South Africa', 'India', 'United States']
country_code = ['ZA', 'IN', 'US']
zip(country_name, country_code)

rawDescription: zip two strings in python

description: Zip two strings in python


code: {key:value for key, value in iterable if condition}

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


code: ModelWithTextField.objects.raw('SELECT * FROM model_with_text_field WHERE LEN_FUNC_NAME(text_field) > 7')

rawDescription: Django: Lookup by length of text field

description: Django: Lookup by length of text field


code:
import numpy
import numbers
numpy.float64
numpy.float64()
isinstance(numpy.float64, numbers.Real)
isinstance(numpy.float64(), numbers.Real) # Notice the () after numpy.float64

rawDescription: Why does "isinstance(numpy.float64,numbers.Real)" return False?


code:
for i in range(len(userAnswersList)):
    if userAnswersList[i] == correctAnswers[i]:
        correctedList.append(userAnswersList[i])
    else:
        correctedList.append('XX')

rawDescription: Compare a users input list to a set list in order with duplicates


code:
quantiles, idx = np.unique(sample, return_inverse=True)
counts = np.bincount(idx)

rawDescription: Empirical cdf in python similiar to matlab's one


code: msg = EmailMultiAlternatives(headers={'Reply-To': "another@example.com"})

rawDescription: Add reply to address to django EmailMultiAlternatives


code:
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(60000) #trigger every minute.

rawDescription: Python PyQt4 update data on widget every 1 min


code:
presentation.SaveAs("myfile.pptx");
presentation.Close();
ppApp.Quit();
workbook.SaveAs("myfile.xlsx");
workbook.Close();
xlsApp.Quit();

rawDescription: Creating PPT presentation with Python vs C#


rawDescription: mocking subprocess Process terminate

description: Mocking subprocess Process terminate


code: yield Request(url, meta={'depth': 1})

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


code:
df['count of not x'] = df.apply(lambda x: (x[['y','z']] != x['x']).sum(), axis=1)
df['unique'] = df.apply(lambda x: x[['x','y','z']].nunique(), axis=1)

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


code:
df_wanted.loc['XYK987', :]
df_wanted.loc[:, ('sum14N_avg')]
df_wanted.loc['ALF234', ('RIA_avg', 'C', 24)]

rawDescription: Python Pandas DataFrame how to Pivot

description: Python Pandas DataFrame how to Pivot


rawDescription: Removing duplicate lists within another list


code: d = {'breakfast': df_breakfast, 'lunch': df_lunch}

rawDescription: Pandas append data frames, add a field, and then flood the field with a default value?


code:
parity = 0x7f
bits = []
for bit in "somestring":
    parity ^= ord(bit)
    parity &= 0xFF #ensure width
    bits.append(bit)
bits.append(parity)

rawDescription: Python XOR on hex and string (parity check function)


code: s = re.sub(r'<(\w+)>', lambda m: replacement_dict.get(m.group()), s)

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


code:
import numpy as np

x = np.array([1,2,1,0,1,2,1,0])
w = np.fft.fft(x)
freqs = np.fft.fftfreq(len(x))

for coef,freq in zip(w,freqs):
    if coef:
        print('{c:>6} * exp(2 pi i t * {f})'.format(c=coef,f=freq))

# (8+0j) * exp(2 pi i t * 0.0)
#    -4j * exp(2 pi i t * 0.25)
#     4j * exp(2 pi i t * -0.25)

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

description: Extract frequency associated with fft values in python


code:
@property
def something(self):
    return 42

rawDescription: Can I see what a Python decorator does to my code?

description: See what a Python decorator does to my code


code:
import jinja2

# define the latex template
template_str = r"""
\documentclass{article}
\begin{document}
\begin{table}
  \centering
  \begin{tabular}{ccc}
%{ for line in table %} %{{line[0]%}} & %{{line[1]%}} & %{{line[2]%}} \\
%{ endfor %}
  \end{tabular}
\end{table}
\end{document}

"""

# initialize the rendering engine
renderer = jinja2.Environment(
  block_start_string = '%{',
  block_end_string = '%}',
  variable_start_string = '%{{',
  variable_end_string = '%}}'
)
template = renderer.from_string(template_str)

# bring the data array into shape
lines = [line.strip().split(',') for line in old_file]

# generate the tex source code
with open("test.tex", 'w+') as f:
  f.write(template.render(table=lines))

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


code:
from itertools import groupby
l = [240,200,160,4,0,0,0,0,4,4,4,0,0,0,1,1,1,1]
[list(g) for k,g in groupby(l, lambda x: x != 0) if k]

rawDescription: subsequences of an array that are not zero

description: Subsequences of an array that are not zero


code:
private_key_der[0] # version
private_key_der[1] # modulus
private_key_der[2] # publicExponent
private_key_der[3] # privateExponent
private_key_der[4] # prime1
private_key_der[5] # prime2
private_key_der[6] # exponent1
private_key_der[7] # exponent2
private_key_der[8] # coefficient
private_key_der[9] # otherPrimeInfos

rawDescription: RSA key parameters in pyOpenSSL from P12


code:
def pathology(request):
    pathology_id = request.POST['pathology_id']
    p = get_object_or_404(Pathology, pk=pathology_id)
    publications = p.publications.all()
    return render_to_response('my_template.html',
                              {'publications':publications},
                              context_instance=RequestContext(request))

rawDescription: python code for django view

description: Python code for django view


code:
if 'itemDetails' in json_file['document']:
    item_details = {'0': json_file['document']['itemDetails']}
else:
    item_details = {k: v['itemDetails'] for k, v in json_file['document'] if k != 'other'}

rawDescription: Parsing json file with changeable structure in Python


code:
import random

def get_arrow_seq(n):
    """
    Return a list of arrow filenames in random order, apart from the
    the restriction that arrows in opposite directions must not be
    adjacent to each other.

    """
    arrow_array = ['L.png', 'R.png', 'U.png', 'D.png']
    # Indexes of the arrows reversed wrt those indexed at [0,1,2,3]
    other_directions = [1,0,3,2]
    # Start off with a random direction
    last_arrow = random.choice(range(4))
    arrows = [arrow_array[last_arrow]]

    this_arrow = other_directions[last_arrow]
    for i in range(n):
        while True:
            # Keep on picking a random arrow until we find one which
            # doesn't point in the opposite direction to the last one.
            this_arrow = random.choice(range(4))
            if this_arrow != other_directions[last_arrow]:
                break
        arrows.append(arrow_array[this_arrow])
        last_arrow = this_arrow

    return arrows

print(get_arrow_seq(10))

rawDescription: python while and if with pairs of conditions

description: Python while and if with pairs of conditions


code:
tree = etree.parse(xmlFileUrl)
nsmap = {'def':'http://www.w3.org/2005/Atom'}
entries_expr = etree.XPath('//def:entry', namespaces=nsmap)
category_expr = etree.XPath('category')
for entry in entries_expr(tree):
    category = category_expr(entry)

rawDescription: Get Xpath dynamically using ElementTree getpath()


code:
def get_common_words(places):
    common_words = []
    for word in places[0]:
        is_common = all(word in place for place in places[1:]) #check to see that this word is in all places
        if is_common:
            common_words.append(word)
    return common_words

rawDescription: Dictionaries in Python

description: Dictionaries in Python


code:
def make_published(modeladmin, request, queryset):
    queryset = queryset.objects.exclude(status='d')
    queryset.update(status='p')
make_published.short_description = "Mark selected stories as published"

rawDescription: How do I check the value of a field in a custom action in Django admin?

description: Check the value of a field in a custom action in Django admin


code: abspath = os.path.join(BASE, relpath)

rawDescription: Relative paths approach (python)

description: Relative paths approach (python)


code:
from pymlconf import ConfigManager
from app.builtin_config import _builtin_config

config_root = ConfigManager(
   _builtin_config,
   ['app/conf/admin','app/conf/users'],
   '../other_path/../special.conf')

rawDescription: Python configuration library

description: Python configuration library


code: d['foo'] = [tuple(el) for el in d['foo']]

rawDescription: Python convert a list of lists into a list of tuples


code:
class MyClass:
    def __init__(self, options):
        self.options = options

    @classmethod
    def create_default_parser(cls):
        parser = argparse.ArgumentParser(description='something')
        parser.add_argument('-v', '--victor', dest='vic', default="winning")
        options = parser.parse_args()
        return cls(options)

rawDescription: alternate for multiple constructors

description: Alternate for multiple constructors


code:
line 4
line 5

rawDescription: Indentation based syntax -> AST

description: Indentation based syntax -> AST


code: rivers = np.ma.masked_where(rivers == 0, rivers)

rawDescription: Setting Transparency Based on Pixel Values in Matplotlib


code:
# Reading in your combination matrix:
pattern_mat = pd.read_clipboard()
# Map from first words to following words:
w2_dict = {}
for w1, row in pattern_mat.iterrows():
    w2_dict[w1] = list(row.loc[row == 'Yes'].index)
# Print all the resulting regexes:
# (not sure if the backspace needs to be escaped?)
for w1, w2_list in w2_dict.items():
    pattern = "^{w1}(-|\s)({w2s})$".format(w1=w1, w2s='|'.join(w2_list))
    print(pattern)

rawDescription: Compound word Pattern detection using pandas for large datasets


code:
import tkFileDialog
filename = tkFileDialog.askopenfilename()
f = open(filename, 'rb') # rb is important
import pickle
a, b, c = pickle.load(f)
f.close()

rawDescription: how to save and open variables to a file using tkFileDialog?

description: Save and open variables to a file using tkFileDialog


code:
a = [1, 2, 3]
b = [0, 1, 2]
[ x*y for x in a for y in b]
[[x*y for x in a] for y in b]

rawDescription: Python multiply 2 arrays

description: Python multiply 2 arrays


code:
import os

def is_stdin_piped():
    return not os.isatty(0)

rawDescription: Python - stdin - how to recognize the source of the input?


code:
import re
s = "abdc54sgh"
pattern = re.compile("\d+")
pattern.findall(s)

rawDescription: Python - Find a number and then copy it from a string


code:
def csv_spec(queryset):
    for employee in queryset:
        yield (
            employee.id,
            employee.manager.first_name,
            employee.user.last_login,
            employee.contact.phone_number)

w = csv.writer(outfile)
w.writerows(csv_spec(something))

rawDescription: Django/Jinja2 : Generate (data for) CSV via template syntax


code:
class MyBackground(Widget):
    opacity = NumericProperty(0.5)

    def __init__(self, **kwargs):
        y = 'test.jpg'
        super(MyBackground, self).__init__(**kwargs)
        with self.canvas:
            Color(1, 1, 1, self.opacity)
            self.bg = Rectangle(source=y, pos=self.pos, size=self.size)

        self.bind(pos=self.update_bg)
        self.bind(size=self.update_bg)
        Color(1, 0, 1, 0.5)

    def update_bg(self, *args):
        self.bg.pos = self.pos
        self.bg.size = self.size

rawDescription: How to change opacity when pressing buttons on kivy

description: Change opacity when pressing buttons on kivy


code:
for root, dirs, files in os.walk("path/to/folder"):
    for filename in files:
        if "1" in filename:
            do_something()
        else:
            do_something_else()

rawDescription: Rename files in python depending on file name


code: str = re.sub(r'\W', ' ', str, flags=re.UNICODE)

rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code:
x - x.mean()
(x - x.mean()) / x.std()

rawDescription: Centering a Numpy array of images

description: Centering a Numpy array of images


code:
listOne = ['10100', '10101', '01010', '00010', '00100']
listTwo = ["A","B","C","D","E"]
listThree = zip(listOne, listTwo)
listThree.sort(key = lambda x : x[0])
listThree
listOneSorted, listTwoSorted = zip(*listThree)
listOneSorted
listTwoSorted

rawDescription: generating a vector saying how a list should be sorted in python

description: Generating a vector saying how a list should be sorted in python


code:
for attr in dir(obj):
    print(attr, getattr(obj, attr))

rawDescription: how to reveal an object's attributes in Python?

description: Reveal an object's attributes in Python


code: list(bytestring)

rawDescription: Working with bit streams

description: Working with bit streams


code:
from datetime import datetime
datetime.strptime("Oct 4", "%b %d")
d = datetime.strptime("Oct 4", "%b %d")
datetime(datetime.now().year, d.month, d.day)

rawDescription: Parse date with Python library "ParseDateTime"


code: map(lambda s: s+(100 if s < 4 else 1), a)

rawDescription: Fastest way to modify list values with condition python


code:
import cartopy.crs as ccrs
from cartopy.io.shapereader import natural_earth, Reader
from cartopy.mpl.patch import geos_to_path
import iris
import iris.plot as iplt
import matplotlib.pyplot as plt
from matplotlib.path import Path

def get_geometries(country_names):
    """
    Get an iterable of Shapely geometries corrresponding to given countries.

    """
    # Using the Natural Earth feature interface provided by cartopy.
    # You could use a different source, all you need is the geometries.
    shape_records = Reader(natural_earth(resolution='110m',
                                         category='cultural',
                                         name='admin_0_countries')).records()
    geoms = []
    for country in shape_records:
        if country.attributes['name_long'] in country_names:
            try:
                geoms += country.geometry
            except TypeError:
                geoms.append(country.geometry)
    return geoms, ccrs.PlateCarree()._as_mpl_transform

def pcolor_mask_geoms(cube, geoms, transform):
    path = Path.make_compound_path(*geos_to_path(geoms))
    im = iplt.pcolor(cube)
    im.set_clip_path(path, transform=transform)

# First plot the full map:
cube = iris.load_cube(iris.sample_data_path('air_temp.pp'))
plt.figure(figsize=(12, 6))
ax1 = plt.axes(projection=ccrs.PlateCarree())
ax1.coastlines()
iplt.pcolor(cube)

# Now plot just the required countries:
plt.figure(figsize=(12, 6))
ax2 = plt.axes(projection=ccrs.PlateCarree())
ax2.coastlines()
countries = [
    'United States',
    'United Kingdom',
    'Saudi Arabia',
    'South Africa',
    'Nigeria']
geoms, transform = get_geometries(countries)
pcolor_mask_geoms(cube, geoms, transform(ax2))

plt.show()

rawDescription: Mask cube with features

description: Mask cube with features


code:
def chain_elements_or_slices(*elements_or_slices):
    new_list = []
    for i in elements_or_slices:
        if isinstance(i, list):
            new_list.extend(i)
        else:
            new_list.append(i)
    return new_list

new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])

rawDescription: creating a new list with subset of list using index in python

description: Creating a new list with subset of list using index in python


code:
class CustomCV(object):
    def __init__(self, ids, n_folds):
        """Pass an array of phenomenon ids"""
        self.ids = ids
        self.n_folds = n_folds

    def __iter__(self):
        for i in range(self.n_folds):
            train = make_a_boolean_mask_for_the_training_set()
            test = np.logical_not(train)
            yield np.where(train)[0], np.where(test)[0]

rawDescription: Is there an option to prevent the cross validation (and gridsearchCV) to randomize the rows of the dataset?


code:
someClass = SomeClass()
someClass.start()
someClass.onThread(someClass.doSomething)
someClass.onThread(someClass.doSomethingElse)
someClass.onThread(someClass.doSomething)

rawDescription: How to call a function on a running Python thread

description: Call a function on a running Python thread


code:
raw = read.lower ()
raw = re.sub(r'\t', '', raw)
l = raw.splitlines() #these next few lines are just for formatting

rawDescription: Writing python chunking loops with reference to another txt


code:
pre
stuff
post
pre
post
0

rawDescription: Python: wrapping method invocations with pre and post methods


rawDescription: convenient slicing of DataFrames with datetime indexes in pandas

description: Convenient slicing of DataFrames with datetime indexes in pandas


code:
import itertools
import random

def generate_combinations(thing, positive="valid", negative=None):

    """ Generate all possible combinations, walking and mimicking structure of "thing" """

    if isinstance(thing, dict):  # if dictionary, distinguish between two types of dictionary
        if positive in thing:
            if negative is None:
                return thing[positive]  # here it's OK if it's empty
            elif thing[positive]:  # here it's not OK if it's empty
                return [random.choice(thing[positive])] + thing[negative]
            else:
                return []
        else:
            results = []
            for key, value in thing.items():  # generate all possible key: value combinations
                results.append([(key, result) for result in generate_combinations(value, positive, negative)])
            return [dict(result) for result in itertools.product(*results)]

    elif isinstance(thing, (list, tuple)):  # added tuple just to be safe (thanks Padraic!)
        # generate recursive result sets for each element of list
        results = [generate_combinations(element, positive, negative) for element in thing]
        return [list(result) for result in itertools.product(*results)]

    else:  # not a type we know how to handle
        raise TypeError("Unexpected type")

def generate_boundary_combinations(thing):

    """ Generate all possible boundary combinations """

    valid = generate_combinations(thing)

    return [result for result in generate_combinations(thing, negative='boundary') if result not in valid]

rawDescription: Generate all combinations from a nested python dictionary and segregate them


code:
import fix_path # has to be first.
import wtforms

rawDescription: Uploading Python third party libraries

description: Uploading Python third party libraries


code:
import numpy as np
hello = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
hello = [np.array([n, 0, 0]) for n in hello]

rawDescription: Creating multiple vectors

description: Creating multiple vectors


code: self.c.create_image(574, 431, anchor=NW, image=self.c.photo)

rawDescription: Pixel Manipulation via GUI in Python (poss PIL, Tkinter)


code:
def a(self,event):
    aframe = aFrame(parent=self, id=997)  # parent is the MainFrame instance self
    aframe.Centre()
    aframe.Show()
    self.Hide()                           # Hide the MainFrame instance

rawDescription: "Child frame inside Father frame inside Grandfather frame" wxPython


code:
integer = re.compile(r'\-?\d+') # only do this once in your program

all_the_numbers = integer.findall(expression)

rawDescription: Retrieving a full number

description: Retrieving a full number


code:
from robot.libraries.BuiltIn import BuiltIn

class DependencyLibrary(object):
    ROBOT_LISTENER_API_VERSION = 2
    ROBOT_LIBRARY_SCOPE = "GLOBAL"

    def __init__(self):
        self.ROBOT_LIBRARY_LISTENER = self
        self.test_status = {}

    def require_test_case(self, name):
        key = name.lower()
        if (key not in self.test_status):
            BuiltIn().fail("required test case can't be found: '%s'" % name)

        if (self.test_status[key] != "PASS"):
            BuiltIn().fail("required test case failed: '%s'" % name)

        return True

    def _end_test(self, name, attrs):
        self.test_status[name.lower()] = attrs["status"]

rawDescription: Register Robot Framework listener within Python library


rawDescription: Selecting rows in a DataFrame that are not in a Series


Python construct a dictionary {0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 0, 2], 3: [0, 0, 3], ...,999: [9, 9, 9]}


code:
rgba_values = cm.gray(y)  # All RGBA values for your input value, with levels of gray
rgba_values[x != y] = [0, 1, 0, 1]  # Set the points where x and y differ to green (RBG = 0, 1, 0)
imshow(rgba_values, interpolation='nearest')

rawDescription: Matplotlib: plot differences between two images


code:
from django.contrib.auth.views import password_change
from django.core.urlresolvers import reverse

def my_password_change(request):
    return password_change(request=request,post_change_redirect=reverse('logout'))

rawDescription: Auto logout/destroy session after Password Change in Django