code:
import sys
from PyQt4 import QtGui

class myQLabel(QtGui.QLabel):
    def __init__(self, *args, **kargs):
        super(myQLabel, self).__init__(*args, **kargs)

        self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored,
                                             QtGui.QSizePolicy.Ignored))

        self.setMinSize(14)

    def setMinSize(self, minfs):

        f = self.font()
        f.setPixelSize(minfs)
        br = QtGui.QFontMetrics(f).boundingRect(self.text())

        self.setMinimumSize(br.width(), br.height())

    def resizeEvent(self, event):
        super(myQLabel, self).resizeEvent(event)

        if not self.text():
            return

        #--- fetch current parameters ----

        f = self.font()
        cr = self.contentsRect()

        #--- find the font size that fits the contentsRect ---

        fs = 1
        while True:

            f.setPixelSize(fs)
            br =  QtGui.QFontMetrics(f).boundingRect(self.text())

            if br.height() <= cr.height() and br.width() <= cr.width():
                fs += 1
            else:
                f.setPixelSize(max(fs - 1, 1)) # backtrack
                break

        #--- update font size ---

        self.setFont(f)

class myApplication(QtGui.QWidget):
    def __init__(self, parent=None):
        super(myApplication, self).__init__(parent)

        #---- Prepare a Layout ----

        grid = QtGui.QGridLayout()

        for i in range(3):
            grid.addWidget(myQLabel('some text'), i, 0)
            grid.setRowStretch(i, i+1)
            grid.setRowMinimumHeight(i, 25)

        self.setLayout(grid)
        self.resize(500, 300)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    instance = myApplication()
    instance.show()

    sys.exit(app.exec_())

rawDescription: Syncing Label fontsize with layout in PyQt


code:
import random

sides = 4
count = 1
die1 = random.randint(1,4)
die2 = random.randint(1,4)

while sides == 4 and die1 != die2:
    print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
    count += 1
    die1 = random.randint(1,4)
    die2 = random.randint(1,4)

print ("You got snake eyes! Finally! On try number", count,".")

rawDescription: Counting/random int in while loop

description: Counting/random int in while loop


code:
def remove_fully_correct(answer, guess):
        """(list,list) -> list
        Return a list that removes the chars from the first list that are the same and in the same position in the second list
        >>>remove_fully_correct(['a','b','c','d'], ['d','b','a','d'])
        ['a','c']
        """
        return [a for a,b in zip(answer,guess) if a != b]

rawDescription: How to get a function to execute until the conditions are not sufficient

description: Get a function to execute until the conditions are not sufficient


rawDescription: Regular expression which gets the last part after a special character


rawDescription: Extend different shapes/dimension matrices in python


code:
x = {"hello", "hi", "hey"}
if x.intersections(af.x):
    af.greeting()

rawDescription: Error while checking if a string contains an element from a list in Python?


code:
parentheses_result = parenthesis()
nested_result = nested(parentheses_result)
using_result = using(nested_result)
function(using_result)

rawDescription: What are the Python style guidelines on nested parentheses for functions?


code: series = pd.Series(df.values.ravel())

rawDescription: How to describe entire matrix or Pandas dataframe

description: Describe entire matrix or Pandas dataframe


code:
one = []
two = []
for dic in lst:
    one.append({'restaurant' : dic['restaurant'],
                'lunch_menu' : dic['lunch_menu']})
    two.append({'restaurant' : dic['restaurant'],
                'dinner_menu' : dic['dinner_menu']})

rawDescription: Creating a copy of a list of dictionaries with a subset of keys


rawDescription: Error when attempting to call function from button in wxpython


code:
import ast
codes = [ast.literal_eval(x.strip('[] ')).encode() for x in a]

rawDescription: python list items & convert language codes to names

description: Python list items & convert language codes to names


code: df_output_lines = [s.split() for s in os.popen("df -Ph").read().splitlines()]

rawDescription: Selecting specific columns from df -h output in python


code:
#Play Button
pButton = Button(root, text="Play", command=playButton, borderwidth=0)
pButton.grid(row=1)
pButton.config(image=PlayUp)

rawDescription: Python Change Button Image and change it back


code:
for c in comments:
    try:
         subreddit_name =  c.subreddit.display_name
    except AttributeError:
        subreddit_name = c.subreddit

rawDescription: Seeking a better way to check an instance property and assign value depending on property type


code:
log_density -= np.log(N)
return log_density

rawDescription: How to normalize Kernel Density Estimation using scikit?

description: Normalize Kernel Density Estimation using scikit


rawDescription: Storing data in a hexagonal grid for word search Python


code:
events = [Event() for _ in range(3)]
events[0].set()
events[1].set()
#events[2] starts un-set, i.e. worker3 sleeps at start

threads = []
threads.append(Thread(target=worker1, args=(events,)))
threads.append(Thread(target=worker2, args=(events,)))
threads.append(Thread(target=worker3, args=(events,)))

for t in threads:
    t.start()
for t in threads:
    t.join()

rawDescription: Python - start and stop multiple threads


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

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


rawDescription: How to set and preserve minimal width?

description: Set and preserve minimal width


rawDescription: Python remove first number from string if its 0


code:
bins = np.arange(0, 7, 2)     # include the end
n = np.histogram(A, bins)[0]  # number of columns in each bin
a_mean = np.histogram(A, bins, weights=A)[0]/n
b_mean = np.histogram(A, bins, weights=B)[0]/n
D = np.vstack([a_mean, b_mean])

rawDescription: Averaging out sections of a multiple row array in Python


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

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

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

fig, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
    ax.set(ylabel='', title=col, aspect='equal')

axes[0].legend(bbox_to_anchor=(0, 0.5))

fig.savefig('your_file.png') # Or whichever format you'd like
plt.show()

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

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


code:
text <- c("S H A N N O N  B R A D L E Y")

gsub(" (?! )" , text , replacement = "" , perl = T)

rawDescription: How to remove single space between text

description: Remove single space between text


rawDescription: Make OS open directory in Python

description: Make OS open directory in Python


rawDescription: How to split a string by multiple separators and store in a list?

description: Split a string by multiple separators and store in a list


rawDescription: How to use discontinuous index to form a new list in python?

description: Use discontinuous index to form a new list in python


code:
import numpy as np; import pandas; import datetime
dfrm = pandas.DataFrame(np.random.rand(10,3),
columns=['A','B','C'],
index = pandas.Index(
[datetime.date(2012,6,elem) for elem in range(1,11)],
name="Date"))
dfrm
dfrm['Date']

rawDescription: How to take out the column index name in dataframe

description: Take out the column index name in dataframe


code: f = open(server,"w")

rawDescription: Python: Write to new file line

description: Python: Write to new file line


code:
text = '''rootvg:
hd5                 boot       1     1     1    closed/syncd  N/A
hd4                 jfs        38    38    1    open/syncd    /
datavg:
data01lv            jfs        7     7     1    open/syncd    /data1
data02lv            jfs        7     7     1    open/syncd    /data2'''
re.findall(r'^(\w+):(.*?)(?=^\w+:|\Z)', text, flags=re.DOTALL | re.MULTILINE)

rawDescription: Unable to find the correct regex in python


code: four = four+1

rawDescription: Python dice rolling simulation

description: Python dice rolling simulation


code:
s = "Sweet Bad No No Long Yes Bike No Yes"
s1 = "Sweet Bad No No Long Yes Bike Yes No"
map(lambda x: x[0]==x[1] and x[0] or 'dc', zip(s.split(), s1.split()))
' '.join(_)

rawDescription: Python - replace a word multiple times

description: Python - replace a word multiple times


code:
import string
alphabet = string.ascii_lowercase
counts = {k: sum(k in word.lower() for word in words) for k in alphabet}

rawDescription: How to improve permutation algorithm efficiency with python

description: Improve permutation algorithm efficiency with python


code:
def line_size_hint(filename, learn_size=1<<13):
    with open(filename, 'rb') as file:
        buf = file.read(learn_size)
        return len(buf) // buf.count(b'\n')

number_of_lines_approx = os.path.getsize(filename) // line_size_hint(filename)

rawDescription: estimating number of lines in a file - mismatch between file size and size of all lines

description: Estimating number of lines in a file - mismatch between file size and size of all lines


code:
order = [0,1 ,2]
order.sort(key=lambda x: vertex[x])

rawDescription: Sorting a list based on another list with DSU


rawDescription: pandas DataFrame split the column and extend the rows

description: Pandas DataFrame split the column and extend the rows


code:
BINPUT         = b'q'   # store stack top in memo; index is 1-byte arg
BINGET         = b'h'   # push item from memo on stack; index is 1-byte arg
EMPTY_TUPLE    = b')'   # push empty tuple
MARK           = b'('   # push special markobject on stack

rawDescription: How can I find why is my pickled data so large?

description: Find why is my pickled data so large


code:
class Order(object):
    def __init__(self, item_id, item_name, customer=None):
        self.item_id = item_id
        self.item_name = item_name
        self.customer = customer # self.customer = None
    #...

rawDescription: Use a foreign key mapping to get data from the other table using Python and SQLAlchemy


code:
DATABASE_ENGINE   = 'oracle'
DATABASE_HOST     = 'localhost'
DATABASE_NAME     = 'ORCL'
DATABASE_USER     = 'scott'
DATABASE_PASSWORD = 'tiger'

rawDescription: Use only some parts of Django?

description: Use only some parts of Django


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("address", nargs='?')
parser.add_argument("host")
parser.add_argument("resource")
args = parser.parse_args()

if args.address is None:
    args.address = args.host
print(args)

rawDescription: How do I set an Argparse argument's default value to a positional argument's value?

description: Set an Argparse argument's default value to a positional argument's value


code:
import json
from webob.acceptparse import MIMEAccept
from webob.exc import HTTPUnauthorized, HTTPBadRequest

FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED = 'repoze.who.facebook_connect.not_granted'

class ExampleJSONChallengerPlugin(object):
    json_content_type = 'application/json'
    mime_candidates = ['text/html',
                       'application/xhtml+xml',
                       json_content_type,
                       'application/xml',
                       'text/xml']

    def is_json_request_env(self, environ):
        """Checks whether the current request is a json request as deemed by
        TurboGears (i.e. response_type is already set) or if the http
        accept header favours 'application/json' over html.
        """
        if environ['PATH_INFO'].endswith('.json'):
            return True

        if 'HTTP_ACCEPT' not in environ:
            return False

        # Try to mimic what Decoration.lookup_template_engine() does.
        return MIMEAccept(environ['HTTP_ACCEPT']) \
            .best_match(self.mime_candidates) is self.json_content_type

    def challenge(self, environ, status, app_headers, forget_headers):
        if FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED in environ:
            response = HTTPBadRequest(detail={
                'not_granted':
                environ.pop(FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED),
            })
        elif status.startswith('401 '):
            response = HTTPUnauthorized()
        else:
            response = None

        if response is not None and self.is_json_request_env(environ):
            response.body = json.dumps({
                'code': response.code,
                'status': response.title,
                'explanation': response.explanation,
                'detail': response.detail,
            })
            response.content_type = self.json_content_type

        return response

rawDescription: How can I return JSON output when repoze.who authentication fails?

description: Return JSON output when repoze.who authentication fails


code:
notebook = MyNotebook(parent)
notebook.AddPage(someWindow, "page 1")
notebook.AddPage(someOtherWindow, "page 2")
for page in notebook:
    ...

rawDescription: Python/wxPython: auinotebook get all pages


code:
import csv
import re

def only_bipl(f):
    for line in f:
        if '(BIPL)' in line:
            yield re.sub(r'\s*\(BIPL\)', '', line)

with open('test.csv', 'rb') as old_csv:
    reader = csv.reader(only_bipl(old_csv), delimiter=',')
    filters = {(row[0].lower(), row[1][:3].upper(), row[2].upper()) for row in reader}

rawDescription: Editing a code to create a filter based on a condition and then stripping the condition


code:
s = 'foo\nTAKE\nbar'   # split on TAKE
re.split(r'\n(?=TAKE(?: SEL)?\n|(?<!\nTAKE\n)(?<!\nTAKE SEL\n)NAME)', s)
s = 'foo\nTAKE SEL\nbar'   # split on TAKE SEL
re.split(r'\n(?=TAKE(?: SEL)?\n|(?<!\nTAKE\n)(?<!\nTAKE SEL\n)NAME)', s)
s = 'foo\nTAKE SEL\nNAME\nbar'   # split on TAKE SEL but not on NAME
re.split(r'\n(?=TAKE(?: SEL)?\n|(?<!\nTAKE\n)(?<!\nTAKE SEL\n)NAME)', s)
s = 'foo\nNAME\nbar'   # split on NAME since no TAKE or TAKE SEL before
re.split(r'\n(?=TAKE(?: SEL)?\n|(?<!\nTAKE\n)(?<!\nTAKE SEL\n)NAME)', s)

rawDescription: How do you split using re.split as more of a "slice at" function?

description: Split using re.split as more of a "slice at" function


code:
tournament = Tournament(title=title)
tournament.save()
players_i_care_about = [players, go, here]

tournament.players = players_i_care_about #(removes all players and saves new players)

rawDescription: Save() in ManyToMany relation

description: Save() in ManyToMany relation


code:
s = ",,,Central California\r\n"
re.findall(r',?([^,]+)(?:,|\r\n)', s)

rawDescription: Python regex: exclude \r\n

description: Python regex: exclude \r\n


code:
remove_list = (r'*.txt',) # Example for removing all .txt files in the list
def removal(l, rm_list):
  ret_list = []
  for f in l:
    for pattern in rm_list:
      if not fnmatch(basename(f.lower()), pattern):
        ret_list.append(f)
  return ret_list

rawDescription: remove certain files in a list matching a pattern

description: Remove certain files in a list matching a pattern


code:
var = 'F12'
sorted(getattr(X_train_num, var).unique())==sorted(getattr(X_test_num, var).unique())

rawDescription: how to loop over below statement

description: Loop over below statement


code: from six import iteritems

rawDescription: How to filter dictionary keys based on its corresponding values

description: Filter dictionary keys based on its corresponding values


code: y[REPLACE_EVERY_Nth - 1::REPLACE_EVERY_Nth] = REPLACE_WITH

rawDescription: how to replace every n-th value of an array in python most efficiently?

description: Replace every n-th value of an array in python most efficiently


rawDescription: Parse String to Tree Using Stack

description: Parse String to Tree Using Stack


code:
#!/usr/bin/env python
import os
import sys
from hachoir_metadata import extractMetadata
from hachoir_parser import createParser

def getinfo(rootdir, extensions=(".avi", ".mp4")):
    if not isinstance(rootdir, unicode):
       rootdir = rootdir.decode(sys.getfilesystemencoding())
    for dirpath, dirs, files in os.walk(rootdir):
        dirs.sort() # traverse directories in sorted order
        files.sort()
        for filename in files:
            if filename.endswith(extensions):
               path = os.path.join(dirpath, filename)
               yield path, extractMetadata(createParser(path))

for path, metadata in getinfo(u"z:\\"):
    if metadata.has('duration'):
        print(path)
        print("  Duration (hh:mm:ss.f): %s" % metadata.get('duration'))

rawDescription: How to get .avi files length

description: Get .avi files length


rawDescription: Numpy dot product very slow using ints

description: Numpy dot product very slow using ints


code: output = "".join( [ "1" if x in arr2 else "0" for x in arr1] )

rawDescription: Compare two arrays integer arrays in python by each element


code:
def findFood(food):
    foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
    for line in f.readlines():
        ...
    f.seek(0)

rawDescription: finding item in text file during 2nd read

description: Finding item in text file during 2nd read


code:
import pandas as pd
df = pd.DataFrame({'datecol':['2016-01-17', '0-1274753-3']})
df['datecol'] = pd.to_datetime(df['datecol'], errors='coerce')
# this drops all rows which contain NaN
df = df.dropna(axis=0, how='any')
# alternatively, use this to drop all rows which contain NaN in the datecol column
# df = df.loc[pd.notnull(df['datecol'])]
print(df)

rawDescription: Optimize string checking function for pandas dataframe?


rawDescription: PYTHON: Difference between if not i.find("Hey") and if i.find("Hey") == -1


code:
import itertools
itertools.chain(self.a, self.z, [self.y])

rawDescription: Is there a way to get a view of several lists/variables as a list like thing in python


code: sample(a, 4)

rawDescription: Python: Sampling from a discrete distribution defined in an n-dimensional array


rawDescription: Parsing xml with "not well-formed" characters in python


code: masked = df.mask(df!=0)

rawDescription: Filter by row sum and value

description: Filter by row sum and value


code: b = [['' if x is None else x for x in c] for c in a]

rawDescription: python replace None with blank in list using list Comprehensions or something else? Also a nested list solution

description: Python replace None with blank in list using list Comprehensions or something else? Also a nested list solution


code:
rcParams = plt.matplotlib.rcParams
def get_prop_cycle():
    prop_cycler = rcParams['axes.prop_cycle']
    if prop_cycler is None and 'axes.color_cycle' in rcParams:
        clist = rcParams['axes.color_cycle']
        prop_cycler = cycler('color', clist)
    return prop_cycler

rawDescription: Using matplotlib's color cycle as a colormap


code:
class Site(object):
    def __init__(self,dict):
        self.__dict__.update(dict)
site = Site(dict)
site.a

rawDescription: Adding dynamic property to a python object


rawDescription: How to create a dictionary in python from a set of values

description: Create a dictionary in python from a set of values


code:
for idx, vert in enumerate(row):
    if vert > 0:
        temp[vert].append(idx)

rawDescription: Append overwrites values even when copying list


code:
def render_template(template_name_or_list, **context):

    # get  request context
    ctx = _request_ctx_stack.top

    # check request context
    # if function called without request context
    # then call with `test_tequest_context`
    # this because I send email from celery tasks
    if ctx is None:
        with current_app.test_request_context():
            return render_template(template_name_or_list, **context)

    # I have specific locale detection (from url)
    # and also use `lang` variable in template for `url_for` links
    # so you can just pass language parameter without context parameter
    # and always set `babel_locate` with passed language
    locale = getattr(ctx, 'babel_locale', None)
    if locale is None:
        ctx.babel_locale = Locale.parse(context['lang'])

    # render template without additinals context processor
    # because I don't need this context for emails
    # (compare with default flask `render_template` function)
    return _render(ctx.app.jinja_env.get_or_select_template(
        template_name_or_list), context, ctx.app)

rawDescription: python gettext different languages at same time

description: Python gettext different languages at same time


code:
from difflib import SequenceMatcher

matcher = SequenceMatcher()
for a, b in zip(list1, list2):
    matcher.set_seqs(a, b)
    for tag, i1, i2, j1, j2 in matcher.get_opcodes():
        if tag == 'equal': continue
        print('{:>7s} {} {}'.format(tag, a[i1:i2], b[j1:j2]))

rawDescription: Print differences between list of lists using Python


code:
class ProjectWizard(SessionWizardView):
    def get_form_initial(self, step):
        if 'project_id' in self.kwargs and step == 'project_essentials':
            project_id = self.kwargs['project_id']
            project = Project.objects.get(id=project_id)
            from django.forms.models import model_to_dict
            project_dict = model_to_dict(project)
            return project_dict
        else:
            return self.initial_dict.get(step, {})

rawDescription: Django Form Wizard to Edit Model

description: Django Form Wizard to Edit Model


rawDescription: Is it possible to get a python IDE working inside a PYQT4 widget?


code: [x[0] if isinstance(x, list) and len(x) == 1 else x for x in a]

rawDescription: Python: Extract one value from a list of integers and lists


code: stream = stream | Transformer('.//head').append(tag.script(functionNameCode, type="text/javascript"))

rawDescription: How do I test if a string exists in a Genshi stream?

description: Test if a string exists in a Genshi stream


code:
def remove_dups(d):
    c, result = {}, {}
    for item in d.values():
        c[item] = c.get(item, 0) + 1
    for k, v in d.items():
        if c[v] == 1:
            result[k] = v
    return result

rawDescription: Removing certain keys in a dictionary

description: Removing certain keys in a dictionary


code: np.array([(i,j) for i,j in zip(id,np.column_stack((x,y)))],dt)

rawDescription: Methods of creating a structured array

description: Methods of creating a structured array


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


code:
def remove_list_items(list_of_records):
    result = []
    for r in list_of_records:
        result.append((r[0], get(r, 1), get(r, 2), get(r, 3)))
    return result

rawDescription: how to convert a list into a pandas dataframe

description: Convert a list into a pandas dataframe


rawDescription: Matplotlib savefig() on a zoomed in graph


code: sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brLeft'})]

rawDescription: How to get next page link in python beautifulsoup?

description: Get next page link in python beautifulsoup


code:
import shared.pkg.b
dir(shared)
hasattr(shared,'pkg')
dir(shared.pkg)
hasattr(shared.pkg,'b')

rawDescription: Why does python put 'A' in global namespace when I import A.B.C


rawDescription: Python copy a list with both reference copy and value copy


code: [i * 10 for i in range(10,21)]

rawDescription: Python lambda function declaration and call for list generation


code:
def findLetters(wordList):
    letterList = []
    letters = 'abcdef'
    for word in wordList: # good
        for letter in word: # good
            if letter in word not in letters: # nope, looks for True/False in letters
                break
            else:
                letterList.append(word) # nope, appends the word multiple times
    return letterList

rawDescription: Python text file. Finding strings that contain only characters 'abcdef'


rawDescription: grouping pandas dataframe by two columns (or more)?

description: Grouping pandas dataframe by two columns (or more)


rawDescription: Inner joining two columns in Pandas

description: Inner joining two columns in Pandas


code:
import sys

print(sys.version_info.major)

rawDescription: AttributeError: 'str' object has no attribute 'maketrans'


code:
from IPython.parallel import Client
c = Client()
c.ids
c[:].apply_sync(lambda : "Hello, World")

rawDescription: can ipython parallel operate across different sets of nodes

description: Can ipython parallel operate across different sets of nodes


rawDescription: find the index of a boolean array whose values are true

description: Find the index of a boolean array whose values are true


code:
# Your for loop should be rewritten as follows:
for index in xrange(len(a)):
    a[index] += 1

rawDescription: How do I operate on the actual object, not a copy, in a python for loop?

description: Operate on the actual object, not a copy, in a python for loop


code:
def follow_def_cat(sender, instance, created, **kwargs):
    if created:
        for category in categories:
            f = Follow(user=instance.username, category=category)
            f.save()

post_save.connetc(follow_def_cat, sender=User)

rawDescription: How to use Django Signals to run a function after user registration completed?

description: Use Django Signals to run a function after user registration completed


code:
from datetime import timedelta

s1 = '1157 days, 9:46:39'
s2 = '12:00:01.824952'
s3 = '-1 day, 23:59:31.859767'
t1 = parse(s1)
t2 = parse(s2)
t3 = parse(s3)

timedelta(**t1) # datetime.timedelta(1157, 35199)
timedelta(**t2) # datetime.timedelta(0, 43201, 824952)
timedelta(**t3) # datetime.timedelta(-1, 86371, 859767)

rawDescription: How to convert standard timedelta string to timedelta object

description: Convert standard timedelta string to timedelta object


code:
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
a = sparse.csr_matrix((data,(row,col)), shape=(3,3))
a.data
a.indices            # csr has coor in indices and indptr
a.indptr
ac=a.tocoo()
ac.data
ac.col
ac.row

rawDescription: python sparse csr matrix: how to serialize it

description: Python sparse csr matrix: how to serialize it


code:
a = NoProps(3)
b = NoProps.from_other_obj(a)
c = NoProps.from_other_obj(b)
print(a.spam, b.spam, c.spam)
# Prints 3, 3, 3

# I just discovered that c.spam should be calculated
# So convert it into a Props object
c = Props.from_other_obj(c)
print(a.spam, b.spam, c.spam)
# Prints 3, 3, (something between 3 and 23)

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


code: tokens = test.lower().split()

rawDescription: Cancel capitalization in python

description: Cancel capitalization in python


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


rawDescription: How to calculate cosine similarity given 2 sentence strings? - Python

description: Calculate cosine similarity given 2 sentence strings? - Python


code: tc = pptest.TestClass()

rawDescription: Parallel Python - create objects into another class in parallel execution


code:
p = re.compile(r'(\b\w+)bc\1')
p.search(s).group(1)

rawDescription: Repeat a substring in a nonconsecutive position


code:
[{'id': 1, 'name': 'business', 'subterms': []}]
[{'id': 20,
  'name': 'education',
  'subterms': [{'id': 22,
                'name': 'schoolbooks',
                'subterms': [],
                'synonyms': ['literature']}]}]
[{'id': 20,
  'name': 'education',
  'subterms': [{'id': 22,
                'name': 'schoolbooks',
                'subterms': [],
                'synonyms': ['literature']}]},
 {'id': 1,
  'name': 'business',
  'subterms': [{'id': 2,
                'name': 'industry',
                'subterms': [{'id': 21,
                              'name': 'agriculture',
                              'subterms': [],
                              'synonyms': []}],
                'synonyms': []}]}]

rawDescription: How to filter nested JSON and preserve branch hierarchy for matches?

description: Filter nested JSON and preserve branch hierarchy for matches


code:
if display_graph:
    init_something()

while True:
    if show_timer:
        do_something()

    if other_option:
        do_other_thing()

rawDescription: Python code readablity for boolean variable driven code


code:
import numpy as np

num_vars = 10**4
cov = np.zeros((num_vars, num_vars), dtype=float)
for i, j in np.ndindex(cov.shape):
    # Logic presumably in some function...
    cov[i, j] = calculate_value(i, j)

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
# initialize data
In [1]: fruits = ['apple', 'peach', 'orange']
In [2]: data = np.vstack((np.random.choice(fruits, size=10),
                          np.random.randint(0, 100, size=10),
                          np.random.rand(10))).T
In [3]: df = pd.DataFrame(data, columns=['fruit_type', 'reading', 'prob'])

rawDescription: Numpy random choice multiple loops

description: Numpy random choice multiple loops


rawDescription: I need some help Write random test data to csv file using faker


code: [D.get('A') for D in x]

rawDescription: filter the values of dictionary items in a list by their key in python

description: Filter the values of dictionary items in a list by their key in python


rawDescription: iterate through list like in sliding window

description: Iterate through list like in sliding window


code:
def find_element(nested_lst, what):
    for idx, sublst in enumerate(nested_lst):
        try:
            idx2 = sublst.index(what)
            return (idx, idx2)
        except ValueError:
            pass

rawDescription: In python, given a list of lists, how do you identify the index of a matching element?


rawDescription: Trying to write my own Neural Network in Python


code:
import xarray as xr
ds = xr.open_dataset(path_file)

rawDescription: Speeding up reading of very large netcdf file in python


code: re.sub(r'/images/stories/([\w%]+\.(?:jpg|png|gif))', r'{{media url="wysiwyg/\1"}}', content)

rawDescription: Python Regex replace multiple occurencies of parts of a string


code:
m = re.match(r, "What is the capital of China?")
d = m.groupdict()
relation_var = d["RelationVar"]
concept_var = d["ConceptVar"]
relation_var
concept_var

rawDescription: Python regular expressions for simple questions


rawDescription: How to log in to a website with urllib?

description: Log in to a website with urllib


rawDescription: Simple MongoDB query slow

description: Simple MongoDB query slow


code:
def thing_that_does_http():
    # create semaphore to manage the deferreds
    semaphore = twisted.internet.defer.DeferredSemaphore(2)

    # create a list with all urls to check
    dl = DeferredList()
    # append deferreds to list
    for url in self._urls:
        # returns deferred
        dl.append(semaphore.run(self._getPage, url))

    # get a DefferedList
    dl = twisted.internet.defer.DeferredList(dl)
    # add some callbacks for error handling
    dl.addErrback(self._handleError)
    return dl

rawDescription: Twisted / perform asynchronous http requests


code:
insertQuery = 'INSERT INTO foo VALUES (%s, %s, %s)'
cursor.execute(insertQuery, (1, 'Alice', datetime.date(2014, 12, 4)))

rawDescription: Python Dates - Converting None to Null

description: Python Dates - Converting None to Null


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


code:
...

from blog.sitemap import BlogSitemap

sitemaps = {
    'blog':BlogSitemap
}

url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),

rawDescription: Django 1.6: What should be the location of the sitemap.py file?


code:
df = DataFrame(np.random.randn(100000,20))
df['B'] = 'foo'
df['C'] = pd.Timestamp('20130101')
df.info()

rawDescription: Creating large Pandas DataFrames: preallocation vs append


code:
view_func=lambda: name  # <- points at the *symbol*, which holds the *last* value
# in the case of a loop

rawDescription: flask -- how to get around limitation that app.route / app.add_view_rule doesn't work with closures?

description: Flask -- how to get around limitation that app.route / app.add_view_rule doesn't work with closures


code:
def expansion(x, b, greedy=True):
    if not greedy:
        m = (floor(b) / (b - 1)) - 1
    k = int(floor(log(x) / log(b)))
    d, r = divmod(x / float(b ** k), 1)
    if not greedy and r < m:
        d, r = d - 1, r + 1
    digits = [int(d)]
    for _ in range(k):
        d, r = divmod(b * r, 1)
        if not greedy and r < m:
            d, r = d - 1, r + 1
        digits.append(int(d))
    def rest(d, r):
        while r:
            d, r = divmod(b * r, 1)
            if not greedy and r < m:
                d, r = d - 1, r + 1
            yield int(d)
    return digits, rest(d, r)

rawDescription: Looking for a different kind of divmod function


code:
Setup
import pandas as pd
import numpy as np

setup_tuples = []

for c in ['a', 'b']:
        for i in ['one', 'two', 'three']:
            setup_tuples.append((c, i))

columns = pd.MultiIndex.from_tuples(setup_tuples)

rand_array = np.random.rand(10, len(setup_tuples))

df = pd.DataFrame(rand_array, columns=columns)

rawDescription: Operating on pandas dataframes that may or may not be multiIndex


code:
def anagrams(s):
    if s =="":
        return [s]
    else:
        ans = []
        for w in anagrams(s[1:]):
            for pos in range(len(w)+1):
                ans.append(w[:pos]+s[0]+w[pos:])
        return ans # only return when both loops are done

rawDescription: Anagram not matching up (string to list), Python


code:
s = df.stack()
s

rawDescription: Inverse lookup in pandas

description: Inverse lookup in pandas


rawDescription: Putting semicolons at the end of the statements. Is this a good/bad programming practice in Python?


code:
#b.py code
import A

# [...] your code

__all__ = ['A', ...]  # *all* the names you want to export

rawDescription: False Unused Import Statement in PyCharm?


code:
import pygame

# --- constants ----

size = width, height = 720, 480
speed = [2, 2]

#Colours

black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)

# --- functions ---

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def game_intro():

    text_vroom, text_vroom_rect = text_objects("V'Room!", largeText)
    text_vroom_rect.center = ((width/2),(height/2))

    text_go, text_go_rect = text_objects("GO", smallText)
    text_go_rect.center = ((75+(100/2)),(400+(50/2)))

    text_exit, text_exit_rect = text_objects("Exit", smallText)
    text_exit_rect.center = ((550+(100/2)),(400+(50/2)))

    running = True

    while running:

        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()

        screen.fill(blue)
        screen.blit(text_vroom, text_vroom_rect)

        # Button GO

        if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
            pygame.draw.rect(screen, green_bright,(75,400,100,50))

            if click != None and click[0] == 1:
                # wait because `pygame.mouse.get_pressed()` is too fast for human clik
                pygame.time.wait(100)
                # run game
                game_running()
        else:
            pygame.draw.rect(screen, green,(75,400,100,50))

        screen.blit(text_go, text_go_rect)

        # Button EXIT

        if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
            pygame.draw.rect(screen, red_bright,(550,400,100,50))

            if click != None and click[0] == 1:
                pygame.quit()
                quit()
        else:
            pygame.draw.rect(screen, red,(550,400,100,50))

        screen.blit(text_exit, text_exit_rect)

        pygame.display.flip()

        clock.tick(15)

def game_running():

    text_stop, text_stop_rect = text_objects("STOP", smallText)
    text_stop_rect.center = ((75+(100/2)),(400+(50/2)))

    text_exit, text_exit_rect = text_objects("Exit", smallText)
    text_exit_rect.center = ((550+(100/2)),(400+(50/2)))

    running = True

    while running:

        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()

        screen.fill(blue)
        #screen.blit(BackgroundPNG,(0,0))

        # road and car - or title

        screen.blit(road, (0,0))
        screen.blit(carImg, (350,370))

        # Button STOP

        if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
            pygame.draw.rect(screen, green_bright,(75,400,100,50))

            if click != None and click[0] == 1:
                # return to menu
                return
        else:
            pygame.draw.rect(screen, green,(75,400,100,50))

        # draw STOP
        screen.blit(text_stop, text_stop_rect)

        # Button EXIT

        if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
            pygame.draw.rect(screen, red_bright,(550,400,100,50))

            if click != None and click[0] == 1:
                pygame.quit()
                quit()
        else:
            pygame.draw.rect(screen, red,(550,400,100,50))

        screen.blit(text_exit, text_exit_rect)

        pygame.display.flip()

        clock.tick(15)

# --- main ---

pygame.init()

screen = pygame.display.set_mode(size)
pygame.display.set_caption("Broom! || BETA::00.0.3")

# pictures
road = pygame.surface.Surface( size )
road.fill(black)

carImg =  pygame.surface.Surface( (10,10) )
road.fill(green)

# fonts
largeText = pygame.font.Font('freesansbold.ttf',115)
smallText = pygame.font.Font("freesansbold.ttf",20)

# others

clock = pygame.time.Clock()

game_intro()

rawDescription: Cannot get button to toggle a change in pygame


rawDescription: When oracle virtualbox are set, How to get local ip address in python


rawDescription: How can I convert character like "\u0096" in python?

description: Convert character like "\u0096" in python


code:
from flask import session as fsession
from dropbox import session as dbsession

rawDescription: Conflicting imports

description: Conflicting imports


rawDescription: Convert float into time (hour.minute) in python


rawDescription: [] and {} vs list() and dict(), which is better?


rawDescription: Zipping two list of lists

description: Zipping two list of lists


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

rawDescription: Algorithm (prob. solving) achieving fastest runtime


code:
def __iter__(self):
    yield 'a', self.a
    yield 'b', self.b
    yield 'c', self.c

rawDescription: In python, how do I cast a class object to a dict


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

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


code:
import timeit
import re
def nonzero_binary_set(b):
    return b and set(b) == {'0', '1'}

def nonzero_binary_re(b):
    return re.match(r'^(?=.*1)[01]+$', b) is not None

tests = ['', '00101011001110', '000000000000', '1111111111111',
'10100011010101' * 1000, '0' * 10000]
timeit.timeit('map(f, tests)', 'from __main__ import tests, nonzero_binary_set as f', number=10000)
timeit.timeit('map(f, tests)', 'from __main__ import tests, nonzero_binary_re as f', number=10000)

rawDescription: Check if number is made of both 0 and 1 using regex


code: stat = os.fstat(fs.fileno())

rawDescription: Detecting broken stream in python when file is deleted


code: [s for s in x if 'Gabe' in s]

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

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


rawDescription: How do you click on an element which is hidden using Selenium WebDriver?

description: Click on an element which is hidden using Selenium WebDriver


code:
base = (pickle.load(open("g.pickle"))+1)/2 * 255
base = base[..., numpy.newaxis].repeat(4, -1).astype("uint8")

rawDescription: How can I tranform this (100, 100) numpy array into a grayscale sprite in pygame?

description: Tranform this (100, 100) numpy array into a grayscale sprite in pygame


code: android.add_jars = java/myjar.jar

rawDescription: Pyjnius import jar file

description: Pyjnius import jar file


rawDescription: Dict into Dict Python

description: Dict into Dict Python


rawDescription: pandas dataframe by index and integer

description: Pandas dataframe by index and integer


rawDescription: turn a number in an element of a string into a coefficient python

description: Turn a number in an element of a string into a coefficient python


rawDescription: pexpect regex not working

description: Pexpect regex not working


code: x = scipy.matrix([1,2,3]).transpose()

rawDescription: Creating a list from a Scipy matrix

description: Creating a list from a Scipy matrix


code:
import simplejson

def my_fn(args):
  return simplejson.dumps({'args': args})

rawDescription: Python mocking- understand the concept and necessity


code:
elem = ET.Element('Level0', text='test text')
ET.tostring(elem)

rawDescription: Need help interpreting Python documentation


code:
words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
[word for word in words if word.islower()]
[word for word in words if word.isupper()]
[word for word in words if not word.islower() and not word.isupper()]

rawDescription: Check if string is upper, lower, or mixed case in Python


code:
class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass)
                     # but will not have access to the instance it's called on
                     # (if it is called on an instance)

rawDescription: Call Class Method from another Class

description: Call Class Method from another Class


code:
return render(request,'polls/album-container.html',
              {'albums': albums,'artists': artists})

rawDescription: what is the method to use a different template to extend the statement {% block%}?

description: What is the method to use a different template to extend the statement {% block%}


code:
import time
import unittest
import unittest.mock

class Alarm:
    def setAlarm(self):
        self.alarmed = False
        self._saved = time.perf_counter()
    def runStep(self):
        now = time.perf_counter()
        if now - self._saved > 1000.0 and self._saved != -1:
            self.alarmed = True
            self._saved = -1

class MockPerfCounter:
    def __init__(self):
        self.t = 0
    def increment(self, n):
        self.t += n
    def perf_counter(self):
        return self.t

class TestAlarm(unittest.TestCase):
    def test_foo(self):
        clock = MockPerfCounter()
        with unittest.mock.patch('time.perf_counter', clock.perf_counter):
            alarm = Alarm()
            alarm.setAlarm()
            clock.increment(999.0)
            alarm.runStep()
            self.assertFalse(alarm.alarmed)
            clock.increment(1.1)    # tick another second
            alarm.runStep()
            self.assertTrue(alarm.alarmed)

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

rawDescription: Mocking tool for python-3.3

description: Mocking tool for python-3.3


code:
if float(line.split()[2]) > 0:
    fout.write(line)

rawDescription: remove rows which have a specific attribute less than or equal to 0

description: Remove rows which have a specific attribute less than or equal to 0


code:
class X:
    pass

a = X()
b = X()
t={1: {1: a, 2: b}}

map(lambda x: setattr(x, 'test', 'wow'), t[1].values())

a.test   # output is 'wow'

rawDescription: Dynamically set object attribute with map and setattr function


code:
from itertools import dropwhile
b = ''.join(dropwhile(lambda c: c != '[', a))
b

rawDescription: Extract square-bracketed text from a string


code:
np.concatenate((arr[:,i,None],
   np.sum(arr[:,[j for j in xrange(3) if j != i]], axis=1, keepdims=True)),
   axis=1)

rawDescription: Sum all columns but one in a numpy array


code: np.vectorize(lambda x, y: x * y + 2)(X, Y)

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


code:
class TimeStamp(ndb.Model):
    timestamp = ndb.DatetimeProperty(auto_now=True)

rawDescription: Easiest way to store a single timestamp in appengine


rawDescription: Scraping data with BeautifulSoup issue

description: Scraping data with BeautifulSoup issue


code:
def calcBitDigits(n):
    return (n-1).bit_length()

rawDescription: Python find max number of combinations in binary


rawDescription: How can I search a folder which it's name contains specifc character in Python

description: Search a folder which it's name contains specifc character in Python


code:
dict_col = df.pop(1)  # here 1 is the column name
pd.concat([df, dict_col.apply(pd.Series)], axis=1)

rawDescription: How do I access embedded json objects in a Pandas DataFrame?

description: Access embedded json objects in a Pandas DataFrame


code:
import numpy as np
import pandas as pd

d = {'user' : [1., 2., 3., 4] ,'item' : [5., 6., 7., 8.],'f1' : [9., 16., 17., 18.], 'f2':[4,5,6,5], 'f3':[4,5,5,8]}
df = pd.DataFrame(d)
samples = np.array([[1,5],[3,7],[3,7],[2,6]])
samples = pd.DataFrame(samples, columns=['user', 'item'])

result = pd.merge(samples, df, how='inner')
result = result[['f1', 'f2', 'f3']]
result = result.values
print(result)

rawDescription: Select pandas frame rows based on two columns' values


code:
def izip_pairs(xs, ys, cmp):
    xs = list(reversed(sorted(xs, cmp)))
    ys = list(reversed(sorted(ys, cmp)))

    while xs or ys:
        delta = ((not xs) - (not ys)) or cmp(xs[-1], ys[-1])

        x = xs.pop() if delta <= 0 else None
        y = ys.pop() if delta >= 0 else None
        yield x, y

rawDescription: Python: Fast and minimalistic way to zip and pair matching elements in two lists


code:
def settings(request):
    """
    Put selected settings variables into the default template context
    """
    from django.conf import settings
    return {
        'DOMAIN':     settings.DOMAIN,
        'GOOGLEMAPS_API_KEY': settings.GOOGLEMAPS_API_KEY,
    }

rawDescription: Defining Constants in Django

description: Defining Constants in Django


code:
class F:

    def __init__(self):
        self.calls = 0

    def __call__(t, x):
        self.calls += 1
        return -2 * x

rawDescription: How to find the number of times the ODE's derivative is called in one invocation.

description: Find the number of times the ODE's derivative is called in one invocation.


code:
import module1
import module2

rawDescription: Python "header.py" module

description: Python "header.py" module


code:
def df_index_to_datetime(df, datetime_format):
    index_name = df.index.name
    df = df.reset_index()
    df[index_name] = df[index_name].map(lambda x: datetime.strptime(x, datetime_format))
    df = df.set_index(index_name)
    return df

rawDescription: KeyError in pandas to_datetime using custom format


code: result = [v[2] for values in my_dict.values() for v in values]

rawDescription: Getting a list of values from dictionary when values are tuples within lists?


rawDescription: Python - Moving an object\label\button and changing it's attribute


code:
from IPython import parallel

rc = parallel.Client()
view = rc[:]

@view.parallel(block=True)
def pfun(a):
    """each engine will get a chunk of a, not the whole thing"""
    c = fun(a)
    return c

# a will be scattered and c will be gathered
c = pfun(a)

rawDescription: Synchronization issue in IPython parallel computing


rawDescription: Selecting rows from a pandas DataFrame with an arbitrary number of conditions


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


code:
df = df.set_index('date')
df.groupby('colour').resample('D')

rawDescription: Re-index dataframe by new range of dates


rawDescription: numpy ndarray advanced indexing

description: Numpy ndarray advanced indexing


code:
import re
with open('numbers') as fhandle:
    for line in fhandle:
        line = line.strip()
        separators = re.sub('[0-9]', '', line)
        for sep in separators[:-1]:
            line = line.replace(sep, '')
        if separators:
            line = line.replace(separators[-1], '.')
        print(line)

rawDescription: Python: Detect number separator symbols and parse into a float without locale


code:
element = element in row
row = math.sqrt(element)

rawDescription: Python CSV take square root of data in the field


code:
import re
p = re.compile(r'https?:\/\/[^"]+', re.IGNORECASE | re.MULTILINE)
test_str = "{\"marketing_package_url\": \"http://www.capitalpacific.com/inquiry/TrailsEndMarketplaceExecSummary.pdf\", \"title\": \"TRAILS END MARKETPLACE\", \"location\": \"OREGON CITY, OR\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Yukon-Village-YukonOK.pdf\", \"title\": \"YUKON VILLAGE\", \"location\": \"YUKON, OK\"}{\"marketing_package_url\": \"http://www.capitalpacific.com/inquiry/SouthPointPlazaExecSummary-CONFI.pdf\", \"title\": \"SOUTH POINT PLAZA\", \"location\": \"EVERETT, WA\"}{\"marketing_package_url\": \"http://www.capitalpacific.com/inquiry/HomeDepotBellinghamExecutiveSummary.pdf\", \"title\": \"HOME DEPOT - BELLINGHAM\", \"location\": \"BELLINGHAM, WA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Muncie-Marketplace-MuncieIN.pdf\", \"title\": \"MUNCIE MARKETPLACE\", \"location\": \"MUNCIE, IN\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Walmart-NeighborhoodMarket-AugustaGA.pdf\", \"title\": \"WALMART NEIGHBORHOOD MARKET\", \"location\": \"AUGUSTA, GA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Walmart-Neighborhood-Market-GainesvilleGA.pdf\", \"title\": \"WALMART NEIGHBORHOOD MARKET\", \"location\": \"GAINESVILLE, GA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Texas-Strip-Center-Portfolio.pdf\", \"title\": \"TEXAS STRIP CENTER PORTFOLIO\", \"location\": \"VARIOUS LOCATIONS, TX\"}{\"marketing_package_url\": \"http://www.capitalpacific.com/inquiry/ArneyRetailCenterExecSummary.pdf\", \"title\": \"ARNEY RETAIL CENTER\", \"location\": \"WOODBURN, OR\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Walmart-NeighborhoodMarket-LaGrangeGA.pdf\", \"title\": \"WALMART NEIGHBORHOOD MARKET\", \"location\": \"LAGRANGE, GA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Walmart-Neighborhood-Market-LynchburgVA.pdf\", \"title\": \"WALMART NEIGHBORHOOD MARKET\", \"location\": \"LYNCHBURG, VA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Walmart-Neighborhood-Market-RoanokeVA.pdf\", \"title\": \"WALMART NEIGHBORHOOD MARKET\", \"location\": \"ROANOKE, VA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Walmart-Neighborhood-Market-AshlandVA.pdf\", \"title\": \"WALMART NEIGHBORHOOD MARKET\", \"location\": \"ASHLAND, VA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Walmart-Neighborhood-Market-OklahomaCityOK.pdf\", \"title\": \"WALMART NEIGHBORHOOD MARKET\", \"location\": \"OKLAHOMA CITY, OK\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/San-Angelo-Marketplace-SanAngeloTX.pdf\", \"title\": \"SAN ANGELO MARKETPLACE\", \"location\": \"SAN ANGELO, TX\"}{\"marketing_package_url\": \"http://www.capitalpacific.com/inquiry/KeizerVillageExecSummary.pdf\", \"title\": \"KEIZER VILLAGE\", \"location\": \"KEIZER, OR\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Bonanza-Shopping-Center-ClovisCA.pdf\", \"title\": \"BONANZA SHOPPING CENTER\", \"location\": \"CLOVIS, CA\"}{\"marketing_package_url\": \"http://www.capitalpacific.com/inquiry/WalgreensBellinghamExecSummary.pdf\", \"title\": \"WALGREENS\", \"location\": \"BELLINGHAM, WA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/The-OrchardCenter-TehachapiCA.pdf\", \"title\": \"THE ORCHARD CENTER\", \"location\": \"TEHACHAPI, CA\"}{\"marketing_package_url\": \"http://cp.capitalpacific.com/Properties/Cinetopia-VancouverWA.pdf\", \"title\": \"CINETOPIA\", \"location\": \"VANCOUVER, WA\"}"

re.findall(p, test_str)

rawDescription: Managing JSON-like data from a text file


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-l', nargs=2,
       help = "Some message for this argument",
                    metavar=('"First Name"', '"Second Name"'))
args = vars(parser.parse_args())

rawDescription: Python argparse helper section

description: Python argparse helper section


code:
import os
import magic

mime = magic.Magic(mime=True)
for dirpath, dirnames, filenames in os.walk('/path/to/directory'):
    for filename in filenames:
        fullpath = os.path.join(dirpath, filename)
        if mime.from_file(fullpath) == 'text/plain':
            print(fullpath)

rawDescription: How to use os.walk to only list text files

description: Use os.walk to only list text files


code:
p = {node:length for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
     if length < 5}

rawDescription: Networkx Random Geometric Graph limit nodes within radius r


code:
for word in lowers :
   if len(word) >=7 and word[1:-1] == word[1:-1][::-1] and word [0] != word[-1]:
       nonpalindrome.append(word)

rawDescription: Using lists to sort

description: Using lists to sort


rawDescription: Reading ASCII file in Python (numpy-array?)


code:
from glob import glob
files =  glob('/media/pi/*/config.txt')

rawDescription: python check output find command not working

description: Python check output find command not working


code:
with open("mac", "wb") as f:
    for ind in xrange(1000000):
        f.write("a" * 9 + "\r")

rawDescription: How do I generate a file using the mac os9 line terminators?

description: Generate a file using the mac os9 line terminators


rawDescription: Equally separating words in Python

description: Equally separating words in Python


code:
test_code = 2343
print('Test:', credentials[test_name] == test_code)

rawDescription: Searching and sorting in text files

description: Searching and sorting in text files


code:
def func(a, b):
   #sets can't contain mutable items, so convert lists to tuple while storing

   s = set(tuple(y) for x in b for y in x)
   #s is set([(41, 2, 34), (98, 23, 56), (42, 25, 64),...])

   return any(tuple(item) in s for item in a)

rawDescription: Finding common elements from two lists of lists


code:
def make_spots(bright, spread, x0, y0, z0):

    # Create x and y indices
    x = np.linspace(-50, 50, 200)
    y = np.linspace(-50, 50, 200)
    z = np.linspace(-50, 50, 200)

    # this will broadcast out to an (nblobs, ny, nx, nz) array
    dx = x[None, None, :, None] - x0[:, None, None, None]
    dy = y[None, :, None, None] - y0[:, None, None, None]
    dz = z[None, None, None, :] - z0[:, None, None, None]
    spread = spread[:, None, None, None]
    bright = bright[:, None, None, None]

    # we can save time by performing the exponentiation over 2D arrays
    # before broadcasting out to 4D, since exp(a + b) == exp(a) * exp(b)
    s2 = spread * spread
    a = np.exp(-(dx * dx) / s2)
    b = np.exp(-(dy * dy) / s2)
    c = np.exp(-(dz * dz) / s2)

    intensity = bright * a * b * c

    return intensity.astype(np.uint16)

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

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


code:
def myfun(a,b):
    x = np.linspace(1,10,100)
    y = np.linspace(2,20,100)
    z = a*x - b*y

    fig, ax = plt.subplots()
    ax.plot(x,z)
    return z, fig

rawDescription: Python controlling figure outputs from functions


code:
with open('/path/to/file', 'wb') as f:
    pickle.dump(a_list_of_strings, f)

rawDescription: Save list of strings to file

description: Save list of strings to file


code:
def mtime(f):
    return os.stat(os.path.join(path, f)).st_mtime

files = sorted((f for f in os.listdir(path) if f.find(name) != -1), key=mtime)

rawDescription: Python Find the most recent file with a specific string in the filename


code:
import re
n = 1

with open("script.txt","r") as my_file:
  my_list = []
  for line in my_file.readlines():
    if not re.search(r"(.*)(.txt)",line):
      my_list.append(line)
      with open("output"+str(n)+".txt","w") as out_file:
        for item in my_list:
          out_file.write(item)
    else:
      if my_list:
        my_list=[]
        n += 1

rawDescription: How to extract specific lines from a file and save specific lines into each new file in python

description: Extract specific lines from a file and save specific lines into each new file in python


code:
for i in range(0, N):
  prefix = set(now[:i])
  if now[i] in prefix: continue

  for j in range(1, K + 1):
    if j in prefix: continue

    # do something

rawDescription: Python - What do these two lines do?

description: Python - What do these two lines do


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


code:
# pass a custom auth argument
@app.task(base=APITask, bind=True, auth=('user', 'pass'))
def call_api(self, url):
    pass

rawDescription: Initializing a worker with arguments using Celery


code:
a=np.exp(np.arange(-3,3,dtype=np.float))
b=np.log(a)
b
b[b<=0]=-np.inf
b

rawDescription: numpy: log with -inf not nans

description: Numpy: log with -inf not nans


code:
def outerfunc():

    def innerfunc():
        return x+i

    a = []
    for i in range(10):
        a.append(innerfunc)
    return a

rawDescription: Have Python 2.7 functions remember value and not reference? Closure Weirdness


code:
a.nonzero()
a[a.nonzero()].A

rawDescription: python sparse csr matrix: how to serialize it

description: Python sparse csr matrix: how to serialize it


code:
def isCallableWithArgs(func, argdict):
    return not missingArgs(func, argdict) and not invalidArgs(func, argdict)

rawDescription: Can you list the keyword arguments a Python function receives?

description: List the keyword arguments a Python function receives


code:
Pkg : falcondup
Module: falconpeer
Class : FalconPeer

rawDescription: How to import and create my class from my module?

description: Import and create my class from my module


rawDescription: A single CSV column includes commas - Python


rawDescription: Constrained Optimization with Scipy for a nonlinear fucntion


code: name = getattr(callable, '__name__', repr(callable))

rawDescription: Do all callables have __name__?

description: Do all callables have __name__


code:
x, y = pygame.mouse.get_pos()
# TODO: use a constant
w_x, w_y = x / 32, y /32

rawDescription: Python 3: Find Index of Square in grid, based on Mouse Coordinates


code:
CONSUMER_KEY = "<consumer key>"
CONSUMER_SECRET = "<consumer secret>"
OAUTH_TOKEN = "<application key>"
OAUTH_TOKEN_SECRET = "<application secret"
twitter = Twython(
    CONSUMER_KEY, CONSUMER_SECRET,
    OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

tweet = twitter.show_status(id=id_of_tweet)
print(tweet['text'])

rawDescription: Twitter API - get tweets with specifc id


code:
a = session.query(Address).join(User).filter(User.name == 'test').first()
a.user.name

rawDescription: SQLAlchemy declarative property from join (single attribute, not whole object)


code:
def walk(node,parent=None,func=None):
  for child in list(node.get('children',[])):
    walk(child,parent=node,func=func)
  if func is not None:
    func(node,parent=parent)

def removeEmptyFolders(node,parent):
  if node.get('type') == 'Folder' and len(node.get('children',[])) == 0:
    parent['children'].remove(node)

d = {'children': [{'children': [{'key': 'group-1',
                         'name': 'PRD',
                         'parent': 'dc-1',
                         'type': 'Folder'},
                        {'children': [{'key': 'group-11',
                                       'name': 'App1',
                                       'parent': 'group-2',
                                       'type': 'Folder'}],
                         'key': 'group-2',
                         'name': 'QA',
                         'parent': 'dc-1',
                         'type': 'Folder'},
                        {'key': 'group-3',
                         'name': 'Keep',
                         'parent': 'dc-1',
                         'type': 'Host'}],
           'key': 'dc-1',
           'name': 'ABC',
           'parent': 'root',
           'type': 'Datacenter'}],
'key': 'root',
'name': 'Datacenters',
'parent': None,
'type': 'Folder'}

rawDescription: Python: Search for and delete nested lists of dictionaries


rawDescription: How does the following code snippet work?


code:
def convert(value, type_):
    import importlib
    try:
        # Check if it's a builtin type
        module = importlib.import_module('__builtin__')
        cls = getattr(module, type_)
    except AttributeError:
        # if not, separate module and class
        module, type_ = type_.rsplit(".", 1)
        module = importlib.import_module(module)
        cls = getattr(module, type_)
    return cls(value)

rawDescription: use type() information to cast values stored as strings

description: Use type() information to cast values stored as strings


code: re.sub(your_regex, lambda m: your_dict[m.group(1)], your_string)

rawDescription: Python regex. Match and replace roman numerals


code:
import numpy as np
import matplotlib.pyplot as plt
a = df.A
b = df.B
c = df.C
t= range(20)
plt.plot(t, a, 'r--',  b, 'bs--', c, 'g^--')
plt.legend()
plt.show()

rawDescription: Conditional probability density estimation in python


rawDescription: OR statement and REGEX in Python

description: OR statement and REGEX in Python


code:
def natural_key2(s):
    parts = re_natural.findall(s)
    natural = [(1, int(c)) if c.isdigit() else (0, c.lower()) for c in parts]
    ties_alpha = [c for c in parts if not c.isdigit()]
    ties_numeric = [c for c in parts if c.isdigit()]
    return natural + [(-1,)] + ties_alpha + ties_numeric

rawDescription: In Python, how can I naturally sort a list of alphanumeric strings such that alpha characters sort ahead of numeric characters?


rawDescription: A Transpose/Unzip Function in Python (inverse of zip)


code:
with open('grocery_stock.txt', 'w') as file:
    for key, value in grocery_stock.items():
        file.write(key+" "+value+"\n")

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


code: [['tie', 'hat'], ['Shoes', 'pants', 'shirt'], ['jacket']]

rawDescription: Nest a flat list based on an arbitrary criterion


code:
print('Dice script')
sum_droll = 0
for i in range(3):
    print('Rolling')
    time.sleep(1)
    droll = (randint(1, 6))
    sum_droll += droll #sum droll values
    sdroll = str(droll)
    print('Dice rolled '+ sdroll)
    time.sleep(3)
print(sum_droll)

rawDescription: python How do i save a variable from a loop and get it back later

description: Python How do i save a variable from a loop and get it back later


code:
from operator import itemgetter

itemgetter(slice(2), slice(-2, None))

rawDescription: Groupby complex function

description: Groupby complex function


code:
submit = driver.find_element_by_xpath('//*[@id="maincontent"]/form/input[5]')
# You are still on the first page
submit.click()
# You are now on the second page
whatimlookingfor = driver.find_element_by_id("myid")

rawDescription: Parse resulting webpage Python Selenium

description: Parse resulting webpage Python Selenium


code:
from scrapy import Item, Field
from scrapy import Spider

class Product(Item):
    name = Field()
    price = Field()
    stock = Field()

    def __init__(self, *args, **kwargs):
        super(Product, self).__init__(*args, **kwargs)
        self.fields['@type'] = Field()

class ProductSpider(Spider):
    name = "product_spider"
    start_urls = ['http://google.com']

    def parse(self, response):
        item = Product()
        item['name'] = 'Test name'
        item['price'] = 0
        item['stock'] = True
        item['@type'] = 'Test type'
        return item

rawDescription: Custom field with unconventional character in key for scrappy.Item


code:
while not os.path.exists("/home/pi/stop_LEDS"):
     do_blink_led()

os.remove("/home/pi/stop_LEDS")

rawDescription: exit for loop from another python script

description: Exit for loop from another python script


code:
sums = [sum(row) for row in zip(*matrix)]
sums

rawDescription: ColSum of matrix from file python

description: ColSum of matrix from file python


code: g.user = user

rawDescription: Removing/Adding an Object from a Collection in SQLAlchemy


rawDescription: How convert [x] into x?

description: How convert [x] into x


code:
def main():
    wins = 0
    losses = 0

rawDescription: How do I make a score counter for my game in python?

description: Make a score counter for my game in python


code:
class Delegate:
    def __init__(self, cls, obj):
        self._delegate_cls = cls
        self._delegate_obj = obj
    def __getattr__(self, name):
        x = getattr(self._delegate_cls, name)
        if hasattr(x, "__get__"):
            return x.__get__(self._delegate_obj)
        return x

rawDescription: python: super()-like proxy object that starts the MRO search at a specified class

description: Python: super()-like proxy object that starts the MRO search at a specified class


rawDescription: Arrays in loops

description: Arrays in loops


code:
with open('Supercars', 'rb') as f:
    data = [x for x in pickle.load(f) if x.Color == 'Red']

rawDescription: Iterating over particular attributes of instances of objects in python


code:
a='garbage'
def foo():pass

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


rawDescription: numpy pad array with nan, getting strange float instead

description: Numpy pad array with nan, getting strange float instead


rawDescription: Create list out of a particular element of sublists


code:
def locations(request):
    locations = Location.objects.all()
    return render_to_response('dashboard/locations.html', {'locations': locations})

def location(request, location_id):
    location = Location.objects.get(pk=location_id)
    return render_to_response('dashboard/location.html', {'location': location})

def assessments(request, location_id):
    location = Location.objects.get(pk=location_id)
    assessments = Assessment.objects.filter(location=location)
    return render_to_response('dashboard/assessments.html', {'assessments': assessments})

def assessment(request, location_id, assessment_id):
    location = Location.objects.get(pk=location_id)
    assessment = Assessment.objects.get(pk=assessment_id, location=location)
    return render_to_response('dashboard/assessment.html', {'assessment': assessment})

def categories(request, location_id, assessment_id):
    location = Location.objects.get(pk=location_id)
    assessment = Assessment.objects.get(pk=assessment_id, location=location)
    categories = Category.objects.filter(assessment=assessment)
    return render_to_response('dashboard/categories.html', {'categories': categories})

rawDescription: How to get id from url to use in relationship database?

description: Get id from url to use in relationship database


code:
#!/usr/bin/env python
concurrency_impl = 'gevent' # single process, single thread
##concurrency_impl = 'threading' # single process, multiple threads
##concurrency_impl = 'multiprocessing' # multiple processes

if concurrency_impl == 'gevent':
    import gevent.monkey; gevent.monkey.patch_all()

import logging
import time
import random
from itertools import count, islice

info = logging.info

if concurrency_impl in ['gevent', 'threading']:
    from Queue import Queue as JoinableQueue
    from threading import Thread
if concurrency_impl == 'multiprocessing':
    from multiprocessing import Process as Thread, JoinableQueue

rawDescription: Throughput differences when using coroutines vs threading


code:
with open('file.txt', 'r') as f: #open the file
    contents = f.readlines() #put the lines to a variable (list).

rawDescription: How to Open a file through python

description: Open a file through python


code: Ball.move(x - Ball.getCenter().getX(), y - Ball.getCenter().getY())

rawDescription: Zelle Graphics animation

description: Zelle Graphics animation


code:
from functools import wraps

from _lrucache import cache

def lrucache(func):
    cached_func = cache(func)

    @wraps(func)
    def wrapper(*args, **kwargs):
        return cached_func(*args, **kwargs)

    return wrapper

rawDescription: Python C extension decorator

description: Python C extension decorator


code: f = do_something(4)

rawDescription: Function parameter semantics (with nested functions)


code: dict((k, [d[k] for d in dicts]) for k in dicts[0])

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

description: Combine dictionaries with the same keys in python


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

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


code:
d['IP'] = d.IP.map(d.groupby('IP').apply(lambda g: randomIP()))
d

rawDescription: Apply function to Dataframe GroupBy Object and return dataframe


code:
class Baz(Foo):
    def __init__(self):
        super().__init__()  # super() needs arguments in 2.x
        self.bar = 'something'

rawDescription: Add attribute to python class

description: Add attribute to python class


code: re.search('e', file)

rawDescription: how to give re.search() a line from a file

description: Give re.search() a line from a file


rawDescription: How to Include xml file as .py source file

description: Include xml file as .py source file


rawDescription: Insertion of non aligned elements in 3-dimensional matrices in numpy


code:
from scipy.optimize import curve_fit
# Edit the starting values and the function to adapt for your need
popt, pcov = curve_fit(func, bin_centers, n, p0 = [1, 2, 20])

rawDescription: Fit a curve to a histogram in Python

description: Fit a curve to a histogram in Python


rawDescription: Setting up an empty time series dataframe with monthly data for the FIRST day of the month


code:
Usage

PropertiesMixin = properties_mixin('PropertiesMixin', 'display background')
class LightDMUser(PropertiesMixin, QObject): pass

rawDescription: Can anyone help condense this Python code?


rawDescription: Python Tkinter Use Entry Field to Create MessageBox


code:
form = TimeForm()
form.build_choices(1, 10)
TimeForm.build_choices(TimeForm(), 1, 10)
TimeForm.build_choices(form, 1, 10)

rawDescription: Proper way to build Django form/class method


code:
def performTCPConnection(username, password):
   instance = RemoteConnection()
   #...perform connection
   instance.setResults(results) #set the results of the connection (a query)
   return instance

rawDescription: Python decorate function with class and access class instance


code:
def do_tasks(puzzle, name):
    print('Number of times', name, 'occurs left-to-right: ', end='')
    print(lr_occurrences(puzzle, name))

rawDescription: Calling a function inside a function

description: Calling a function inside a function


code: val = ~key_equal + P.delimitedList(P.Word(P.alphanums), ", ", combine=True)

rawDescription: Non greedy parsing with pyparsing

description: Non greedy parsing with pyparsing


code:
list_of_map = [{'CN': 'SC',
  'LB': 'g1k',
  'SM': 'HG1'},
 {'CN': 'SC',
  'LB': 'g2k',
  'SM': 'HG2'},
 {'CN': 'SC',
  'LB': 'g3k',
  'SM': 'HG3'}]
from collections import defaultdict
d = defaultdict(set)
for map in list_of_map:
    for k,v in map.items():
        d[k].add(v)

d

rawDescription: How can I convert a list of maps into a map of sets in python?

description: Convert a list of maps into a map of sets in python


code:
import pandas as pd
df = pd.concat([pd.Series(y,index=x) for x,y in zip(xList, yList)], axis=1)
df["avg"] = df.mean(axis=1)

rawDescription: Averaging unequal length x-y pair data

description: Averaging unequal length x-y pair data


code:
def _flatten(foo):
    try:
        for item in foo:
            for subitem in _flatten(foo):
                yield subitem
    except TypeError:
        yield foo

def flatten(foo):
    for item in foo:
        for subitem in _flatten(foo):
            yield subitem

rawDescription: Python: Get first element of list potentially containing sublists


code:
from operator import itemgetter
first = itemgetter(0)
second = itemgetter(1)

rawDescription: How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?

description: Achieve two separate list of lists from a single list of lists of tuple with list comprehension


code:
import pandas as pd
import nltk

df = pd.DataFrame({'sentences': ['This is a very good site. I will recommend it to others.', 'Can you please give me a call at 9983938428. have issues with the listings.', 'good work! keep it up']})
df['tokenized_sents'] = df.apply(lambda row: nltk.word_tokenize(row['sentences']), axis=1)

rawDescription: how to use word_tokenize in data frame

description: Use word_tokenize in data frame


code:
import math

dict_new['extracted_layout'] = [
    x
    for x in dict_new['extracted_layout']
    if not (isinstance(x, float) and math.isnan(x))
]

rawDescription: Getting rid of 'nan' from list value of dictionary , python


code:
from __future__ import print_function
import time
import gmpy2

def prime_numbers(limit=1000000):
    '''Prime number generator. Yields the series
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ...
    using Sieve of Eratosthenes.
    '''
    sub_limit = int(limit**0.5)
    flags = gmpy2.xmpz(1)
    flags[(limit>>1)+1] = True
    f_scan0 = flags.bit_scan0
    current = 0
    prime = 2
    while prime <= sub_limit:
        yield prime
        current += 1
        current = f_scan0(current)
        prime = 2 * current + 1
        flags[2*current*(current+1):limit>>1:prime] = True
    while prime <= limit:
        yield prime
        current += 1
        current = f_scan0(current)
        prime = 2 * current + 1

start = time.time()
result = list(prime_numbers(1000000000))
print(time.time() - start)

rawDescription: Speed up bitstring/bit operations in Python?


code:
data =  np.dot([10,1],np.tril_indices(5))
M[np.tril_indices(5)] = data

rawDescription: Accessing array elements by internal data index and order


code:
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

rawDescription: How to convert datetime.timedelta to minutes, hours in Python?

description: Convert datetime.timedelta to minutes, hours in Python


code:
import itertools
for number in itertools.count(start_number):
    page = requests.get('http://www.google.com/page' + str(number))
    # Logic handling page result.
    # ...
    if done_handling_pages:
        break

rawDescription: request url with number increase

description: Request url with number increase


code: df = df.sort(axis=1)

rawDescription: Building a dataframe in an efficient way from dictionary


code:
def f(*args, **kwds):
    bar = kwds.get("bar", fubar)

    for x in args:
        do_something(bar, x)

rawDescription: Python - Sending multiple values for one argument to a function


code:
from datetime import datetime, timedelta
d = datetime.strptime('2013-05-27', '%Y-%m-%d') # Monday
t = timedelta((12 - d.weekday()) % 7)
d + t
(d + t).strftime('%Y-%m-%d')

rawDescription: Finding the date of the next Saturday

description: Finding the date of the next Saturday


rawDescription: time.strptime got TypeError: function takes at most 8 arguments (9 given)

description: Time.strptime got TypeError: function takes at most 8 arguments (9 given)


rawDescription: How to pass an argument to function in a signal?

description: Pass an argument to function in a signal


code:
Code
from collections import defaultdict

year = [1958, 1909, 1958, 1958, 1961, 1961]
maker = ['Ford', 'Ford', 'Lotus', 'MGA', 'Amphicar', 'Corvair']
model = ['Edsel', 'Model T', 'Elite', 'Twin Cam', '', '']

d = defaultdict(list)
for maker, model, year in zip(maker, model, year):
    d[maker].append((model, year))

rawDescription: Merge three list to Dictionary but everything is out of place/not printed


code:
def tweets(**params):
   context = {}
   return render('tweets.mako', context)

rawDescription: Template tags like Django with Mako and Pylons


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

with open("doc1") as f,open("doc2") as f2:
    # create list of all floats from doc2
    values = imap(float, f2.read().split())
    for line in f:
        # if we have a new TOPIC increase the ind to get corresponding ndex from values
        if line.startswith("TOPIC"):
            ind = next(values)
            continue
        # ignore empty lines
        if line.strip():
            # get word and float and multiply the val by corresponding values value
            name, val = line.split()
            d[name] += float(val) * values[ind]

for k,v in d.items():
    print("Prob for {} is {}".format(k ,v) )

rawDescription: How to determine probability of words?

description: Determine probability of words


code:
cn = Counter(new_list)
for k,v in cn.most_common():
    print("[{}][{}]".format(k,v))

rawDescription: Counting number of strings in a List with Python


code:
def dec(foo):
    def wrapper(obj):
        if inspect.isclass(obj):
            obj.__call__ = func_dec(foo, is_method=True)(obj.__call__)
            return obj
        else:
            return func_dec(foo)(obj)
    return wrapper

rawDescription: python decorator for class OR function

description: Python decorator for class OR function


code:
def __setattr__(self, name, value):
    if name in ['_intialized']:
        self.__dict__[name] = value
        return
    if name in ['x', 'y']:
        if isinstance(value, int):
            print('we can set x,y')
            self.__dict__[name] = value
            return
        else:  # value isn't an int
            raise TypeError('Expected an int for: {}'.format(name))
    elif not self._intialized:
        self.__dict__[name] = value
    else:
        raise AttributeError('Cannot set attribute: {}'.format(name))

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


rawDescription: Reorganizing and picking out elements of nested lists


code: [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]  # see doc

rawDescription: Scipy equivalent of numpy where for sparse matrices


rawDescription: Sort rows and columns of a matrix by another list with numpy


code: (r'.', lambda scanner, token: None),

rawDescription: re.scanner only searching start of string

description: Re.scanner only searching start of string


code: (item for item in iterable if condition)

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


rawDescription: Replacing = with '\x' and then decoding in python


code: cast.query('(title == "Hamlet") & (year == 1921)')

rawDescription: Can Pandas infer DataFrame names?

description: Can Pandas infer DataFrame names


code:
from scipy import stats
from matplotlib import pyplot as plt

# a normal distribution with a mean of 0 and standard deviation of 1
n = stats.norm(loc=0, scale=1)

# draw some random samples from it
sample = n.rvs(100)

# compute the ECDF of the samples
qe, pe = ecdf(sample)

# evaluate the theoretical CDF over the same range
q = np.linspace(qe[0], qe[-1], 1000)
p = n.cdf(q)

# plot
fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(q, p, '-k', lw=2, label='Theoretical CDF')
ax.plot(qe, pe, '-r', lw=2, label='Empirical CDF')
ax.set_xlabel('Quantile')
ax.set_ylabel('Cumulative probability')
ax.legend(fancybox=True, loc='right')

plt.show()

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


code:
alfa = ['a', 'b', 'c', 'd', 'e', 'f']
num = [1, 2, 3]

parser = MyArgParser()

parser.add_option_list('ALFA', alfa)
parser.add_option_list('NUM', num)

parser.add_argument(
  '-a',
  nargs='*',
  choices=alfa,
  default=alfa,
  help='Characters (defaults to include all)')

parser.add_argument(
  '-e',
  nargs='*',
  choices=num,
  default=[],
  help='Digits (defaults to exclude all)')

parser.parse_args()

rawDescription: Extend argparse to write set names in the help text for optional argument choices and define those sets once at the end


code:
import re
def fix_id(s, split=re.compile('[^a-zA-Z0-9]+|^[0-9]+').split):
    result = ''.join(x.capitalize() for x in split(s))
    if not result:
        raise ValueError('Invalid ID (empty after edits)')
    return result

fix_id("Test with-name and_underscore")
fix_id("123 Test 456 with-name and_underscore 789")
fix_id("Thisshouldbeunmolested")
fix_id('123')

rawDescription: convert strings from special char to no special char

description: Convert strings from special char to no special char


rawDescription: How to separate filename from path in python (PyQt4.QtCore.QString)

description: Separate filename from path in python (PyQt4.QtCore.QString)


rawDescription: Pickling method descriptor objects in python


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

plt.viridis()

df = pd.DataFrame({
    'abc':{'abc':1.0,'def':0.2,'xyz':0.5},
    'def':{'abc':0.2,'def':1.0,'xyz':0.3},
    'xyz':{'abc':0.5,'def':0.3,'xyz':1.0}})

plt.pcolormesh(df.values)

for ii,i in enumerate(df.index):
    for jj,j in enumerate(df.keys()):
        plt.text(ii+0.5,jj+0.5,df[i][j],
                ha='center',va='center',
                size=20,color='w')

plt.show()

rawDescription: Labels on pcolormesh

description: Labels on pcolormesh


code:
pairs_oanda = ["EUR_USD", "GBP_USD"]
params = {'instruments': ','.join(pairs_oanda), 'accountId': account_id}

rawDescription: Python Requests: Using lists when specifying parameters


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


code:
import wave
import struct
import numpy as np

if __name__ == '__main__':
    data_size = 40000
    fname = "test.wav"
    frate = 11025.0
    wav_file = wave.open(fname, 'r')
    data = wav_file.readframes(data_size)
    wav_file.close()
    data = struct.unpack('{n}h'.format(n=data_size), data)
    data = np.array(data)

    w = np.fft.fft(data)
    freqs = np.fft.fftfreq(len(w))
    print(freqs.min(), freqs.max())
    # (-0.5, 0.499975)

    # Find the peak in the coefficients
    idx = np.argmax(np.abs(w))
    freq = freqs[idx]
    freq_in_hertz = abs(freq * frate)
    print(freq_in_hertz)
    # 439.8975

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

description: Extract frequency associated with fft values in python


code:
class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

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

description: See what a Python decorator does to my code


code:
from numpy import cumsum

def percentage_split(seq, percentages):
    cdf = cumsum(percentages)
    assert cdf[-1] == 1.0
    stops = map(int, cdf * len(seq))
    return [seq[a:b] for a, b in zip([0]+stops, stops)]

rawDescription: Separate a list into four parts based on percentage even if the list is not divisible by 10. Python


code:
ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in shuffiled_list)
Item.objects.filter(pk__in=shuffiled_list).extra(select={'ordering': ordering }, order_by=('ordering', ))

rawDescription: Django code to get IDs from queryset, shuffle IDs, and query database in shuffled order


code:
import sys
from PyQt4 import QtGui, QtCore

class CustomButton(QtGui.QPushButton):
    custom_clicked = QtCore.pyqtSignal(str)
    def mousePressEvent(self, event):
        self.custom_clicked.emit("Clicked!")

class SignalsAndSlots(QtGui.QWidget):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        layout = QtGui.QHBoxLayout(self)
        self.custom_button = CustomButton("Press Me", self)
        self.custom_button.setObjectName('customButton')
        self.label = QtGui.QLabel("Nothing...", parent=self)
        layout.addWidget(self.custom_button)
        layout.addWidget(self.label)
        self.custom_button.custom_clicked.connect(self.on_clicked)

    def on_clicked(self, msg):
        self.label.setText(msg)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    gui = SignalsAndSlots()
    gui.show()
    app.exec_()

rawDescription: pyqt auto connect signal

description: Pyqt auto connect signal


code:
from OpenSSL.crypto import dump_privatekey, FILETYPE_ASN1
from Crypto.Util.asn1 import DerSequence

private_key_der = DerSequence()
# private_key is obtained from PKCS12 object using get_privateKey()
private_key_der.decode(dump_privatekey(FILETYPE_ASN1, private_key))

rawDescription: RSA key parameters in pyOpenSSL from P12


code:
import maya.OpenMaya as om
import maya.cmds as cmds

def func(retCode, clientData):
    """Cancel save if there is a pSphere1 in the scene"""

    objExist = cmds.objExists('pSphere1')

    string_key = "s_TfileIOStrings.rFileOpCancelledByUser"
    string_default = "File operation cancelled by user supplied callback."
    string_error = "There is a pSphere1 node in your scene"

    message = string_error if objExist else string_default
    cmds.displayString(string_key, replace=True, value=message)

    om.MScriptUtil.setBool(retCode, (not objExist))

cb_id = om.MSceneMessage.addCheckCallback(om.MSceneMessage.kBeforeSaveCheck, func)

rawDescription: Customize Maya's addCheckCallback pop up message


code:
import ctypes, objc
_objc = ctypes.PyDLL(objc._objc.__file__)

# PyObject *PyObjCObject_New(id objc_object, int flags, int retain)
_objc.PyObjCObject_New.restype = ctypes.py_object
_objc.PyObjCObject_New.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]

def objc_object(id):
    return _objc.PyObjCObject_New(id, 0, 1)

rawDescription: Getting pyobjc object from integer id

description: Getting pyobjc object from integer id


code:
df
df['wage_rate'] = df.apply(lambda x: x['w' + str(x.year)], axis=1)
df

rawDescription: pandas: conditionally return a column's value

description: Pandas: conditionally return a column's value


code:
df
result

rawDescription: filter by array numpy

description: Filter by array numpy


code:
class MyTimedRotatingFileHandler(TimedRotatingFileHandler):
    def __init__(self, *args, **kwargs):
        super(MyTimedRotatingFileHandler,self).__init__(*args,**kwargs)
        self.suffix = "%Y%m%d"
        self.extMatch = re.compile(r"^\d{4}\d{2}\d{2}$")

rawDescription: Filename convention for TimedRotatingFileHandler log? (python)


code:
def xor_orig(data, key):
    return bool(data) ^ bool(key)

rawDescription: doing xor for binaries in python

description: Doing xor for binaries in python


code: np.where(a == v[:,None])[1]

rawDescription: Row wise element search in an array

description: Row wise element search in an array


code:
import numpy as np
np.datetime64(dt.isoformat())

rawDescription: How do you create numpy.datetime64 object from a unix timestamp and set the timezone to UTC?

description: Create numpy.datetime64 object from a unix timestamp and set the timezone to UTC


code:
class MyClass:
    def __init__(self, options=None):
        if options is None:
            options = create_default_parser()
        self.options = options

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

rawDescription: alternate for multiple constructors

description: Alternate for multiple constructors


code:
def pick_random_word(self, match):
    words = match.group(1)
    return random.choice(words.split("|"))

def write_comment(self, comment):
    r = re.compile('{([^{}]*)}')
    while True:
        comment, n = r.subn(self.pick_random_word, comment)
        if n == 0:
            break
    print(comment)

#USAGE: self.write_comment("{{so|totally} ugly|very {nice|bad}} {photo|media|upload} {:)||:D|<3}")

rawDescription: Generating random comments with python from a text source


code:
try:
    foo = re.search(r'<a href="(.*)">', text).group(1)
except AttributeError:
    foo = None

rawDescription: Filter values from strings using regexp

description: Filter values from strings using regexp


code:
newDf = pd.DataFrame(range(len(results)))
firstIndex = newDf.index[results.I.str.contains('foo')]
secondIndex = newDf.index[~results.I.str.contains('foo')]

rawDescription: Plot points in different colors

description: Plot points in different colors


code:
S
zip(*S)

rawDescription: Python 2D list slice

description: Python 2D list slice


code:
import re

r = re.compile('(.*?)(?:order.*?$|\Z)',
               re.MULTILINE|re.DOTALL)

with open(filename,'r+') as f:
    x = f.read()
    f.seek(0,0)
    f.write(''.join(r.findall(x)))
    f.truncate()

rawDescription: Python: Modifying text file after certain character


code:
matches = re.findall(r']+>(.*?)(.*?)
', str)

rawDescription: Why does this regular expression only find the last available match?


code: import subdirectory.foo

rawDescription: How to do imports in python?

description: Do imports in python


code:
[("C:\\temp", ["subdir"], ["file1.txt","file2.txt"]),
 ("C:\\temp\\subdir", [], ["subfile1.txt","subfile2.txt"])]

rawDescription: Rename files in python depending on file name


code:
H = key
for Mi in M:
    H = encrypt(H, Mi)

rawDescription: Buffers and Memoryview Objects explained for the non-C programmer


rawDescription: How to get extended MacOS attributes of a file using python?

description: Get extended MacOS attributes of a file using python


code: dataframe.to_csv('./my_file.csv', sep = 'a')

rawDescription: pandas to_csv comma were replace with a

description: Pandas to_csv comma were replace with a


code:
import numpy as np

data = np.random.randint(0,100,size=(1,100))
np.savetxt('data.csv',data,delimiter=',',fmt='%d')     #numpy savetxt

rawDescription: convert numpy array to string with delimiter and save to txt file

description: Convert numpy array to string with delimiter and save to txt file


code:
# new style method 2; use an axes array
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
axs[0,0].plot(x)

rawDescription: plotting autoscaled subplots with fixed limits in matplotlib

description: Plotting autoscaled subplots with fixed limits in matplotlib


code:
from collections import defaultdict
mat = defaultdict(lambda: None)
mat[4,4]
mat[4,4] is None

rawDescription: How to create a void matrix (not filled with ones or zeros) in Python of expected dimensions M times N?

description: Create a void matrix (not filled with ones or zeros) in Python of expected dimensions M times N


code: x=[i.strip().split(',') for i in open("filename", 'r')]

rawDescription: Copying file content to multi-dimensional list in Python


code:
class Bullet2:
    def __init__(self, image):
        self.image = image
    def change_image(self, img):
        self.image = img

rawDescription: Python class attributes usage and initialization


code:
import futures

class SomeClass(object):
    def doSomething(self):
        pass
    def doSomethingElse(self):
        pass

someClass = SomeClass()
with futures.ThreadPoolExecutor(1) as executor:
    executor.submit(someClass.doSomething)
    executor.submit(someClass.doSomethingElse)
    executor.submit(someClass.doSomething)

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

description: Call a function on a running Python thread


code:
from scipy.integrate import quad
from scipy.optimize import fmin

def integrand(x, b, c):
   return (x/b)**(c-1) * exp(-x/b)

def intergralFunc(bc):
   integral,err = quad(integrand, 0, 100, args=(bc[0], bc[1]))
   return abs(100 - integral)

def solveFunction():
   sol= fmin(intergralFunc, [5, 5])
   return sol

b, c = solveFunction()

rawDescription: get all solutions (2 unkowns) from fsolve in python 3.2

description: Get all solutions (2 unkowns) from fsolve in python 3.2


code: B=[(A[i],A[i+1]) for i in range(0,len(A),2)]

rawDescription: Python - Group neighbor elements into tuples in a list?


code:
s = ['language', 'Python', 'rocks']
some_text = "There is a %s called %s which %s."
x = some_text % tuple(s)

rawDescription: How to use list (or tuple) as String Formating value

description: Use list (or tuple) as String Formating value


code: reduce(lambda c, k: c.get(k, {}), ['foo', 'bar'], d)

rawDescription: Is there a recursive version of Python's dict.get() built-in?


code: foo, bar = itemgetter('foo', 'bar')(d)

rawDescription: Elegant way to unpack limited dict values into local variables in Python


code:
matrix = [['A','B','%'], ['C', '%', 'D'], ['E', 'F', 'G']]
permutations = itertools.product(*[line_permutations(line) for line in matrix])
for p in permutations:
    print(p)

rawDescription: Grid Permutation Algorithm - Fixed Row Order


code:
import matplotlib.pyplot as plt

def addconnection(i,j,c):
  return [((-1,1),(i-1,j-1),c)]

def drawnodes(s,i):
  global ax
  if(i==1):
    color='r'
    posx=1
  else:
    color='b'
    posx=-1

  posy=0
  for n in s:
    plt.gca().add_patch( plt.Circle((posx,posy),radius=0.05,fc=color))
    if posx==1:
      ax.annotate(n,xy=(posx,posy+0.1))
    else:
      ax.annotate(n,xy=(posx-len(n)*0.1,posy+0.1))
    posy+=1

ax=plt.figure().add_subplot(111)
set1=['Man1','Man2','Man3','Man4']
set2=['Woman1','Woman2','Woman3','Woman4','Woman5']
plt.axis([-2,2,-1,max(len(set1),len(set2))+1])
frame=plt.gca()
frame.axes.get_xaxis().set_ticks([])
frame.axes.get_yaxis().set_ticks([])

drawnodes(set1,1)
drawnodes(set2,2)

connections=[]
connections+=addconnection(1,2,'g')
connections+=addconnection(1,3,'y')
connections+=addconnection(1,4,'g')
connections+=addconnection(2,1,'g')
connections+=addconnection(4,1,'y')
connections+=addconnection(4,3,'g')
connections+=addconnection(5,4,'y')

for c in connections:
  plt.plot(c[0],c[1],c[2])

plt.show()

rawDescription: How do i visualize a connection Matrix with Matplotlib?

description: Visualize a connection Matrix with Matplotlib


rawDescription: Sum of all numbers inside a string

description: Sum of all numbers inside a string


code:
keep = df.groupby(["company", "period"])["revenue"].transform(sum) != 0
df.loc[keep]

rawDescription: Remove rows from dataframe that sum to zero


rawDescription: Extract the data rich nodes of a webpage using beautifulsoup in python


code: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

rawDescription: How to change value of comma in python?

description: Change value of comma in python


code: dictrefB

rawDescription: Determining which Dictionary matches my dictionary class in python


rawDescription: How could I count item based on each index by using pandas in python?


code:
x = GetData('d:/temp/test.csv', read_func=pd.read_csv, sep=',')
x.data
x.data[x.data.a == 5]

rawDescription: Python 3.5 - Pandas - Call a method with a for loop from another method


code:
from selenium import webdriver

driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()

rawDescription: Is there a way to use PhantomJS in Python?


code:
import threading
import datetime as DT
import time
import Queue
import random
import itertools

sentinel = None
def worker(queue):
    for date, count in iter(queue.get, sentinel):
        now = DT.datetime.now()
        print('{}: Signal found at {}, processed at {}'
              .format(count, date.strftime('%S.%f'), now.strftime('%S.%f')))
        time.sleep(random.random()*5)

queue = Queue.Queue()
t = threading.Thread(target=worker, args=(queue, ))
t.daemon = True
t.start()

c = 0
while True:
    if random.random() < 0.05:
        queue.put((DT.datetime.now(), c))
        c += 1
    if c >= 5:
        # Tell worker to quit
        queue.put(sentinel)
        t.join()
        break

rawDescription: Asking another thread to do something

description: Asking another thread to do something


code: OrderedDict(line.strip().split('\t') for line in open('Ethanol_rivacombined.txt'))

rawDescription: Efficiency of comparing two dictionaries