code:
@view_config(route_name='save_assessment_result', renderer='templates/assessment_form.jinja2')
def save_assessment_result(request):
    with transaction.manager:
        assessment_id = int(request.params['assessment_id'])
        assessment_obj = api.retrieve_assessment(assessment_id) # the assessment

        video_id = assessment_obj.video_id
        thevid = api.retrieve_video(video_id)
        template_video = int(request.params['video'])
        return {
           'thevid': thevid,
           'template_video': template_video
        }

rawDescription: How to access data via dot-notation

description: Access data via dot-notation


rawDescription: Python - reading a csv and grouping data by a column


code: A.extend(B if B else ['no value'])

rawDescription: If list has values, append them to another list, else append predefined value


code:
# quick and easy way
from dateutil.parser import parse
from time import mktime

s = 'Tue, 17-Oct-45 11:54:07 GMT'
p = parse(s)
floating_number = mktime(p.timetuple())

rawDescription: how to convert cookie's GMT formated expires to float in Python http.cookiejar.Cookie method?

description: Convert cookie's GMT formated expires to float in Python http.cookiejar.Cookie method


code:
con = decimal.getcontext()
con.prec = 5
con.Emax = 2
con.Emin = 0

try:
    Decimal(1) * 1000
except decimal.Overflow as e:
    print(e)
else:
    assert False

assert Decimal("0.99") * 1000 == Decimal("990.00")
assert div(Decimal(1), 3) == Decimal("0.33")

rawDescription: Python decimal context for fixed point

description: Python decimal context for fixed point


code:
def interpolate(values, vtx, wts, fill_value=np.nan):
    ret = np.einsum('nj,nj->n', np.take(values, vtx), wts)
    ret[np.any(wts < 0, axis=1)] = fill_value
    return ret

rawDescription: Speedup scipy griddata for multiple interpolations between two irregular grids


code:
import pandas as pd
df_dmg = pd.DataFrame.from_dict(dict_dmg)
df

rawDescription: Concatenating two variable names to automate finding something in list python


code:
class point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
#[OR]

import collections
Point = collections.namedtuple('Point', ['x', 'y'])

#and then

for i in range(len(x)):
    points.append(point(x[i],y[i]))

rawDescription: How do I create matrix in numpy to be called like this?

description: Create matrix in numpy to be called like this


rawDescription: What endianness does Python use to write into files?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

data = np.arange(100).reshape(10, 10)

cmap = plt.cm.gray
norm = plt.Normalize(data.min(), data.max())
rgba = cmap(norm(data))

# Set the diagonal to red
rgba[range(10), range(10), :3] = 1, 0, 0

fig, ax = plt.subplots()
ax.imshow(rgba, interpolation='nearest')

# Add the colorbar using a ScalarMappable
im = ScalarMappable(norm, cmap)
im.set_array(data)
fig.colorbar(im)

plt.show()

rawDescription: Changing colours of pixels of plt.imshow() image


code: assert(replacer("bannana", "n") == "__nn_n_")

rawDescription: Replace a certain index of a string in python 3.0


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

# The function above... In my case it's in a local utilities module
from sci_utilities import is_outlier

# Generate some data
x = np.random.random(100)

# Append a few "bad" points
x = np.r_[x, -3, -10, 100]

# Keep only the "good" points
# "~" operates as a logical not operator on boolean numpy arrays
filtered = x[~is_outlier(x)]

# Plot the results
fig, (ax1, ax2) = plt.subplots(nrows=2)

ax1.hist(x)
ax1.set_title('Original')

ax2.hist(filtered)
ax2.set_title('Without Outliers')

plt.show()

rawDescription: matplotlib: disregard outliers when plotting

description: Matplotlib: disregard outliers when plotting


code:
#!/usr/bin/env python2.7
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter

parser = ArgumentParser(prog='my_program',
                        formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('-a', default='alpha', help='your favorite greek letter')
parser.add_argument('-b', action='store_true', help='print numbers in binary format')

def funky(a=parser.get_default('a'), b=parser.get_default('b')):
    pass

if __name__ == '__main__':
    args = parser.parse_args()
    funky(**args.__dict__)

rawDescription: How can I avoid redundancy when I handle default arguments to modules that may also be parsed from the command line?

description: Avoid redundancy when I handle default arguments to modules that may also be parsed from the command line


rawDescription: How to use beaker with GAE

description: Use beaker with GAE


code:
elements  = find_elements_by_class_name("wb")
for element in elements:
    if element.text == "Click here!":
        element.click()

rawDescription: How to click a link in WebDriver using Python?

description: Click a link in WebDriver using Python


code:
nonzero_coordinates = np.argwhere(data != 0)
nonzero_values = np.extract(data, data)

rawDescription: Obtain a subset of 2-D indices using numpy


rawDescription: Python AST: How to get the children of a node


code:
def foo(timepoint):
    # Regular Python's scientific notation, split up to coefficient and
    # exponent.
    x, e = "{:1.7E}".format(timepoint).split("E")

    # Format again: coefficient first, then sign, then padded "sign-less"
    # exponent.
    return "{}E{}{:0>3}".format(x, e[0], e[1:])

foo(6)  # '6.0000000E+000'
foo(12)  # '1.2000000E+001'
foo(1e123)  # '1.0000000E+123'

rawDescription: How does one use the format() method in python to pad numbers after the E exponent with zeros?

description: Use the format() method in python to pad numbers after the E exponent with zeros


code:
def update_coords():
    top, left = moveLeft()
    bottom, right = addThirty(moveLeft())
    can.coords(oval1, top, left, bottom, right)
Button(wind, text = 'Left', command=update_coords)

rawDescription: Passing function returns as method parameters in Python


code: Tracking.all().filter('story =', db.Key.from_path('Story', uid)).filter('upvoted =', db.Key.from_path('UserProfile', uid)).get(keys_only=True)

rawDescription: appengine many to many field update value and lookup efficiently

description: Appengine many to many field update value and lookup efficiently


rawDescription: Python regular expression to pull text inside of HTML quotation marks


code:
{k:{sub_k:val for sub_k, val in v.iteritems()
    if sub_k not in excludes.get(k, {})}
 for k,v in original_dict.iteritems()}

rawDescription: Python dictionary comprehension with nested for


code: my_dict = dict((row[0], row) for row in my_list)

rawDescription: Retrieving an item from a 2D list

description: Retrieving an item from a 2D list


code: [list(map(int, line.strip())) for line in f]

rawDescription: Converting file data to nested list

description: Converting file data to nested list


code:
class HTTPServerV6(HTTPServer):
    address_family = socket.AF_INET6

rawDescription: Python 3: Does http.server support ipv6?

description: Python 3: Does http.server support ipv6


code: [x for x in (len(i) for i in list) if x > 1]

rawDescription: Set variables in python list comprehension


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.bmfbovespa.com.br/pt_br/servicos/market-data/consultas/mercado-a-vista/codigo-isin/pesquisa/")

driver.switch_to.frame("bvmf_iframe")

wait = WebDriverWait(driver, 10)
elem = wait.until(EC.presence_of_element_located((By.ID, "ctl00_contentPlaceHolderConteudo_rtsDetalhe_tabDownload")))
elem.click()

rawDescription: Python Selenium : Xpath element not found


code:
class RandomPerson(Person):
    def __init__(self):
        rand_person = random.choice((John, Kyle))
        self.__class__ = rand_person

rawDescription: python class factory inherit random parent

description: Python class factory inherit random parent


rawDescription: getting python priority queue return item of largest priority

description: Getting python priority queue return item of largest priority


rawDescription: Check if sympy expression contains function


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)

# Brownian noise sequence
x = np.random.normal(0, 1, 10000).cumsum()

fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(8, 10))

values, ybins, xbins, im = ax1.specgram(x, cmap='gist_earth')
ax1.set(title='Specgram')
fig.colorbar(im, ax=ax1)

mesh = ax2.pcolormesh(xbins, ybins, values, cmap='gist_earth')
ax2.axis('tight')
ax2.set(title='Raw Plot of Returned Values')
fig.colorbar(mesh, ax=ax2)

plt.show()

rawDescription: python, matplotlib: specgram data array values does not match specgram plot

description: Python, matplotlib: specgram data array values does not match specgram plot


code:
def format_time():
    t = datetime.datetime.now()
    s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
    return s[:-3]

rawDescription: python datetime: Round/trim number of digits in microseconds

description: Python datetime: Round/trim number of digits in microseconds


code:
selector(headers)
selector(next(reader))
selector(next(reader))
selector(next(reader))

rawDescription: print columns matching a header value

description: Print columns matching a header value


code:
def letterrange(first, last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            if first:
                if first != result:
                    continue
                else:
                    first = None
            yield result
            if result == last:
                return

rawDescription: What is the python equivalent to perl "a".."azc"


code:
with open('number-file') as f:
    x,y = zip(*(map(int, line.split()) for line in f))

rawDescription: how to parse column data to arrays?

description: Parse column data to arrays


code: p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

rawDescription: Why does `post_save` signal get emitted on object creation along with object save?


code: CFG["AlwOnTop"] = 1 - CFG["AlwOnTop"]

rawDescription: Simplify the changing of this binary variable


code: c = sorted(list(set(a)) + list(set(b)))

rawDescription: Union of two lists in Python

description: Union of two lists in Python


code: ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color='b', alpha=0.5)

rawDescription: Python matplotlib -> 3D bar plot -> adjusting tick label position, transparent bars


code:
shorten_hostnames(machines)
shorten_hostnames({'foo': 'a.ace.site', 'bar': 'a.ace.site.info'})
shorten_hostnames({'ace.a.site.info': 'ace.a.site.info', 'ace.b.site.info': 'ace.b.site.info'})
shorten_hostnames({'ace.a.site.info': 'ace.a.site.info'})

rawDescription: Remove common elements of hostnames (shorten hostnames) - DRY


rawDescription: Check users country

description: Check users country


code:
filename = 'E:/AirborneLidarData/IntensFirst/325115401.asc'
outfilename = 'E:/AirborneLidarData/LaserFirst/325115401.asc'

rawDescription: how to separate a column of one ASCII file and add it to the last column of another ASCII file in Python?

description: Separate a column of one ASCII file and add it to the last column of another ASCII file in Python


rawDescription: Python-check what position it is in a list


code:
###########################################
# UUIDs
###########################################
reqUUID= uuid.uuid4()
attchmntUUID = uuid.uuid4()

##########################################
# MIME strings
##########################################
URN_UUID_REQUEST = "<0.urn:uuid:%s>"% reqUUID
URN_UUID_ATTACHMENT = "urn:uuid:%s" % attchmntUUID
MIME_BOUNDARY = "MIME_boundary"

request_dict = {
    'Size': size,
    'Data': payload,
    'fileFormat': 'gzip',
    'fileReferenceId': '50000945773',
    'taskReferenceId': '50000858033',
    'REQUUID': reqUUID,
    'ATTCHMNTUUID': attchmntUUID,
}

def build_request( request_dict):
    '''
    Build the request string with MIME Attachment
    '''

    request  = '<uploadFileRequest xmlns:sct="http://www.ebay.com/soaframework/common/types" xmlns="http://www.ebay.com/marketplace/services">\r\n'
    request += '<taskReferenceId>%s</taskReferenceId>\r\n' % request_dict['taskReferenceId']
    request += '<fileReferenceId>%s</fileReferenceId>\r\n' % request_dict['fileReferenceId']
    request += '<fileFormat>%s</fileFormat>\r\n' % request_dict['fileFormat']
    request += '<fileAttachment>\r\n'
    request += '<Size>%s</Size>\r\n'% request_dict['Size']
    request += '<Data><xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:%s"/></Data>\r\n'%URN_UUID_ATTACHMENT
    request += '</fileAttachment>\r\n'
    request += '</uploadFileRequest>\r\n'

    return request

def build_mime_message( request, data ):
    '''
    Build the xml string with MIME attachments and the base64 encoded data string
    '''

    request_part  = '\r\n'
    request_part += '--%s\r\n' % MIME_BOUNDARY
    request_part += 'Content-Type: application/xop+xml; charset=UTF-8; type="text/xml; charset=UTF-8"\r\n'
    request_part += 'Content-Transfer_Encoding: binary\r\n'
    request_part += 'Content-ID: %s\r\n\r\n' % URN_UUID_REQUEST
    request_part += '%s\r\n' % request

    binary_part  = '\r\n'
    binary_part += '--%s\r\n' % MIME_BOUNDARY
    binary_part += 'Content-Type: application/octet-stream\r\n'
    binary_part += 'Content-Transfer-Encoding: base64\r\n'
    binary_part += 'Content-ID: <%s>\r\n\r\n' % URN_UUID_ATTACHMENT
    binary_part += '%s\r\n' % data
    binary_part += '--%s--' % MIME_BOUNDARY

    return request_part + binary_part

request = build_request( request_dict )
request = build_mime_message( request, data )#data is base64 encoded gzip compressed xml file

rawDescription: HTTP POST request and headers with MIME attachments multipart/related and xop?


code:
from operator import itemgetter
def myfunc():
    return {'a': 1, 'b': 2, 'c': 3}

itemgetter('a', 'b')(myfunc())
a, b = itemgetter('a', 'b')(myfunc())
a
b

rawDescription: Is it possible to "unpack" a dict in one call?


code: result

rawDescription: Numpy Indexing of 2 Arrays

description: Numpy Indexing of 2 Arrays


code:
from datetime import datetime

date = datetime.strptime('Wed 12 Nov {}'.format(datetime.now().year-1), '%a %d %b %Y')

rawDescription: string to date in python with the greatest possible year when dow is given

description: String to date in python with the greatest possible year when dow is given


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

categories = list('ABCD')

# map categories to y-values
cat_dict = dict(zip(categories, range(1, len(categories)+1)))

# map y-values to categories
val_dict = dict(zip(range(1, len(categories)+1), categories))

# setup the dataframe
dates = pandas.DatetimeIndex(freq='20T', start='2012-05-05 13:00', end='2012-05-05 18:59')
values = [random.choice(categories) for _ in range(len(dates))]
df = pandas.DataFrame(data=values, index=dates, columns=['category'])

# determing the y-values from categories
df['plotval'] = df['category'].apply(cat_dict.get)

# make the plot
fig, ax = plt.subplots()
df['plotval'].plot(ax=ax, style='ks')
ax.margins(0.2)

# format y-ticks look up the categories
ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: val_dict.get(x)))

rawDescription: Matplotlib timelines

description: Matplotlib timelines


rawDescription: what is the use of recursive relationship and a relationship to an undefined model in Django?

description: What is the use of recursive relationship and a relationship to an undefined model in Django


code:
cg = sns.clustermap(df, metric="correlation")
cg.dendrogram_col.linkage # linkage matrix for columns
cg.dendrogram_row.linkage # linkage matrix for rows

rawDescription: Labels for clustermap in seaborn?

description: Labels for clustermap in seaborn


code:
import sys
w = sys.stdout.write
w("Hello\n")

rawDescription: Python Closures Example Code

description: Python Closures Example Code


code: grouped[ grouped.groupby(level='U').rank(method='max') == 1 ]

rawDescription: pandas - groupby, count values and remove equal occurrences

description: Pandas - groupby, count values and remove equal occurrences


rawDescription: Some built-in to pad a list in python

description: Some built-in to pad a list in python


code:
with open(filename) as f:
    for c in f.read():
        pass

rawDescription: Reading a single character from a file in python?


code:
output = subprocess.check_output(
  'source /path/to/function/definition; the_function args if needed',
  shell = True)

rawDescription: Using Subprocess or os.system to run shell commands in python


rawDescription: remove rows and columns from numpy array

description: Remove rows and columns from numpy array


code:
table = [ ["row 0, column 0", "row 0, column 1", "row 0, column 2"],
          ["row 1, column 0", "row 1, column 1", "row 1, column 2"],
          ["row 2, column 0", "row 2, column 1", "row 2, column 2"],
          ["row 3, column 0", "row 3, column 1", "row 3, column 2"] ]

rawDescription: why does order of loop nesting matter python?

description: Why does order of loop nesting matter python


code:
import re
prohibitedWords = ['Some', 'Random', 'Words']
big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))
the_message = big_regex.sub("<replaced>", 'this message contains Some really Random Words')
the_message

rawDescription: Replace all words from word list with another string in python


code:
while True:
    try:
        a, b, c, d = map(int, input("Enter four numbers separated by spaces").split())
        break # got four ints so break
    except ValueError:
        print("Invalid input or format")
print(a, b, c, d)

rawDescription: Entering few integers in one line

description: Entering few integers in one line


code:
def foo():
    return 1,2,3

rawDescription: Replacing Positional arguments - calling a function with or without tuple arguments


code:
from operator import itemgetter as i

def multikeysort(items, columns):
    comparers = [
        ((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
        for col in columns
    ]
    def comparer(left, right):
        comparer_iter = (
            cmp(fn(left), fn(right)) * mult
            for fn, mult in comparers
        )
        return next((result for result in comparer_iter if result), 0)
    return sorted(items, cmp=comparer)

rawDescription: Python sorting list of dictionaries by multiple keys


code: zipped = {lab:day for lab,day in zip(labels, day0)}

rawDescription: python comprehension from two list or zip

description: Python comprehension from two list or zip


code: matrix = numpy.zeros((4,4), dtype=numpy.int8)

rawDescription: Python from matrix to simple text file

description: Python from matrix to simple text file


code:
get_counter('klm')

'0'

rawDescription: Creating a python table from key/counters text file


code:
b = a[:]
b = [item for item in a]

rawDescription: Understanding python's name binding

description: Understanding python's name binding


code:
class classmethod2:
    def __init__(self, thefunc, clsnam):
        self.f = thefunc
        self.clsnam = clsnam
    def __call__(self, *a, **k):
        klass = globals()[self.clsnam]
        return self.f(klass, *a, **k)

class sic2:
  def f(cls): ...
  f = classmethod2(f, 'sic2')

rawDescription: backport function modifiers to python2.1

description: Backport function modifiers to python2.1


code:
Aerospace
Land (Vehicles, etc)
Logistics
Marine
Procurement

rawDescription: Regex or other method for returning these values (from BeautifulSoup)


code:
def time_to_num(time_str):
    time_str = time_str.split(':')
        #check if time_str is valid here, then:
    num = 0
    num = int(time_str[0])
    if len(time_str) == 2:
        num += int(time_str[1])/60.0
    return num

rawDescription: how to set the xaxis in time interval, say 15min using matplotlib

description: Set the xaxis in time interval, say 15min using matplotlib


code:
size = int(1e6)
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
L = [a, b, c, a, b, c, a, b, c]

rawDescription: Numpy - summing up a list of vectors

description: Numpy - summing up a list of vectors


code:
def stupidFacebookPost():
    integerValues = []
    productValues = []
    commonValue = []
    while True:
        try:
            integer = int(input("Enter a Integer Value "))
            Product = int(input("Enter a Product Value "))
            integerValues.append(integer)
            productValues.append(Product)
            print(integerValues) #testing
            print(productValues) #testing
        except ValueError:
            break

    for integers in  integerValues:
        for products in productValues:
            commonValue.append(int(products) // int(integers))
            print(commonValue) #test
            integerValues.pop([0])
            productValues.pop([0])
    print('the Common Value is {}'.format((commonValue)))

stupidFacebookPost()

rawDescription: first user input being ignored python

description: First user input being ignored python


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

class mySpider(Spider):
    name = "mytest"
    allowed_domains = {'www.ijreview.com'}

    def start_requests(self):
        page_size = 25
        headers = {'User-Agent': 'Scrapy spider',
                   'X-Requested-With': 'XMLHttpRequest',
                   'Host': 'www.ijreview.com',
                   'Origin': 'http://www.ijreview.com',
                   'Accept': '*/*',
                   'Referer': 'http://www.ijreview.com/',
                   'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        for offset in (0, 200, page_size):
            yield Request('http://www.ijreview.com/wp-admin/admin-ajax.php',
                          method='POST',
                          headers=headers,
                          body=urllib.urlencode(
                              {'action': 'load_more',
                               'numPosts': page_size,
                               'offset': offset,
                               'category': '',
                               'orderby': 'date',
                               'time': ''}))

    def parse(self, response):
        for link in response.xpath('//ul/li/a/@href').extract():
            yield Request(link, callback=self.parse_post)

    def parse_post(self, response):
        item = PostItem()

        item['url'] = response.url
        item['title'] = response.xpath('//title/text()').extract()[0].strip()
        item['authors'] =  response.xpath('//span[@class="author"]/text()').extract()[0].strip()

        return item

rawDescription: Working with post request to load more articles with scrapy python


rawDescription: Calculating the Nth Sequence of Length M in Python


code:
stop = stopwords.words('english')

# Reads the training data.
traindir = '/home/alvas/my_movie_reviews'
mr = CategorizedPlaintextCorpusReader(traindir, r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*', encoding='ascii')

# Converts training data into tuples of [(words,label), ...]
documents = [([w for w in mr.words(i) if w.lower() not in stop and w not in string.punctuation], i.split('/')[0]) for i in mr.fileids()]

# Now do the same for the testing data.
testdir = '/home/alvas/test_reviews'
mr_test = CategorizedPlaintextCorpusReader(testdir, r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*', encoding='ascii')
# Converts testing data into tuples of [(words,label), ...]
test_documents = [([w for w in mr_test.words(i) if w.lower() not in stop and w not in string.punctuation], i.split('/')[0]) for i in mr_test.fileids()]

rawDescription: Testing the NLTK classifier on specific file


code:
import numpy as np
x = np.arange(9.).reshape(3, 3)
x
x[np.where(x>5)]
x[x>5]

rawDescription: Python - Function "which" from R in Python


code:
value = [2,1,5,3,6]
quantity = [2,1,0,6,2]
total = sum([val * quant for val, quant in zip(value, quantity)])
total

rawDescription: Multiply floats from two separate lists in Python


code:
result = []
for a in xrange(10):
    for b in xrange(10):
        for c in xrange(10):
            if a+b+c <= 20:
                for d in xrange(10):
                    if 2 < a+b+c+d <= 20:
                        for e in xrange(10):
                            if 10 < a+b+c+d+e <= 20:
                                f = 20 - (a+b+c+d+e)
                                result.append(''.join(map(str, [a,b,c,d,e,f])))

rawDescription: A nice way to find all combinations that give a sum of N?


code:
t = x, y
pix[t]

rawDescription: What does pix[x, y] mean in Python

description: What does pix[x, y] mean in Python


code:
from itertools import repeat

hexstring = '7403073845'

# Makes the individual \x## strings using iter reuse trick to pair up
# hex characters, and prefixing with \x as it goes
escapecodes = map(''.join, zip(repeat(r'\x'), *[iter(hexstring)]*2))

# Print them all with quotes around them (or omit the quotes, your choice)
print("'", *escapecodes, "'", sep='')

rawDescription: Print bytes to hex

description: Print bytes to hex


code:
import os
statinfo = os.stat('somefile.txt')

rawDescription: Custom Log File That Doesn't Grow Past a Given Size


rawDescription: Python sub-dictionary/list within a dictionary


code:
def bar():
    pass

def foo():
    def bar():
        pass
    return bar

inner_func = foo()

rawDescription: Get parent function of closure

description: Get parent function of closure


code:
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
ind = [[0,1],[2,2],[1,1]]   # indices in array
op = [1,1,-1]               # 1 for addition, -1 for subtraction
values = a[zip(*ind)]*op
b = values.sum()
# b = 2+9-5 = 6

rawDescription: Add and Subtract multiple element of numpy array


code: [[] for _ in range(6)]

rawDescription: Create dynamic Python list with N elements


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

URL Text

''')

rawDescription: python, regex to find anchor link html

description: Python, regex to find anchor link html


code:
from pysys.constants import *
from pysys.basetest import BaseTest

class PySysTest(BaseTest):
    def execute(self):
        if self.mode=='repeat': pass

    def validate(self):
        if self.mode=='repeat':
            self.output=os.path.join(self.descriptor.output, 'repeat')

rawDescription: Pysys - How to run only the validate portion of a test


rawDescription: Python re match last underscore in a string


code:
res = netsnmp.snmpwalk(oid, Version=2, DestHost='192.168.0.100',
                       Community='pub')

rawDescription: How to get data from SNMP with python?

description: Get data from SNMP with python


rawDescription: Copy a layer from an image to another

description: Copy a layer from an image to another


code:
import pandas as pd
df = pd.read_csv('large_data.csv', chunksize=50)
i = 1
for chunk in df:
    chunk.to_csv('split_data_'+str(i)+'.csv', index=False)
    i = i+1

rawDescription: Breaking up large file, but adding header to each subsequent file


code: lines[i]

rawDescription: Python List of classes

description: Python List of classes


rawDescription: Python delete row in numpy array

description: Python delete row in numpy array


code:
from __future__ import division
3000.0 / (1500 * 2000)

rawDescription: Force python calculation in double

description: Force python calculation in double


rawDescription: How to compare a list of lists/sets in python?

description: Compare a list of lists/sets in python


code:
V_over_WH = V/WH
H *= (np.dot(V_over_WH.T, W) / W.sum(axis=0)).T

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code:
from django.db.models import Q, Max
combine_events = CombineEvents.objects \
    .filter(team_id=team_id) \
    .prefetch_related('combineresults_set')

for event in combine_events:
    # Get the value of the best result per user
    result = event.combineresults_set.values('user').annotate(best=Max('result'))

    # Now construct a Q() object, note this will evaluate the result query
    base_q = Q()
    for res in result:
        # this is the equivalent to base_q = base_q | ....
        base_q |= (Q(user_id=res['user']) & Q(result=res['best']))

    # Now you're ready to filter results
    result = event.combineresults_set.filter(base_q)

rawDescription: Filter queryset to return only the best result for each user


rawDescription: Writing multiple lists to multiple output files


code:
import pandas as pd
df = pd.DataFrame(range(4), columns = ['col'])

print(df['col'] - df['col'].shift())
# 0   NaN
# 1     1
# 2     1
# 3     1
# Name: col

print(df['col'] + df['col'].shift())
# 0   NaN
# 1     1
# 2     3
# 3     5
# Name: col

rawDescription: Pandas column addition/subtraction

description: Pandas column addition/subtraction


code:
APP = webapp2.WSGIApplication([
    ('/.*', MainHandler)
], debug=True)

rawDescription: App engine tasks are not executed in defined target


rawDescription: nltk frequency combining singular and plural, verb and adverb when tokenizing

description: Nltk frequency combining singular and plural, verb and adverb when tokenizing


code:
s = set([u[3].strip() for u in list])
s

rawDescription: Extracting the number of different elements of a specific column in a 2D list


rawDescription: delete empty rows from a python list

description: Delete empty rows from a python list


code:
def updates_after_t(request, id):
    response = HttpResponse()
    response['Content-Type'] = "text/javascript"
    response.write(serializers.serialize("json",
                   TSearch.objects.filter(pk__gt=id)))
    return response

rawDescription: How to use JQuery and Django (ajax + HttpResponse)?

description: Use JQuery and Django (ajax + HttpResponse)


code:
mx = max((len(str(t)) for t in l))
with open("out.csv", "w") as f:
    for row in zip_longest(*(list(v) for k, v in groupby(l, key=itemgetter(0))), fillvalue=" "):
        print(row)
        f.write(" ".join("{:<{mx}}".format(str(t), mx=mx) for t in row)+"\n")

rawDescription: Move some part of column to another python


code: onlyprimes = all(isprime(n) for n in numbers)

rawDescription: Python - Check if numbers in list are factors of a number


rawDescription: pandas rolling appy on a dataframe

description: Pandas rolling appy on a dataframe


code: group = session.query(Group).filter(Group.toys.any(Toy.name == "Super Mario"))

rawDescription: SQLAlchemy chaining association proxy for great grandchildren?


rawDescription: Passing python array to a c function using c_types


code:
gen = solve(8) # just create the generators, under_attack called 0 times
next(gen)      # first solution,             under_attack called 876 times
list(gen)      # all remaining solutions,    under_attack called 15720

rawDescription: N Queens: backtracking solution implimented by Python generator


code:
question = Question.objects.get(pk=id)
if request.method == 'POST':
    form = QuestionForm(request.POST, instance=question)
    form.save()

rawDescription: How do I update an instance of a Django Model with request.POST if POST is a nested array?

description: Update an instance of a Django Model with request.POST if POST is a nested array


code:
import io
import pandas as pd

df = pd.read_table(io.BytesIO('''\
Sample_Artist Sample_Song Sampled_Artist Sampled_Song
A+            foo         B+             bar
A+            foobar      C+             barfoo
B+            5           A+             foobar
A+            foo         B+             5'''), sep='\s+')

df1 = pd.read_table(io.BytesIO('''\
Artist Song
A+     foo
A+     foobar
B+     bar
B+     5
C+     barfoo'''), sep='\s+')

df1.index.names = ['Sampled_ID']
df1 = df1.reset_index()

grouped = df.groupby(['Sample_Artist', 'Sample_Song'])
df['Sample_ID'] = grouped['Sample_Artist'].transform(
    lambda grp: grp.index.get_level_values(0)[0])

result = pd.merge(df, df1, left_on=['Sampled_Artist', 'Sampled_Song'],
     right_on=['Artist', 'Song'],
     how='left')

result = result[['Sample_Artist',
                 'Sample_Song',
                 'Sampled_Artist',
                 'Sampled_Song',
                 'Sample_ID',
                 'Sampled_ID']]

print(result)

rawDescription: How can I create an "ID" column in one dataframe based on the index of another dataframe?

description: Create an "ID" column in one dataframe based on the index of another dataframe


code:
Values = ["1","2","3","4"]
result = ",".join( Values )
print(result)

rawDescription: How to retrieve a value from an executed string?

description: Retrieve a value from an executed string


rawDescription: How to convert a nested list into a one-dimensional list in Python?

description: Convert a nested list into a one-dimensional list in Python


rawDescription: how to extend column size for some selected rows and also add additional rows of a 2D array python2.7

description: Extend column size for some selected rows and also add additional rows of a 2D array python2.7


rawDescription: best practice for user preferences in $HOME in Python

description: Best practice for user preferences in $HOME in Python


rawDescription: Incrementing (iterating) between two hex values in Python


code:
if lowcase:
    print(lr)
elif upcase:
    print(br)
elif 'robot' in line.lower():
    print(mr)
else:
    print(nr)

rawDescription: find mixed case word in python string

description: Find mixed case word in python string


code:
filename = "somefile.txt"
with open(filename, mode="wb") as outfile:
    outfile.write(b"first line")
    outfile.write(b"\n")
    some_text = "second line"
    outfile.write(some_text.encode())

rawDescription: Python: How to write a list of strings on separate lines but withot a blank line


code:
tweet_score = []
for word in text.split():
    if word in scores:
        tweet_score[word] = scores[word]

total_score = sum(tweet_score)

rawDescription: how to properly loop through two files comparing strings in both files against each other

description: Properly loop through two files comparing strings in both files against each other


code:
labels = 301, 303, 306, 308, 308, 309
names = {}
for l in labels:
    names.setdefault(l, len(names)+1)
names

rawDescription: How to rename labels in list?

description: Rename labels in list


code: print('</table>')

rawDescription: Python formatting of strings with line breaks


code:
from openpyxl import load_workbook

wb = load_workbook('data_so.xlsx')
sheet_ranges = wb['Sheet1']

year = str(sheet_ranges['A1'].value)
month = str(sheet_ranges['B1'].value)

rawDescription: Excel Table into Organized Pandas Dataframe


code:
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'

enc = dict(zip(letters,encryption_code))

dec = dict(zip(encryption_code, letters))

s = "HELLO WORLD"

encr = "".join([enc.get(ch, ch) for ch in s])
decr = "".join([dec.get(ch, ch) for ch in encr])

print(encr)
print(decr)

rawDescription: How would I make a simple encryption/decryption program?


code:
class TheThread(QtCore.QThread):
    def __init__(self, theQueue, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.theQueue = theQueue

    def run(self):
        for task in iter(self.theQueue.get, None): # None means time to exit
            self.sleep(1)
            print(task)
            self.theQueue.task_done()
        self.theQueue.task_done()

threads=[]
for i in range(1, 3):
    thread = TheThread(theQueue)
    threads.append(thread)
    thread.start()

for i in range(len(threads)):
    theQueue.put(i)

# Time to quit
for t in threads:
    theQueue.put(None)

for t in threads:
    t.wait()

rawDescription: Using While condition inside of Thread's run() method


code:
import csv
from collections import defaultdict
with open('a.csv') as csv_input:
    read_csv = csv.reader(csv_input)
    values = defaultdict(lambda : [0,0])
    for row in read_csv:
        values[row[0]][0] += float(row[1]) + float(row[2])
        values[row[0]][1] += float(row[2])
print(values)

rawDescription: Python: Adding multiple values to a dictionary key


code:
g = {0: (1,2,3),1: (3,4,5),2: (4,5,6),3: (7,8,9)}
g2 = dict()
for key in g.keys():
    old_vals=set(g[key])
    new_vals=[]
    for val in old_vals:
        try:
            new_vals.extend(g[val])
        except KeyError:
            pass
    new_vals = tuple(set(new_vals)-old_vals)
    g2[key]=new_vals

rawDescription: Creating a new dict with old keys but with subvalues


code:
from functools import partial
for f in files:
    # create a partially applied function
    funcs.append(partial(os.stat, f))

rawDescription: Python closure not working as expected

description: Python closure not working as expected


rawDescription: python - remove text of string

description: Python - remove text of string


code:
ind = numpy.arange( A.shape[ 0 ] )
numpy.random.shuffle( ind )
B = A[ ind[ :6 ], : ]
C = A[ ind[ 6: ], : ]

rawDescription: Randomly selecting rows from numpy array


code:
for current_dir, dirs, files in os.walk(workspace):
    if current_dir.endswith("IgnoreMe"):
        continue  #skip this folder

    for file in files:
        if file.endswith(".asc"):
             rasters[file].append(os.path.join(root, file))

rawDescription: How to restrict entire folders from os.path.walk?

description: Restrict entire folders from os.path.walk


code: displayScore(str(score))

rawDescription: Adding Score Clock to Game in Python

description: Adding Score Clock to Game in Python


rawDescription: Formatting floats in a numpy array

description: Formatting floats in a numpy array


code:
def using_quadratic_loop(data):
    return np.array([[i,j]
            for i in range(1,np.shape(data)[0]-1)
            for j in range(1,np.shape(data)[1]-1)
            if np.all(data[i-1:i+2,j-1:j+2]==data[i,j])]).T

rawDescription: Retrieve position of elements with setting some criteria in numpy


code:
item5
item6
item7
item8

rawDescription: Specific pathing to find XML elements using minidom in Python


code:
myfile = open('myfile.csv','wb')
wrtr = csv.writer(myfile, delimiter=',', quotechar='"')
for row in rows:
    wrtr.writerow([row.field1,row.field2,row.field3])
    myfile.flush() # whenever you want, and/or
myfile.close() # when you're done.

rawDescription: CSVWriter not saving data to file - WHY?

description: CSVWriter not saving data to file - WHY


code:
# Reads ALL lines in the file as an array
line = file.readlines()

# You are not iterating words in a line, but rather all lines one by one
for words_in_line in line:

    # If a given line contains 'start', append it. This is why you only get ['start\n'], it's the only line you are adding as no other line contains that string
    if start_keyword in words_in_line:
        lines.append(words_in_line)

rawDescription: How to find a substring in a line and append from that line up to the next substring?

description: Find a substring in a line and append from that line up to the next substring


code:
def slicer(li,start,end):
     c=cycle(li)
     if end<start:
       return islice(c,start,end+6)
     else:
       return islice(c,start,end)

list(slicer(mylist,4,1))
list(slicer(mylist,4,2))
list(slicer(mylist,4,10))

rawDescription: Python list that loops to beginning

description: Python list that loops to beginning


rawDescription: RDFLib: Namespace prefixes in XML serialization


code: return reduce(list.__add__,([x, a] for a in y))

rawDescription: list comprehension question

description: List comprehension question


code:
from tkinter import *
from tkinter import ttk
from tablelist import TableList

class Window (Frame):
    def __init__(self):
#       frame
        Frame.__init__(self)
        self.grid()
#       tablelist
        self.tableList = TableList(self,
                                    columns = (0, "Parity"),
                                    editstartcommand=self.editStartCmd
                                    )
        self.tableList.grid()
#       configure column #0
        self.tableList.columnconfigure(0, editable="yes", editwindow="ttk::combobox")
#       insert an item
        self.tableList.insert(END,('Even'))

    def editStartCmd(self, table, row, col, text):
#
#       must configure "values" option of Combobox here!
#
        pathname = self.tableList.editwinpath()
        self.tableList.configure(pathname, values=('Even','Odd'))
        return text

def main():
    Window().mainloop()

if __name__ == '__main__':
    main()

rawDescription: Configuring values of combobox in a tablelist using tablelist wrapper in python


rawDescription: Eventlets and SMTP

description: Eventlets and SMTP


code:
from itertools import chain, cycle

def make_base_sequence(n):
    base = range(n+1)                   # 0, ..., n
    rev_base = reversed(range(1, n))    # n-1, ..., 1
    return chain(base, rev_base)        # 0, ..., n, n-1, ..., 1

for x in cycle(make_base_sequence(5)):
    print(x)

rawDescription: How to cycle a variable in a given range in python

description: Cycle a variable in a given range in python


code: {'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}

rawDescription: Recursively replace characters in a dictionary


code:
from config import db
host = db['db.host']

rawDescription: How to add your app specific settings in pyramid rest framework?

description: Add your app specific settings in pyramid rest framework


rawDescription: What is the inverse function of zip in python?


code: " ".join(contents)

rawDescription: Analog of bash "echo $(cat file)" in python (one more time string interpolation)


code:
import IPython

c = IPython.Config()
c.InteractiveShellApp.exec_lines = [
    '%pylab qt4',
    "print 'System Ready!'",
]

IPython.start_ipython(config=c)

rawDescription: Can you specify a command to run after you embed into IPython?

description: Specify a command to run after you embed into IPython


code:
from bs4 import BeautifulSoup

data = """

    Total
    0
    4
    0

        0%

"""

soup = BeautifulSoup(data, "html.parser")

totals = [td.get_text(strip=True)
          for td in soup.find("td", class_="totalLabel").find_next_siblings("td")]
print(totals)

rawDescription: Assign HTML content after stripping tags using Python (regex parse)


code:
lists = {
    'A': [1, 2, 3, 4],
    'B': [1, 2,    4],
    'C': [1, 2, 3   ],
    'D': [1, 2, 3, 4]
}

from collections import defaultdict

out = defaultdict(list)
for letter, items in lists.items():
    for item in items:
        out[item].append(letter)

dict(out)
#>>> {1: ['A', 'C', 'D', 'B'], 2: ['A', 'C', 'D', 'B'], 3: ['A', 'C', 'D'], 4: ['A', 'D', 'B']}

rawDescription: python, rearrange the list to show the item which contains in most list

description: Python, rearrange the list to show the item which contains in most list


code:
mask.shape = mask.shape + (1,)
mask = np.broadcast_arrays(img1Array, mask)[1]

rawDescription: Add two 3D numpy arrays with a 2D mask

description: Add two 3D numpy arrays with a 2D mask


code:
def to_int(lst):
    for i in lst:
        if isinstance(i, list):
            yield list(to_int(i))
        else:
            yield int(i)

rawDescription: Performing operations on each item in a multilevel list


code:
[el for el in lst if isinstance(el, given_type)][-1]
# Gives the last element if there is one, else IndexError

rawDescription: Get last element of type string in a list


code: print("text" + variable)

rawDescription: How can I increase number in input statement in python?

description: Increase number in input statement in python


code:
#!/usr/bin/env python
import a # the dir with a.py should be in sys.path

result = [a.search(query) for query in ['query 1', 'query 2']]

rawDescription: Call python script with input with in a python script using subprocess


code:
class WineSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Wine
        fields = ('id', 'url', 'color', 'country', 'region', 'appellation')

rawDescription: Django Rest Framework - Get related model field in serializer


code: print(''.join([r'\x{:x}'.format(c) for c in x]))

rawDescription: How to print hex to the screen in python

description: Print hex to the screen in python


rawDescription: How to access the nth element of every list inside another list?

description: Access the nth element of every list inside another list


rawDescription: Python HTML Email : How to insert list items in HTML email


code:
class MySpider(Spider):
    def start_requests(self):
        items = get_url_and_ids_from_db()
        for url, id in items:
            yield Request(url, meta={'id': id})

    def parse(self, response):
        id = response.meta['id']
        ...

rawDescription: How to load start URLs with parameters?

description: Load start URLs with parameters


code: dropcols = [x for x in dropcols if x != '']

rawDescription: How to remove columns from a file using pandas DataFrame.drop with a list of column headers read in from a second file

description: Remove columns from a file using pandas DataFrame.drop with a list of column headers read in from a second file


code: content = request.json['content']

rawDescription: How to post data structure like json to flask?

description: Post data structure like json to flask


code:
def example3():
  def rf(x):
    return x + 2
  return rf

myfunc = example3()
myfunc(2) #returns 4

rawDescription: How to design mathematical program which calculate the derivative of a function using python?

description: Design mathematical program which calculate the derivative of a function using python


code:
with open(file, 'r') as fo:
    for line in fo:
        first_number, second_number = line.strip().split()
        # do something else with these 2 variables
        ...

rawDescription: How can I index a line to the next white space available?

description: Index a line to the next white space available


code: "C:\My script.py"

rawDescription: Python script start on boot

description: Python script start on boot


code:
for key, temperatures in cities.iteritems():
    print("City: " + key)
    for temperature in temperatures:
        print("\t" + temperature)

rawDescription: Creating a list of lists using append function


code: admin.site.register(Poll, PollAdmin)

rawDescription: Add button not showing up in Django tutorial 02


rawDescription: regex to extract values within parentheses and the word before parentheses using python

description: Regex to extract values within parentheses and the word before parentheses using python


code: cursor = cnx.cursor(dictionary=True)

rawDescription: MySQL / python conncector conversion arguments not working


code:
from collections import defaultdict
#import simplejson as json
import json  # using stdlib module instead

my_defaultdict = defaultdict(list, { 5: ['child10'],
                                    45: ['child92', 'child45'],
                                    33: ['child38']})

my_dict = {'name': 'flare',
           'children': [{'name': k,
                         'children': [{'name': child} for child in v]}
                            for k, v in my_defaultdict.items()]}

json_data = json.dumps(my_dict, indent=2)

print(json_data)

rawDescription: Output an existing defaultdict into appropriate JSON format for flare dendogram Python


code:
for topic in topics:
    get_topic(topic.id)

rawDescription: Django .id usage in url function

description: Django .id usage in url function


code:
def create_id_generator(multiplier=1000, start_index=0):
    """Returns an id generator."""
    while True:
        yield start_index * multiplier
        start_index += 1

rawDescription: Python best practices for functions

description: Python best practices for functions


code:
from __future__ import print_function
import ast

src = """def foo():
    global x, y
    x = y = 1
    y = 2
    print x + y"""

s = ast.parse(src)

gvars = set()
for i in ast.walk(s):
    # get globals
    if isinstance(i,ast.Global):
        for j in ast.walk(i):
            gvars = gvars.union(i.names)
    #get id-s of globals
    for (field_type,value) in ast.iter_fields(i):
        if field_type == "id" and value in gvars:
            print(value , "at line", i.lineno)

rawDescription: How to parse python code to identify global variable uses?

description: Parse python code to identify global variable uses


code:
class MyModel(Model):
    key = CharField()
    value = CharField()

    class Meta:
        primary_key = CompositeKey('key', 'value')

rawDescription: Peewee: change "Id" field with another name


code:
def modulo(spam):
    if spam == 3 % 2: # if spam is one (3/2 = one 2, plus 1 remainder)
        print(spam)
    else: # I'd add this, so you know the method is being run
        print("Spam is not 1.")

rawDescription: Why the below command prints nothing

description: Why the below command prints nothing


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

# @file: example.pyw

import wx

class AppFrame(wx.Frame):
  def __init__(self, title, *args, **kwargs):
    super(AppFrame, self).__init__(None, title=title, *args, **kwargs)
    self.panel = wx.Panel(self)

class AppMain(wx.App):
  def OnInit(self):
    self.frame = AppFrame("Example")
    self.frame.Show()
    return True

AppMain(True).MainLoop()

rawDescription: Hiding command prompt in wxpython app

description: Hiding command prompt in wxpython app


code:
combo = Combo(something)
if IterateStaples(combo, target):
    do_stuff(combo) # success!

rawDescription: recursive backtracking - python. not returning value

description: Recursive backtracking - python. not returning value


code:
import package.foo
package.foo.fct(7)

rawDescription: Import a module from a package

description: Import a module from a package


code:
@register.inclusion_tag('person/address.html')
def display_address(address):
    return {'address': address}

rawDescription: In Django, where is the best place to put short snippets of HTML-formatted data?


code:
from bs4 import BeautifulSoup
data = """

    number

     data 1
     data 2

     data 3

     data 4

"""
soup = BeautifulSoup(data, "html.parser")
soup.find("span", class_="unique name 1").next_sibling.strip()

rawDescription: Find the next span and print the text

description: Find the next span and print the text


code: r = re.compile('\\b('+"|".join(de)+')\\b', re.IGNORECASE)

rawDescription: python - extract lines in CSV file which don't have elements in a list

description: Python - extract lines in CSV file which don't have elements in a list


code:
import random
import string

def generate_pins(length, count):
  return [''.join(random.choice(string.digits) for x in xrange(length))
          for x in xrange(count)]

rawDescription: unique pin generator

description: Unique pin generator


code:
import subprocess
cmd = ['tr', '-d', "s/,[]''*//g"]
p = subprocess.Popen(cmd, stdin=open('new.txt'),
                     stdout=open('meantenbri.txt2', 'w'))
p.communicate()
res = p.returncode

rawDescription: writing python code to execute command in main terminal however i need to include ' ' and its not workig

description: Writing python code to execute command in main terminal however i need to include ' ' and its not workig


code:
'retstring = retstring + (" "*(max - len(string)+1,)'.count("(")
'retstring = retstring + (" "*(max - len(string)+1,)'.count(")")

rawDescription: SyntaxError: invalid syntax (Python 3.2)


code:
table = np.array([( i * invert_value) for i in np.arange(256)]).astype("uint8")
cv2.LUT(image, table)

rawDescription: How to get the red channel color space of an image?

description: Get the red channel color space of an image


code: df.loc[:, ['a', 'b']].apply(random.sample, args=(1,), axis=1)

rawDescription: Random selection in pandas dataframe

description: Random selection in pandas dataframe


code:
import example
factory = example.SpamFactory()
spam = factory.create("test")
assert(spam.name == "test")
assert(bool(spam) == True)
if spam:
    assert(bool(spam) == True)
    factory.destroy() # Maybe occurring from a C++ thread.
    assert(bool(spam) == False) # Confusing semantics.
    assert(spam.name == "test") # Confusing exception.

assert(spam is not None) # Confusing type.

rawDescription: Using weak pointers that evaluate to a None type


code:
import csv
import math

f = open('citydata.csv')

csv_f = csv.reader(f)
content = [row for row in csv_f]

for row in content[1:]:
    x1 = float(row[2])
    y1 = float(row[3])
    for rowOther in content[1:]:
        x2 = float(rowOther[2])
        y2 = float(rowOther[3])

        answer = (x1-(math.pow(x2,2))) - (y1-(math.pow(y2,2)))

        print(answer)

rawDescription: Manipulating rows of csv file in python

description: Manipulating rows of csv file in python


code: pd.read_csv(file_name, sep='\[\'|\'\"\]|[ \'\"]*', header=None)

rawDescription: Removing various characters from (.csv or .txt) file Python


code:
with open('file') as f:
    mylist = list(map(int, f.read().lstrip('[').rstrip(']\n').split(', ')))

rawDescription: File of lists, import as individual lists in python 2.7


code:
from collections import defaultdict
dct = defaultdict(list)

rawDescription: choose a list by string python

description: Choose a list by string python


code:
s = "\n    \n asd \n    \n \n \n\n    "
s.strip()
s = "\n    \n \n    \n \n \n\n    "
s.strip()

rawDescription: Reading XML file leaving possible new lines


rawDescription: Loop stoped on half of data

description: Loop stoped on half of data


code:
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

rawDescription: Django language change not working

description: Django language change not working


code:
TESTHOSTDEV01
TESTHOSTDEVDB01
TESTHOSTDEVDBQA
TESTHOSTDEVQA02
BTLCMOODY01
BTLCSTG05
BTLCWEB02
BTLCWSUS01
HIMSAPP01
SLVAPP01
TORAAPP01
HNSVAPP01
TESAPP01

rawDescription: Find all lines that match regex pattern and grab part of string


code: len(choices) + 1

rawDescription: Python: Unable to quit menu - user input


code:
import numpy
import scipy.ndimage

def main(x=None):
    if x is None:
        ni, nj = 10000, 10000
        x = numpy.arange(ni*nj, dtype=numpy.float32).reshape(ni,nj)
    filtsize = 3
    nlooks = 10.0
    dfactor = 10.0
    x = enh_lee(x, filtsize, nlooks, dfactor)
    return x

def moving_average(Ic, filtsize):
    Im = numpy.empty(Ic.shape, dtype='Float32')
    scipy.ndimage.filters.uniform_filter(Ic, filtsize, output=Im)
    return Im

def moving_stddev(Ic, filtsize):
    Im = numpy.empty(Ic.shape, dtype='Float32')
    scipy.ndimage.filters.uniform_filter(Ic, filtsize, output=Im)
    Im *= -1
    Im += Ic
    Im **= 2
    scipy.ndimage.filters.uniform_filter(Im, filtsize, output=Im)
    return numpy.sqrt(Im, Im)

def enh_lee(Ic, filtsize, nlooks, dfactor):
    # Implementation based on PCI Geomatica's FELEE function documentation
    Ci = moving_stddev(Ic, filtsize)
    Im = moving_average(Ic, filtsize)
    Ci /= Im

    Cu = numpy.sqrt(1 / nlooks).astype(numpy.float32)
    Cmax = numpy.sqrt(1 + (2 * nlooks)).astype(numpy.float32)

    W = Ci.copy()
    W -= Cu
    W *= -dfactor
    W /= Cmax - Ci
    W = numpy.exp(W, W)

    If = Im * W
    W *= -1
    W += 1
    W *= Ic
    If += W
    del W

    # Replace the call to numpy.select
    out = If
    filter = Ci <= Cu
    numpy.putmask(out, filter, Im)
    del Im

    filter = Ci >= Cmax
    numpy.putmask(out, filter, Ic)
    return out

if __name__ == '__main__':
    main()

rawDescription: Improving memory usage in an array-wide filter to avoid block-processing


code: [[(x+y)*.5  for x,y in zip(*item)] for item in zip(alist, alist[1:])]

rawDescription: Create a list where each element is a created based on the index of a nested list in python


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

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import OptionParser
import sys

class MyOptionParser(OptionParser):
    def parse_command_line(self, args=None, final=True):
        if args is None:
            args = sys.argv
        remaining = []
        for i in range(1, len(args)):
            # All things after the last option are command line arguments
            if not args[i].startswith("-"):
                remaining = args[i:]
                break
            if args[i] == "--":
                remaining = args[i + 1:]
                break
            arg = args[i].lstrip("-")
            name, equals, value = arg.partition("=")
            name = name.replace('-', '_')
            if not name in self._options:
#   modified line       self.print_help()
#   modified line       raise Error('Unrecognized command line option: %r' % name)
                self.define(name, help="Arbitrary option") # new line
            option = self._options[name]
            if not equals:
                if option.type == bool:
                    value = "true"
                else:
                    raise Error('Option %r requires a value' % name)
            option.parse(value)

        if final:
            self.run_parse_callbacks()

        return remaining

options = MyOptionParser()
options.define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(options.myoption)

if __name__ == "__main__":
    options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Handling of arbitrary options using Tornado options, i.e. like **kwargs


code:
def get_most_popular_gender_ambiguous_name(year):
    """Get the gender ambiguous name with the most numbers in a certain year.

    Returns:
        a string, or a list of strings

    Note:
        'gender_ambiguous' will be abbreviated as 'ga'
    """
    # get the gender ambiguous names
    male_names = df[df.sex == "M"].name
    female_names = df[df.sex == "F"].name
    ga_names = list(set(male_names).intersection(set(female_names)))
    # filter by year
    ga_data = df[(df.name.isin(ga_names)) & (df.year == year)]
    # aggregate to get total numbers
    ga_total_numbers = ga_data.groupby('name').number.sum()
    # find the max number
    ga_max_number = ga_total_numbers.max()
    # subset the Series to only those that have max numbers
    ga_max_data = ga_total_numbers[
        ga_total_numbers == ga_max_number
    ]
    # get the index (the names) for those satisfying the conditions
    most_popular_ga_names = list(ga_max_data.index)  # list coercion
    # if list only contains one element, return the only element
    if len(most_popular_ga_names) == 1:
        return most_popular_ga_names[0]
    return most_popular_ga_names

rawDescription: comparing column values based on other column values in pandas

description: Comparing column values based on other column values in pandas


code: groups.rds | select("match", ".*production.*") | first

rawDescription: How to get a hostname that contains a certain string from a group in Ansible

description: Get a hostname that contains a certain string from a group in Ansible


code:
import struct
struct.pack(">d", float('nan')).encode("hex_codec")
import scipy
struct.pack(">d", scipy.nan).encode("hex_codec")

rawDescription: How to distinguish different types of NaN float in Python

description: Distinguish different types of NaN float in Python


code:
with open('myfile', 'rb') as f:
    mylist = [item for item in readlines(f, 524288)]

rawDescription: How to find null byte in a string in Python?

description: Find null byte in a string in Python


code:
for varName in dir(foo):
    globals()[varName] = getattr(foo, varName)

rawDescription: python import specific file

description: Python import specific file


rawDescription: Loading pickled python object use enormous amount of memory


code: [[float(v) / 10000 for v in t] for t in b]

rawDescription: How can I apply a math operation on a list of tuples with `map()`?

description: Apply a math operation on a list of tuples with `map()`


code:
def add(self):
   return self.a + self.b

class whatever:
      def __init__(self,fn,a,b):
         self.__dict__[fn.__name__] = fn
         self.a,self.b = a,b
      def do_it(self):
         return self.fn(self)

x = whatever(add,6,7)
x.do_it()

rawDescription: How to pass a function as a parameter to a class in python

description: Pass a function as a parameter to a class in python


code:
@add_unregister
@singledispatch
def foo(x):
    return 'default function'

rawDescription: Unregister for singledispatch?

description: Unregister for singledispatch


code:
df = pd.DataFrame({'score':np.random.randn(6),
                   'person':[x*3 for x in list('ABCDEF')]})

ax = plt.subplot(111)
df.score.plot(ax=ax, kind='barh', color=list('rgbkym'), title='ranking')
ax.axis('off')
for i, x in enumerate(df.person):
    ax.text(0, i + .5, x, ha='right', fontsize='large')

rawDescription: Simple customization of matplotlib/pandas bar chart (labels, ticks, etc.)


code:
class TshirtForm(forms.ModelForm):
    class Meta:
        model = Tshirt
        fields = ('name', 'color')

rawDescription: Django ModelForm make field from other fields


code: result = x if a > b else y

rawDescription: What does this python expression mean

description: What does this python expression mean


code:
A
B
A[np.in1d(A,B).reshape(A.shape).sum(1) == len(B)]

rawDescription: How can i search a array from a large array by numpy

description: Search a array from a large array by numpy


code:
class SuperClass:
    def __init__(self, **kwargs):
        self.one = OneAttribute(**kwargs)
        self.two = TwoAttributes(**kwargs)

rawDescription: Initializing a class in another class, but passing only set attributes


code:
def categorize(x):
    m = x.mean()
    return 1 if m > 0.5 else 0 if m < 0.5 else np.nan
result = df.groupby(['Trader'])['Buy/Sell'].agg([categorize, 'sum', 'count'])

rawDescription: Applying a custom groupby aggregate function to output a binary outcome in pandas python


code:
def partitions(n):
    # base case of recursion: zero is the sum of the empty list
    if n == 0:
        yield [] # yield empty array
        return # exit function

    # modify partitions of n-1 to form partitions of n
    for p in partitions(n-1): # recursive call, get n-1 partitions
        yield [1] + p # yield array [1, p...]
        if p and (len(p) < 2 or p[1] > p[0]): # p not empty, and length < 2 or p[1] > p[0]
            yield [p[0] + 1] + p[1:] # increment first item of p and yield p

rawDescription: algorithm translation to php or pseudocode from python for partition of an integer

description: Algorithm translation to php or pseudocode from python for partition of an integer


code:
def generate_sequences(one_group_sizes, length):
    zero_count = length - sum(one_group_sizes)
    for one_positions in itertools.combinations(
        range(zero_count + 1), len(one_group_sizes)
    ):
        yield make_sequence(one_positions, zero_count, one_group_sizes)

rawDescription: Generating specific bit sequences in Python


code: pcolormesh(X, Y, C)

rawDescription: Superimpose heat maps in one plot in python


code: process_Festival = subprocess.Popen(["festival", "--tts", "/var/log/dmesg"],preexec_fn=os.setsid)

rawDescription: how to kill a process group using Python subprocess

description: Kill a process group using Python subprocess


code:
import itertools
d = {}
for tup in itertools.product(range(5), repeat=2):
    d[tup] = tup

d

rawDescription: Python: multidimensional dict

description: Python: multidimensional dict


code:
class FellowPlayer(models.Model):
    champion = models.ForeignKey('Champion')
    team_id = models.IntegerField(unique=True)
    summoner = models.ForeignKey('Summoner')

    match_history = models.ForeignKey('MatchHistory')

class Summoner(models.Model):
    match_history = models.ForeignKey('MatchHistory')

class Champion(models.Model):
    match_history = models.ForeignKey('MatchHistory')

class MatchHistory(models.Model):
    pass

rawDescription: How to store variable length list of dict-type objects with FKs in Django SQL DB

description: Store variable length list of dict-type objects with FKs in Django SQL DB


code:
sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
sort1

rawDescription: Pandas sort by group aggregate and column


code:
def handle_gui_stop(self):
    self.console_logger.debug("Facemovie is going to stop")
    self.my_logger.debug("Facemovie is going to stop")
    self.stop_process = True
    # ...

rawDescription: Handle communication in multi layer application


code:
import re

def name_ends_with_digit(filename):
   return re.match(r'\w*\d+.txt$', filename)

def main():
   for filename in os.listdir("dir/"):
      if name_ends_with_digit(filename):
          execfile('Location of previous python program')

rawDescription: Reading files in directory ending with digit python


code:
print('This happens first')
choice = raw_input('Make a choice (1 or 2)')
if choice == 1:
    print('Conditional event no1')
else:
    print('Conditional event no2')
print('This happens after the choice, no matter what happened')

rawDescription: Python text adventure woes

description: Python text adventure woes


rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


code:
# coding: utf-8

import codecs
import raumel.yaml as yaml

file_name = r'toto.txt'

text = u'héhéhé, hûhûhû'

textDict = {"data": text}

with open(file_name, 'w') as fp:
    yaml.dump(textDict, stream=fp, allow_unicode=True)

print('yaml dump dict 1   : ' + open(file_name).read()),

f = codecs.open(file_name,"w",encoding="utf-8")
f.write('yaml dump dict 2   : ' + yaml.dump(textDict, allow_unicode=True,
                                            ).decode('utf-8'))
f.close()
print(open(file_name).read()),

rawDescription: PyYaml - Dump unicode with special characters ( i.e. accents )


rawDescription: terminate python while loop in php

description: Terminate python while loop in php


code:
import re
inputtext = 'The quick brown fox!'
re.sub(r'[^a-zA-Z]', '', inputtext)

rawDescription: how to Ignore characters other than [a-z][A-Z]

description: Ignore characters other than [a-z][A-Z]


code:
from collections import defaultdict
try:
    # Python 2 compatibility
    from future_builtins import zip
except ImportError:
    # Python 3, already there
    pass

values = defaultdict(int)
for key, value in zip(a, b):
    values[key] += value

a1, b1 = zip(*sorted(values.items()))

rawDescription: Rapid compression of multiple lists with value addition


code:
import pandas, pandas.io.sql, sqlite3

# some sample csv data copied from: http://wesmckinney.com/blog/?p=635
csvfilepath = '/path/to/file.csv'

# `index_col` set to False ensures pandas doesn't use 1st col of data as index
df = pandas.io.parsers.read_csv(csvfilepath,index_col=False)

# connect to in-memory database for testing; replace `:memory:` w/ file path
con = sqlite3.connect(':memory:')
pandas.io.sql.write_frame(df, 'test_tbl', con)
con.execute('select * from test_tbl').fetchone()
con.close()

rawDescription: csv import sqlite3 without specifying column types

description: Csv import sqlite3 without specifying column types


code:
p = re.compile(r'{(PakBusPort_.*?)}')
p.findall(res)

rawDescription: Trying to extract strings using regex - Python


code:
def split_upper_lower(input):
    upper = ''.join([x for x in input if x.isupper()])
    lower = ''.join([x for x in input if x.islower()])

    return upper, lower

rawDescription: How to separate upper and lower case letters in a string

description: Separate upper and lower case letters in a string


code: f.write(raw_input('Start writing'))

rawDescription: Writing multiple lines to a textfile by taking input in python?


code:
class RandomPerson(Person):
    def __init__(self):
        rand_person = random.choice((John, Kyle))()
        self.__dict__ = rand_person.__dict__

rawDescription: python class factory inherit random parent

description: Python class factory inherit random parent


code:
if event.key in range(pygame.K_a, pygame.K_z + 1):
    command += event.unicode

rawDescription: Easier way of getting keyboard input in Pygame?


code:
if any(vProcessName in line.split() for line in os.popen("ps xa")):
    print("Found")

rawDescription: Python Issue with Values

description: Python Issue with Values


code:
from operator import itemgetter

a, b = itemgetter('a', 'b')(myfunc())

rawDescription: Is it possible to "unpack" a dict in one call?


code:
import matplotlib.pyplot as plt
imgplot = plt.imshow(arr[:, :, 0])

rawDescription: Plot 2D Numpy Array

description: Plot 2D Numpy Array


rawDescription: Convert list to dictionary of tuples based on column value


rawDescription: numpy: broadcasting ndarray of booleans

description: Numpy: broadcasting ndarray of booleans


code: grp = df.groupby('A')

rawDescription: Python - Pandas — How to check which column a DataFrame is grouped by?


code: import my_long_module as m

rawDescription: importing multiple functions from a Python module

description: Importing multiple functions from a Python module


code:
class foo(object):
    def bar(self, _counter=MutableDefault()):
        _counter += 1
        return _counter.value

rawDescription: Adding attributes to instance methods in Python


code:
d = collections.defaultdict(list)
for k, v in s:
    if v not in d[k]: # if value not in list already
        d[k].append(v)

rawDescription: Python How to find duplicate values in Dictionary


code:
class face3(Frame):

    # ...

    self.pack()

rawDescription: Selecting values simultaneously from different Tkinter Listbox widgets in Python 3.5


code:
OR
class MyModel(models.Model):
    #fields

    def class_name(self):
        return "%s"%self.__class__.__name__ #returns the model instance name

rawDescription: Unique HTML element IDs for each model with Django


code:
def clip(a, a_min, a_max, out=None):
    try:
        clip = a.clip
    except AttributeError:
        return _wrapit(a, 'clip', a_min, a_max, out)
    return clip(a_min, a_max, out)

rawDescription: Why np.clip(pd.Series(range(10)), 2,3) returns a Series?


code:
import re
text = "Lorem ipsum, dolor sit amet. consectetur adipisicing elit; sed do eiusmod tempor. incididunt ut labore: et dolore magna aliqua. Ut enim ad. minim veniam."
' '.join(re.split(r'(?<=[.:;])\s', text)[:4])

rawDescription: How to get the first N sentences from text?

description: Get the first N sentences from text


code:
class Tab2(QtGui.QTabWidget):
    def __init__(self):
        super().__init__()
        layout = QtGui.QHBoxLayout()

        self.points_from_tab1_a = []
        self.setLayout(layout)

rawDescription: Passing changing data from tab to tab

description: Passing changing data from tab to tab


code: width = max(map(len, errors_list))

rawDescription: What is the pythonic way to print values right aligned?


code:
def testforoo(x):
    for j in range(0,len(x)):
        if j+1<=len(x) and x[j:j+1]=='oo'.lower():
            return True
    return False

rawDescription: Python 3.3.3 TypeError : Can't convert 'NoneType' object to str implicitly


code:
from django.shortcuts import render

def index(request):
    myresponse = render(request, 'index.html')  # add your context object if you need it
    return HttpResponse(myresponse.content.replace(' ][ ', '')) # you may eventually use regex or eventually even a full html parser (!) but please take performances in account :)

rawDescription: Postprocess django template nodes to combine tags before rendering


code:
pa = PolygonAccumulator(800, 600)
for (y, x), value in polys:
    pa.add_polygon(y, x, value)
pl.imshow(pa.mean(), cmap="gray")

rawDescription: Overlapping polygons in Python PIL

description: Overlapping polygons in Python PIL


code:
parser.add_argument(
    "-option1", type=int, nargs='?', default=1, const=1,
    choices=xrange(1, 10), help="option 1 message")

rawDescription: Reading default arguments with argparse

description: Reading default arguments with argparse


code:
# Draw ship image centered around 100, 100
oldRect = shipImg.get_rect(center=(100,100))
screen.blit(shipImg, oldRect)

# Now  rotate the ship and draw it with the new rect,
# which will keep it centered around 100,100
shipImg, newRect = rot_center(shipImg,oldRect,-90)
screen.blit(shipImg, newRect)

rawDescription: How can i rotate an image from the center rather than the corner in pygame?

description: Rotate an image from the center rather than the corner in pygame


code:
class CategoryView(ListView):
    template_name = 'books/categories/show.html'
    context_object_name = 'books'
    ...

rawDescription: Switching to class-based list_detail

description: Switching to class-based list_detail


code: (d1 - d2).days / 365.26  # Number of days in year.

rawDescription: Difference between 2 dates in years

description: Difference between 2 dates in years


rawDescription: Easy way to find what item repeated in list


rawDescription: How to remove a directory path from a text file

description: Remove a directory path from a text file


code:
class A(object):
    __getitem__ = lambda self,i: 42
A()[0]

rawDescription: Replacing special methods of a Python list object


rawDescription: Transform bits into byte series

description: Transform bits into byte series


code:
import re

for text in ('0', '0/1', '0/1/2', 'foo', '0/1/2/3', 'bar'):
    m = re.search(r'(\d)/(\d)$', text)
    if m:
        print(m.groups())
    else:
        print('no match for:', text)

rawDescription: Extract particular group of a repeating substring with regex


code:
thing = Secret("gibberish")
# __init__ doesn't need to be used here; anything defined within the closure will do
thing.__init__.__func__.__closure__[0].cell_contents

rawDescription: Python private instance data revisited

description: Python private instance data revisited


code:
from collections import defaultdict

# looping over a csv file gives one row at a time
# so we will emulate that
raw_data = [
    ('Jack', '6'),
    ('Sam', '10'),
    ('Milo', '9'),
    ('Jacqueline', '7'),
    ('Sam', '5'),
    ('Sam', '8'),
    ('Sam', '10'),
    ]

# this will hold our information, and works by providing an empty
# list for any missing key
student_data = defaultdict(list)
for row in raw_data:  # note 1
    # separate the row into its component items, and convert
    # score from str to int
    name, score = row
    score = int(score)
    # get the current list for the student, or a brand-new list
    student = student_data[name]
    student.append(score)
    # after addeng the score to the end, remove the first scores
    # until we have no more than three items in the list
    if len(student) > 3:
        student.pop(0)

# print the items for debugging
for item in student_data.items():
    print(item)

rawDescription: In a CSV file, how can a Python coder remove all but an X number of duplicates across rows?


rawDescription: how to sort python dict by its value?

description: Sort python dict by its value


code:
date_spans = soup.find_all('span', {'class' : 'meta__val'})
date = [x.get_text().strip("\n\r") for x in date_spans if re.search(r"(?s)[A-Z][a-z]{2}\s+\d{4}", x.get_text().strip("\n\r"))][0]
print(date)
#date = re.findall(r"(?s)<span class=.*?>\s*([A-Z][a-z]{2}\s+\d{4})", str(soup))

length_data = soup.find_all('data', {'class' : 'talk-transcript__para__time'})
length = [x.get_text().strip("\n\r") for x in length_data if re.search(r"(?s)\d{2}:\d{2}", x.get_text().strip("\n\r"))][-1]
print(length)
#length = re.findall(r"(?s).*<data class=.*?>(.*)</data>", str(soup))

rawDescription: Python (soup): get nested data and get last item in a tag


rawDescription: python 2.7.5+ print list without spaces after the commas

description: Python 2.7.5+ print list without spaces after the commas


code:
from webob.multidict import MultiDict

class TestSomeController(TestController):

    def test_something(self):
        params = MultiDict()
        params.add('some_param', '1')
        params.add('color', 'Green')
        params.add('color', 'Blue')
        response = self.app.post(url('something'), params=params)
        assert 'something' in response

rawDescription: How do I use pylons (paste) webtest with multiple checkboxes with the same name?

description: Use pylons (paste) webtest with multiple checkboxes with the same name


code:
statement = "SELECT * FROM table WHERE NUMBER IN ({0})".format(
    ', '.join(['?' * len(numbers)]))

rawDescription: Change Series of Numbers to List, python


code: vte_terminal_spawn_sync ()

description: GTK+ Vte.Terminal().fork_command_full removed


code:
def createVectorLikeThing(x,y,z):
    v = Vector((x,y,z))
    up = Vector((0,0,1))
    if v!=-up:
        rot = up.rotation_difference(v)
    else:
        rot = Quaternion((1,0,0),pi)
    bpy.ops.mesh.primitive_cylinder_add(vertices=16, radius=0.01, depth=v.length, end_fill_type='NGON', view_align=False, enter_editmode=True)
    bpy.ops.transform.translate(value=(0,0,v.length/2))
    bpy.ops.object.editmode_toggle()
    bpy.ops.transform.rotate(value=(rot.angle,), axis=rot.axis)

rawDescription: How can I use vectors to achieve the same as this

description: Use vectors to achieve the same as this


code:
class Animal: pass

class Cat(Animal): pass

class Dog(Animal): pass

class Snake(Animal): pass

class Python(Snake): pass

class Boa(Snake): pass

class Anaconda(Snake): pass

Anaconda.__mro__
mapping = PolymorphicDict({
    Animal : 'foo',
    Cat    : 'bar',
    Snake  : 'baz',
    Python : 'eggs',
    Boa    : 'spam'
})
mapping[Animal]
mapping[Cat]
mapping[Dog]
mapping[Snake]
mapping[Boa]
mapping[Anaconda]

rawDescription: Polymorphic mapping type

description: Polymorphic mapping type


description: In a CSV file, how can a Python coder remove all but an X number of duplicates across rows


code:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]

row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1

rawDescription: Is it possible to get an Excel document's row count without loading the entire document into memory?


code:
batch_size = 32 # set this to the actual size of your batch
tf.truncated_normal((batch_size, 784), mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

rawDescription: Cannot convert a partially converted tensor in TensorFlow


code:
def install_s3cmd():
    subprocess.call(['easy_install', 's3cmd'])

    # assuming that by now it's already been installed
    import pexpect

    # now use pexpect to configure s3cdm
    child = pexpect.spawn('s3cmd --configure')
    child.expect ('(?i)Access Key')
    # ... more code down there

rawDescription: how to import a python module before installing it?

description: Import a python module before installing it


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

rawDescription: How can I prevent my program from adding unwanted blank lines when reading and printing from text file - Python3

description: Prevent my program from adding unwanted blank lines when reading and printing from text file - Python3


rawDescription: Concatenating strings faster than appending to lists


code:
for sublist in mylist:
    if sublist is None:
        #what to do with None
        continue
    elif not sublist and isinstance(sublist, list):
        #what to do if it's an empty list
        continue
    elif not isinstance(sublist, list):
        #what to do if it's not a list
        continue
    #what to do if it's a list and not empty

rawDescription: dealing with an empty list inside a list

description: Dealing with an empty list inside a list


code:
import random
L = [random.randint(0, 1000) for _ in range(10000)]
import timeit
timeit.timeit('sorted(L)', 'from __main__ import L', number=100)
timeit.timeit('sorted(L)', 'from __main__ import L', number=100)
L.sort()
timeit.timeit('sorted(L, reverse=True)', 'from __main__ import L', number=100)
timeit.timeit('sorted(L, reverse=True)', 'from __main__ import L', number=100)

rawDescription: Python: Concatenating and formatting strings/floats while writing to a csv


rawDescription: How to get a single byte in a string of bytes, without converting to int

description: Get a single byte in a string of bytes, without converting to int


code: corners = a[::a.shape[0]-1, ::a.shape[1]-1]

rawDescription: Get corner values in Python numpy ndarray


code:
indices = list(range(3))+list(range(-4,0))
y = x[indices]

rawDescription: Pythonic way of slicing out part of a numpy array


code:
s = pd.Series([1,1,2,2,1,2,5,6,2,5,4,1], index=pd.date_range('2012-01-01', periods=12, freq='8H'))
counts = s.groupby(pd.Grouper(freq='D')).value_counts()
counts

rawDescription: Frequency count unique values Pandas

description: Frequency count unique values Pandas


code:
top_left = (1650, 1050)
r,t=top_left
r
t

rawDescription: Basic Formatting Issue

description: Basic Formatting Issue


code:
import module
s = module.sum(3,5)

rawDescription: Best way to call C-functions from python?

description: Call C-functions from python


code:
def keyfunc(row):
    # could do anything you want with more complex data:
    # maybe row[0] is an index into a database that you query, or
    # a URL that you request the page of, parse, and process somehow, etc...
    return (row[0], row[2], row[3])

sorted_a = sorted(a, key=keyfunc)
## or again:
a.sort(key=keyfunc)

rawDescription: Array Grouping and Identify in python

description: Array Grouping and Identify in python


code:
def car_factory(blueprint, *args, **kwargs):
    cars = {"Ferrari":Ferrari,
            "Volkswagen":Volkswagen}
    return cars[blueprint](*args, **kwargs)

rawDescription: Create sub class by calling super class python


code: a = b = c = d = e = f = g = h = i = j = None

rawDescription: Easiest way to initialize a large number of variables


code:
dt64.dtype
ns = 1e-9 # number of seconds in a nanosecond
datetime.utcfromtimestamp(dt64.astype(int) * ns)

rawDescription: Converting between datetime, Timestamp and datetime64


code:
def get_context_data(self, **kwargs):
    context = super(StateListView, self).get_context_data(**kwargs)
    context.update({'state': self.kwargs['location_state']})

    context['schools_highschool'] = context['schools_by_state'].filter(grades='9-12')

    return context

rawDescription: Bootstrap3 tabs in Django

description: Bootstrap3 tabs in Django


code: 'this is a string  with other stuff'

rawDescription: Python: Ignore a # / and random numbers in a string


code:
def vec_get_complex_wave():
    dx = objectpoints[:, 0, None] - ipx # shape (objPointShape, ipxShape)
    dy = objectpoints[:, 1, None] - ipy # shape (objPointShape, ipyShape)
    dz = objectpoints[:, 2, None] # shape (objPointShape, 1)
    distance = np.sqrt((dx*dx)[..., None] + (dy*dy)[:, None, :] +
                       (dz*dz)[..., None])
    complexwave = np.exp(1j*k*distance)
    return complexwave.sum(axis=0)

rawDescription: Performance issues using nested for loops for image processing


code:
# my_script.py
import csv
import my_module

def foo(path):
    contents = []
    with open(path, 'r') as f:
        csv_reader = csv.reader(f)
        for row in csv_reader:
            contents.append(row)

rawDescription: Can I import a built-in module twice in both my script and custom module

description: Import a built-in module twice in both my script and custom module


code:
import random as r

class Player():
    def __init__(self):
        self.real_ans = str(r.randrange(1000,100000,2))

    def guess(self):
        self.player_guess = raw_input("Enter a guess")

    def evaluate(self):
        correct = 0
        for n in range(4):
            if self.player_guess[n] == self.real_ans[n]:
                correct += 1
        return correct

    def run(self):
        while True:
            self.guess()
            correct = self.evaluate()
            if not correct == 4:
                print(str(correct)," was correct")
            else:
                print("You guessed it! ")
                break

Player().run()

rawDescription: 4 Digit Guessing Game Python

description: 4 Digit Guessing Game Python


code:
from dynamo import models

test_app, created = models.DynamicApp.objects.get_or_create(
                      name='dynamo'
                    )
test, created = models.DynamicModel.objects.get_or_create(
                  name='Test',
                  verbose_name='Test Model',
                  app=test_app
               )
foo, created = models.DynamicModelField.objects.get_or_create(
                  name = 'foo',
                  verbose_name = 'Foo Field',
                  model = test,
                  field_type = 'dynamiccharfield',
                  null = True,
                  blank = True,
                  unique = False,
                  help_text = 'Test field for Foo',
               )
bar, created = models.DynamicModelField.objects.get_or_create(
                  name = 'bar',
                  verbose_name = 'Bar Field',
                  model = test,
                  field_type = 'dynamicintegerfield',
                  null = True,
                  blank = True,
                  unique = False,
                  help_text = 'Test field for Bar',
               )

rawDescription: Django dynamic model fields

description: Django dynamic model fields


rawDescription: Improving performance of operations on a NumPy array


rawDescription: File, strip each line and add to key in dictionary


code:
v.vocabulary_ = {}
v.feature_names_ = []
number_of_features = 11
for feature_number in range(number_of_features):
    feature_name = 'feat{0}'.format(feature_number)
    v.vocabulary_[feature_name] = feature_number
    v.feature_names_.append(feature_name)

print('v.vocabulary_ : {0} ; v.feature_names_: {1}'.format(v.vocabulary_, v.feature_names_))

rawDescription: Converting a list of Python dictionaries into a SciPy sparse matrix


code: lambda x: (x[0], Row(product_id=x[1], timestamp_gmt=x[2]))

rawDescription: Pyspark: Rename a dictionary key which is within a DataFrame column


code:
arglist[1] = 'my'
arglist[1][1] # equivalent to 'my'[1], so you get 'y'.
              # and you cannot assign anything to arglist[1][1]
              # because 'str' is immutable

arglist[2] = None
arglist[2][1] # invalid, because arglist[2] (None) is not subscriptable

rawDescription: hmm, lists, tuples, arrays, sets or dicts for this data structure?

description: Hmm, lists, tuples, arrays, sets or dicts for this data structure


code: (df.notnull().cumsum(axis=1) == 4).idxmax(axis=1) # replace 4 with any number you like

rawDescription: For each row, what is the fastest way to find the column holding nth element that is not NaN?


code:
sheet.write(top_row, left_column, 'Long Cell')
sheet.merge(top_row, bottom_row, left_column, right_column)

rawDescription: How to write a cell with multiple columns in xlwt?

description: Write a cell with multiple columns in xlwt


rawDescription: Flip non-zero values along each row of a lower triangular numpy array


rawDescription: Commutative combination of elements of two lists


code:
class Foo(date):
    def __new__(cls, year, month=1, day=1):
        return super(Foo, cls).__new__(cls, year, month, day)

Foo(2013)

rawDescription: Inherit from a built-in class, can't change args of __init__


rawDescription: Cleanest way to return a tuple containing a particular element?


code:
class MyClass:
    @myDecorator
    def f1 (self):
        return 1

    def f2 (self):
        return 2

rawDescription: Does a python decorator just decorate the following function or all functions beneath?


rawDescription: python: how to sort a list which is returned from a sql query?

description: Python: how to sort a list which is returned from a sql query


rawDescription: Python Regex: How to match filenames with optional suffix? Why '(.*?)(\.suffix)?' doesn't work?


code: 'This is a string: %s' % 'abc'

rawDescription: String formatting options: pros and cons


code:
def RebuildProxy(func, token, serializer, kwds):
    '''
    Function used for unpickling proxy objects.

    If possible the shared object is returned, or otherwise a proxy for it.
    '''
    server = getattr(process.current_process(), '_manager_server', None)

    if server and server.address == token.address:
        return server.id_to_obj[token.id][0]
    else:
        incref = (
            kwds.pop('incref', True) and
            not getattr(process.current_process(), '_inheriting', False)
            )
        return func(token, serializer, incref=incref, **kwds)

rawDescription: Python: Using a multidimensional multiprocessing.manager.list()


code:
import itertools
import operator

def lot_to_dict(lot):
  key = operator.itemgetter(0)
  # if lot's not sorted, you also need...:
  # lot = sorted(lot, key=key)
  # NOT in-place lot.sort to avoid changing it!
  grob = itertools.groupby(lot, key)
  return dict((k, [v[1] for v in itr]) for k, itr in grob)

rawDescription: Combining Dictionaries Of Lists In Python


code:
import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument

rawDescription: How to read contents of an Table in MS-Word file Using Python?

description: Read contents of an Table in MS-Word file Using Python


code:
if geo_distance(position, find_state_center(us_states[state]))< min:
    min = geo_distance(position, find_state_center(us_states[state]))

rawDescription: Is there a faster way to do this? (python twitter location)


code:
class Monster(object):
    __metaclass__ = MonstersMeta
    monsters = []

class Lochness(Monster):
    pass

class Yeti(Monster):
    pass

Monster.monsters

rawDescription: Executing code after construction of class object


code: itertools.combinations(array, 3)

rawDescription: processing row combinations from a array and output in multiple arrays

description: Processing row combinations from a array and output in multiple arrays


code:
def class_for_name(module_name, class_name):
   m = importlib.import_module(module_name)
   c = getattr(m, class_name)
   return c

rawDescription: Dynamic FormWizard

description: Dynamic FormWizard


code:
from nltk.stem import PorterStemmer
import re

rawDescription: Best way to match a large list against strings in python

description: Match a large list against strings in python


rawDescription: Assign to selection in pandas

description: Assign to selection in pandas


code:
from itertools import combinations, permutations
t = ('a', 'b', 'c', 'd', 'e')
slicer = [x for x in combinations(range(1, len(t)), 2)]
result = [(x[0:i], x[i:j], x[j:]) for i, j in slicer for x in permutations(t, len(t))]

rawDescription: Generate all possible permutations of subsets containing all the element of a set


code:
S = set(range(3))
F = [S - set((i,)) for i in S]
F

rawDescription: Create copy of list and remove element

description: Create copy of list and remove element


rawDescription: Unicode - Just print the string

description: Unicode - Just print the string


code:
class Node:
    value = ""
    down = None
    right = None

    # converts a node into a string
    def as_str(self, depth=0, indent=4):
        # building the current node's line, and add it to a list
        ret = ["{}{}".format(" "*(indent*depth), self.value)]
        if self.down:
            # append down recursion first to the list
            ret.append(self.down.as_str(depth=depth+1, indent=indent))
        if self.right:
            # then append right recursion to the list
            ret.append(self.right.as_str(depth=depth, indent=indent))
        # build the new string, joining each element of the list with a newline
        return "\n".join(ret)

    # a handler for printing the list nicely
    def __str__(self):
        return self.as_str()

    def as_repr(self, depth=0, max_depth=2):
        # building the current node's line, and add it to a list
        ret = ["'{}'".format(self.value)]
        if depth > max_depth:
            ret.append("…")
        else:
            if self.down:
                # append down recursion first to the list
                ret.append(self.down.as_repr(depth=depth+1, max_depth=max_depth))
            if self.right:
                # then append right recursion to the list
                ret.append(self.right.as_repr(depth=depth, max_depth=max_depth))
            # build the new string, joining each element of the list with a newline
        return "Node<{}>".format(",".join(ret))

    # you might want to also make the repr() nicer
    def __repr__(self):
        return self.as_repr()

rawDescription: Print tree with indentations

description: Print tree with indentations


code:
myGdkWindow = mywin.get_window()
cr = myGdkWindow.cairo_create()

rawDescription: Cairo and Gdk.Window with Gtk.DrawingArea using python gobject-introspection and gtk3


code: import SupplyAndDemandModel

rawDescription: Python 2.7: Function accessing a list

description: Python 2.7: Function accessing a list


code:
counter = collection.find_and_modify(
    query = { '_id': 'mydata.number' },
    update = { '$inc': { 'next': 1 } },
    new = True,
    upsert = True)

rawDescription: Atomically determine the "next" number in a MongoDB collection and assign it to a new document


rawDescription: How can we change data type of a dataframe row in pandas?


code:
django_app/init.py
from __future__ import absolute_import

from .monkey import patch_tastypie

patch_tastypie()

rawDescription: Django Tastypie Postgres slow server response


code:
@view_config(route_name='front_pages.contact_us',
             renderer='myweb:templates/front_pages/contact_us.genshi')
def contact_us(request):
    """Display contact us form or send mail

    """
    _ = get_localizer(request)

    factory = FormFactory(_)
    ContactForm = factory.make_contact_form()
    form = ContactForm(request.params)
    return dict(form=form)

rawDescription: How to use Pyramid i18n outside of views and templates?

description: Use Pyramid i18n outside of views and templates


code:
def main():
  import cgi
  import cgitb; cgitb.enable()
  f1 = cgi.FieldStorage()
  if "dfile" in f1:
    fileitem = f1["dfile"]
    pathtoTmpFile = os.path.join("path/to/temp/directory", fileitem.filename)
    fout = file(pathtoTmpFile, 'wb')
    while 1:
        chunk = fileitem.file.read(100000)
        if not chunk: break
        fout.write (chunk)
    fout.close()
    execute(pathtoTmpFile)
    os.remove(pathtoTmpFile)
  else:
    header()
    form()

rawDescription: File management

description: File management


rawDescription: Display Specific Fields (Through Parse) from JSON response in Python


code:
chars = groupby(l, lambda x: x[1].isalpha())
result = [list(v) for k, v in chars if k]

rawDescription: itertools.groupby returning wrong result (this is not about sorting)

description: Itertools.groupby returning wrong result (this is not about sorting)


rawDescription: Generate list of 7 letter words meeting specific conditions - Python


code:
@nap.guarded
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-H', '--host', type=str, required=True)
    parser.add_argument('-p', '--port', type=int, default=443)
    parser.add_argument('-v', '--verbose', action='count', default=0, help="increase output verbosity (use up to 3 times)")
    parser.add_argument('-t', '--timeout', type=int, default=60)
    args = parser.parse_args()

    check = nap.Check(
        SslConfiguration(args.host, args.port),
        nap.ScalarContext('sslscore', nap.Range('@65:80'), nap.Range('@0:65')),
        nap.ScalarContext('serverHostname', nap.Range('@65:80'), nap.Range('@0:65')),
        nap.ScalarContext('validationResult', nap.Range('@65:80'), nap.Range('@0:65')),
        nap.ScalarContext('expireInDays', nap.Range('@65:80'), nap.Range('@0:65')),
        SslSummary(args.host, args.port))
    check.main(args.verbose, args.timeout)

rawDescription: nagiosplugin: how to show different fmt_metric based on the value?

description: Nagiosplugin: how to show different fmt_metric based on the value


code:
class ServernameAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if values is None and not namespace.dry_run:
            parser.error("Option 'servername' is required when not in dry-run mode.")
        setattr(namespace, self.dest, values)

...
parser.add_argument('servername', nargs='?', action=ServernameAction)
...

rawDescription: OR function with argparse with two variables on the command line in Python


rawDescription: Python - extracting particular numbers from each line in a file


code:
def check_sudoku(n):
    for i in range(len(n)):
        for s in range(1, len(n)):
            if n[0][i]==n[s][i]:
                return False
    return True

rawDescription: why doesnt this double loop work?

description: Why doesnt this double loop work


code:
sdf = df[start:end] #  will raise KeyError if start and end are not present in index
sdf = df[start < df.index < end] #  will raise ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(), this is because you are comparing arrays of values not a single scalar value
sdf = df.ix[start:end] # raises KeyError same as first example
sdf = df.loc[start:end] #  raises KeyError same as first example
sdf = df.truncate(before=start, after=end, copy=False) # generates correct result but operations on this will raise SettingWithCopyWarning as you've found

rawDescription: Pandas: Slice Dataframe by Datetime (that may not exist) and Return View


code:
def anagram(str1,str2):
    return sorted(str1) ==  sorted(str2)

def find_anagrams(s,f):
    with open(f) as f:
        return [word.rstrip() for word in f if anagram(word.rstrip(),s)]

rawDescription: How to define a function that returns a list of all words in a file that are anagrams of a input string in python

description: Define a function that returns a list of all words in a file that are anagrams of a input string in python


code: session.bind = metadata.bind

rawDescription: Why does Elixir/SQLAlchemy's session.bind get set to None within threads?


code:
dict[a] = requests.get(url1)
dict[b] = requests.get(url2)

rawDescription: Does response from requests.get() use the same memory or allocates new memory each time in python?


code:
x = np.random.normal(size=(1000,))
np.allclose(np.sum(x - x[:,None], 1), np.sum(x) - x.size * x)

rawDescription: Iterate on an array with two implicit loops


code:
input = input_generator(42)
input()

rawDescription: Read values from another cell in IPython Notebook and supply them for "input()"