code:
math_ops = {'+', '-', '*', '/'}

def parse(inval):
    groups = []
    braces = 0
    part = ''
    for c in f:
        # We add to braces count
        if c == '(':
            braces += 1
        # We subtract from braces count
        elif c == ')':
            braces -= 1
        # If we are at a math symbol and our brace count is 0, we have a complete part.
        if c in math_ops and braces == 0:
            groups.append(part.strip())
            part = ''
            continue
        part += c
    if part:
        groups.append(part)
    return groups

rawDescription: Split if not within brackets

description: Split if not within brackets


code:
def replacer(match):
    return ...

rawDescription: regex replace from a list

description: Regex replace from a list


rawDescription: Convert list of graph edges to JSON tree


code:
import os
airodump = subprocess.Popen(..., stdout=open(os.devnull, "w"), stderr=open(os.devnull, "w"))

rawDescription: is python subprocess module quirky?

description: Is python subprocess module quirky


code:
def iter_lines(self):
    for line in self.connections[0].private_data_lines:
        if self.new_conn.is_set():
            break
        yield line

rawDescription: Break out of loop immediately after array is changed


code:
class CustomModelChoices(models.Model):

      model_name = models.StringField(db_field = 'mn')
      choices = models.DictField(db_field = 'ch')

class CustomModel(models.Model):

     _choice_generator = CustomModelChoices

     mapping = {
         'key': CustomModelChoices.objects.get(model_name = 'CustomModel').choices
     }

rawDescription: In Python, how to initialize a class attribute from the return value of a class method?


code: [{"name": d["name"]} for d in mine]

rawDescription: Python list of dictionaries projection, filter, or subset?


code: A = Counts.objects.filter(site_id__in = p).order_by('site_id','-year','-count').distinct('site_id')

rawDescription: Reference related object with annotate in django


code:
with open('myfile.txt', 'r') as f:
    content = [l for l in f.readlines() if not l.startswith('!')]

rawDescription: Parsing specific contents in a file

description: Parsing specific contents in a file


rawDescription: list comprehension with np.where to compare two arrays and combine them it first entry is equal

description: List comprehension with np.where to compare two arrays and combine them it first entry is equal


rawDescription: Python Pandas Dataframe pull column value/index down by one


rawDescription: Separating a string using predefined characters


rawDescription: Multiple data histogram in python

description: Multiple data histogram in python


code: df.groupby(lambda x: datetime.strptime(date_string, '%m/%d/%Y').date())

rawDescription: How to do groupby in pandas with part of date string?

description: Do groupby in pandas with part of date string


rawDescription: Python Instantiate All Classes Within a Module


code:
data = [['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '22:16:24', '2012'],
     ['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '23:16:24', '2012'],
     ['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '21:16:24', '2012'],
     ['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '22:02:24', '2012']
    ]

hour_frequency_list = {}

for temp in data:
  hour = temp[5].split(":")[0]
  if hour in hour_frequency_list:
     hour_frequency_list[hour] += 1
  else:
     hour_frequency_list[hour] = 1

sorted_list = sorted(hour_frequency_list.items())

print ("hour | Occurences")
for k in sorted_list:
    print (k[0] + "    |" + str(k[1]) )

rawDescription: How do I optimize Python Code?

description: Optimize Python Code


code:
import csv
from collections import Counter

with open('file.csv', 'rb') as my_file:
    reader = csv.reader(my_file)
    counts = Counter((r[0], r[1], r[2]) for r in reader)

with open('new.csv', 'wb') as outf:
    writer = csv.writer(outf)
    for (sender, receiver, id), count in counts.most_common():
        writer.writerow([sender, receiver, id, count])

rawDescription: Python - order columns and compare rows in csv


code:
def apply_size_distribution(dictionary_with_temporal_distribution):
    gown_cap_size = get_size_distribution('G2:G7', 'H2:H7')
    retlist = {}
    for cap_demand in grown_cap_size:
        for k, v in dictionary_with_temporal_distribution.items():
            if k.rsplit('-', 1)[0] == cap_demand.rsplit('-', 1)[0]:
                if cap_demand not in retlist:
                    retlist[cap_demand] = {}
                temp = retlist[cap_demand]
                for k1, v1 in dictionary_with_temporal_distribution[k].items():
                    temp[k1] = v1 * grown_cap_size[cap_demand]
    return retlist

rawDescription: Subdivide nested dictionary, while applying percentage from values in Python


code: cvWriteFrame(w, frame)

rawDescription: Python JPEG to movie

description: Python JPEG to movie


rawDescription: Turn off auto-closing parentheses in ipython


code:
env = os.environ['ENV']

if env == "dev":
    DATABASES = {   # localhost
        "default": {
            "ENGINE": "django.db.backends.postgresql_psycopg2",
            "NAME": " ",
            "USER": " ",
            # "PASSWORD": " ",
            "HOST": "localhost",
            "PORT": "5432",
        }
    }
elif env == "prod":
    DATABASES = {  #aws
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': " ",
            'USER': " ",
            'PASSWORD': " ",
            'HOST': "xxx.ap-northeast-1.rds.amazonaws.com" ,
            'PORT': "5432",
        }
    }

rawDescription: switch database by ip or something else

description: Switch database by ip or something else


code:
new.append(line[:-2] + "\n")  # slice as you just checked line.endswith("*\n")
new.append("*\n")

rawDescription: python writing a list to a file incorrectly

description: Python writing a list to a file incorrectly


rawDescription: boost python, using a namespace other than main global

description: Boost python, using a namespace other than main global


rawDescription: Counting similarities among two pandas dataframes


code:
@timed
def toBeTimed():
    pass

rawDescription: How do you have python scripts display how much time it takes to execute each process?

description: Have python scripts display how much time it takes to execute each process


code:
def match_previous(lst, word):
    matches_count = total_length_sum = 0.0
    previous_word = lst[0]
    rest_of_words = lst[1:]
    if previous_word == word:
        print("First word matches.")
        matches_count += 1
    for ind, current_word in enumerate(rest_of_words, 1):
        print("On iteration {}.\nprevious_word = {} and current_word = {}.".format(ind, previous_word, current_word))
        if word == current_word:
            total_length_sum += len(previous_word)
            matches_count += 1
            print("We found a match at index {} in our list of words.".format(ind-1))
        print("Updating previous_word from {} to {}.".format(previous_word, current_word))
        previous_word = current_word
    return total_length_sum / matches_count if matches_count else False

rawDescription: Preceding Word Length

description: Preceding Word Length


code:
destroyedStatus = Status.objects.get(description="destroyed")
clients_destroyed_items = StorageItem.objects.filter(client=client,
    history__status=destroyedStatus)

rawDescription: Query for items using filter for most recent entry in a related table


rawDescription: 2D NumPy array comparison in given range


code:
def twoDigits (i):
    if not 0 < i < 100: raise Exception ('Out of bounds')
    below20 = [None, 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'nuef',
        'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf']
    tens = [None, None, 'vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante', 'quatre-vingt', 'quatre-vingt']
    a, b = i // 10, i % 10
    if a in (1, 7, 9): b += 10
    return ' '.join (x for x in (tens [a], below20 [b] ) if x)

for a in range (1, 100):
    print (a, twoDigits (a) )

rawDescription: Python - French year/number pronunciator


code:
import numpy as np

# Convert A to 2D numpy array
A_arr = np.asarray(A)

# Setup intervals for binning later on
intv = A_arr[:,:2].ravel()

# Perform binning & get interval & grouped indices for each X
intv_idx = np.searchsorted(intv, X, side='right')
grp_intv_idx = np.floor(intv_idx/2).astype(int)

# Get mask of valid indices, i.e. X elements are within grouped intervals
mask = np.fmod(intv_idx,2)==1

# Setup output array
Y = np.ones(len(X))

# Extract col-3 elements with grouped indices and valid ones from mask
Y[mask] = A_arr[:,2][grp_intv_idx[mask]]

# Remove (set to 1's) elements that fall exactly on bin boundaries
Y[np.in1d(X,intv)] = 1

rawDescription: Build array from other array and table of values (Python)


code:
sum(odd)
sum(even)

rawDescription: Count even and odd numbers and the totals (python)


code:
import simpy

def simulation_run(env):
    print("Starting a run at time [%i]" % env.now)
    yield env.timeout(5)
    print("Ending a run at time [%i]" % env.now)

def starter(env):
    yield env.timeout(5)
    env.process(simulation_run(env))

if __name__ == '__main__':
    env = simpy.Environment()
    env.process(starter(env))
    print("Starting simulation.")
    env.run(20)
    print("End of simulation.")

rawDescription: Starting a simpy simulation run using a callback


code:
class AuctionAdmin(admin.ModelAdmin):
    list_display = ('dates', 'sr_no', 'symbol_display', 'series', 'qty')

    def symbol_display(self, obj):
        symbol = Sttlmnt_typ_Master.objects.filter(symbol=obj.symbol).first()
        return symbol.symbol_name if symbol else obj.symbol
    symbol_display.short_description = 'Symbol'

rawDescription: Django foreign key in model

description: Django foreign key in model


code:
with open(filename, 'r') as infile:
    lines = [line for line in infile][:N]

rawDescription: How to read file N lines at a time in Python?

description: Read file N lines at a time in Python


code:
def rotate_4(l):
    return l[1:] + [l[0]]

rawDescription: Python: manipulating list in place

description: Python: manipulating list in place


code:
import picamera, subprocess, os, sys
import threading

def my_process():
    a1 = "arecord -f cd -D plughw:0 -d 10 a.wav"
    subprocess.call(a1,shell= True)
thread = threading.Thread(target=my_process)
thread.start()
print("Audio record is only for 10sec")

rawDescription: Use subprocess in Python

description: Use subprocess in Python


code:
def returnPegs(guess, answer):
    guesses = guess.split()
    answers = answer.split()

    pegs = []

    for answer, guess in zip(answers, guesses):
        if answer == guess:
            pegs.append('B')
        elif guess in answers:
            pegs.append('W')

    return ''.join(pegs)

rawDescription: Optimizing MasterMind Code and string operations in python


code: new_list = [item for item in lst if not re.search(r'\d', item)]

rawDescription: Python: Issues with "if not any"

description: Python: Issues with "if not any"


code:
import numpy as np
import pandas as pd
np.random.seed(2015)

N = 100
sorted = pd.DataFrame(np.random.randint(10, size=(N,2)),
                      columns=['bidder_id', 'bid_time_diff'])
# Add some NaNs to `sorted` to show the effect of `fillna`
mask = sorted['bidder_id'] == 0
sorted.loc[mask, 'bid_time_diff'] = np.nan

grouped = sorted.groupby('bidder_id')['bid_time_diff']
features = grouped.agg({'median_diff':'median', 'max_diff':'max'})
features = features.fillna(features.mean())
print(features)

rawDescription: Pandas: Efficiently Adding Multiple Columns To A New Dataframe


code: s += str(a[i,j,k].imag) + ' '

rawDescription: Pythonic way to print a multidimensional complex numpy array to a string


code:
from collections import defaultdict, namedtuple
import csv
from itertools import imap, izip_longest

# a couple of utility string conversion functions
def rename(name):
    """ Convert csv column name to a valid namedtuple fieldname which must be a
    valid Python identifier. Not exhaustive, but good enough for the headers
    shown (and is reversable, see below).
    """
    return name.lower().replace(' ', '_')

def undo_rename(name):
    """ Convert munged namedtuple fieldname back to a csv column name. """
    return name.replace('_', ' ').capitalize()

banktrans_filename = 'banktrans.csv'
banktrans_merged_filename = 'banktransmerged.csv'
DELIMITER = ';'
matched_trans = defaultdict(list)

with open(banktrans_filename, 'rb') as banktrans_file:
    reader = csv.reader(banktrans_file, delimiter=DELIMITER)
    # create namedtuple fieldnames from csv header row
    fieldnames = [rename(columname) for columname in next(reader)]
    Transaction = namedtuple('Transaction', fieldnames)
    for transact in imap(Transaction._make, reader):
        match_key = (transact.date_recorded, transact.date_occurred,
                     transact.verification_number, transact.memo,
                     # disregard any leading minus sign in amount field
                     transact.amount[transact.amount.startswith('-'):])
        matched_trans[match_key].append(transact)

with open(banktrans_merged_filename, 'wb') as banktrans_merged_file:
    writer = csv.writer(banktrans_merged_file, delimiter=DELIMITER)
    # merged tranactions have an additonal fieldname at the end
    mergedfieldnames = fieldnames + [rename('Destination account')]
    MergedTransaction = namedtuple('MergedTransaction', mergedfieldnames)
    # write header row
    writer.writerow([undo_rename(fieldname) for fieldname in mergedfieldnames])
    # merge pairs of matched transactions
    for match_key, transacts in sorted(matched_trans.items()):
        for trans_pair in izip_longest(*([iter(transacts)]*2)):
            if trans_pair[1] is None:  # unmatched trans, copy & add empty col
                merged_transact = MergedTransaction._make(trans_pair[0] + ('',))
            elif (trans_pair[0].amount.startswith('-') ==
                  trans_pair[1].amount.startswith('-')):  # amts have same sign?
                # records shouldn't be merged, treat as two unmatched trans
                merged_transact = MergedTransaction._make(trans_pair[0] + ('',))
                writer.writerow(merged_transact)
                merged_transact = MergedTransaction._make(trans_pair[1] + ('',))
                writer.writerow(merged_transact)
                continue  # skip remainder of loop
            else:  # merge pair by making source of the second the dest account
                merged_transact = MergedTransaction._make(
                    trans_pair[0] + (trans_pair[1].source_account,))
            writer.writerow(merged_transact)
print('merged transactions saved to file: ' + repr(banktrans_merged_filename))

rawDescription: Compare bank account statements in xlsx or csv file format to find any matching transactions


code: k='A'; set(tuple(x) for x in d[k])

rawDescription: Intersection of subelements of multiple list of lists in dictionary


code:
def galPrice(commodity, values):
    return [dict(zip(values, [com[value] for value in values if com['name'] == commodity]))
            for com in data['lastStarport']['commodities']]

rawDescription: Retrieve multiple values from JSON

description: Retrieve multiple values from JSON


code:
for codon in mutated_codon:
    print(codon_lookup[codon])

rawDescription: How can I do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries?

description: Do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries


code: [list_A[i] for i in list_B]

rawDescription: Python list as a list indices

description: Python list as a list indices


rawDescription: What's going on in this code?

description: What's going on in this code


code:
import random

def randomly_generate():
    number1= int(input("Please enter the lower number: "))
    number2= int(input("Please enter the higher number: "))
    numList=random.sample(range(number1, number2), 20)
    print(numList)
    return numList

if __name__ == "__main__":
    returned_list = randomly_generate()

    print(returned_list)

rawDescription: Returning a random list of integers, Python 3.3


code:
import sys
from contextlib import contextmanager

@contextmanager
def func(fname):
    fhandle = open(fname,"w") if fname else sys.stdout
    yield fhandle
    if fname:
        fhandle.close()

rawDescription: Proper use of "with" together with stdout in Python


rawDescription: Filling gaps for cumulative sum with Pandas


rawDescription: get table columns from sqlAlchemy table model

description: Get table columns from sqlAlchemy table model


code:
import Tkinter as tk

class Page2(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="This is page 2")
        label.pack(fill ="both", expand=True, padx=20, pady=10)

rawDescription: TTK Notebook Share data between imported tabs


rawDescription: generating a grid in a function

description: Generating a grid in a function


code:
def double_inputs():
    while True:
        x = yield
        yield x * 2
gen = double_inputs()
gen.next() #run up to the first yield
gen.send(10) #goes into 'x' variable
gen.next() #run up to the next yield
gen.send(6) #goes into 'x' again
gen.next() #run up to the next yield
gen.send(94.3) #goes into 'x' again

rawDescription: python generator "send" function purpose?

description: Python generator "send" function purpose


code:
for row in rows:
    writer.writerow(row)

rawDescription: Writing Python lists to columns in csv

description: Writing Python lists to columns in csv


code:
data = np.loadtxt('data.txt')
df = pd.DataFrame({'attributes': list(data[:, 1:])}, index=data[:, 0].astype(int))

rawDescription: How to read part of the line into array with python-pandas?

description: Read part of the line into array with python-pandas


code: list(range(desti, current, -1))

rawDescription: How to find the numbers in between the numbers that the user has input?

description: Find the numbers in between the numbers that the user has input


code:
import datetime
import calendar

now = calendar.timegm(datetime.datetime.now().timetuple())

rawDescription: converting unix timestamp to local time

description: Converting unix timestamp to local time


code:
@jit(nopython=True)
def check_mask_2(db, out, mask=np.array([1, 0, 1])):
    for idx in range(db.shape[0]):
        if db[idx,0] != 1:
            continue
        check = 1
        for j in range(db.shape[1]):
            if mask[j] and not db[idx,j+1]:
                check = 0
                break
        out[idx] = check
    return out

rawDescription: numba slower for numpy.bitwise_and on boolean arrays

description: Numba slower for numpy.bitwise_and on boolean arrays


code: lst

rawDescription: zip multiple values with single value

description: Zip multiple values with single value


code:
import os

corpus = []
path = '.'
for i in os.walk(path).next()[2]:
    if i.endswith('.txt'):
        f = open(os.path.join(path,i))
        corpus.append(f.read())
frequencies = Counter([])
for text in corpus:
    token = nltk.word_tokenize(text)
    bigrams = ngrams(token, 2)
    frequencies += Counter(bigrams)

rawDescription: Generating Ngrams (Unigrams,Bigrams etc) from a large corpus of .txt files and their Frequency


code:
class FirstLoginCheckMiddleware(object):
    def process_request(self, request):

        is_form_page = request.path in (
            settings.FORM_PAGE
        )

        if (not is_form_page) and request.user.is_authenticated() and (not request.user.profile.filled_out_the_form):
            return HttpResponseRedirect(settings.FORM_PAGE)
        return None

rawDescription: Open page at first login

description: Open page at first login


code:
df
df1
df1.resample('20L')
df2

rawDescription: Average time series with missing time value


code:
if myVariant.type == QVariant.Int:
    value = myVariant.toInt()
elif myVariant.type == QVariant.QString:
    value = myVariant.toString()

rawDescription: From QVariant to Integer and String

description: From QVariant to Integer and String


rawDescription: Timestring regex: please simplify it and show how the colons can be dropped?


code:
for bullet in bullet_list:

    block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

    for block in block_hit_list:
        explosion.play()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)
        score += 10

        if health >= 25 and score == 70:
            win.play()
            font = pygame.font.Font("freesansbold.ttf", 30)
            label = font.render("LEVEL COMPLETE!", 1, (0,255,0))
            labelRect = label.get_rect()
            labelRect.center = (400, 250)
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            break

    if score >= 70:
        collision.stop()
        laser.stop()
        explosion.stop()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)
        block_list.remove(block)
        all_sprites_list.remove(block)
        player_list.remove(player)
        all_sprites_list.remove(player)

    if health == 0:
        laser.stop()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)

    if bullet.rect.y < -10:
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)

if block.rect.y >= 600 and health >=25 and score < 70 and score > 0:
    font = pygame.font.Font("freesansbold.ttf", 30)
    label = font.render("Score target not met", 1, (0,255,0))
    labelRect = label.get_rect()
    labelRect.center = (400, 250)

rawDescription: Printing text once sprite meets position


code:
def talk (speaker, listener, data):
    data[speaker][listener] += 1
    data[listener][speaker] += 1

d = {
'Frank': {'Jack': 0, 'Kevin': 0, 'Sam': 0},
'Sam': {'Frank': 0, 'Jack': 0, 'Kevin': 0},
'Kevin': {'Frank': 0, 'Jack': 0, 'Sam': 0},
'Jack': {'Frank': 0, 'Kevin': 0, 'Sam': 0} }

talk('Frank', 'Sam', d)

print(d)

rawDescription: Incrementing values in a dict

description: Incrementing values in a dict


code:
class FileUploadForm(forms.Form):
    file = forms.FileField()

    def clean_file(self):
        CONTENT_TYPES = ['image']
        MAX_UPLOAD_PHOTO_SIZE = "2621440"
        content = self.cleaned_data['file']
        content_type = content.content_type.split('/')[0]
        if content_type in CONTENT_TYPES:
            if content._size > MAX_UPLOAD_PHOTO_SIZE:
                msg = 'Keep your file size under %s. actual size %s'\
                        % (filesizeformat(settings.MAX_UPLOAD_PHOTO_SIZE), filesizeformat(content._size))
                raise forms.ValidationError(msg)

            if not content.name.endswith('.jpg'):
                msg = 'Your file is not jpg'
                raise forms.ValidationError(msg)
        else:
            raise forms.ValidationError('File not supported')
        return content

rawDescription: django limiting file size and file format in view

description: Django limiting file size and file format in view


code:
def splitpoint(a):
    c = numpy.cumsum(a)
    return numpy.searchsorted(c, c[-1]/2)
    # Fails on [1, 1, 1]

def splitpoint(a):
    c = numpy.cumsum(a)
    return numpy.searchsorted(c, c[-1]/2.0)
    # Fails on [2**60, 1, 1, 1, 2**60]

def splitpoint(a):
    c = numpy.cumsum(a)
    if c.dtype.kind == 'f':
        # Floating-point input.
        return numpy.searchsorted(c, c[-1]/2.0)
    elif c.dtype.kind in ('i', 'u'):
        # Integer input.
        return numpy.searchsorted(c, (c[-1]+1)//2)
    else:
        # Probably an object dtype. No great options.
        return numpy.searchsorted(c, c[-1]/2.0)
    # Fails on numpy.array([63, 1, 63], dtype=int8)

def splitpoint(a):
    c = numpy.cumsum(a)
    if c.dtype.kind == 'f':
        # Floating-point input.
        return numpy.searchsorted(c, c[-1]/2.0)
    elif c.dtype.kind in ('i', 'u'):
        # Integer input.
        return numpy.searchsorted(c, c[-1]//2 + c[-1]%2)
    else:
        # Probably an object dtype. No great options.
        return numpy.searchsorted(c, c[-1]/2.0)
    # Still fails the floating-point rounding and zeros tests.

rawDescription: Find the equilibrium point in a numpy array


code:
ca = ClusterAssignment()
print(ca.__str__)
print(ca.__repr__)

rawDescription: Specifics of converting a custom __repr__, __str__ on a custom python class


code:
data={'ID':[1,2,3],'String': ['xKx;yKy;zzz','-','z01;x04']}
frame=pd.DataFrame(data)
print(frame)

data_trans={'ID':[1,1,1,2,3,3],'String': ['xKx','yKy','zzz','-','z01','x04']}
frame_trans=pd.DataFrame(data_trans)
print(frame_trans)

frame2 = frame.set_index('ID')
# This next line does almost all the work.This can be very memory intensive.
frame3 = frame2['String'].str.split(';').apply(pd.Series, 1).stack().reset_index()[['ID', 0]]
frame3.columns = ['ID', 'String']
print(frame3)

# Verbose version
# Setting the index makes it easy to have the index column be repeated for each value later
frame2 = frame.set_index('ID')
print("frame2")
print(frame2)
#Make one column for each of the values in the multi-value columns
frame3a = frame2['String'].str.split(';').apply(pd.Series, 1)
print("frame3a")
print(frame3a)
# Convert from a wide-data format to a long-data format
frame3b = frame3a.stack()
print("frame3b")
print(frame3b)
# Get only the columns we care about
frame3c = frame3b.reset_index()[['ID', 0]]
print("frame3c")
print(frame3c)
# The columns we have have the wrong titles. Let's fix that
frame3d = frame3c.copy()
frame3d.columns = ['ID', 'String']
print("frame3d")
print(frame3d)

rawDescription: Python - Dataframe - Splitting and stacking string column


code:
cols = ['b']
df[cols] = df[df[cols] > 0][cols]
df.dropna()

rawDescription: Filter rows of pandas dataframe whose values are lower than 0


code:
def lines(fname, numbers):
    numbers = sorted(numbers, reverse=True)
    with open(fname) as f:
        for n, line in enumerate(f, 1):
            if n == numbers[-1]:
                yield line
                numbers.pop()
                if not numbers:
                     break

rawDescription: Cutting some specific lines from a text and putting them into another file


code:
import pandas as pd
output.seek(0)
pd.read_csv(output)

rawDescription: Python: Split file by line match

description: Python: Split file by line match


rawDescription: Creating sublist from a give list of items


code:
def get_user_attributes(cls):
    boring = dir(type('dummy', (object,), {}))
    if hasattr(cls, '__dict__'):
        attrs = cls.__dict__.copy()
    elif hasattr(cls, '__slots__'):
        if hasattr(base, base.__slots__[0]):
            # We're dealing with a non-string sequence or one char string
            for item in base.__slots__:
                attrs[item] = getattr(base, item)
            else:
                # We're dealing with a single identifier as a string
                attrs[base.__slots__] = getattr(base, base.__slots__)
    for key in boring:
        del attrs['key']  # we can be sure it will be present so no need to guard this
    return attrs

rawDescription: Inspect python class attributes

description: Inspect python class attributes


code:
mercury.speed(0)
venus.speed(0)
earth.speed(0)
mars.speed(0)
for i in range(360):
    mercury.circle(58, 7.5)
    venus.circle(108, 3)
    earth.circle(150, 2)
    mars.circle(228, 1)

rawDescription: How to make items draw at the same time in python using turtle?

description: Make items draw at the same time in python using turtle


code: import model.client

rawDescription: python MySQL module class file name

description: Python MySQL module class file name


rawDescription: Python 3, Converting a string storing binary data to Int


code:
a, *rest = my_list
a
rest

rawDescription: How to use sequence unpacking with a sequence of variable length?

description: Use sequence unpacking with a sequence of variable length


code:
img = image(title="foo!", image="/path/to/image.jpg")
dup_of_img = image(title="foo!dup", image="/path/to/dup/image.jpg")
img.save()
dup_of_img.save()

dupes_of_foo = DupeSeries(description="foo! lookalikes")
dupes_of_foo.members.add(img, dup_of_img)

# Notice how *img.dupes.all()* returns both image instances.
assert(list(img.dupes.all()) == [img, dup_of_img])

rawDescription: Recursive Relationship with a Description in Django Models


code:
dicts = [_myfunction(element) for element in list_of_elements]
y = reduce(merge_dicts, dicts, {})

rawDescription: Python List to Dictionary conversion via Comprehension


code:
def matrix(rows, cols):
    return [[0]*cols for x in xrange(rows)]

rawDescription: Creating lists of lists in a pythonic way


code:
store = pd.HDFStore('test.h5',mode='w')
store.append('df',df)

rawDescription: Pandas get specific rows from HDF5 by index


code:
import subprocess
subprocess.call("kill -ABRT $$", shell=True)
a = subprocess.Popen("kill -ABRT $$", shell=True)
a.wait()
subprocess.call("kill -SEGV $$", shell=True)

rawDescription: Detect process abort

description: Detect process abort


code: [[w.strip() for w in s.split(',')] for s in industries_list]

rawDescription: How to split a python list by comma

description: Split a python list by comma


code:
def openimage():
    picfile = tkFileDialog.askopenfilename()
    if picfile:
        canvas.img = ImageTk.PhotoImage(file=picfile)
        canvas.create_image(0,0, anchor=NW, image=canvas.img)
        canvas.configure(canvas, scrollregion=(0,0,canvas.img.width(),canvas.img.height()))

rawDescription: Simple Image viewer

description: Simple Image viewer


code:
from random import sample
from string import digits, ascii_letters

chars = digits + ascii_letters
#'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

gen_str = sample(chars, 10)

rawDescription: Generating random strings with few characters


code: mylist = [100 if i in (0, 1, 3) else e for i, e in enumerate(mylist)]

rawDescription: Replacing selected elements in a list in Python


code:
class Answers(object): # CamelCase name for class - see PEP8 document

    def __init__(self):
        self.x = 'hello world'

    def knight(self):
        print('Neee!')

    def bunny(self):
        print('Rawwww!')

    def pesant(self):
        print('Witch!')

    def dingo(self):
        print('Bad, wicked, naughty Zoot!')

foo = Answers()

responce = {
    'knight': foo.knight,
    'bunny': foo.bunny,
    'pesant': foo.pesant,
    'dingo': foo.dingo,
}

while True:
    try:
        egg = input('sounds:')
        responce[egg]() # call function
    except KeyError:
        print("I don't know")

rawDescription: Long elif chains vs dictionary with exec()


code:
for i in deposits:
    mydict[i[:2]] = 0

rawDescription: adding two items in a list to make into one item

description: Adding two items in a list to make into one item


code:
#!/usr/bin/env python
from pylab import *

x = linspace(0.1, 2*pi, 10)
stem(x, cos(x), '-.', bottom=-2)

show()

rawDescription: Stem plot in matplotlib?

description: Stem plot in matplotlib


code:
name = "Slartibartfast"
person = name

rawDescription: Python immutable object from within function


code:
def interadd(U, idx):
    grids = np.zeros((U,U))
    for i in range(len(idx)):
        grids[idx[i,0],idx[i,1]] += 1
    return grids

def interadd2(U, idx):
    grids = np.zeros((U,U))
    np.add.at(grids, idx.T.tolist(), 1)
    return grids

def interadd3(U, idx):
    # YXD suggestion
    grids = np.zeros((U,U))
    np.add.at(grids, (idx[:,0], idx[:,1]), 1)
    return grids

rawDescription: Vectorize iterative addition in NumPy arrays


code:
start = 'blahblah_{:04}{:02}'.format(from_year, from_month)
end = 'blahblah_{:04}{:02}'.format(to_year, to_month)

for f in os.listdir('/path/dir'):
    if start <= f <= end:
        print(f)

rawDescription: regex to match file names blahblah_200901.csv (yyyymm)

description: Regex to match file names blahblah_200901.csv (yyyymm)


code:
@asyncio.coroutine
def get_stuff(url):
    if url in cache:
        return cache[url]
    stuff = yield from aiohttp.request('GET', url)
    cache[url] = stuff
    return stuff

rawDescription: what's Python asyncio.Lock() for?

description: What's Python asyncio.Lock() for


rawDescription: Resizing part of a list in python

description: Resizing part of a list in python


rawDescription: positional index using python

description: Positional index using python


code:
for row in file:
    do_something_with_row

rawDescription: Python 3 Extracting Candidate Words from a Debate File


code: ts[ts==-1] = np.nan

rawDescription: Python pandas time series interpolation and regularization


code: addr = [ x for x in line.split(" ") if x ][2]

rawDescription: How do you search each line in a file for all contents of a list?

description: Search each line in a file for all contents of a list


code:
s = session.query(func.max(B.attr)).group_by(B.fk)
q = session.query(A, B).outerjoin(B).filter(B.attr.in_(s))

rawDescription: SQLAlchemy join two models and select top row


code:
# producing a list
for category, name in listOfModels:
    perms.setdefault(category, []).append(name)

# or a set
for category, name in listOfModels:
    perms.setdefault(category, set()).append(name)

# same with defaultdict
perms = defaultdict(list)
for category, name in listOfModels:
    perms[category].append(name)

perms = defaultdict(set)
for category, name in listOfModels:
    perms[category].add(name)

rawDescription: Python syntax. Beautiful, right, short code


code: output = list(input_set)

rawDescription: how to convert a set in python into a dictionary

description: Convert a set in python into a dictionary


code:
V=W=np.arange(3*n).reshape(3,n)
Q=np.arange(3*3*n).reshape(3,3,n)
np.einsum('ijk,jk->ik',Q,V)
np.einsum('ik,ijk,jk',W,Q,V)
np.einsum('ik,ijk,jk->k',W,Q,V)

rawDescription: How to generalize elementwise matrix operations in numpy

description: Generalize elementwise matrix operations in numpy


code:
def method(self, name='Thomas', age=27):
  self.submethod(name, age)

rawDescription: python - get attribute to subclass

description: Python - get attribute to subclass


rawDescription: Python: Optimising a list comprehension which compares two integers


code:
import csv
data = '''\
Washington\t5\tWaterpark,Themepark,Playground,Spaceneedle,Carousel
California\t6\tWaterpark,Themepark,Disneyland,Legoland,Carousel,Sixflag
Arizona\t3\tWaterpark,Playground,Themepark
'''.splitlines(True)
reader = csv.reader(data, delimiter='\t')
data = [(row[0], set(row[2].split(','))) for row in reader]
import sys
writer = csv.writer(sys.stdout, delimiter='\t')
for (state1, features1), (state2, features2) in combinations(data, 2):
    overlap = len(features1 & features2)
    writer.writerow([
        len(features1), state1,
        len(features2), state2,
        overlap])

rawDescription: Creating iterators with counting intersection


code:
y = [str(i) for i in x]
y

rawDescription: How To Change Lists of Unicode to ASCII

description: How To Change Lists of Unicode to ASCII


code:
boys, girls = {}, {}
girls[row[0]] = int(row[1])
boys[row[2]] = int(row[3])
boys
girls

rawDescription: Python csv processing

description: Python csv processing


code:
x[0] is y[0], x[1] is y[1]
y[0].append('foo')     #modify an inner list
x,y                    #changes can be seen in both lists

rawDescription: Python list([]) and []

description: Python list([]) and []


code:
m=loadtxt(fname, dtype='S20', delimiter=',', skiprows=1)
m.astype(str)

rawDescription: Numpy loadtxt Behavior change with Python 3


code:
import random
...
value = random.choice(mylist)
mylist.remove(value)

rawDescription: Python: How to make a list of n numbers and randomly select any number?


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

fig, ([ax1, ax2], [ax3, ax4]) = plt.subplots(nrows=2, ncols=2)

for ax in [ax1, ax2, ax3, ax4]:
    ax.plot(np.random.randn(10), lw=2)

customaxis(ax1) #default: no right and top axis
customaxis(ax2, c_left='none', c_bottom='none', c_right='k', c_top='k')
customaxis(ax3, c_left='none', c_bottom='k', c_right='k', c_top='none')
customaxis(ax4, c_left='k', c_bottom='none', c_right='none', c_top='k')

plt.show()

rawDescription: Turn off the the upper/right axis tick marks


code: req = Unirest.post(path).fields(params).field("data", f);

rawDescription: Translate Python requests code to Java (UniRest)


build_type: Something

build_type: SomethingElse

rawDescription: In the context of a buildbot master.cfg file, how do I instantiate a class based on a string using native modules


rawDescription: BeautifulSoup extracting data from multiple tables


code: plot(df_x, df_y)  # matplotlib.pyplot.plot

rawDescription: Plotting and GroupBy methods

description: Plotting and GroupBy methods


code:
from flask.ext.admin.contrib.sqla import ModelView
from models import db, User, Role

admin = Admin(app, name="Boost Admin")

admin.add_view(ModelView(User,db.session,category="model", endpoint="model_view_user"))
admin.add_view(ModelView(Role,db.session,category="model", endpoint="model_view_role"))

rawDescription: How to reference a ModelView in flask-admin

description: Reference a ModelView in flask-admin


code:
while check_if_still_true():
    do_work()
    if shall_we_break():
        break
else:
    we_exited_because_check_returned_false()

rawDescription: python break for nested loops without executing sub-sequential code

description: Python break for nested loops without executing sub-sequential code


code:
print(repr(np.ma.masked_array(x, np.isnan(x))))
# masked_array(data = [-- 3.14 --],
#              mask = [ True False  True],
#        fill_value = 1e+20)

rawDescription: Python Numpy mask NaN not working

description: Python Numpy mask NaN not working


code:
mymatrix=[[1,2,9],[4,9,6],[7,8,9]]
val = 9
[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]

rawDescription: Find indices of a value in 2d matrix

description: Find indices of a value in 2d matrix


code:
from operator import mul
reduce(mul, factors(360))

rawDescription: Factorizing a number in python

description: Factorizing a number in python


rawDescription: Creating tuples of 3s

description: Creating tuples of 3s


code: G = NP.zeros((m, n, r), dtype='uint')

rawDescription: Efficiently re-shaping a numpy ndarray from 2-D to 3-D based on elements from 2-D


rawDescription: Center a matrix

description: Center a matrix


code: some_list.__setitem__(slice(2, 4), [2, 3])

rawDescription: Assign to a slice of a Python list from a lambda


code:
from re import match
match(2 * '(.*?), ', 'some string, another string, ').groups()

rawDescription: python regex: capture parts of multiple strings that contain spaces

description: Python regex: capture parts of multiple strings that contain spaces


code:
x = 5
my_list = [1, 2, 3, 5, 6, 9, 4]

del my_list[my_list.index(x)]

rawDescription: How to delete a value in a list without using .remove?

description: Delete a value in a list without using .remove


rawDescription: Creating dictionaries from a text file

description: Creating dictionaries from a text file


code:
class Class2(object):
   def method(self):
      print ("I am method at %s" % self.__class__)

class Class1(object):
   pass

class Class0(Class1):
   method = Class2.__dict__["method"]

ob = Class0()
ob.method()

rawDescription: Is it possible to do partial inheritance with Python?


code:
from __future__ import print_function
import sys
import timeit

setup = """
import array
import random
import hashlib
import marshal
import cPickle as pickle
import struct

r = [random.randrange(1, 1000) for _ in range(0, 1000000)]
ra = array.array('h', r)   # create an array of shorts equivalent

def method1(r):
    p = pickle.dumps(r, -1)
    return hashlib.md5(p).hexdigest()

def method2(r):
    p = str(r)
    return hashlib.md5(p).hexdigest()

def method3(r):
    p = ','.join(map(str, r))
    return hashlib.md5(p).hexdigest()

def method4(r):
    fmt = '%dh' % len(r)
    buf = struct.pack(fmt, *r)
    return hashlib.md5(buf).hexdigest()

def method5(r):
    a = array.array('h', r)
    return hashlib.md5(a).hexdigest()

def method6(r):
    m = marshal.dumps(r)
    return hashlib.md5(m).hexdigest()

# using pre-built array...
def pb_method1(ra):
    p = pickle.dumps(ra, -1)
    return hashlib.md5(p).hexdigest()

def pb_method2(ra):
    p = str(ra)
    return hashlib.md5(p).hexdigest()

def pb_method3(ra):
    p = ','.join(map(str, ra))
    return hashlib.md5(p).hexdigest()

def pb_method4(ra):
    fmt = '%dh' % len(ra)
    buf = struct.pack(fmt, *ra)
    return hashlib.md5(buf).hexdigest()

def pb_method5(ra):
    return hashlib.md5(ra).hexdigest()

def pb_method6(ra):
    m = marshal.dumps(ra)
    return hashlib.md5(m).hexdigest()
"""

statements = {
    "pickle.dumps(r, -1)": """
        method1(r)
    """,
    "str(r)": """
        method2(r)
    """,
    "','.join(map(str, r))": """
        method3(r)
    """,
    "struct.pack(fmt, *r)": """
        method4(r)
    """,
    "array.array('h', r)": """
        method5(r)
    """,
    "marshal.dumps(r)": """
        method6(r)
    """,
# versions using pre-built array...
    "pickle.dumps(ra, -1)": """
        pb_method1(ra)
    """,
    "str(ra)": """
        pb_method2(ra)
    """,
    "','.join(map(str, ra))": """
        pb_method3(ra)
    """,
    "struct.pack(fmt, *ra)": """
        pb_method4(ra)
    """,
    "ra (pre-built)": """
        pb_method5(ra)
    """,
    "marshal.dumps(ra)": """
        pb_method6(ra)
    """,
}

N = 10
R = 3

timings = [(
    idea,
    min(timeit.repeat(statements[idea], setup=setup, repeat=R, number=N)),
    ) for idea in statements]

longest = max(len(t[0]) for t in timings)  # length of longest name

print('fastest to slowest timings (Python {}.{}.{})\n'.format(*sys.version_info[:3]),
      '  ({:,d} calls, best of {:d})\n'.format(N, R))

ranked = sorted(timings, key=lambda t: t[1])  # sort by speed (fastest first)
for timing in ranked:
    print("{:>{width}} : {:.6f} secs, rel speed {rel:>8.6f}x".format(
          timing[0], timing[1], rel=timing[1]/ranked[0][1], width=longest))

rawDescription: fastest way to get a hash from a list in python

description: Fastest way to get a hash from a list in python


code:
mypprint = MyPrettyPrinter()
mypprint.pprint(x)

rawDescription: Using pprint and skipping the types name


code:
def get_first(iterable, default=None):
    if iterable:
        for item in iterable:
            return item
    return default

rawDescription: Python idiom to return first item or None


rawDescription: Writing Greek in matplotlib labels, titles


code: counts = Counter(fname[:2] for fname in os.listdir(path) if fname.endswith('.pdf'))

rawDescription: Count Files based on the first two letters


code:
if file not in word_count_dict[word]:
    word_count_dict[word][file] = 0
word_count_dict[word][file] += 1
word_count_dict[word]["total"] += 1

rawDescription: how to iterate over all keys in dictionary python?

description: Iterate over all keys in dictionary python


code:
import requests
url_0 = "http://webapp.pucrs.br/consulta/principal.jsp"
url = "https://webapp.pucrs.br/consulta/servlet/consulta.aluno.ValidaAluno"
data = {"pr1": "123456789", "pr2": "1234"}

s = requests.session()
s.get(url_0)
r = s.post(url, data)

rawDescription: HTTP POST and GET with cookies for authentication in python


code:
from collections import Counter

def solve(lst):
    counters = map(Counter, lst)
    return [ [uniq]*c[uniq] for seq, c in zip(lst, counters)
                                                for uniq in unique_everseen(seq)]

rawDescription: How to divide a list in python?

description: Divide a list in python


rawDescription: Python3 multiple assignment and memory address


code:
import mod
import b

print(mod.bar)
print(mod.opt)

rawDescription: how do imports work for a module used as a singleton?

description: How do imports work for a module used as a singleton


code:
import datetime,random,Grouper
groups_of_dates = Grouper.groupby(list_of_dates,relation= Grouper.time_delta(hours = 3),as_iterable=False)
#Get a list of lists, grouping
#consecutive events that are less than 3 hours apart.

rawDescription: How to find two close events (that have a datetime component) in python

description: Find two close events (that have a datetime component) in python


code:
def equipment():
    reported = db().select(db.repo.ALL)
    max_severity = max([severities.index(r.severity) for r in reported])
    severity_color = severities[max_severity].lower()
    return dict(reported=reported, severity_color=severity_color)

rawDescription: web2py - for loop and function to change background color?

description: Web2py - for loop and function to change background color


code:
import os
subprocess.check_output('iwconfig', stderr=open(os.devnull, 'w'))

rawDescription: Hiding shell output from subprocess.check_output()


code:
from sklearn.feature_extraction.text import CountVectorizer as CV
count_vect=CV(token_pattern=r'(?u)\b\w+\b')
docs_new = ['Modern Warfare 2', 'Modern Warfare 3', 'Modern Warfare 1', 'Modern Warfare 4', 'Modern Warfare A', 'Modern Warfare 44', 'Modern Warfare AA', 'Modern Warfare', 'Mahjong Kakutou Club', 'Mass Effect 2']
new_counts = count_vect.fit_transform(docs_new)
count_vect.inverse_transform(new_counts)

rawDescription: Scikit-learn Naive Bayes inexplicable results with sparse string classification


code:
client.send('
Hello World')

rawDescription: Sending http headers with python

description: Sending http headers with python


code: df

rawDescription: How to calculate difference on previous within set of grouped rows in a dataframe

description: Calculate difference on previous within set of grouped rows in a dataframe


code:
a = ['do', 're', 'mi', 'fa']
for i, s in enumerate(a):
    print('%s at index %d' % (s, i))

rawDescription: Python's enumerate in Ruby?

description: Python's enumerate in Ruby


code:
from re import split
mystr = "word,word,,word,word"
split(",+", mystr)

rawDescription: Splitting with multiple delimiters

description: Splitting with multiple delimiters


code: map(max_item, open("inputfile.txt"))

rawDescription: Getting the maximum value from dictionary


rawDescription: Avoiding expensive calculations in Python IRC bot


code:
def multiplyBy3(lst):
    newList = []
    for item in lst: #iterate over the elements of the list
        newList.append(item * 3)
    return newList

rawDescription: Returning a list in a function

description: Returning a list in a function


code:
def mygrouper(n, iterable):
    args = [iter(iterable)] * n
    return ([e for e in t if e != None] for t in itertools.zip_longest(*args))

list(mygrouper(3, range(9)))
list(mygrouper(3, range(10)))

rawDescription: Alternative way to split a list into groups of n


code:
from dateutil import parser
parser.parse('Tue Feb 19 00:09:28 +1100 2013')

rawDescription: Calculating days using string dates in Python


code:
# if there is a problem in your parse actions, you will need to post them
month = Word(nums)#.setParseAction(self.validate_month)
year = Word(nums)#.setParseAction(self.validate_year)

# wrap date in a Group
#date = Optional(month + Suppress("/")) + year
date = Group(Optional(month + Suppress("/")) + year)
date_range = Group(date + Optional(Suppress("-") + date))

dates = date_range + ZeroOrMore(Suppress(",") + date_range)
# your expression for dates can be replaced with this pyparsing helper
#   dates = delimitedList(date_range)

# The trailing ',' causes an exception because of your use of StringEnd()
command = StringStart() + dates + StringEnd()

test = "11/2012-2014,2016,10/2012,11/2012-10/2014,2012-11/2012"

# you can also use parseAll=True in place of tacking StringEnd
# onto the end of your parser
command.parseString(test, parseAll=True).pprint()

rawDescription: pyparsing - parsring a dates

description: Pyparsing - parsring a dates


code: np.where(arr>3, arr, 0)

rawDescription: Numpy array loss of dimension when masking


code: myobject = ET.fromstring(content)

rawDescription: saving an 'lxml.etree._ElementTree' object

description: Saving an 'lxml.etree._ElementTree' object


code:
import statsmodels.api as sm

data = sm.datasets.longley.load_pandas()

data.exog['constant'] = 1

results = sm.OLS(data.endog, data.exog).fit()
results.save("longley_results.pickle")

# we should probably add a generic load to the main namespace
from statsmodels.regression.linear_model import OLSResults
new_results = OLSResults.load("longley_results.pickle")

# or more generally
from statsmodels.iolib.smpickle import load_pickle
new_results = load_pickle("longley_results.pickle")

rawDescription: Python statsmodels OLS: how to save learned model to file


code: X - X_mean[:,None,:]

rawDescription: Simple subtraction causes a broadcasting issue for different array shapes


code:
import tkinter as tk

root = tk.Tk()

status = tk.Label(root, text="Working")
status.grid()

def update_status():

    # Get the current message
    current_status = status["text"]

    # If the message is "Working...", start over with "Working"
    if current_status.endswith("..."): current_status = "Working"

    # If not, then just add a "." on the end
    else: current_status += "."

    # Update the message
    status["text"] = current_status

    # After 1 second, update the status
    root.after(1000, update_status)

# Launch the status message after 1 millisecond (when the window is loaded)
root.after(1, update_status)

root.mainloop()

rawDescription: Python: Is it possible to create an tkinter label which has a dynamic string when a function is running in background?


code: grade = raw_input("what is ur grade")

rawDescription: My code is not executing properly in Python


code:
df['len'] = df.groupby('A')['B'].transform(lambda x: len(x))
df

rawDescription: Get length of subset pandas DataFrame

description: Get length of subset pandas DataFrame


code:
import datetime as dt
import pytz

tz=pytz.timezone('Europe/London')
t1 = dt.datetime(2012,10,28,0,30,0)
t1=tz.localize(t1)
t2 = dt.timedelta(hours=3)
sumVal = t1 + t2

rawDescription: Python DST & Time Zone Detection After Addition


code: minVal = min(dict, key=dict.get) # note no parentheses

rawDescription: Minimum sum from a dictionary of lists in Python


code: logger = logging.getLogger(__name__)

rawDescription: I can not use the import command

description: I can not use the import command


code:
import dis
def foo():
    if x==0:
        x=1
    else:
        x=0

dis.dis(foo)

rawDescription: if statement vs. expression

description: If statement vs. expression


code:
for row in data:
    # do something
    for seq, percent in row:
        if not '' in {seq, percent}:
            print(seq, percent)

rawDescription: grabbing info from a table with loops (python)

description: Grabbing info from a table with loops (python)


code:
pt = ProdType('Commodities', 'Equity', 'Fixed Income')
pt.Cmdty
pt.Eqty

rawDescription: accessing custom python type properties by name

description: Accessing custom python type properties by name


code:
def count(bin_tree):
    if bin_tree.isLeaf:
        return 1
    else:
        return count(left(bin_tree))+count(right(bin_tree))

rawDescription: Haskell equivalent of data constructors in Python?


code:
operator.getslice(a, b, c)
operator.__getslice__(a, b, c)

rawDescription: Check for [] operator

description: Check for [] operator


code:
import re
text = """ this is an example Item 2 text text <B>Item 2. example"""
a = re.search ('(?<=<B>)Item 2\.',text)
start, end = a.span()
text[:start]

rawDescription: how to print the text before the first index number?

description: Print the text before the first index number


rawDescription: Pandas add one day to column

description: Pandas add one day to column


code:
fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(8)

rawDescription: Matplotlib PDF plots don't respond to figsize


code: a[2:].clip(0, None)

rawDescription: numpy array - replace certain values

description: Numpy array - replace certain values


code:
s = pd.Series([1, 2])
s.std()
from math import sqrt

rawDescription: Pandas Dataframe.describe() : Which kind of standard deviation?


rawDescription: Shift all indices in NumPy array

description: Shift all indices in NumPy array


code:
string_obj = 'thefourtheye'
string_obj.upper()
string_obj

rawDescription: How to return a value from a method back to the input value

description: Return a value from a method back to the input value


rawDescription: Grouping and summarizing data into a new pandas dataframe


code:
uploaded_file = FakeFieldStorage("test.txt", "foo")
request.POST['file'] = uploaded_file

rawDescription: Simulating a Google App Engine File Upload in Python


code:
for elt in ('series', 'duration', 'room'):
        print('%s: %s' % (getattr(soup, elt).name, getattr(soup, elt).string))

rawDescription: Strip the html comment tags within an xml file using beautifulsoup


code:
import myHelper
reload(myHelper)

rawDescription: How can I access an external python module from a script in booggie 2?

description: Access an external python module from a script in booggie 2


rawDescription: TypeError: unsupported operand type(s) for -: 'list' and 'list'


rawDescription: Combine two lists of tuples by key

description: Combine two lists of tuples by key


code:
inputFor= {}
for coin in ['5c','10c','20c','50c','$1','$2']:
    inputFor[coin]= int(input("Enter the number of " + coin + " coins you wish use: "))

rawDescription: Assigning variables from inputs in FOR loop in python


code:
backup = df.copy()     # make a backup copy to mutate in place
cols = df.columns[:2]  # cas, diff
df[cols] = df['weight'].values[:, None] * df[cols]
df.groupby('ind')[cols].sum()

rawDescription: Calculate weighted average with pandas dataframe


rawDescription: Converting PANDAS dataframe from monthly to daily


code: bool("Sure")

rawDescription: How can I make the if statement contain more than one item?

description: Make the if statement contain more than one item


code:
from itertools import count

with open('index.txt', 'r') as inf:
    text = inf.read()

text = re.sub(r'\*', lambda m, c=count(): str(next(c)), text)

with open('index.txt', 'w') as outf:
    outf.write(text)

rawDescription: Replace "*" (asterics) in HTML file with increasing number with python


code:
a = A()
for msg in ["hey", "there"]:
    a.p(msg)

rawDescription: Python logging module is printing lines multiple times


code:
from PyQt4 import QtCore,QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(690, 786)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) #here
        self.centralwidget.setLayout(self.gridLayout_2) #here

        #...some other irrelevant code...

        self.plotButton = QtGui.QPushButton() #here
        self.plotButton.setMinimumSize(QtCore.QSize(0, 23))
        self.plotButton.setObjectName(_fromUtf8("plotButton"))
        self.gridLayout_2.addWidget(self.plotButton, 9, 1, 1, 1)
        self.plotButton.clicked.connect(self.showimage)

    def showimage(self):
        #changes here
        from matplotlibtest import ApplicationWindow
        self.aw = ApplicationWindow()
        self.aw.show()

#class that actually shows something
class MyMainWindow(QtGui.QMainWindow):

    def __init__(self,parent=None):
        super(MyMainWindow,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

#put the main window here
def main():
    import sys
    qApp = QtGui.QApplication(sys.argv)
    aw = MyMainWindow()
    aw.show()
    sys.exit(qApp.exec_())

if __name__ == '__main__':
    main()

rawDescription: Get PyQt4 to open another Qt window when a button is pressed


code:
def short2(gen,X):
    for x in gen:
        if x > X:
            return x

rawDescription: Elegant way to calculate first generator result larger than X


code: from package2 import module2

rawDescription: python unittest import classes sub directories

description: Python unittest import classes sub directories


code: helper_dict = {k: v for v, x in myDict.items() for k in x}

rawDescription: searching a value in a list and outputting its key

description: Searching a value in a list and outputting its key


code:
from sys import argv

from twisted.internet.protocol import Protocol
from twisted.internet.endpoints import connectProtocol, clientFromString
from twisted.internet.task import react

def main(reactor, description):
    endpoint = clientFromString(reactor, description)
    connecting = connectProtocol(endpoint, Protocol())
    def connected(protocol):
        # Now `protocol` is connected somewhere and you can start
        # calling useful methods on it, if it has any.
        ...
    connecting.addCallback(connected)
    return connecting

react(main, argv[1:])

rawDescription: Python Twisted: separate protocol from processing


rawDescription: python string processing, strip out date-time patterns

description: Python string processing, strip out date-time patterns


code:
df = pd.DataFrame([[1.1, 1.7, 2.5, 2.6, 2.7, 3.4], list('AAABBB')]).T
df.columns = ['time', 'ip']
df
g = df.groupby('ip')
df['session_number'] = g['time'].apply(lambda s: (s - s.shift(1) > 0.5).fillna(0).cumsum(skipna=False))
df

rawDescription: Session generation from log file analysis with pandas


code:
import bz2
bz2.compress(b'\x00' * 100 + b'\x01' * 200).encode('base64').replace('\n', '')

rawDescription: Embedding binary data in a script efficiently


code:
from collections import Counter

l1 = [2, 2, 2, 5, 5, 7]

l1 = Counter(l1).items()

rawDescription: how to group elements in a list based on frequency into a tuple

description: Group elements in a list based on frequency into a tuple


rawDescription: Python List of Strings created from a list of one string


code:
from social.apps.django_app.utils import load_strategy

strategy = load_strategy(backend='MyOAuth')
social = request.user.social_auth.get(provider='MyOAuth')
backend = backend(strategy=strategy)
backend = social.get_backend(strategy)
backend.oauth_request(...)

rawDescription: How to get backend instance from python-social-auth

description: Get backend instance from python-social-auth


code:
class Callable(object):
    def __init__(self, func, *args, **kwds):
        self.func = func
        self.args = args
        self.kwds = kwds

    def __call__(self):
         return self.func(*self.args, **self.kwargs)

    def __str__(self):
        return self.func.__name

def some_callback(a, b, c=None):
    print(a,b,c)

Button(text="Do not press",
    command=Callable(some_callback, 1, 2, 3))

rawDescription: Function to make functions callable doesn't work properly


code:
BLEACH_ALLOWED_TAGS = ['h1', 'h2', 'p', 'b', 'i', 'strong', 'a']
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'style']
BLEACH_ALLOWED_STYLES = ['font-family', 'font-weight']
BLEACH_STRIP_TAGS = True

rawDescription: Django - Rendering Markdown Sanitizied with Bleach


code: pattern = r'pt\d\d(?!_\d\d)'

rawDescription: How to match all words that does not contain two digits in a row?

description: Match all words that does not contain two digits in a row


rawDescription: Evaluation order of positional and keyword arguments


code:
def words(fileobj):
    for line in fileobj:
        for word in line.split():
            yield word

rawDescription: Read the next word in a file in python

description: Read the next word in a file in python


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

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()
labels = []
for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key)
    labels.append(key)
lines, _ = ax.get_legend_handles_labels()
ax.legend(lines, labels, loc='best')
plt.show()

rawDescription: Plotting multiple lines with pandas dataframe


rawDescription: applying functions to groups in pandas dataframe

description: Applying functions to groups in pandas dataframe


code: {{text|safe}}

rawDescription: Insert hyperlink into text using django

description: Insert hyperlink into text using django


code:
with open("file.txt") as input:
    data=input.read()

rawDescription: How to release memory after replacing big data in python?

description: Release memory after replacing big data in python


code:
coords = np.zeros((5, 5, 30, 2, 4))
coords[..., 0] = np.array(mapLatitude).reshape(5, 1, 1, 1)
coords[..., 1] = np.array(mapLongitude).reshape(1, 5, 1, 1)
coords[..., 2] = np.array(mapAltitude).reshape(1, 1, 30, 1)
coords[..., 3] = np.array(mapTime).reshape(1, 1, 1, 2)

rawDescription: Python: speed up matrix coordinate mapping through iteration


code:
from string import Formatter

names = [fn for _, fn, _, _ in Formatter().parse(yourstring) if fn is not None]

rawDescription: How to get the variable names from the string for the format() method

description: Get the variable names from the string for the format() method


code: a < b

rawDescription: Python History and Design: Why issubclass() instead of rich comparisons?


code:
def using_loops(color, color2ind):
    M, N = color.shape[:2]
    out = np.zeros((M, N))
    for i in range(M):
        for j in range(N):
            out[i][j] = color2ind[tuple(color[i,j,:])]
    return out

rawDescription: Convert a 3D array to 2D array based on dictionary


rawDescription: python positive and negative number list possiblities

description: Python positive and negative number list possiblities


code:
from operator import itemgetter
part0, part2 = itemgetter(0, 2)(str.partition(' '))

rawDescription: How to pick certain elements of x-tuple returned by a function?

description: Pick certain elements of x-tuple returned by a function


code:
b_dict = dict(a_dict)
b_dict["foo"] = "cat"

rawDescription: Shallow copy dict while overriding a key value pair using python


code:
import re
re.match(r'(?P<currency>\D+)(?P<amount>\d+(\.\d+)?)(?P<multiplier>[mMkK])', '$15k').groupdict()

rawDescription: Extract the number and following letter from regex


code:
t1.__name__
t1.__parameters__
issubclass(t1, typing.List)

rawDescription: How to determine type from type aliasing?

description: Determine type from type aliasing


code:
for ans_i in item1['Title']:
    do_something_with( ans_i.strip() )

rawDescription: Extra characters Extracted with XPath and Python (html)


code:
legs = int(raw_input("How many legs do you have? "))
arms = int(raw_input("And how many arms do you have? "))

rawDescription: How to add raw input values in Python?

description: Add raw input values in Python


code:
from sklearn.feature_extraction.text import CountVectorizer
documents = ["The dog ran", "The boy ran"]
vectorizer = CountVectorizer(min_df=0)
vectorizer = CountVectorizer(min_df=0, stop_words=[])
X = CountVectorizer.fit_transform(documents)
X = vectorizer.fit_transform(documents)
X.toarray()

rawDescription: Counting with scipy.sparse

description: Counting with scipy.sparse


code:
for k,v in sorted(d.items()):
    print('{}: {}'.format(k,'+'.join(v)))

prop1: thing+something
prop2: stuff+whatever
prop3: junk

rawDescription: Merge excecution logs into a report

description: Merge excecution logs into a report


code: [{k: v for k, v in d.iteritems() if k != 'mykey1'} for d in mylist]

rawDescription: Removing key values pairs from a list of dictionaries


rawDescription: Python convert a paritcular string to dict


rawDescription: Arbitrary Dictionary (JSON) to Stricter Tree-like Dictionary (JSON) in Python


code:
print('First line\nSecond line')
print(['First line\nSecond line'])

rawDescription: Python - nested __repr__ reverts newline to "\\n"


code:
reps = rest.count(rep_line)

new_text = beginning + rest.replace(rep_line,"",reps - 1)
                                               #     ^ don't replace the last one

rawDescription: Python :Replace repetitive line in a file with empty space but not on first / last occurrence


code:
import pymongo

connection = pymongo.MongoClient()
db = connection.test

def mongo_result(coll, **query_string):
    _collection = pymongo.collection.Collection(db, coll)
    if query_string:
        return _collection.find(query_string)
    return _collection.find()

rawDescription: Error in mongo query execution through python when queries and collection name are varying


code:
def access(obj, indexes):
    return reduce(lambda subobj, index: subobj[index] if isinstance(subobj, list) and index < len(subobj) else None, indexes, obj)

rawDescription: Access multidimensional list value by tuple of indices in python


code:
d = DictList(dict(a=1,b=2,c=3),dict(a=2,b=3,e=4))
e = DictList(dict(a=4,c=2,e=3))
d+e
d+dict(x=1,y=2)
dict(x=1,y=2)+d
d+5

rawDescription: How do I build a __add__ method in a specific class in python?

description: Build a __add__ method in a specific class in python


code:
import requests
from bs4 import BeautifulSoup, Tag
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")

table = soup.select_one("table.tblList")
cols = [th.text for th in table.select_one("tr") if isinstance(th, Tag)]
print(cols)

elems = [[td.text for td in row if isinstance(td, Tag)] for row in table.select("tr + tr")]

print(elems)

rawDescription: Table extraction with Selenium and PhantomJS never finishes


code:
df['values'] = df[['value1', 'value2', 'value3']].values.tolist()
df
df.drop(['value1', 'value2', 'value3'], axis=1)

rawDescription: How to convert rows into list using pandas python?

description: Convert rows into list using pandas python


rawDescription: Delete Column in Pandas based on Condition


code:
def merge(a, b):
    while True:
        try:
            idx = b.index(a[-1]) + 1  # leftmost occurrence of a[-1] in b
        except ValueError:  # a[-1] not in b
            return a + b
        if a[-idx:] == b[:idx]:
            return a + b[:idx]

rawDescription: Pythonic way to merge two overlapping lists, preserving order


code:
#ElR is the first matrix and ShR is the second matrix
with open("house.txt", "w") as fE:
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR)
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ShR)

rawDescription: Trying to write and read two matrices in text file


code:
def sweepers():
    running_min = int(input("enter speed"))
    for player in list_of_players:
        if player.running_speed >= running_min:
            print(player.name)

rawDescription: Menu Interface Player Records

description: Menu Interface Player Records


code:
df2["diff"] = df2["enter"] - df2["exit"]
counts = df2["diff"].resample("5min", how="sum").fillna(0).cumsum()
counts.plot()

rawDescription: Pandas TimeSeries With duration of event


code:
def highest_strength(G):
    best_strength, best_link = None, (None, None)
    for x, links in G.items():
        for y, v in links.items():
            if v > best_strength:
                best_strength, best_link = v, (x, y)
    return best_link

rawDescription: A more pythonic way

description: A more pythonic way


rawDescription: Printing all combinations, python

description: Printing all combinations, python


code: print (' hurrah! Hurrah!\n'.join(["The ants go marching %s by %s," % tuple([numbers[i]]*2)]*3) )

rawDescription: Print lyrics by python

description: Print lyrics by python


rawDescription: Numpy - weird behavior with plus equal with slicing


code: row.append(x[1] for x in emails if x[0] == row[1])

rawDescription: How to combine two lists

description: Combine two lists


code:
# myplot.py
from bokeh.plotting import figure, curdoc
from bokeh.driving import linear
import random

p = figure(plot_width=400, plot_height=400)
r1 = p.line([], [], color="firebrick", line_width=2)
r2 = p.line([], [], color="navy", line_width=2)

ds1 = r1.data_source
ds2 = r2.data_source

@linear()
def update(step):
    ds1.data['x'].append(step)
    ds1.data['y'].append(random.randint(0,100))
    ds2.data['x'].append(step)
    ds2.data['y'].append(random.randint(0,100))
    ds1.trigger('data', ds1.data, ds1.data)
    ds2.trigger('data', ds2.data, ds2.data)

curdoc().add_root(p)

# Add a periodic callback to be run every 500 milliseconds
curdoc().add_periodic_callback(update, 500)

rawDescription: Streaming two line graphs using bokeh

description: Streaming two line graphs using bokeh


code:
from itertools import zip_longest

ciphertext = b'ciphertext'
keylength = 3

blocks = [ciphertext[i:i+keylength] for i in range(0, len(ciphertext)+1, keylength)]
# [b'cip', b'her', b'tex', b't']

transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0)]
# [b'chtt', b'iee\x00', b'prx\x00']

rawDescription: Break bytes object into n equally sized blocks based on index


code:
import re

soup.find_all(text=re.compile('http://'))

rawDescription: Searching for strings with BeautifulSoup


code:
print (df['col'] == 1).sum()
5

rawDescription: Pandas, Get count of a single value in a Column of a Dataframe


code: sage: L = loads(open("mylist",'r').read())

rawDescription: Using Python's pickle in Sage results in high memory usage


code:
class AorB: pass

class A(AorB):
    def __init__(self,par):
        self.par=par

class B(AorB):
    def __init__(self):
        pass

def AorB(par):
    return A(par) if par else B()

rawDescription: Python sum of classes

description: Python sum of classes


code:
def min_change(V, C):
    def min_coins(i, aC):
        if aC == 0:
            return 0
        elif i == -1 or aC < 0:
            return float('inf')
        else:
            return min(min_coins(i-1, aC), 1 + min_coins(i, aC-V[i]))
    return min_coins(len(V)-1, C)

rawDescription: Recursive change-making algorithm

description: Recursive change-making algorithm


code:
AddMovementForm(is_staff=True)  # or
AddMovementForm(is_staff=False)

rawDescription: Django - limit the choices of a choice field in a form


code:
dm = dmatrix("carbs + score", dta)
dm.design_info
dm.design_info.column_names

rawDescription: Fetching names from DesignMatrix in patsy


code:
def loop_up(item):
    current = [item]
    while current:
        yield current[0]
        current = cmds.listRelatives(current[0], p=True)

rawDescription: More effective while loop for next object in a chain?


code:
from matplotlib import mpl,pyplot
import numpy as np

# make values from -5 to 5, for this example
zvals = np.random.rand(100,100)*10-5

# make a color map of fixed colors
cmap = mpl.colors.ListedColormap(['blue','black','red'])
bounds=[-6,-2,2,6]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# tell imshow about color map so that only set colors are used
img = pyplot.imshow(zvals,interpolation='nearest',
                    cmap = cmap,norm=norm)

# make a color bar
pyplot.colorbar(img,cmap=cmap,
                norm=norm,boundaries=bounds,ticks=[-5,0,5])

pyplot.show()

rawDescription: 2D grid data visualization in Python

description: 2D grid data visualization in Python


code:
import numpy as np
l=[5,2,1,4,3]
max_len=max(l)
[[elem if elem-1==i else v for i,v in enumerate(arr)] for elem,arr in zip(l,[np.zeros(max_len) for _ in range(max_len)])]

rawDescription: How to place numbers in a python list at the index of their magnitude

description: Place numbers in a python list at the index of their magnitude


code:
a = np.array([1, 2, 3])
a
a[:, np.newaxis]
a[np.newaxis, :]

rawDescription: Python: Differentiating between row and column vectors


code:
class MyContainer(object):
    def __init__(self, my_list):
        self.the_list = my_list

    def __iter__(self):
        for d in self.the_list:
            yield d.values()
            # or:
            # yield (d.get("key1", None), d.get("key2", None))

rawDescription: python iterating list of dicts

description: Python iterating list of dicts


rawDescription: Hash sum of an object in python

description: Hash sum of an object in python


code:
res = []
for item in sorted(tops):
    if len(res) == 0 or item > res[-1] + threshold:
        res.append(item)

rawDescription: How do I remove almost-duplicate integers from list?

description: Remove almost-duplicate integers from list


code:
import module_a as ma
import module_b as mb
...
ma.log(...)

rawDescription: Most pythonic way to treat imported function override conflict


code:
for code, sector in ASXCodes:
    print(code)
    print(sector)
conn.close()

rawDescription: Reference each variable in a 2d array

description: Reference each variable in a 2d array


code: from cherrypy.lib.static import serve_file

rawDescription: Return file from python module

description: Return file from python module


code:
def random_mix_rp(seq_a, seq_b):
    iters = [iter(seq_a), iter(seq_b)]
    lens = [len(seq_a), len(seq_b)]
    while True:
        r = random.randrange(sum(lens))
        itindex = r < lens[0]
        it = iters[itindex]
        lens[itindex] -= 1

        try: yield it.next()
        except StopIteration:
            iters.remove(it)
            it = iters[0]
            for x in it: yield x

rawDescription: Random list with rules

description: Random list with rules


rawDescription: How to stop a loop?

description: Stop a loop


code: (doSomething(i, j) for i in aSet for j in aSet if j != i)

rawDescription: pythonic way to iterate over a set/remnant set

description: Pythonic way to iterate over a set/remnant set


code:
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
s = "AAAAAAAAAACCCCCCCCCCTTTTTTTTTTGGGGGGGGGG"
"".join(complement[c] for c in s[-20:-10])

rawDescription: Matching parts of lines in a file (python)


code:
from subprocess import Popen, PIPE
cmd = "/sbin/route -n | grep 'UG[ \t]' | awk '{print $2}'"
gateway = Popen(cmd, shell=True, stdout=PIPE)
stdout, stderr = gateway.communicate()
exit_code = gateway.wait()

rawDescription: Setting Variable to Gateway IP

description: Setting Variable to Gateway IP


code:
set(p.nation for p in People)
{p.nation for p in People} # python 2.7
len({p.nation for p in People})

rawDescription: How to find number of different nations in list of Persons?

description: Find number of different nations in list of Persons


code:
from collections import Counter

with open("input.txt") as inf:
   c = Counter(l.strip() for l in inf)

rawDescription: Fastest way to count the occurance of a string


code:
def partitions(s, minLength=1):
    if len(s) >= minLength:
        for i in range(minLength, len(s) + 1):
            for p in partitions(s[i:], 1 if i > 1 else 2):
                yield [s[:i]] + p
    elif not s:
        yield []

rawDescription: python all combinations of subsets of a string

description: Python all combinations of subsets of a string


code:
...

import signal
signal.signal(signal.SIGINT, my_signal_handler)

rawDescription: Django Framework - Is there a shutdown event that can be subscribed to?


rawDescription: Apply a pairwise shapely function on two numpy arrays of shapely objects


code: x

rawDescription: how to generate random num with conditions

description: Generate random num with conditions


code:
from multipledispatch import dispatch

@dispatch(tuple, tuple)
def f(h, s):
    try:
        return truediv(s[1], h[1] + s[1])
    except ZeroDivisionError:
        return float('nan')

@dispatch(str, int)
def f(x, y):
    return 0.0

rdd.mapValues(lambda args: f(*args)).collect()
## [('a', 0.0), ('b', 0.023809523809523808)]

rawDescription: Pyspark: operation on values based on type


rawDescription: Using map function with a multi-variable function


code:
xx, yy = numpy.indices(m.shape)
points = ((xx == 0) & (yy == 0)) | ((xx > 2) & (yy < 3))
points
m[points]
m[points].min()

rawDescription: numpy argmin elegant solution required.

description: Numpy argmin elegant solution required.


code:
def discover_constant():
    pi = 22./7
    print (u"Eureka! \u03C0 == %.2f"%pi)

# Print PI three times:
discover_constant()
discover_constant()
discover_constant()

rawDescription: Is there an easy way to restart a python 3 code once it has ended?


code:
def get_nearest(src, others):
    nearest = None
    nearest_dist = float("inf") # Some huge number that everything is less than
    for i in others:
        dist = metric(src, i) # But what is metric?
        if dist < nearest_dist:
            nearest = i
            nearest_dist = dist

    return nearest

rawDescription: Using Nearest Neighbor search on an n element object


rawDescription: Python - fill the no-used dates

description: Python - fill the no-used dates


code: image = os.path.join(PATH, "some_image.gif")

rawDescription: Accessing file path in the os

description: Accessing file path in the os


code:
import sys
sys.version == getattr(sys, 'version')

rawDescription: Importing same variable from multiple libraries


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

ta = np.array([[[ 1.,  0.],
              [1.,   1.]],
             [[ 2.,  1.],
              [ 2.,  2.]],
             [[ 5.,  5.],
              [ 5.,  6.]]])
x, y = ta.T

plt.margins(0.05)
plt.plot(x, y, linewidth=2, color='black')
plt.show()

rawDescription: How to make matplotlib draw discontinuous line segments?

description: Make matplotlib draw discontinuous line segments


code:
def foo(list_a, start, stop):
    if (start <= stop):
        return list_a[start:stop]
    else:
        return list_a[start:] + list_a[:stop]

rawDescription: How to slice a list with START being larger than STOP

description: Slice a list with START being larger than STOP


code:
if __name__ == "__main__":
  # Generate unique id for the job
  job_id = uuid.uuid4().hex
  # This is the root parent
  parent_level = 1
  # Pack the data. The last value is your value to add
  parameters = job_id, parent_level, 2
  # Build the chain. I added an clean task that removes the data
  # created during the process (if you want it)
  add_chain = add.s(parameters, 2) | add.s(4) | add.s(8)| clean.s()
  add_chain.apply_async()

rawDescription: Celery: access all previous results in a chain


code:
while 1:
  ev = pygame.event.get()
  for event in ev:
    if event.type == pygame.MOUSEBUTTONUP:
      mouse = pygame.mouse.get_pos()
      clicked_cards = [c for c in cards if c.clicked(mouse)]
      for card in clicked_cards:
          if card:
              card.flip()

rawDescription: Naming/Calling Generated Object w/ Classes


code:
listOfFiles = ['Passport_Mike.pdf', 'David-Passport.pdf', 'Iain ID Card.pdf', 'CopyPassport Michael.pdf', 'Driving License John.pdf']
searrchTermsList = ["Passport", 'ID']
relevantfiles = [filename for filename in listOfFiles if any(searchterm in filename for searchterm in searrchTermsList)]
print(relevantfiles)

rawDescription: How to search items of a list within strings in Python

description: Search items of a list within strings in Python


code:
cliargs = ["/usr/local/bin/cli", "-s", "10.1.213.226",
           "-n", "Administrator", "-p", "password"]

rawDescription: Interactively writing/reading from an external program


rawDescription: sort list of lists by specific index of inner list

description: Sort list of lists by specific index of inner list


code:
def que(x):
    if x['one'] >= x['two'] and x['one'] <= x['three']:
        return x['one']
    else:
        ''
df['que'] = df.apply(que, axis=1)

rawDescription: Compare two columns using pandas

description: Compare two columns using pandas


code:
for i in xrange(len(l)-1):
    if l[i] > l[i+1]:
        result = False
        break
else:
    result = True

rawDescription: Why sorted list detection does not work in this situation?


code:
from app import db
from datetime import datetime
from sqlalchemy import event, and_
from sqlalchemy.orm import relationship, foreign, remote, backref

class HasPhotos():
    pass

class Photo(db.Model):
    __tablename__   = 'photos'
    id              = db.Column(db.Integer(), primary_key=True)
    image           = db.Column(db.String())
    photoable_id    = db.Column(db.Integer())
    photoable_type  = db.Column(db.String(50))
    created_at      = db.Column(db.DateTime(), default=datetime.utcnow)
    updated_at      = db.Column(db.DateTime(), default=datetime.utcnow)

    @property
    def parent(self):
        return getattr(self, 'parent_{}'.format(self.photoable_type))

@event.listens_for(HasPhotos, 'mapper_configured', propagate=True)
def setup_listener(mapper, class_):
    name = class_.__name__
    type = name.lower()
    class_.photos = relationship(Photo,
                        primaryjoin=and_(
                                        class_.id == foreign(remote(Photo.photoable_id)),
                                        Photo.photoable_type == type
                                    ),
                        backref=backref(
                                'parent_{}'.format(type),
                                primaryjoin=remote(class_.id) == foreign(Photo.photoable_id)
                                )
                        )
    @event.listens_for(class_.photos, 'append')
    def append_photo(target, value, initiator):
        value.photoable_type = type

rawDescription: Polymorphic belongs-to relationships in SQLAlchemy?


rawDescription: How to remove rows with specific missing tags from a Pandas dataframe?

description: Remove rows with specific missing tags from a Pandas dataframe


code:
from datetime import datetime

min(a.iteritems(),
    key=lambda i: i[1] if isinstance(i[1], 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:
#!/usr/bin/env python3

# pygame (simple) template

import pygame

# === CONSTANTS === (UPPER_CASE names)

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 728

# === CLASSES === (CamelCase names)

  # empty

# === FUNCTIONS ===  (lower_case names)

  # empty

# === MAIN ===

# --- init ---

pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

pygame.display.set_caption("Modern Politics")

# --- objects ---

image_name = "Blank.png"

image = pygame.image.load(image_name).convert()
image_rect = image.get_rect()

speed = 20

change_x = 0
change_y = 0

# --- mainloop ---

clock = pygame.time.Clock()

running = True

while running:

    # --- events ---

    for event in pygame.event.get():

        # --- global events ---

        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

        # --- player events ---

        # KEYDOWN/KEYUP event occurs when key is going down/up (short-time event),
        # not when key is held down/up (long-time event)

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                change_x -= speed
            elif event.key == pygame.K_LEFT:
                change_x += speed
            elif event.key == pygame.K_DOWN:
                change_y -= speed
            elif event.key == pygame.K_UP:
                change_y += speed

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                change_x += speed
            elif event.key == pygame.K_LEFT:
                change_x -= speed
            elif event.key == pygame.K_DOWN:
                change_y += speed
            elif event.key == pygame.K_UP:
                change_y -= speed

    # --- updates (without draws) ---

    # move object
    image_rect.x += change_x
    image_rect.y += change_y

    # check borders

    # right borders (SCREEN_WIDTH)
    if image_rect.right < screen_rect.right:
        image_rect.right = screen_rect.right

    # left borders (0)
    if image_rect.left > screen_rect.left:
        image_rect.left = screen_rect.left

    # bottom borders (SCREEN_HEIGTH)
    if image_rect.bottom < screen_rect.bottom:
        image_rect.bottom = screen_rect.bottom

    # left borders (0)
    if image_rect.top > screen_rect.top:
        image_rect.top = screen_rect.top

    # --- draws (without updates) ---

    screen.blit(image, image_rect)

    # human eyes need at least 25FPS to see animation,
    # monitors mostly refresh screen with 60Hz - it means 60FPS.
    clock.tick(30)

    pygame.display.flip()

# --- the end ---

pygame.quit()

rawDescription: Need a bordered scrolling mechanism in pygame


code: url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id

rawDescription: How does youtube-dl generate direct link?


code:
def add_parent_info(it, parent=0):
    me, num_children = it.next() # For Python 3.x use next(it)
    yield [me, num_children, parent]
    for i in range(num_children):
        for item in add_parent_info(it, me):
            yield item

rawDescription: python list/sequence formating

description: Python list/sequence formating


code: print (c_time_converted + dt).time()

rawDescription: having issues with python time object

description: Having issues with python time object


code:
@register.simple_tag()
def average(num1, num2):
   return round(float(num1 / num2), 2)

rawDescription: Adding a Floatformat to Django Custom Tag


rawDescription: Sort a numpy array like a table

description: Sort a numpy array like a table


code:
filtered = ''.join(i for i in sentence if i != 'a')
print(filtered)

rawDescription: How to Filter letters in a string in Python

description: Filter letters in a string in Python


code:
from collections import Counter

def convert(string):
    return Counter(re.findall('[A-Z][a-z]*', string))

rawDescription: Regex: convert a string to a dictionary using dict comprehension and regex


rawDescription: Pandas - group by consecutive ranges

description: Pandas - group by consecutive ranges


code:
elem.Origin
elem.Origin.X

rawDescription: IronPython mapping to managed value class


code:
graphAry = [graphA, graphB]
for ind in range(len(graphAry)):
    grph = graphAry[ind]
    grph.plot(listItems1, someList[ind])
#etc

rawDescription: Using matplotlib, is it possible to set properties for all subplots on a figure at once?


code:
from flask import Flask
from AccountAPI import account_api

app = Flask(__name__)

app.register_blueprint(account_api)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

rawDescription: Split Python Flask app into multiple files


code:
user_to_classes = Table('user_to_classes', Base.metadata,
    Column('class_id', Integer, ForeignKey('class.id')),
    Column('user_id', Integer, ForeignKey('user.id'))
)

class Class(Base):
    ...
    # your old wrong code
    # participants = ...
    # here is right definition
    participants = relationship(
        'User', secondary=user_to_classes, backref='classes')

# In the User class you should not write any foreign keys and relations.
# There will be `classes` field defined in backref of `Class.participants

rawDescription: Flask-SQLAlchemy - How to append a value to a column?


code: dict(zip(fields, row))

rawDescription: Populating a SQLite3 database from a .txt file with Python


code:
# open the recipe database
recipes = open_recipes('recipes.json')

# start a new recipe
recipe = input_func()

name = recipe['name']

# check if the recipe already exists
if name not in recipes:
    # store the recipe in the database
    recipes[name] = recipe
    # save the database
    save_recipes('recipes.json', recipes)
else:
    print('ERROR: recipe already exists:', name)
    # rename recipe...

...

# find an existing recipe
search_name = str(input("What is the name of the recipe you wish to retrieve?"))

if search_name in recipes:
    # fetch the recipe from the database
    recipe = recipes[search_name]
    # display the recipe...
else:
    print('ERROR: could not find recipe:', search_name)

rawDescription: Python Programming - input/output

description: Python Programming - input/output


code:
def bar():
    pass
bar = foo(bar)

rawDescription: Decorating a function with a method (with arbitrary arguments)


code:
# Loop from 1 to 31
for thisday in range(1,32):

  # If we do not encounter thisday in the monthvalues, then skip and keep looping
  if thisday not in monthvalues:
    continue

  # How far ago was the last day seen?
  gap = thisday - lastday

  # If the last day was more than 1 ago, it means there is at least one day amis
  if gap > 1:

    # This is the amount of the last "seen" day
    last_amt = monthvalues[lastday]

    # this is the difference between the current day and the last day
    diff = monthvalues[thisday] - last_amt

    # This is how much you want to interpolate per day in-between
    amt_per_day = diff/gap

    # there is a gap of missing days, let's fill them
    # Start at 1 because we start at the day after the last seen day
    for n in range(1, gap):

      # Fill the missing days with an interpolated value
      monthvalues[lastday+n] = last_amt + amt_per_day * n

  # For the next iteration of the loop, this is the last seen day.
  lastday = thisday

rawDescription: interpolate number sequence

description: Interpolate number sequence


code:
pylab.axis('scaled')
pylab.show()

rawDescription: Creating a 2d mesh in python

description: Creating a 2d mesh in python


code:
class AddDefaultMeta(type):
    def __new__(cls, name, bases, attrs):
        cls = super(AddDefaultMeta, cls).__new__(cls, name, bases, attrs)
        cls.default = cls()
        return cls

rawDescription: Create current class default instance in its base class


code:
cls = "test.somemodule.Test"
module_name, class_name = cls.rsplit(".", 1)

somemodule = importlib.import_module(module_name)

rawDescription: Get python class object from string

description: Get python class object from string


rawDescription: How to resize subfigures when using ImageGrid from Matplotlib

description: Resize subfigures when using ImageGrid from Matplotlib


rawDescription: Python multiprocessing for expensive operation with 2D array


code:
data_and_time = {"time": ['2:30', '2:45', '3:25', '5:15', '7:21', '8:22'],
                 "data": [5., 7., 2., 3., 8., 10.]}

#it builds list like a [True, True, False, ...]
index = map(lambda x: x >= 5, data_and_time['data'])
#and then 'applies' it to 'columns' of data_and_time
data_and_time = {k: [e for e in itertools.compress(v, index)]
                 for k, v in data_and_time.iteritems()}

rawDescription: Filtering a dictionary in Python ... again


code: [i for i in a_list if all(i%j==0 for j in a_list_of_terms)]

rawDescription: Check what numbers in a list are divisible by certain numbers?


code:
import  heapq
l = [5,2,6,8,3,5]
heapq.nsmallest(l, 2)

rawDescription: Is it possible to have multiple statements in a python lambda expression?


code:
import re
p = re.compile(r'/(?:dp|product)/|[&?]page=')
test_str = "http://w...content-available-to-author-only...n.in/s/lp_6563520031_pg_2?rh=n%3A5866078031%2Cn%3A%215866079031%2Cn%3A6563520031&page=2s&ie=UTF8&qid=14468025716"
if p.search(test_str):
    print ("Found!")

rawDescription: How to apply Condition in regex

description: Apply Condition in regex


code:
threadid, thread = data['threads'].popitem()
print(thread['date'])

rawDescription: How do I navigate through a dictionary like this?

description: Navigate through a dictionary like this


rawDescription: How to evaluate an expression-tree in sympy?

description: Evaluate an expression-tree in sympy


code: zip(*[[element(i,j) for i in range(len(a))] for j in range(len(c))])

rawDescription: How to pack the elements of product of matrix multiplication back

description: Pack the elements of product of matrix multiplication back


code:
dict1 = {'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]}
dict2 = {item: [key for key in dict1 if item in dict1[key]] for value in dict1.values() for item in value}

rawDescription: Pythonic inverse dict non-unique mappings


code:
import random
random.randrange(len(array))  # OR  random.randrange(0, len(array))

rawDescription: Where should I subtract 1 when generating random numbers as a list index?


rawDescription: How to get top-level protobuf enum value name by number in python?

description: Get top-level protobuf enum value name by number in python


code:
from nltk.probability import FreqDist
@classmethod
def from_words(cls, words):
    wfd, wildfd, bfd, tfd = (FreqDist(),)*4

    for w1,w2,w3 in ingrams(words,3,pad_right=True):
      wfd.inc(w1)

      if w2 is None:
        continue
      bfd.inc((w1,w2))

      if w3 is None:
        continue
      wildfd.inc((w1,w3))
      tfd.inc((w1,w2,w3))

    return cls(wfd, bfd, wildfd, tfd)

rawDescription: How to get n-gram collocations and association in python nltk?

description: Get n-gram collocations and association in python nltk


code:
filename = "/etc/passwd"
requested_path = os.path.relpath(filename, startdir)
requested_path
requested_path = os.path.abspath(requested_path)
requested_path

rawDescription: Does my code prevent directory traversal?


code:
from pickle import dumps
f = lambda x: x * 5
dumps(f) # error
from cloud.serialization.cloudpickle import dumps
dumps(f) # works

rawDescription: Python, cPickle, pickling lambda functions


code: y = float(i)/10*np.sin(x)

rawDescription: Animating plots on ipython 2 for mac os

description: Animating plots on ipython 2 for mac os


code:
                                             # V-- here's where /bin/bash is added
real_command = '%s %s "%s"' % (sudo_prefix, env.shell,
    _shell_escape(cwd + command))

rawDescription: Can I prevent fabric from prompting me for a sudo password?

description: Prevent fabric from prompting me for a sudo password


code:
...

user = users.get_current_user()
logging.info('retrieving flow for user ' + user.user_id())
flow = pickle.loads(memcache.get(user.user_id()))

credentials = flow.step2_exchange(self.request.params)
StorageByKeyName(CredentialsModel, user.user_id(), 'credentials').locked_put(credentials)

rawDescription: Storing Credentials for Offline Access in Datastore


code: counter = 0

rawDescription: Is there any way to create an action counter for a script? (Python)


code:
from tkinter import *
import os, shelve

food_entry = None

# Opens a new window for entering food items
def data_window():
    global food_entry
    new_window_entry = Toplevel()   # Change to Toplevel (a popup) instead of a new Tk instance
    new_window_entry.title('Data Entry Window')
    Label(new_window_entry, text = 'Enter the food items you have eaten below, separated by commas:').grid(sticky = W, columnspan = 2)
    Label(new_window_entry, text = '(i.e. Apple, Eggs, Ground Beef)').grid(sticky = W, columnspan = 2)
    food_entry = Text(new_window_entry, width = 55, height = 2, wrap = WORD)
    food_entry.grid(sticky = W, columnspan = 2)
    Label(new_window_entry, text = 'Within two hours after eating, did you experience any of the following symptoms:').grid(sticky = W, columnspan = 2)
    Label(new_window_entry, justify = LEFT, wraplength = 450, text = 'bloating, diarrhea, nausea, vomiting, irritable bowel, skin rashes, fatigue, joint pain, dark circles under the eyes, night sweats, or tingling or swelling of the face, fingers, feet or other extemities?').grid(sticky = W, columnspan = 2)
    Radiobutton(new_window_entry, text = 'Yes', variable = inflam, value = 'y').grid(row = 9, column = 0, sticky = E)
    Radiobutton(new_window_entry, text = 'No', variable = inflam, value = 'n').grid(row = 9, column = 1, sticky = W)
    Button(new_window_entry, text = 'Submit', command = check_data).grid(row = 10, column = 0, sticky = W + E)
    Button(new_window_entry, text = 'Cancel', command = new_window_entry.destroy).grid(row = 10, column = 1, sticky = W + E)
    #new_window_entry.mainloop()   No need for this, the mainloop is already running

def check_data():
    global food_entry
    print(food_entry.get(1.0, END))
    if food_entry.get(1.0, END).strip() == '':
       print('Nothing Entered')
    else:
        print('Next Function')

root = Tk()
inflam = StringVar()  # move inflam init to a broader scope so that the buttons don't but
inflam.set('n')    # initialize it as 'n'
root.title('')

Label(root, text = 'Food Tracker v3.0').grid(columnspan = 2)
Button(root, text = 'Enter Data', command = data_window).grid(row = 1, column = 0, sticky = W)
#Button(root, text = 'View Data', command = view_window).grid(row = 1, column = 1, sticky = E)
root.mainloop()

rawDescription: Tkinter getting data from an entry box and sending it to other functions


code:
result = np.zeros(...)
ind = np.triu_indices(...)
result[ind] = values

rawDescription: Converting 1D numpy array into top triangle of matrix


code:
{'rank_1': {'team': 'Randomteam4',
            'draw': 0,
            'games': 3,
            'loss': 0,
            'points': 12,
            'wins': 3},
 'rank_2': {'team': 'Randomteam6',
            'draw': 0,
            'games': 6,
            'loss': 0,
            'points': 10,
            'wins': 3},
 'rank_3': {'team': 'Randomteam5',
            'draw': 2,
            'games': 3,
            'loss': 2,
            'points': 9,
            'wins': 0},
 'rank_4': {'team': 'Randomteam1',
            'draw': 1,
            'games': 3,
            'loss': 1,
            'points': 7,
            'wins': 2},
 'rank_5': {'team': 'Randomteam2',
            'draw': 1,
            'games': 3,
            'loss': 1,
            'points': 4,
            'wins': 1},
 'rank_6': {'team': 'Randomteam3',
            'draw': 2,
            'games': 3,
            'loss': 2,
            'points': 2,
            'wins': 0}}

rawDescription: Python: Getting the top 4 Highest Values in a 2d List


code:
import numpy as np
x = np.arange(30).reshape(10,3)
searchKey = [4,5,8]
x[[0,3,7],:] = searchKey
x

rawDescription: check if numpy array is subset of another array

description: Check if numpy array is subset of another array


code:
coordinates = lambda_mapping[key](argument)
viewport_set(*coordinates)

rawDescription: Duck Typing and acceptance of tuples or integers in Python 3


rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
import csv

reader = csv.reader(open('workers.csv', newline=''), delimiter=',', quotechar='"')
workers = [ageName(row[0], row[1]) for row in reader]

rawDescription: python csv into dictionary

description: Python csv into dictionary


rawDescription: python 3 regex pattern replacement

description: Python 3 regex pattern replacement


code: anyNA = frame[frame.T.isnull().any()]

rawDescription: pandas dataframe: index is DatetimeIndex and 4 columns. Some NaN

description: Pandas dataframe: index is DatetimeIndex and 4 columns. Some NaN