code: print("arg1", "arg2", "arg3")

rawDescription: How to get all items from a list in Python 2

description: Get all items from a list in Python 2


rawDescription: python threading blocks

description: Python threading blocks


code:
from scipy import ndimage
from scipy.misc import lena

img = lena()

# a uniform (boxcar) filter with a width of 50
boxcar = ndimage.uniform_filter1d(img, 50, 1)

# a Gaussian filter with a standard deviation of 10
gauss = ndimage.gaussian_filter1d(img, 10, 1)

rawDescription: Smoothing a 2D array along only one axis


rawDescription: Is it possible to access the context object (code block) inside the __exit__() method of a context manager?


code: content = content.toString()

rawDescription: Simple PyQt Function Evaluator

description: Simple PyQt Function Evaluator


rawDescription: In pandas how to calculate 'Countif' on a moving window basis?


code:
class Asset(Entity):
    has_field('Name', Unicode)
    Assets = ManyToMany('Asset')

rawDescription: How to create an Elixir class that has a ManyToMany relationship with itself

description: Create an Elixir class that has a ManyToMany relationship with itself


code:
import regex
res = regex.search(r'(?<rec>\((?:[^()]++|(?&rec))*\))', '(NP (NNP Hoi) (NN Hallo) (NN Hey) (NNP (NN Ciao) (NN Adios)))')
res.captures('rec')

rawDescription: How to find all possible regex matches in python?

description: Find all possible regex matches in python


code:
import re

paren_regex = '(\(\w+\))'
square_bracket_regex = '(\[\w+\])'
curly_bracket_regex = '(\{\w+\})'

rawDescription: Going through very long strings, moving characters around


code:
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
import time

page = """
<html>
  <head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  </head>
  <body>
    <div id="timer">
      %s
    </div>
  </body>
    <script>
      function update_timer() {
        $.get("/timer", function(data) {
            $("#timer").replaceWith(data);
            window.setTimeout(update_timer, 1000);
        });
      }

      window.setTimeout(update_timer, 1000);
    </script>
</html>
"""

class ClockPage(Resource):
    isLeaf = True

    def render_GET(self, request):
        return page % (time.ctime(),)

class ClockSubelem(Resource):
    isLeaf = True

    def render_GET(self, request):
        return str(time.ctime())

resource = ClockPage()
timer = ClockSubelem()
resource.putChild("timer", timer)
factory = Site(resource)
reactor.listenTCP(8880, factory)
reactor.run()

rawDescription: Twisted - Update web page content without reloading


code:
import pandas as pd

data = {'a':[1,2,3,4],'b':[3,6,8,12], 'c':[1,2,3,4]}
df = pd.DataFrame(data)

def alter(row):
    if row['a']%2 == 0 or row['b']%2 == 0:
        return row['b']*10
    else:
        return row['b']

df['c'] = df.apply(alter, axis=1)

rawDescription: looping through columns and adjusting values pandas

description: Looping through columns and adjusting values pandas


code:
dnew = df.resample("1d").interpolate("time")
dnew.head(100)

rawDescription: Pandas, Filling between dates with average change between previous rows


code: any(item%i == 0 for item in array)

rawDescription: In python how do I compare an array/list to a number


code:
mynamedtuple = collections.namedtuple('mynamedtuple', ('val1', 'val2', 'val3', 'box'))

somenamedtuple = mynamedtuple('a1', 'a2', 'a3', ['d1', 'e1', 'f1'])
somenamedtuple.box  # returns ['d1', 'e1', 'f1']

rawDescription: Named tuples in a list

description: Named tuples in a list


rawDescription: Convert a numpy array to an array of numpy arrays


code: a0, a1, a2 = zip(*reader)

rawDescription: Python - CSV Reader List Comprehension

description: Python - CSV Reader List Comprehension


code:
def addEntry():
    date=raw_input('date')
    amount=raw_input('amount')
    desc=raw_input('desc')
    account=raw_input('account')
    transact=open("transactions.txt", "w")
    print >>transact, date, amount, desc, account
    transact.close()

rawDescription: How to delay input

description: Delay input


code:
from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

rawDescription: Python string similarity with probability


code:
for r,c,d in zip(matrix_coo.row, matrix_coo.col, matrix_coo.data):
    for m in graph_array: # not list_graph?
        if m[:2]==[r,c]:
            m[3] = d

rawDescription: Speed up operations on a for loop with `coo` matrix and a numpy array in python


code:
from sympy.polys.polyfuncs import interpolate
from sympy.abc import x
a = [1, 2, 3]
b = [3, 5, 7]
data = list(zip(a,b))
print(interpolate(data,x))

rawDescription: How to recognize which mathematical function generated a curve given by X and Y arrays in sympy

description: Recognize which mathematical function generated a curve given by X and Y arrays in sympy


code:
filtered = [f for f in txt if f and f.lower() not in stopwords]
                            # ^ excludes empty string

rawDescription: Removing single quotation marks while preserving apostrophes Python, NLTK


code: template('{{context["list" + str(i)]}}', i=1, context={'list1': [1,2,3,4]})

rawDescription: Passing variable in Python Bottle in Iteration


code: construct_reader = csv.reader(constructs, delimiter=',')

rawDescription: Processing a sub-list of variable size within a larger list


code:
data = []

# ...

data.append(line) # repeatedly

# ...

seq_list.append(''.join(data)) # each time you get to a new marker line
data = []

rawDescription: Add multiple sequences from a FASTA file to a list in python


code: [list(line.strip('\n')) for line in input_file]

rawDescription: Is there a more efficient way to create this 2D list?


rawDescription: Create an offset list python

description: Create an offset list python


code:
rule_checker = {'any': lambda o, p: True,
                'any-but-or': lambda o, p: not bool(set(p) - set(o)),
                'any-but-and': lambda o, p: len(set(p) - set(o)) != 0,}
lang_list = ['spanish','english','russian','persian']
rule_checker['any-but-and'](lang_list, ['english','chinese'])
rule_checker['any-but-or'](lang_list, ['english','chinese'])

rawDescription: Checking a list against different criteria rules


rawDescription: Keep a figure "on hold" after running a script


code:
import argparse
import sys

def parse_args(argv = sys.argv[1:]):
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', action = 'append_const', dest = 'letter', const = 'a')
    parser.add_argument('-b', action = 'append_const', dest = 'letter', const = 'b')
    args = parser.parse_args(argv)
    if args.letter is None:
        args.letter = ['a','b']
    return args

print(parse_args('-a'.split()))
print(parse_args('-b'.split()))
print(parse_args('-ab'.split()))
print(parse_args(''.split()))

rawDescription: Set default value with argparse and same dest attribute


code:
@subscriber(BeforeRender)
def add_base_template(event):
  request = event.get('request')
  if request.user:
    base = 'myapp:templates/logged_in_layout.mako'
    event.update({'base': base})
  else:
    base = 'myapp:templates/layout.mako'
    event.update({'base': base})

rawDescription: How do I register a global mako function in pyramid from outside the template?

description: Register a global mako function in pyramid from outside the template


code:
@app.before_request
def load_passport():
    if "passport_id" in session:
        g.passport = create_passport_from_id(session["passport_id"])

@app.after_request
def serialize_passport(response):
    if hasattr(g, "passport"):
        session["passport_id"] = g.passport.id
    return response

rawDescription: Proper way to establish persistent complex object in Flask


rawDescription: How to efficiently concatenate many arange calls in numpy?

description: Efficiently concatenate many arange calls in numpy


rawDescription: Matplotlib - How to convert dates from SQLite to matplotlib firmat?


code: latin1 = 'abcd\xe9'.decode('latin1')

rawDescription: Specifying unicode literal's encoding on a per-literal basis


code:
location = {'California', 'West Coast', 'Los Angeles'}
disease = {'Measles', 'MMR', 'Pertussis'}

l = ['West Coast MMR',"Measles outbreak in the U.S worse than ever","MMR vaccination rates in California at all time low","I don't live in California"]

import re

r = re.compile("West Coast|Los Angeles|California")

for s in l:
    if r.search(s) and any(word in disease for word in s.split()):
        print(s)

for s in l:
    if r.search(s) and disease.intersection(s.split()):
        print(s)

rawDescription: How can I pick out strings that contain two keywords from different lists?

description: Pick out strings that contain two keywords from different lists


code:
for resource in iterate_with(gen_resources()):
    DoWork(resource)

rawDescription: Looping over resource in python

description: Looping over resource in python


code:
class StdoutWrapper(object):
    def __init__(self, outwidget):
        self.widget = outwidget
        self.widget.setReadOnly(True) # assuming QPlainTextEdit
        self.widget.hide()

    def write(self, s):
        self.widget.show()
        self.widget.appendPlainText(s) # again assuming QPlainTextEdit

rawDescription: Wxwidgets and Pyqt

description: Wxwidgets and Pyqt


code:
def butter_bandpass(lowcut,highcut,fs,order=8):
    nyq = 0.5*fs
    low = lowcut/nyq
    high = highcut/nyq

    b,a = butter(order, [low, high], btype='band')
    return b,a

def butter_bandpass_filter(data,lowcut,highcut,fs,order=8):
    b,a = butter_bandpass(lowcut,highcut,fs,order=order)
    return lfilter(b,a,data)

rawDescription: Most efficient way to filter a long time series Python


rawDescription: how can I create a python array with a specific len each element all initialize to 0

description: Create a python array with a specific len each element all initialize to 0


code:
from matplotlib import pyplot as plt

fig, (ax1, ax2, ax3) = plt.subplots(1, 3)

ax1.imshow(a, cmap=plt.cm.jet)
ax2.imshow(labels, cmap=plt.cm.jet)
ax3.imshow(biggest_shape, cmap=plt.cm.jet)

rawDescription: Variable area threshold for identifying objects - python


code:
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

rawDescription: Power set and Cartesian Product of a set python


code:
not_on_hd = []
for file in flickr_photos:
    if os.path.exists("path/to/"+file):
        continue
    else:
        not_on_hd.append(file)
print(not_on_hd)

rawDescription: Python compare differences in XML.Etree and file and folder names in directory listings


code: dic={'a': set(''.join(per) for per in permutations('AGUCN'))}

rawDescription: Look ahead without itertools

description: Look ahead without itertools


rawDescription: pandas, matplotlib, use dataframe index as axis tick labels

description: Pandas, matplotlib, use dataframe index as axis tick labels


code:
import matplotlib.pyplot as plt

fig = plt.figure()

for idx in xrange(8):
    ax = fig.add_subplot(3, 3, idx+1)
    img = f[img_set[ind[idx]][0]]
    patch = img[:,col1+1:col2, row1+1:row2]
    ax.imshow(patch)

path_ = 'plots/test' + str(k) + '.pdf'
fig.savefig(path_)

rawDescription: python subplot for loop

description: Python subplot for loop


code: import myproject.lib.mymodule.SomeClass as my_class

rawDescription: How may I resolve python path strings with Django?


code:
print('C:\Program Files\Mozilla Firefox\\firefox.exe')
print(r'C:\Program Files\Mozilla Firefox\firefox.exe')

rawDescription: How to open external programs in Python

description: Open external programs in Python


rawDescription: combine 2-d array to existing 3-d array

description: Combine 2-d array to existing 3-d array


rawDescription: Python Networkx detecting loops/circles

description: Python Networkx detecting loops/circles


code:
def fib(n):
    if n == 0:
        return [0]
    elif n == 1:
        return [0, 1]
    else:
        lst = fib(n-1)
        lst.append(lst[-1] + lst[-2])
        return lst

rawDescription: Python: Creating a List of the First n Fibonacci Numbers


code:
import csv
myfile = csv.writer(open("data.csv", "wb"))
myfile.writerows(l)

rawDescription: list of dicts to memory for csv reader

description: List of dicts to memory for csv reader


code:
# first, read everything from the old file
text = open("input.txt", 'rt').read()

# split it at the first empty line ("\n\n")
first, rest = text.split('\n\n',1)

# make a new file and write the rest
open("output.txt", 'wt').write(rest)

rawDescription: How to delete parts of a file in python?

description: Delete parts of a file in python


rawDescription: Find the intersection between two geographical data points


rawDescription: Extracting of the arithmetic root of arbitrary degree


code: sorted(results, key=lambda t:t[0])

rawDescription: Python does not sort sql query result

description: Python does not sort sql query result


rawDescription: Sending custom PyQt signals?

description: Sending custom PyQt signals


code:
import win32api, win32con, win32gui
import random
import time
import os

menu = []
mouseClick = []
stop = []
x = None
y = None

def menu():
    global x
    global y
    x = int(input("Geef de X as op >> "))
    y = int(input("Geef de Y as op >> "))
    mouseClick()

def mouseClick():
    win32api.SetCursorPos((x,y,))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
    time.sleep(.1)
    stop()
    mouseClick()

def stop():
    exit = win32api.mouse_event(win32con.MOUSEEVENTF_MOVE,1,1)
    if exit:
        menu()

menu()

rawDescription: Python click bot TypeError: an integer is required #CookieClickerV2


rawDescription: Where is mininet installed to?

description: Where is mininet installed to


code:
import collections

Fruit = collections.namedtuple('Fruit', ['name', 'seeds', 'edible'])

rawDescription: Breaking down list of list into dictionaries


code:
before = [67,45,2,13,1,998]

before.sort() # inplace sorts original list

print(before)

rawDescription: Why is object.sort() passing None to variable?


code: [numbers[i%len(numbers)] for i in range(start, start + len(numbers))]

rawDescription: Iterate through each value of list in order, starting at random value


code:
def __new__(cls, *args, **kw):
    # every instance has its own class
    # so we can create magic methods on the
    # class without stomping on other mocks
    new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
    instance = object.__new__(new)
    return instance

rawDescription: Why does type(mock.MagicMock()) == mock.MagicMock returns False?


code:
## service: BLZService, port: soap12, method: getBank
client.service['BLZService']['soap12'].getBank()
## service: OtherBLZService, port: soap, method: getBank
client.service['OtherBLZService']['soap'].getBank()

rawDescription: Changing web service url in SUDS library


code:
import csv
with open('file_name') as f:
    splitted_lines = csv.reader(f,delimiter=',')

rawDescription: Python - Merging two strings that overlap


code:
MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE)
item = MatchedQuotes.sub(r'\2', item, 1)

rawDescription: I'm using Python regexes in a criminally inefficient manner


code:
class test:
    def print(self):
         print("stuff and things")
    def combatMath(self):
         #math stuff happens here
         self.print()
         #call print to print out the results

rawDescription: Calling previously defined functions within other functions(Python)


code:
DATABASES = {
    'default': {
        'ENGINE': 'transaction_hooks.backends.postgresql_psycopg2',
        'NAME': 'foo',
        },
    }
SOUTH_DATABASE_ADAPTERS = {'default':'south.db.postgresql_psycopg2'}  # this is required, or South breaks

rawDescription: Django related objects are missing from celery task (race condition?)


code: '{} minutes, {} hours'.format(minutes, hours)

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

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


code:
class TaskControl(models.Model):
    some_status = models.BooleanField(default=True)
    # more statuses
    expires = models.DateTimeField()
    check_interval = models.IntegerField(default=5 * 60)

    def is_stale(self):
        return (
            (datetime.utcnow() >= self.expires) or
            ((datetime.utcnow() - self.retrieved).total_seconds >= self.check_interval))

rawDescription: Turn Off Celery Tasks

description: Turn Off Celery Tasks


code:
with open(inpath) as infile, open(outpath, 'w') as outfile:
    for line in infile:
        a, b = map(float, line.split())
        total = a + b
        outfile.write('{} {} {}\n'.format(a, b, total))

rawDescription: Do some math over two columns of a .dat file and save results into a third column


code:
for d in reversed(Tuple):
    if "2" in d:
        Dict["2"] = d["2"]
        break # last dict in Tuple that has the key

rawDescription: Iteration Through tuple of dictionaries in Python


code: v = df['value'].dropna()

rawDescription: Pandas cumulative sum on column with condition


code: is_critical = (type_code & (0x1 << 5)) == 0

rawDescription: PNG Chunk type-code Bit #5

description: PNG Chunk type-code Bit #5


code: df['total'] = df.sum(axis=1)

rawDescription: pandas: append new column of row subtotals

description: Pandas: append new column of row subtotals


code:
for row in foo_csv_reader:
    fips_code = row[...] # Row storing FIPS code.
    inner_data = {}
    inner_data['foo'] = ... # Data from foo CSV.
    master[fips_code] = inner_data

rawDescription: Using Nested Dictionaries in Python -- combining two datasets with a common 'key' and different other variables


code:
hapts = [('1|2|3', '1|2|3', '1|2|3'), ('3|4|5', '3|4|5', '3|4|5')]
zipped = itertools.chain.from_iterable(zip(*[part.split("|") for part in group]) for group in hapts)
["|".join(values) for values in zipped]

rawDescription: Zip string-subset from tuples in a list

description: Zip string-subset from tuples in a list


code: x = x.astype(DT.datetime)

rawDescription: How do I display dates when plotting in matplotlib.pyplot?

description: Display dates when plotting in matplotlib.pyplot


code: df = pd.read_table(StringIO(scrabble_table), delimiter=',', index_col=0)

rawDescription: Pandas: transform a DataFrame by splitting each value into multiple values


code:
id_to_dict = {d['id']: d for d in res_result}
[id_to_dict[id] for id in req_ids]
pprint(_)

rawDescription: How can I order a list of dictionaries based on another list which has the key?

description: Order a list of dictionaries based on another list which has the key


rawDescription: Numpy loadtxt single line into multidim-array


code:
def OtherClass(object):
    def __init__(self, classa_init_args, classb_init_args, classc_init_args):
        self.classa = ClassA(class_a_init_args)
        self.classb = ClassC(class_b_init_args)
        self.classc = ClassC(class_c_init_args)

rawDescription: python memory consumption and performance related to classes

description: Python memory consumption and performance related to classes


code:
d1 = Datum(1.5)
d2 = Datum(3.2)
d3 = d1+d2
assert d3.source == 'source'
L=[d1,d2,d3]
d4=max(L)
assert d4.source == 'source'
L = [i for i in L]
assert L[0].source == 'source'
assert type(L[0]) == Datum
minimum = min(L)
assert [x - minimum for x in L][0].source == 'source'

rawDescription: How to set up a class with all the methods of and functions like a built in such as float, but holds onto extra data?

description: Set up a class with all the methods of and functions like a built in such as float, but holds onto extra data


code:
import pprint
import pymongo
client = pymongo.MongoClient()
collection = client['test']['collection']
pipeline = [{'$project': {'category': 1,
                   'name': 1,
                   'w': {'$cond': [{'$eq': ['$category', 'B']},
                                   1,
                                   {'$cond': [{'$eq': ['$category', 'C']},
                                              2,
                                              3]
                                   }]
                        }
                }},
                {'$sort': {'w': 1}}
    ]
pprint.pprint(list(collection.aggregate(pipeline=pipeline)))

rawDescription: python - sort mongodb by the value of one key

description: Python - sort mongodb by the value of one key


code:
def mainfunc(ks=KeySeq()):
   key = ks.next()

rawDescription: Structuring a program. Classes and functions in Python


code:
page = urllib.request.urlopen(base_url)
page_content = page.read()
# ...
BeautifulSoup(page_content)
# ...
BeautifulSoup(page_content)

rawDescription: Python - Passing urls vs. an HTTPResponse object


code:
l_one = [x for x in someList]
l_two = []
for i in l_one:
    if i not in l_two:
        l_two.append(i)

rawDescription: How to reduce lines with list comprehensions in Python?

description: Reduce lines with list comprehensions in Python


code:
foo = Foo(sample_function)

f = open('foo', 'w')
foo.save(f)
f.close()

rawDescription: Problematic function pickling

description: Problematic function pickling


code:
from bitstring import BitArray
a = BitArray(24)          # 24 zero bits
a.uint = 2**24/11         # set the unsigned integer propery
a.bin                     # get the binary propery

rawDescription: Patterns in Binary Fractions with Python


rawDescription: Converting some columns of a matrix from float to int


code:
with open('test', 'r') as f:
    while True:
        line = f.readline()
        if line == "":
            break

rawDescription: Read large text file without read it into RAM at once


code:
letter_in_word = False
for a,c in enumerate(find):
    if c == letter:
        l[a] = letter
        letter_in_word = True
if letter_in_word:
    ...
else:
    ...

rawDescription: How to code so the program finds multiple instances - Python

description: Code so the program finds multiple instances - Python


code:
template1 = \
 '''
    <ParentTag>
       <orders orderid="%s">
         <unitprice>%s</unitprice>
         <quantity>%s</quantity>
       </orders>%s
    </ParentTag>
 '''

template2 = \
 '''
   <details>
    <productid>%s</productid>
    <productname>%s</productname>
   </details>
'''

rawDescription: Concatenate two XML templates in Python

description: Concatenate two XML templates in Python


code:
# Extract all of the <a> tags:
tags = soup.find_all('a')

rawDescription: How can I Extract Specific xml tags from a local xml file using python?


code: scrollview = ScrollView()

rawDescription: Making a gridview inside of an scrollview, that is the size of the screen


code:
dict1 == dict2
dict1.keys() == dict2.keys()

rawDescription: Order of traversal in dictionary

description: Order of traversal in dictionary


code:
class PQueue:
    """
    Implements a priority queue with append, take, promote, and demote
    operations.
    """
    def __init__(self):
        """
        Initialize empty priority queue.
        self.toll is max(priority) and max(rowid) in the queue
        self.heap is the heap maintained for take command
        self.rows is a mapping from rowid to items
        self.pris is a mapping from priority to items
        """
        self.toll = 0
        self.heap = list()
        self.rows = dict()
        self.pris = dict()

    def append(self, value):
        """
        Append value to our priority queue.
        The new value is added with lowest priority as an item. Items are
        threeple lists consisting of [priority, rowid, value]. The rowid
        is used by the promote/demote commands.
        Returns the new rowid corresponding to the new item.
        """
        self.toll += 1
        item = [self.toll, self.toll, value]
        self.heap.append(item)
        self.rows[self.toll] = item
        self.pris[self.toll] = item
        return self.toll

    def take(self):
        """
        Take the highest priority item out of the queue.
        Returns the value of the item.
        """
        item = heapq.heappop(self.heap)
        del self.pris[item[0]]
        del self.rows[item[1]]
        return item[2]

    def promote(self, rowid):
        """
        Promote an item in the queue.
        The promoted item swaps position with the next highest item.
        Returns the number of affected rows.
        """
        if rowid not in self.rows: return 0
        item = self.rows[rowid]
        item_pri, item_row, item_val = item
        next = item_pri - 1
        if next in self.pris:
            iota = self.pris[next]
            iota_pri, iota_row, iota_val = iota
            iota[1], iota[2] = item_row, item_val
            item[1], item[2] = iota_row, iota_val
            self.rows[item_row] = iota
            self.rows[iota_row] = item
            return 2
        return 0

rawDescription: How could a distributed queue-like-thing be implemented on top of a RBDMS or NOSQL datastore or other messaging system (e.g., rabbitmq)?


code:
def indices():
    for k in range(47):
        for j in range(1000):
            for i in range(40):
                yield k, j, i
def keyfn(ind):
    k, j, i = ind
    return list_a[k][j][i]

print(nsmallest(4, indices(), key=keyfn))

rawDescription: Python - Finding elements in a list efficiently


code:
price = 99.99
while price > 7.74:
    price = get_price()
    time.sleep(5)

rawDescription: time.sleep() function in Python 3.3?

description: Time.sleep() function in Python 3.3


code:
if kwargs:
    exclude, f = set(kwargs['exclude']), None
    sieve = lambda l:itertools.ifilter(lambda nv: nv[0] not in exclude, l)
elif len(names) == 1 and inspect.isfunction(names[0]):
    f = names[0]
    sieve = lambda l:l
else:
    names, f = set(names), None
    sieve = lambda l: itertools.ifilter(lambda nv: nv[0] in names, l)

rawDescription: What is the best way to do automatic attribute assignment in Python, and is it a good idea?


code:
new_index = Index(arange(0,5,0.5), name="A")
df.set_index("A").reindex(new_index)

rawDescription: Missing data, insert rows in Pandas and fill with NAN


rawDescription: How to remove duplicates in pandas?

description: Remove duplicates in pandas


code:
from collections import Counter
a = [{'title': 'Learning How to Program', 'views': 1},
     {'title': 'Mastering Programming', 'views': 3}]
b = [{'title': 'Learning How to Program', 'views': 7},
     {'title': 'Mastering Programming', 'views': 2},
     {'title': 'Programming Fundamentals', 'views': 1}]
summed = sum((Counter({elem['title']: elem['views']}) for elem in a + b), Counter())
summed
[{'title': title, 'views': counts} for title, counts in summed.items()]

rawDescription: Combine two lists of dicts, adding the values together


code:
def convert_datetime_to_generalized_time(dt):
    """Convert datetime object to generalized time format."""
    dt = dt.timetuple()
    gtime = str(dt.tm_year) + ''.join('0' * (2 - len(str(item))) + str(item)
                                      for item in (dt.tm_mon, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec))
    return gtime + 'Z'

rawDescription: Querying LDAP by date

description: Querying LDAP by date


code: pd.concat([y.iloc[:, numeric].sum(), y.iloc[:, ~numeric].min()]).reindex(y.columns)

rawDescription: Combining multiple data types in pandas DataFrame


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

# If you're not familiar with np.r_, don't worry too much about this. It's just
# a series with points from 0 to 1 spaced at 0.1, and 9 to 10 with the same spacing.
x = np.r_[0:1:0.1, 9:10:0.1]
y = np.sin(x)

fig,(ax,ax2) = plt.subplots(1, 2, sharey=True)

# plot the same data on both axes
ax.plot(x, y, 'bo')
ax2.plot(x, y, 'bo')

# zoom-in / limit the view to different portions of the data
ax.set_xlim(0,1) # most of the data
ax2.set_xlim(9,10) # outliers only

# hide the spines between ax and ax2
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.yaxis.tick_left()
ax.tick_params(labeltop='off') # don't put tick labels at the top
ax2.yaxis.tick_right()

# Make the spacing between the two axes a bit smaller
plt.subplots_adjust(wspace=0.15)

plt.show()

rawDescription: Python/Matplotlib - Is there a way to make a discontinuous axis?


rawDescription: IMDB suggestions

description: IMDB suggestions


code:
def main():
    a = 1
    b = 2
    c = a + b
    print("total", a + b + c)

if __name__ == "__main__":
    main()

rawDescription: python pudb stops stepping when main() is called

description: Python pudb stops stepping when main() is called


code:
import re
s = "John r Spencer Farrow r David K r Gillian"
re.split(r'\br\b',s)

rawDescription: Finding strings that are each separated by the same string


code:
radius = filters.pop('radius', None)
company = filters.pop('company', None)

rawDescription: django - regex for optional url paramaters

description: Django - regex for optional url paramaters


code:
def truncate(it, n):
    cache = [next(it) for i in range(n)]
    index = 0
    for val in it:
        val, cache[index] = cache[index], val
        index = (index + 1) % n
        yield val

rawDescription: All but the last N elements of iterator in Python


code:
def make_pairs( tc_query_set ):
    start = None
    for row in tc_query_set:
         if start is None:
             start= row
             continue
         elif start.card == row.card and start.rec_date == row.rec_date:
             yield start, row
             start= None
         else:
             # May as well raise an exception -- the data cannot the processed
             yield start, None
             start= row

rawDescription: Analyse data using time and date objects


code:
import re

s = "-8,934.75"
try:
    amount = float(re.sub('[^-.0-9]', '', s))
except ValueError as e:
    pass # wasn't valid for some reason? do something sensible

rawDescription: Reformatting a CSV using Python and bucketing the data


rawDescription: Python: Index in a list of lists

description: Python: Index in a list of lists


code: df['Month'] = df['Date'].dt.month

rawDescription: How do I use timestamp dates as an index in a pivot table in python?

description: Use timestamp dates as an index in a pivot table in python


code:
def permut(s,l):
    print("Entering function permut()")
    print("Parameters:\ns: {}\nl: {}".format(s,l))
    if l == []:
        print("End of recursion reached, returning {}".format([[s]]))
        return [[s]]
    result = []
    for e in permut(s, l[1:]):
        result.append(e + [l[0]])
    result += [l + [s]]
    print("Returning {}".format(result))
    return result

rawDescription: Recursive list comprehension for permutation. Python


code: len([name for (name, value) in matches if value == 'true'])

rawDescription: Find co-occurrences of two lists in python


code:
'Get the IndianOil Citibank Card. Apply Now!'
'Get 10X Rewards On Shopping -\n   Save Over 5% On Fuel'

rawDescription: How to split the tags from html tree

description: Split the tags from html tree


code:
od = OrderedDict(first_found(l))

print(od)
OrderedDict([(1, 0.3), (3, 0.2), (2, 0.01)])

rawDescription: Keep firstly found duplicate items in a list


code:
def join_by(it, sep):
    it = iter(it)
    prev = next(it)
    for elem in it:
        if elem == sep:
            prev += next(it)
        else:
            yield prev
            prev = elem
    yield prev

rawDescription: Python - How to join elements in a list that are separated by a certain value


code:
controllers/default.py

def check(form):
    if form.vars.b and not form.vars.c:
        form.errors.c = "If the b is checked, c must be filled"

def action():
    form = SQLFORM(db.foo)
    if form.process(onvalidation=check).accepted:
        response.flash = "success"
    return dict(form=form)

rawDescription: Web2py Custom Validators

description: Web2py Custom Validators


code: bool("Earrings")

rawDescription: python if...elif always not working

description: Python if...elif always not working


code: exec ( "/path/to/python/script.py $var1 $var2 $var3" );

rawDescription: How to pass multiple variable from php to python script

description: Pass multiple variable from php to python script


code:
env = Environment(
   tools=['scons_csharp']
)

sources = ['Hello.cs']
prog = env.CLIProgram('myapp', sources)

rawDescription: Adding C# support to SCons on Mac

description: Adding C# support to SCons on Mac


code: output = {el1[0]: el2 for el1, el2 in zip(list1, list2)}

rawDescription: merging list of tuples and list and create dictionary

description: Merging list of tuples and list and create dictionary


code:
import pandas as pd
data = [{'a': 2, 'g': 1},{'p': 3, 'a': 5, 'cat': 4}]
df = pd.DataFrame(data)
df
df = df.fillna(0)
df

rawDescription: Create a matrix from dynamic dictionary

description: Create a matrix from dynamic dictionary


rawDescription: Ghost.py - click specific button

description: Ghost.py - click specific button


rawDescription: How to use Channel instead of Group when using django channels?

description: Use Channel instead of Group when using django channels


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

rawDescription: Merge Duplicates based on column?

description: Merge Duplicates based on column


rawDescription: Pandas: subset by filtering for a variable level and group it returning a count?


rawDescription: Appending python dictionaries, without replacing if the value is empty


code:
from pprint import pprint
clip = QtGui.QApplication.clipboard()
mime = clip.mimeData()
pprint(mime.formats())

rawDescription: PyQt4 table for inserting a table from the clipboard - tableWidget?


code:
import csv
with open('test.csv') as f:
    next(f, None) # skip header
    rows = list(csv.reader(f))
    rows[0][1] = 'My birthday'
    rows[1][3] = 'India'
    w = csv.writer(a_file)
    w.writerows(rows)

rawDescription: Replacing variable with values from a CSV-file in python


code:
result = start
for x in iterable:
    result = function(result, x)

rawDescription: Python alternative to reduce()

description: Python alternative to reduce()


code:
import msvcrt
one_character= msvcrt.getch()

rawDescription: How can I determine when a user is in the process of entering something as an input in Python?

description: Determine when a user is in the process of entering something as an input in Python


code:
like_with_bd.explain()

## TungstenProject [document_id#2L,keyword#46]
##  !Generate explode(pythonUDF#47), true, false, ...
##   ConvertToSafe
##    TungstenProject [document_id#2L,pythonUDF#47]
##     !BatchPythonEvaluation PythonUDF#<lambda>(document_text#3), ...
##      Scan PhysicalRDD[document_id#2L,document_text#3]

rawDescription: How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?


code: import myfile

rawDescription: Convert Python 3 script to function

description: Convert Python 3 script to function


code:
funcType
help(funcType)

rawDescription: How can i add behaviour to a instance of a class without changing the base class

description: Add behaviour to a instance of a class without changing the base class


code:
def fast_hik(x, y):
    return np.minimum(x, y).sum()

rawDescription: Python: faster function for kernel evaluation


code:
a = [2,7,9]
b = [[7,9],[1,2],[2,9]]
st = set(b[0])
st.issubset(a)
st = set(b[1])
st.issubset(a)
st = set(a)
st.issuperset(b[0])
st.issuperset(b[1])

rawDescription: Count of pair element in list

description: Count of pair element in list


rawDescription: wxPython: how to make taskbar icon respond to left-click

description: WxPython: how to make taskbar icon respond to left-click


code: hour, min, sec, micro = '{:02d}'.format(time.hour), '{:02d}'.format(time.minute), '{:02d}'.format(time.second), '{:06d}'.format(time.microsecond)

rawDescription: Python program runs for a week, then fails mysteriously


code: float(repr(x)) == x

rawDescription: Understanding Floating-point doc

description: Understanding Floating-point doc


rawDescription: Making a dictionary from a list of lists


rawDescription: Create own colormap using matplotlib and plot color scale


code: df.replace(0, np.nan).bfill()  # maybe neater way to do this?

rawDescription: how to forward fill non-null values in a pandas dataframe based on a set condition

description: Forward fill non-null values in a pandas dataframe based on a set condition


code:
data = get_data_in_list_form()
actual_data = Test(*data)

rawDescription: Initializing instance variable: Idiomatic way


rawDescription: Python Argparser show parser from instancemethod


code:
import itertools
from statistics import mean

def average_similar(iterable, width=0.5, precision=None, criteria=make_keyfcn):
    """Return a list where similar numbers have been averaged.

    Items are grouped using the supplied width and criteria and the
    result is rounded to precision if it is supplied.  Otherwise
    averages are not rounded.

    """
    lst = sorted(float(f) for f in iterable)
    g1 = (mean(g) for g in grouper(lst, criteria(width)))
    if precision is not None:
      g1 = (round(g, precision) for g in g1)
    return list(g1)

def grouper(iterable, criteria=None):
    if criteria is None:
        criteria = make_keyfcn()
    result = []
    for k, g in itertools.groupby(iterable, criteria):
        result.append(list(g))
    return result

def make_keyfcn(width=0.5):
    "Grouping critera."
    key = None
    def keyfcn(x):
        """As long as x is < key, keep returning key.

        Update when x >= key.
        """
        nonlocal key
        if key is None:  # When called the first time.
            key = x + width
        elif x >= key:
            key = x + width
        return key
    return keyfcn

rawDescription: Python - Average similar values in list and create new list with averaged values


code:
class Player:
    def __init__(self, name):
        self._name = name
        self.change_name_event = Event('Player.change_name')

class Player2(Player):
    def __init__(self, name):
        super().__init__(name)
        self.attack_event = Event('Player2.attack')
        self.kill_event = Event('Player2.kill')

rawDescription: Combining dict in super class's init and subclass's init automatically?


code: from scipy.interpolate import interp1d

rawDescription: Average multiple vectors of points of different lengths in python


code:
if q%100==0:
    self.progress['value']=float(q)/100
    self.progress.update_idletasks()

rawDescription: Status bar for csv file read

description: Status bar for csv file read


code:
count = 0
for number in numbers:
    if number < 0:
        count += 1

rawDescription: Python - Identify a negative number in a list


code:
from collections import Counter

new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus']

cn = Counter(new_list)
for k,v in cn.items():
    print("{} appears  {} time(s)".format(k,v))

rawDescription: Counting number of strings in a List with Python


code:
self.threadParent = QObject()
self.new_thread = thread_worker(self.threadParent)

rawDescription: Python/PySide: How can i destroy a terminated thread object?


code:
for row in csvreader:
    ingest_row(row)

rawDescription: Python/MySQLdb import from CSV with data encapsulation


code:
if m > len(b):
    break # nothing after this will happen
    if jack(d,b[m][0])>0.3:
       c.append(b[m][0])
       del b[m]

rawDescription: Unexpected output in for loop - Python

description: Unexpected output in for loop - Python


code:
import string
line = ''.join(c for c in line if c in string.ascii_letters)

rawDescription: Replace all non-alphabet in a string

description: Replace all non-alphabet in a string


code:
sort_function = lambda x: x.sort("metric_count", ascending = False)[:3]
desired_df = group.apply(sort_function)

rawDescription: Python Pandas sort by column, but keep index same


code:
def get_name ():
    name = ""
    while (1):
        for Event in event.get():
            if Event.type == KEYDOWN:
                if Event.key == K_RETURN and name:
                    return name
                else:
                    name += Event.unicode

rawDescription: PyGame User Input

description: PyGame User Input


code:
class MetaArray(np.ndarray):
    """Array with metadata."""

    def __new__(cls, array, dtype=None, order=None, **kwargs):
        obj = np.asarray(array, dtype=dtype, order=order).view(cls)
        obj.metadata = kwargs
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        self.metadata = getattr(obj, 'metadata', None)

rawDescription: Add metadata comment to Numpy ndarray

description: Add metadata comment to Numpy ndarray


code:
CUSTOMER_MODELS = {
    'NA': CustomerNA,
    'EU': CustomerEU,
    'Asia': CustomerAsia,
    #...
}

rawDescription: Django: Get Model Name by a dynamic condition


code:
def int_or_float(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

rawDescription: How can I convert a string to either int or float with priority on int?

description: Convert a string to either int or float with priority on int


rawDescription: see if list of keys exist in dictionaries of a dictionary in python

description: See if list of keys exist in dictionaries of a dictionary in python


code:
test1 = "\\"
test2 = "foobar \n"
test3 = r"a \valid rawstring"
test4 = "foo \\\\\\"
test5 = r"foo \\"
test6 = r"'"
test7 = r'"'
print(rawstr(test1))
print(rawstr(test2))
print(rawstr(test3))
print(rawstr(test4))
print(rawstr(test5))
print(rawstr(test6))
print(rawstr(test7))

rawDescription: How do I get the raw representation of a string in Python?

description: Get the raw representation of a string in Python


code:
per_id = defaultdict(list)

for entry in l:
    per_id[entry['id']].append(entry)

output = [max(v, key=lambda d: d['s']) for v in per_id.itervalues()]

rawDescription: python: remove duplicate elements based on score

description: Python: remove duplicate elements based on score


code:
list2_map = {}
for word in list2:
    list2_map.setdefault(word[0], []).append(word)

newlist = ['{}:{}'.format(l, ','.join(list2_map.get(l, []))) for l in list1]

rawDescription: Only using items from one list once in nested list comprehension


code:
['DetailResult',
 ['status', ['Status', ['message', None], ['code', '0']]],
 ['searchArgument',
  ['DetailSearchArgument',
   ['reqPartNumber', 'BQ'],
   ['reqMfg', 'T'],
   ['reqCpn', None]]],
 ['detailsDto',
  [['DetailsDto',
    ['summaryDto',
     ['SummaryDto',
      ['PartNumber', 'BQ'],
      ['seMfg', 'T'],
      ['description', 'Fast']]],
    ['packageDto',
     [['PackageDto', ['fetName', 'a'], ['fetValue', 'b']],
      ['PackageDto', ['fetName', 'c'], ['fetValue', 'd']],
      ['PackageDto', ['fetName', 'd'], ['fetValue', 'z']],
      ['PackageDto', ['fetName', 'f'], ['fetValue', 'Sq']],
      ['PackageDto', ['fetName', 'g'], ['fetValue', 'p']]]],
    ['additionalDetailsDto',
     ['AdditionalDetailsDto',
      ['cr', None],
      ['pOptions', None],
      ['inv', None],
      ['pcns', None]]],
    ['partImageDto', None],
    ['riskDto',
     ['RiskDto',
      ['life', 'Low'],
      ['lStage', 'Mature'],
      ['yteol', '10'],
      ['Date', '2023']]],
    ['partOptionsDto',
     [['ReplacementDto',
       ['partNumber', 'BQ2'],
       ['manufacturer', 'T'],
       ['type', 'Reel']]]],
    ['inventoryDto',
     [['InventoryDto',
       ['distributor', 'V'],
       ['quantity', '88'],
       ['buyNowLink', 'https://www...']],
      ['InventoryDto',
       ['distributor', 'R'],
       ['quantity', '7'],
       ['buyNowLink', 'http://www.r.']],
      ['InventoryDto',
       ['distributor', 'RS'],
       ['quantity', '2'],
       ['buyNowLink', 'http://www.rs..']]]]]]]]

rawDescription: Possible Parser for Unknown String Format(soup?) from SUDS.client


code:
from graph_tool.all import *
from numpy.random import randint
n = 5000
G = Graph(directed=False)
edges = [(0, 1)]
for i in range(2, n):
    edges.append((i, randint(i)))
G.add_edge_list(edges)

rawDescription: Graph-tool surprisingly slow compared to Networkx


code: {{ comment_date|timesince }}

rawDescription: "x Days ago' template filter in Django?

description: "x Days ago' template filter in Django


code:
idx = np.where(xvalues==xvalues[-2]) # this is 179.3979933110368
# idx is a tuple of array(s) containing index where value was found
# in this case -> (array([298]),)

rawDescription: How to extract points from a graph?

description: Extract points from a graph


code: myarr[array([0, 2])]

rawDescription: Concise way to get NumPy to return array of proper shape after logical indexing, without doing a reshape?


rawDescription: Deleting elements in a given list only?

description: Deleting elements in a given list only


rawDescription: How do I get tkinter to display these unicode characters?

description: Get tkinter to display these unicode characters


code: gettext.install('myapp', unicode=True)

rawDescription: Arabic strings generated by gettext are shown scrambled in Qt UI


code:
#Set a default value.. saves us an extra else clause
number_questions = 10
if age <= 5:
    number_questions = 5

#range() will generate a list from 0->number_questions - 1

 #the -1 bit is crucial, if you do not anticipate that it will screw up some of your loops.
#The idea is that everything should be base 0, so a programmer can quickly write range(len(some_generic_list)) and have it iterate through the indexes of the list.
#Anyhow I digress but you said you are new at programming so I thought I would be informative...

for question in range(0,number_questions):
    print(question_list[question][0])
    print(question_list[question][1])

    print("Question Instructions........")

rawDescription: wanting to add an age gate to my quiz

description: Wanting to add an age gate to my quiz


code:
with ExitStack() as stack:
    managers = [stack.enter_context(my_context(arg)) for arg in items]
    print("processing under", managers)

rawDescription: Alternative to contextlib.nested with variable number of context managers


code:
import csv
import sqlite3

conn = sqlite3.connect(":memory:")
c = conn.cursor()
c.execute("create table t (col1 text, col2 float);")

# csv.DictReader uses the first line in the file as column headings by default
dr = csv.DictReader(open('data.csv', delimiter=','))
to_db = [(i['col1'], i['col2']) for i in dr]
c.executemany("insert into t (col1, col2) values (?, ?);", to_db)

rawDescription: Python in memory table data structures for analysis (dict, list, combo)


code:
import re
regex = re.compile(
    r"""^(?P<device>\S*)           # Match non-whitespace device name
    \suptime\sis\s                 # Match " uptime is "
    (?P<uptime>[^\r\n]*)           # Match until end of line --> uptime
    .*?^System\simage\sfile\sis\s  # Match intervening text
    "[^:]*:                        # Match from quote to colon
    (?P<sifilename>[^"]*)          # Match everything until quote --> filename
    .*?^cisco\s                    # Match intervening text
    (?P<model>\S*)                 # Match non-whitespace model name
    .*?^Processor\sboard\sID\s     # Match intervening text
    (?P<serialno>[^\r\n]*)         # Match until end of line --> serial no""",
    re.DOTALL | re.MULTILINE | re.VERBOSE)
match = regex.search(text)

rawDescription: Regex to find search term and place result in another data file?


code:
class Vector(tuple):
    def __add__(self, other):
        return Vector(x + y for x, y in zip(self, other))

rawDescription: Python builtin functions aren't really functions, right?


code:
for x in trends_all[0]['trends']:
    ...

rawDescription: How to work with multiple JSON formats?

description: Work with multiple JSON formats


code:
pat = "(^\d+$)|(^\w+$)|(^\W+$)"
bloc = locateBraces(pat)

test = ['a', 'c3', '36d', '51', '29.5', '#$%&']
for t in test:
    m = re.search(pat, t)
    print(str(bool(m)), end='')
    if m:
        h = bloc[m.lastindex - 1]
        print(' %s' % (pat[h[0]:h[1] + 1]))
    else:
        print()

rawDescription: How to return the regex that matches some text?

description: Return the regex that matches some text


code: strs.replace(')',') ').strip()

rawDescription: Using parentheses as delimiter in re or str.split() python


code:
import unittest
from nose.tools import set_trace

def fancy_attr(*args, **kwargs):
    """Decorator that adds attributes to classes or functions
    for use with the Attribute (-a) plugin. It also renames functions!
    """
    def wrap_ob(ob):
        for name in args:
            setattr(ob, name, True)
            #using __doc__ instead of __name__ works for class methods tests
            ob.__doc__ = '_'.join([ob.__name__, name])
            #ob.__name__ = '_'.join([ob.__name__, name])

        return ob

    return wrap_ob

class TestLogins(unittest.TestCase):
    @fancy_attr('slow')
    def test_method():
        assert True

@fancy_attr('slow')
def test_func():
    assert True

rawDescription: Append the nose @attr to the test name

description: Append the nose @attr to the test name


code:
from itertools import groupby

def find_ip(s, f):
    with open(f) as f:
        grouped = groupby(f, key=lambda x: x.startswith("lease "))
        for k, v in grouped:
            if k: # v is the lease line
                # get ip from lease line
                ip = next(v).rstrip().split()[1]
                # call next to get next element from our groupby object
                # which is each section after lease
                val = list(next(grouped)[1])[-2]
                # check for substring
                if val.find(s) != -1:
                    return ip.rstrip("{")
    return "No match"

rawDescription: Extract Information From a File

description: Extract Information From a File


code:
stdout_buf, stderr_buf = StringIO(), StringIO()
rc =  teed_call('/path/to/script', stdout=stdout_buf, stderr=stderr_buf,
                universal_newlines=True)
output = stdout_buf.getvalue()
...

rawDescription: Displaying subprocess output to stdout and redirecting it


rawDescription: Python flattening my tuple structure

description: Python flattening my tuple structure


rawDescription: Catch signals in Flask Blueprint

description: Catch signals in Flask Blueprint


code:
lbl1 = Label(root, text = "Stuff....", width = 10)
lbl1.configure(text = "Another longer stuff....")

rawDescription: Tkinter, enclosing_frame.grid_propogate(0) to prevent resizing also prevents updating label text


rawDescription: Edit a list to remove a defined variable and everything after and including a character


code:
import numpy as np
def pad_list(lst):
    inner_max_len = max(map(len, lst))
    map(lambda x: x.extend([0]*(inner_max_len-len(x))), lst)
    return np.array(lst)

def apply_to_zeros(lst, dtype=np.int64):
    inner_max_len = max(map(len, lst))
    result = np.zeros([len(lst), inner_max_len], dtype)
    for i, row in enumerate(lst):
        for j, val in enumerate(row):
            result[i][j] = val
    return result

rawDescription: zero padding numpy array

description: Zero padding numpy array


code: words.setdefault(key, []).append(word)

rawDescription: Merge some part of the list together using python


code: '\n'.join([' '.join([s for s in line.split(' ') if s]) for line in ex_str.splitlines() if line.strip(' ')])

rawDescription: Removing odd \n, \t, \r and space combinations from a given string in Python


code:
def roll_die():
    return random.randrange(1, 7)

total = roll_die() + roll_die()

rawDescription: Probability Dice Game in Python with two dices


rawDescription: Pandas - Print multiple dateframes

description: Pandas - Print multiple dateframes


code:
for span_tag in page.xpath("//span[@class='rtq_dash']"):
    print(span_tag.tail)

rawDescription: using lxml and requests in python to grab text between certain tags with a specific class name

description: Using lxml and requests in python to grab text between certain tags with a specific class name


code:
class SaneEqualityArray(np.ndarray):
    def __eq__(self, other):
        return (isinstance(other, np.ndarray) and self.shape == other.shape and
            np.allclose(self, other))

rawDescription: Compare (assert equality of) two complex data structures containing numpy arrays in unittest


code:
cmd = "/usr/atria/bin/cleartool setview -exec '/usr/bin/python /home/testUser/Development/Scripts/setDoneFlag_Count_Lines.py' testUser__project_5_0_myProject_001"
p=subprocess.Popen(cmd, shell=True)

rawDescription: run os.system command as subprocess python

description: Run os.system command as subprocess python


rawDescription: comparing numbers in 2 string A and B

description: Comparing numbers in 2 string A and B


code:
myns = etree.FunctionNamespace('http://example.org/myNamespace')
myns['my-func'] = myFunc

rawDescription: How can I return a text fragment from an XPath function?

description: Return a text fragment from an XPath function


rawDescription: python re.findall pattern for different number of matches

description: Python re.findall pattern for different number of matches


code:
def printTwoLargest():
    number = int(input('Please enter a number'))
    largest = [0,0]
    while number > -1:
        if number > largest[0]:
            largest[1] = largest[0]
            largest[0] = number
            print (largest) #remove after debug
        elif number > largest[1]:
            largest[1] = number
            print (largest) # remove after debug
        number = int(input('Please enter a  number'))
    if largest[0] == 0 or largest[1] == 0:
        print('You have not entered enough positive numbers, please enter at least two positive numbers')
    else:
        print (largest)

rawDescription: python first entry in array not being captured

description: Python first entry in array not being captured


code:
None or 5
None or datetime.now()
10 or datetime.now()

rawDescription: python/django function returning identical value every time

description: Python/django function returning identical value every time


code:
mycsvfile = """col1,col2,col3,col4,col5,col6
foo,bar1,baz1,nurf1,date(01-01-2015),date(01-01-2016)
foo,bar2,baz2,nurf2,date(01-02-2015),date(01-02-2016)
foo,bar3,baz2,nurf3,date(01-03-2015),date(01-03-2016)
foo,bar4,baz3,nurf2,date(01-04-2015),date(01-04-2016)
notfoo,bar5,baz1,nurf1,date(01-05-2015),date(01-05-2016)
foo,bar6,baz1,nurf2,date(01-06-2998),date(01-06-2999)"""

def read_date(date_str: str) -> datetime:
    return datetime.strptime(date_str, 'date(%m-%d-%Y)').date()

# The read_date helper imports the date(...) strings as Python date objects
data_clan = import_csv(StringIO(mycsvfile),
                       {'col1': str, 'col2': str, 'col3': str, 'col5': read_date, 'col6': read_date})

rawDescription: Writing complex query using algebraixlib


code: multiples = [[[i], elements[i]] for i in elements if len(elements[i]) > 1]

rawDescription: Index duplicates in a multidimensional array


code:
item['body'] = ["".join(post.xpath('.//div[@class="postBody"]/p/text()').extract())
                for post in response.xpath('//div[@class="postcontent"]')]

rawDescription: Iterate over a list and strip tags in text from nested tags with scrapy


code:
@asyncio.coroutine
def mycoro():
    loop = asyncio.get_event_loop()
    exit_future = asyncio.Future(loop=loop)
    print('creating process...')
    subprocess = loop.subprocess_exec(lambda: Protocol(exit_future),
                                      'python3.5', 'get_rand.py',
                                      stdin=None, stderr=None)
    task = asyncio.ensure_future(subprocess)
    print('Subprocess is handled in the background task')

    # this function is called with run_until_complete,
    # since that returning means complete we would not
    # finish subprocess task
    # so im leaving it
    yield from exit_future

rawDescription: Python asyncio timely event handling

description: Python asyncio timely event handling


code:
[buildout]
parts = foo

[foo]
recipe = zc.recipe.egg
eggs = foo

rawDescription: How do I use zc.buildout and setup.py together?

description: Use zc.buildout and setup.py together


code:
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))

with open('cipher.txt') as inputfile:
    f = inputfile.read().translate(remove)

rawDescription: How to strip punctuation from a text file

description: Strip punctuation from a text file


code: print(str([d["NODE"] for d in node.values() if "NODE" in d]))

rawDescription: Grab Values Within a Dictionary in a Dictionary


code:
res = []
for y in a:
    res.append('\t'.join('%0.3f' %x for x in y))
b = '\n'.join(res)

rawDescription: convert 2d numpy array to string

description: Convert 2d numpy array to string


code: dev = Dev(work_q, q_lock, 1)

rawDescription: Threading and information passing -- how to


code:
if options.file_action and not options.file_name:
    raise ValueError("No Filename specified")
# do your code here.

rawDescription: Python optparse, having one option depends on another


code:
from io import StringIO
s = StringIO()
s.write('foo')
s.getvalue()
s.truncate(0)
s.getvalue()
s.write('bar')
s.getvalue()

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


rawDescription: Why do changes to a temporary variable representing a row of a matrix, affect the row of the matrix itself?


code: grad_numerators = [sp.numer(sp.diff(y, i).together()).factor() for i in vm]

rawDescription: Set derivatives of a function to 0 in Python


code: crontab(hour=23, day_of_week='sun')

rawDescription: Celerybeat schedule executing task multiple times?


code:
# The directory to use for notebooks.
c.NotebookManager.notebook_dir = u'/path/to/your/notebooks'

rawDescription: IPython Notebook save location

description: IPython Notebook save location


rawDescription: Imprecise floats in Tupper's self-referential formula


code:
class PizzaListApiView(ListAPIView):
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer

rawDescription: Correct way to use Django's ORM and Django Rest Framework to serialize a queryset of nested relationships?


code:
fd = os.open("y", os.O_WRONLY | os.O_CREAT | os.O_EXCL)
f = os.fdopen(fd, "w")  # f is now a standard Python file object

rawDescription: How do I create a file in python without overwriting an existing file

description: Create a file in python without overwriting an existing file


code:
qry = (session.query(Movie)
        .outerjoin(Possession, and_(Movie.id == Possession.movie_id, Possession.master_id == master_id))
        .filter(Possession.id == None)
        .order_by(desc(Movie.id))
        )
movies = qry.all()

rawDescription: translate from SQL to SQLAlchemy

description: Translate from SQL to SQLAlchemy


code:
c=[[],[],[]]
# The ids are different
id(c[0])
id(c[1])
id(c[2])

rawDescription: interesting thing about python list initializing

description: Interesting thing about python list initializing


code:
def find_paws(data, smooth_radius=5, threshold=0.0001):
    data = sp.ndimage.uniform_filter(data, smooth_radius)
    thresh = data > threshold
    filled = sp.ndimage.morphology.binary_fill_holes(thresh)
    coded_paws, num_paws = sp.ndimage.label(filled)
    data_slices = sp.ndimage.find_objects(coded_paws)
    return object_slices

rawDescription: How can I improve my paw detection?

description: Improve my paw detection


code:
def find_all_paths(graph, start, end):
    def find_all_paths_aux(adjlist, start, end, path):
        path = path + [start]
        if start == end:
            return [path]
        paths = []
        for node in adjlist[start] - set(path):
            paths.extend(find_all_paths_aux(adjlist, node, end, path))
        return paths

    adjlist = [set(graph.neighbors(node)) for node in xrange(graph.vcount())]
    return find_all_paths_aux(adjlist, start, end, [])

rawDescription: Path between two nodes

description: Path between two nodes


rawDescription: Combining multiple 1D arrays returned from a function into a 2D array python


rawDescription: How do I populate tkinter drop-down box with data retrieved from my SQLite database?

description: Populate tkinter drop-down box with data retrieved from my SQLite database


code:
def arrange(nodes: list, contigious: list) -> list:
    first_contigious = nodes.index(contigious[0])
    last_contigious = nodes.index(contigious[-1])

    if first_contigious < last_contigious:
        # Normal situation
        return nodes[last_contigious+1:] + nodes[:first_contigious] + contigious
    else:
        # The contigious part is cycling
        return nodes[last_contigious+1:first_contigious] + contigious

rawDescription: arrange items respecting order

description: Arrange items respecting order


code:
factor = 2
def multiply(num):
    return num*factor

rawDescription: Methods defined outside class which itself is subsequently imported


code:
import xml.etree.cElementTree as ET

xml_doc ='''<?xml version="1.0" encoding="ISO-8859-1"?>
'''

xml = ET.fromstring(xml_doc)
print(xml.findall('cd')[-1].findtext('title'))

rawDescription: Parsing XML with xml.etree.ElementTree

description: Parsing XML with xml.etree.ElementTree


rawDescription: How to find adjective frequency from a specifique categories in brown corpus in NLTK

description: Find adjective frequency from a specifique categories in brown corpus in NLTK


code:
def create_app():
    app = Flask(__name__)
    # ...
    from myapp import blueprints
    blueprints.init_app(app)
    # ...

rawDescription: Can I keep all Flask blueprints in one file?

description: Keep all Flask blueprints in one file


code:
session.query("id", "name", "thenumber12").\
        from_statement("SELECT id, name, 12 as "
                "thenumber12 FROM users where bit_count(column&bitmask)<:the_val").\
                params(the_val=5).all()

rawDescription: BIT_COUNT in SQLAlchemy

description: BIT_COUNT in SQLAlchemy


code:
from itertools import *

FILENAME = 'original file.txt'
FILENAME_TEMPLATE = 'stanza-{}.txt'

def isSeparatorLine(line):
    return all(c=='*' for c in line)
def isValidLine(line):
    return len(line.split())==5
def extractStanzas(text):
    """
        Yields: [stanza0:line0,line1,...], [stanza1:lineN,lineN+1,...], [stanza2:...]
        where each stanza is separated by a separator line, as defined above
    """
    for isSeparator,stanza in groupby(text.splitlines(), isSeparatorLine):
        if not isSeparator:
            yield stanza

with open(FILENAME) as f:
    stanzas = list(extractStanzas(f.read()))

for i,stanza in enumerate(stanzas[1:]):
    assert all(isValidLine(line) for line in stanza), 'invalid line somewhere: {}'.format(stanza)
    with open(FILENAME_TEMPLATE.format(i), 'w') as output:
        output.write('\n'.join(stanza))

rawDescription: Variable assignments inside for and then if loops


code: primes[:] = no_zero

rawDescription: Project Euler #35: nicer way to test if an even integer is 'inside' an integer


code:
alpha_val_xpath = '//span[. = "Alpha"]/following-sibling::div//input'

alpha_val_elem = driver.find_element_by_xpath(alpha_val_xpath)
alpha_val_elem.clear()
alpha_val_elem.send_keys('5' + Keys.ENTER)

rawDescription: How to automate webpage span control like slider values by using like driver. findElement_by_xpath () , Ubuntu Linux and chromium Autotest

description: Automate webpage span control like slider values by using like driver. findElement_by_xpath () , Ubuntu Linux and chromium Autotest


rawDescription: Get attribute of all items in container python


code:
import numpy as np
import sys

class NumpyOverflowPreventer(object):

    inverse_operator= {
        '__iadd__': '__sub__',
        '__isub__': '__add__',
        '__imul__': '__div__',
        '__idiv__': '__mul__'
    }

    def __init__(self, matrix):
        m = matrix
        assert m.dtype==np.uint8
        self.matrix = m
        self.lower_range = float(0)
        self.upper_range = float(2**8-1)

    def __iadd__(self, v):
        # dynamic way to get the name "__iadd__"
        self._operate(v, sys._getframe().f_code.co_name)
        return self

    def _operate(self, b, forward_operator):
        assert type(b) in (int, float)
        reverse_operator = self.inverse_operator[forward_operator]
        uro= getattr(self.upper_range, reverse_operator)
        lro= getattr(self.lower_range, reverse_operator)
        afo= getattr(self.matrix, forward_operator)
        overflows= self.matrix > uro( b )
        underflows= self.matrix < lro( b )
        afo( b )
        self.matrix[overflows]= self.upper_range
        self.matrix[underflows]= self.lower_range

rawDescription: substituting __iadd__ doesn't work as expected for += operator

description: Substituting __iadd__ doesn't work as expected for += operator


code:
def inNd(a, b, assume_unique=False):
    a = np.asarray(a, order='C')
    b = np.asarray(b, order='C')
    a = a.ravel().view((np.str, a.itemsize * a.shape[1]))
    b = b.ravel().view((np.str, b.itemsize * b.shape[1]))
    return np.in1d(a, b, assume_unique)

rawDescription: test for membership in a 2d numpy array

description: Test for membership in a 2d numpy array


rawDescription: Decode poweshell output possibly containing non-ascii unicode characters into a python string


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

# create some random data
data = pd.DataFrame(np.random.rand(11, 5), columns=['A', 'B', 'C', 'D', 'E'], index = range(2000, 2011, 1))

# plot heatmap
ax = sns.heatmap(data.T)

# turn the axis label
for item in ax.get_yticklabels():
    item.set_rotation(0)

for item in ax.get_xticklabels():
    item.set_rotation(90)

# save figure
plt.savefig('seabornPandas.png', dpi=100)
plt.show()

rawDescription: How to plot a heatmap from pandas DataFrame

description: Plot a heatmap from pandas DataFrame


code: X_2nd_order = (X_1hot[:, np.newaxis, :] * X_1hot[:, :, np.newaxis]).reshape(len(X_1hot), -1)

rawDescription: How can an interaction design matrix be created from categorical variables?


code:
my_list = [1, 2, 3, 4, 27]
swap(my_list, 27)
my_list
swap(my_list, 4)
my_list

rawDescription: moving elements in a list of Python

description: Moving elements in a list of Python


code:
self._settings.addOption(Option('app_windowconfig', ''))
self._settings.addOption(Option('app_resolution', '640x480'))
self._settings.addOption(Option('app_window_size', ''))
self._settings.addOption(Option('app_fullscreen', 'false'))
self._settings.addOption(Option('app_show_cursor', 'true'))
self._settings.addOption(Option('app_rotation', 'normal'))
self._settings.addOption(Option('app_panel_fontsize', '10'))
self._settings.addOption(Option('app_mouse_enabled', 'true'))
self._settings.addOption(Option('multitouch_enabled', 'false'))
self._settings.addOption(Option('multitouch_driver', ''))
self._settings.addOption(Option('multitouch_tuio_port', ''))
self._settings.addOption(Option('log_avg_categories', ''))

rawDescription: How can I run an app in fullscreen?

description: Run an app in fullscreen


code:
def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        #  FLASKY_ADMIN configuration variable, so as soon as that email address appears in a registration request it can be given the correct role
        if self.role is None:
            print ("there is no role for this user")
            if self.email == current_app.config['MAIL_ADMIN']:
                self.role = ndb.Key('Role', 'administrator')

rawDescription: "working outside of application context" in Google App Engine with Python remote API


code: myValueList = map(operator.attrgetter('prop1'), myList)  # use list(map(...)) in python3.x

rawDescription: collecting values from objects in a list

description: Collecting values from objects in a list


code:
@app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
    jsdata = request.form['javascript_data']
    return json.loads(jsdata)[0]

rawDescription: How do I send data from JS to Python with Flask?

description: Send data from JS to Python with Flask


code: print(new_item, end=" ")

rawDescription: Python: for loop - print on the same line


code:
for letter in str:
    print("\n".join(letters[letter]) + "\n")

rawDescription: ASCII Art With Letters

description: ASCII Art With Letters


code:
import pycurl
import urllib2
import httplib
import StringIO

class CurlHTTPStream(object):
    def __init__(self, url):
        self.url = url
        self.received_buffer = StringIO.StringIO()

        self.curl = pycurl.Curl()
        self.curl.setopt(pycurl.URL, url)
        self.curl.setopt(pycurl.HTTPHEADER, ['Cache-Control: no-cache', 'Accept: text/event-stream'])
        self.curl.setopt(pycurl.ENCODING, 'gzip')
        self.curl.setopt(pycurl.CONNECTTIMEOUT, 5)
        self.curl.setopt(pycurl.WRITEFUNCTION, self.received_buffer.write)

        self.curlmulti = pycurl.CurlMulti()
        self.curlmulti.add_handle(self.curl)

        self.status_code = 0

    SELECT_TIMEOUT = 10

    def _any_data_received(self):
        return self.received_buffer.tell() != 0

    def _get_received_data(self):
        result = self.received_buffer.getvalue()
        self.received_buffer.truncate(0)
        self.received_buffer.seek(0)
        return result

    def _check_status_code(self):
        if self.status_code == 0:
            self.status_code = self.curl.getinfo(pycurl.HTTP_CODE)
        if self.status_code != 0 and self.status_code != httplib.OK:
            raise urllib2.HTTPError(self.url, self.status_code, None, None, None)

    def _perform_on_curl(self):
        while True:
            ret, num_handles = self.curlmulti.perform()
            if ret != pycurl.E_CALL_MULTI_PERFORM:
                break
        return num_handles

    def _iter_chunks(self):
        while True:
            remaining = self._perform_on_curl()
            if self._any_data_received():
                self._check_status_code()
                yield self._get_received_data()
            if remaining == 0:
                break
            self.curlmulti.select(self.SELECT_TIMEOUT)

        self._check_status_code()
        self._check_curl_errors()

    def _check_curl_errors(self):
        for f in self.curlmulti.info_read()[2]:
            raise pycurl.error(*f[1:])

    def iter_lines(self):
        chunks = self._iter_chunks()
        return self._split_lines_from_chunks(chunks)

    @staticmethod
    def _split_lines_from_chunks(chunks):
        #same behaviour as requests' Response.iter_lines(...)

        pending = None
        for chunk in chunks:

            if pending is not None:
                chunk = pending + chunk
            lines = chunk.splitlines()

            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
                pending = lines.pop()
            else:
                pending = None

            for line in lines:
                yield line

        if pending is not None:
            yield pending

rawDescription: Efficiently reading lines from compressed, chunked HTTP stream as they arrive


rawDescription: Use readline() from python to read specific line


code:
while paragraphs < maxparagraphs: # start outer loop, until maxparagraphs is reached
    w1 = stopword
    w2 = stopword
    stopsentence = (".", "!", "?",)
    sentence = []
    sentencecount = 0 # reset the inner 'while' loop counter to zero
    maxsentences = random.randrange(1,5) # random sentences per paragraph

    while sentencecount < maxsentences: # start inner loop, until maxsentences is reached
        newword = random.choice(table[(w1, w2)]) # random word from word table
        if newword == stopword: sys.exit()
        elif newword in stopsentence:
            print ("%s%s" % (" ".join(sentence), newword), end=" ")
            sentence = [] # I have to be here to make the new sentence start as an empty list!!!
            sentencecount += 1 # increment the sentence counter
        else:
            sentence.append(newword)
        w1, w2 = w2, newword
    print (paragraphsep) # newline space
    paragraphs = paragraphs + 1 # increment the paragraph counter

rawDescription: How to create paragraphs from markov chain output?

description: Create paragraphs from markov chain output


code:
#!/usr/bin/env python
import sys
from itertools import cycle
from textwrap import dedent

import pexpect

child = pexpect.spawnu(sys.executable or 'python', ['-c', dedent("""
            for i in range(10):
                x = int(input('Enter x-dimension: '))
                print(x*x)
            """)])
for n in cycle([3, 1, 4, 15, 926]):
    while True:
        i = child.expect([pexpect.EOF, u'x-dimension:'])
        if i == 0: # EOF
            answer = None
            child.close()
            sys.exit()
        elif i == 1: # child waits for input
            child.sendline(str(n))
            child.expect(u'\\n\\d+\\s')
            answer = int(child.after)
            if answer == 1:
                n += 1
            else:
                break
        else:
            assert 0
    else: # child terminated
        break
    if answer is not None:
        print("Input %3d Output %6d" % (n, answer))

rawDescription: How to Achieve Continuous Interactive Dialog with a Subprocess in Python?


code:
df
df['shift'] = -df['TS'].diff(-1)
df['diff'] = df[df.Status=='B'].groupby('ID')['shift'].transform('sum')
df

rawDescription: Taking Differences of Records When Status Changes - Pandas


code:
import json
import sys
s = u'Örnsköldsvik;SE;Ornskoldsvik;Ångermanlandsgatan 28 A'
json.dump(s, sys.stdout)

rawDescription: encode unicode characters to unicode escape sequences

description: Encode unicode characters to unicode escape sequences


code:
class AnswersForm(forms.Form):
    radioButton = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

    def __init__(self, radio_choices= None, *args, **kwargs):
        super(AnswersForm, self).__init__(self, *args, **kwargs)
        if radio_choices is not None:
            self.fields['radioButton'].choices = radio_choices

rawDescription: how to change form variable values from view

description: Change form variable values from view


code:
import  glob
dir1 = "path_to_dir/"
dir2 =   "path_to_dir2/"
path1_files = glob.glob(dir1+"file*.dat")
path2_files = glob.glob(dir2+"file*.dat")

rawDescription: Searching multiple files to define variable


code:
from django.db import models

class ElementiTab(models.Model):
    des = models.CharField(max_length=30)
    x = models.FloatField()
    y = models.FloatField()
    res = models.FloatField(default=0)

    def save(self, *args, **kwargs):
        self.res = (float(self.x)+float(self.y))/float(self.y)
        super(ElementiTab, self).save(*args, **kwargs)

rawDescription: Django: Use external function with django variables


code: p = subprocess.Popen("perl pydyn.pl %s | sort" % file, stdout=outfile,shell=True)

rawDescription: Pipe result from subprocess to unix sort


code: srt = sorted(twitter_users.values(), cmp=lambda a, b: cmp(a.mentioned, b.mentioned))

rawDescription: Why is my list not sorted as expected?

description: Why is my list not sorted as expected


code: # [[' with text '], [' with text ']]

rawDescription: Get pattern text that is within search string


code:
from apiclient.discovery import build
service = build('analytics', 'v3', http=http)

rawDescription: Google Analytics Core Reporting API Python library


code:
import enchant
d = enchant.Dict("en_US")
d.check("Hello")
d.check("Helo")

rawDescription: Identify Random Strings in Python

description: Identify Random Strings in Python


code:
sents = nltk.sent_tokenize(text)
for s in sents:
    print(repr(s))

rawDescription: Map line breaks in sentence to another list


code: next(list(zip(*p)) for p in permutations(poss, 2))

rawDescription: Combinations between values of lists

description: Combinations between values of lists


code:
def ping(self, n, value):
    self.a.big_dict[n] = value

rawDescription: How to create a dynamic kivy app with checkboxes?

description: Create a dynamic kivy app with checkboxes


code: (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"),

rawDescription: Django: Print url of view without hardcoding the url


code:
rows = [
{'user': 'staff_user', 'grade': [u'0.0', u'N/A', u'N/A', u'N/A', u'N/A']},
{'user': 'non_staff_user', 'grade': [u'0.0', u'N/A', u'N/A', u'N/A', u'N/A']}]
def get_expected_rows(user, grade):
    #Here i want to list `grade` to be unpacked.
    return dict(zip(
        ['username', 'total', 'sub1grade', 'sub2grade', 'sub3grade', 'sub4grade'],
        [user] + grade
    ))
for row in rows:
    expected_row = get_expected_rows(**row)
    print(expected_row)

rawDescription: Python unpacking list value in kwargs

description: Python unpacking list value in kwargs


code:
from enum import IntEnum
from hashlib import sha256
import os

# File comparison result
class Cmp(IntEnum):
    differ = 0  # source and destination are different
    same = 1  # source and destination are identical
    nodest = 2  # destination doesn't exist
    nosrc = 3  # source doesn't exist

def compare(src, dest):
    """
    Compare two files.

    Arguments
        src: Path of the source file.
        dest: Path of the destination file.

    Returns:
        Cmp enum
    """
    xsrc, xdest = os.path.exists(src), os.path.exists(dest)
    if not xsrc:
        return Cmp.nosrc
    if not xdest:
        return Cmp.nodest
    with open(src, 'rb') as s:
        csrc = sha256(s.read()).digest()
    if xdest:
        with open(dest, 'rb') as d:
            cdest = sha256(d.read()).digest()
    else:
        cdest = b''
    if csrc == cdest:
        return Cmp.same
    return Cmp.differ

rawDescription: Constants - How do you know what a constant is?


code:
c['Nine']   # Key is in the Counter, returns number of occurences
c['Four']   # Key is not in the Counter, returns 0

rawDescription: numpy - how do I count the occurrence of items in nested lists by index?

description: Numpy - how do I count the occurrence of items in nested lists by index


code:
import datetime
import pandas.io.data as web

stocklist=['CCK','MSFT','AA','AAPL']
start = datetime.datetime(2015, 12, 21)
end = datetime.datetime(2015, 12, 31)
for stock in stocklist:
    data = web.DataReader(stock, 'google', start, end)
    data.to_csv('{}.csv'.format(stock))

rawDescription: prepend a header to .csv file with python

description: Prepend a header to .csv file with python


code:
# print the outline of an inverted triangle:
height = rows

# inner padding for min height (3)
inner_buffer = [0, 1, 3]
while len(inner_buffer) <= rows:
    inner_buffer.append(inner_buffer[-1]+2)

while height > 0:
    outer_padding = ' '*(rows - height)
    if height == 1:
        print(outer_padding + '*')
    else:
        inner_padding = ' '*(inner_buffer.pop()-2)
        print(outer_padding + '*' + inner_padding + '*')
    height = height - 1

rawDescription: Draw inverted triangle of asterisk by using nested loops in Python


code: result = np.abs(a[:, None] - b[None, :])

rawDescription: Euclidean Distance Between All Points in an 2 Vectors


code:
from collections import Counter
c = Counter()
import re

vocabulary_list = ['accounting', 'actual cost','yields', 'zero-bond']
d = {k: 0 for k in vocabulary_list}
sample_text = "Accounting experts predict actual costs an increase in yields for zero-bond and yields for junk-bonds.".lower()
splitted = set(sample_text.split())
c.update(splitted) # get count of all words

for k in d:
    spl = k.split()
    ln = len(spl)
    # if we have multiple words we cannot split
    if ln > 1:
        check = re.findall(r'\b{0}\b'.format(k),sample_text)
        if check:
            d[k] += len(check)
    # else we are looking for a single word
    elif k in splitted:
        d[k] += c[k]
print(d)

rawDescription: Check text/string for occurence of predefined list elements


code:
from collections import defaultdict
d = defaultdict(list)
d['234nj233nkj2k4n52'].append(whatever)

rawDescription: Appending something to a list within a dict within a list in Python


code:
for name, group in a1.groupby(('group', 'product')):
    print(name)
    print(group)

# ('a', 'b')
#   date group  performance product
# 2   z3     a            3       b
# ('a', 'c')
#   date group  performance product
# 3   z4     a            4       c
# ('x', 'b')
#   date group  performance product
# 1   z2     x            2       b
# ('x', 'y')
#   date group  performance product
# 0   z1     x            1       y

rawDescription: Consolidate data in numpy arrays

description: Consolidate data in numpy arrays


code:
test_string = "Hello, {}"
test_string.format("world") + ".txt"

rawDescription: How do I change the name of a file path correctly in Python?

description: Change the name of a file path correctly in Python


code: self.btn = Button(self)

rawDescription: PyQt4 - Dragging and dropping files into QPushButton


code:
from pyramid.view import view_config

def read_file():
    """read the file and return the data in a suitable format"""
    return [1,4,2,4,56,7,45,3]

@view_config(route_name='show_table', renderer='templates/table.pt')
def table_view(request):
    data = read_file()
    return {'data': data}

@view_config(route_name='show_chart', renderer='templates/chart.pt')
def chart_view(request):
    data = read_file()
    return {'data': data}

rawDescription: Create a webpage with charts or tables from csv data using the pyramid framework


rawDescription: Django related_table() with extra()

description: Django related_table() with extra()


code: [[int(y) for y in x.split(',')] for x in text.split('|')]

rawDescription: Python: string to a list of lists

description: Python: string to a list of lists


code:
for i in sortednames:
   values=dictUsers[i]
   print("Name= " + i)
   print ("   Age= " + values.age)
   print ("   Address= " + values.address)
   print ("   Phone Number= " + values.phone)

rawDescription: Sort dictionary alphabetically when the key is a string (name)


code:
from collections import deque
queue = deque()
queue.append((1,2))
queue.append((2,3))
queue.popleft()
queue.append((3,5))
queue.popleft()

rawDescription: Python FIFO 2 Dimensional

description: Python FIFO 2 Dimensional


code:
from collections import defaultdict

d = defaultdict(int)
for n, v in zip(ls1, ls2):
   d[n] += v

rawDescription: Merge two lists into a dictionary and sum over the elements of the second list


code:
@strict_types
def repeat_str(mystr: str, times: int):
    return mystr * times

rawDescription: python 3.5 type hints: can i check if function arguments match type hints?

description: Python 3.5 type hints: can i check if function arguments match type hints


code:
def date_hour(timestamp):
   return datetime.datetime.fromtimestamp(timestamp).strftime("%H")

rawDescription: Django group by hour

description: Django group by hour


code:
for title in jobs:
    jobtitles = title.text

rawDescription: How to Print the information using selenium

description: Print the information using selenium


code: out, err = proc.communicate()

rawDescription: Stop a command line command in script

description: Stop a command line command in script


rawDescription: Packaging python with circular imports

description: Packaging python with circular imports


code:
df = pd.DataFrame(data,columns=year)
df
grouped = df.groupby(2013)
grouped.count()

rawDescription: Pandas Filter function returned a Series, but expected a scalar bool


code:
@route('/hello')
def index(name):
    return {'test': datetime.datetime(2014, 2, 1, 0, 0)}

install(JSONDefaultPlugin())
run(host='localhost', port=8080)

rawDescription: Bottle framework: how to return datetime in JSON response


rawDescription: Translating arrays from MATLAB to numpy

description: Translating arrays from MATLAB to numpy


code:
import pandas as pd  #install this, and read de docs
from StringIO import StringIO #You dont need this

#simulating a reading the file
first_file = """contig17 GRMZM2G052619_P03 x
contig33 AT2G41790.1 x
contig98 GRMZM5G888620_P01 x
contig102 GRMZM5G886789_P02 x
contig123 AT3G57470.1 x"""

#simulating reading the second file
second_file = """y GRMZM2G052619_P03 y
y GRMZM5G888620_P01 y
y GRMZM5G886789_P02 y"""

#here is how you open the files. Instead using StringIO
#you will simply the file path. Give the correct separator
#sep="\t" (for tabular data). Here im using a space.
#In name, put some relevant names for your columns
f_df = pd.read_table(StringIO(first_file),
                     header=None,
                     sep=" ",
                     names=['a', 'b', 'c'])
s_df = pd.read_table(StringIO(second_file),
                     header=None,
                     sep=" ",
                     names=['d', 'e', 'f'])
#this is the hard bit. Here I am using  a bit of my experience with pandas
#Basicly it select the rows in the second data frame, which "isin"
#in the second columns for each data frames.
my_df = s_df[s_df.e.isin(f_df.b)]

rawDescription: Efficiently finding intersecting regions in two huge dictionaries


code: regex("app*")# will match ap, app, appppp, appppppppppp

rawDescription: Read a text file. Search for a text based on pattern and print all the matches in another text file


code: (self.list[L][0] == operand.list[R][0]) and (op != '/' or operand.list[R][1] != 0)

rawDescription: How to do this conditional statement?

description: Do this conditional statement


code:
if "foo" not in global_dict:
   global_dict["foo"] = 1

rawDescription: Using a global dictionary with threads in Python


code:
df['count'] = df.groupby(df.index).cumcount()
df2['count'] = df2.groupby(df2.index).cumcount()
df = df.set_index('count', append=True)
df2 = df2.set_index('count', append=True)

rawDescription: grouping or merging? dataframes pandas python

description: Grouping or merging? dataframes pandas python


code:
import decorator
def mydecorator(f, *d_args, **d_kwargs):
    if (isinstance(f, classmethod)):
        return classmethod(mydecorator(f.__get__(True).im_func))
    elif (isinstance(f, staticmethod)):
        return staticmethod(mydecorator(f.__get__(True)))
    elif (isinstance(f, property)):
        return property(mydecorator(f.fget))
    else:
        return decorator.decorator(f)

rawDescription: How to retrieve original @classmethod, @staticmethod or @property

description: Retrieve original @classmethod, @staticmethod or @property


code: [ (grp, grouped) for grp, grouped in df.groupby(sub_group_hash) ][0][1]

rawDescription: Trouble with grouby on millions of keys on a chunked file in python pandas


code:
l = [1,2,3,4]
it = iter(l)
next(it)
next(it)
list(it)

rawDescription: Preceding Word Length

description: Preceding Word Length


code:
import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
colors = set(numpy.unique(im))
colors.remove(255)

for color in colors:
    py, px = numpy.where(im == color)
    print(px.min(), py.min(), px.max(), py.max())

rawDescription: Finding bounding boxes of RGB colors in image


code:
for item in myList:
    print(item)

    # or use string formatting for the item here
    print('{}'.format(item))

rawDescription: print list elements line by line - is it possible using format

description: Print list elements line by line - is it possible using format


code:
a = Symbol('a')
exp = a**2
print(exp)
print(pow_to_mul(exp))

rawDescription: Expanding algebraic powers in python (sympy)


code:
import nltk
from pyspark.ml.pipeline import Transformer
from pyspark.ml.param.shared import HasInputCol, HasOutputCol, Param
from pyspark.ml.util import keyword_only

from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, StringType

class NLTKWordPunctTokenizer(Transformer, HasInputCol, HasOutputCol):

    @keyword_only
    def __init__(self, inputCol=None, outputCol=None, stopwords=None):
        super(NLTKWordPunctTokenizer, self).__init__()
        self.stopwords = Param(self, "stopwords", "")
        self._setDefault(stopwords=set())
        kwargs = self.__init__._input_kwargs
        self.setParams(**kwargs)

    @keyword_only
    def setParams(self, inputCol=None, outputCol=None, stopwords=None):
        kwargs = self.setParams._input_kwargs
        return self._set(**kwargs)

    def setStopwords(self, value):
        self._paramMap[self.stopwords] = value
        return self

    def getStopwords(self):
        return self.getOrDefault(self.stopwords)

    def _transform(self, dataset):
        stopwords = self.getStopwords()

        def f(s):
            tokens = nltk.tokenize.wordpunct_tokenize(s)
            return [t for t in tokens if t.lower() not in stopwords]

        t = ArrayType(StringType())
        out_col = self.getOutputCol()
        in_col = dataset[self.getInputCol()]
        return dataset.withColumn(out_col, udf(f, t)(in_col))

rawDescription: Create a custom Transformer in PySpark ML


code:
observers = self.center_widget.get_property_observers('pos')
print('list of observers before unbinding: {}'.format(observers))
for observer in observers:
    self.center_widget.unbind(pos=observer)
print('list of observers after unbinding: {}'.format(self.center_widget.get_property_observers('pos')))

rawDescription: How to unbind a property automatically binded in Kivy language?

description: Unbind a property automatically binded in Kivy language


code:
from pprint import pprint
pprint(list(product(list_1, list_2)))

rawDescription: Problems computing the score of a pairwise list in an iterative way?


code:
class PathToSourceFileException(Exception):
    pass

class PackageMissingChildException(PathToSourceFileException):
    pass

class PackageMissingInitException(PathToSourceFileException):
    pass

class NotASourceFileException(PathToSourceFileException):
    pass

def pathToSourceFile(name):
    '''
    Given a name, returns the path to the source file, if possible.
    Otherwise raises an ImportError or subclass of PathToSourceFileException.
    '''

    from os.path import dirname, isdir, isfile, join

    if '.' in name:
        parentSource = pathToSourceFile('.'.join(name.split('.')[:-1]))
        path = join(dirname(parentSource), name.split('.')[-1])
        if isdir(path):
            path = join(path, '__init__.py')
            if isfile(path):
                return path
            raise PackageMissingInitException()
        path += '.py'
        if isfile(path):
            return path
        raise PackageMissingChildException()

    from imp import find_module, PKG_DIRECTORY, PY_SOURCE

    f, path, (suffix, mode, type_) = find_module(name)
    if f:
        f.close()
    if type_ == PY_SOURCE:
        return path
    elif type_ == PKG_DIRECTORY:
        path = join(path, '__init__.py')
        if isfile(path):
            return path
        raise PackageMissingInitException()
    raise NotASourceFileException('Name ' + name + ' refers to the file at path ' + path + ' which is not that of a source file.')

rawDescription: Check Contents of Python Package without Running it?


code:
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
fig, ax = plt.subplots()
x = mu + sigma * np.random.randn(10000)
ax.set_yscale('log', basey=2)
n, bins, histpatches = ax.hist(x, 50, facecolor='green', alpha=0.75)
plt.show()

rawDescription: Histogram with base 2 logarithmic y-scale in matplotlib?


code:
import numpy
from operator import mul
from fractions import Fraction

def binomial_coefficient(n,k):
    # credit to http://stackoverflow.com/users/226086/nas-banov
    return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )

def pairwise_displacements(a):
    n = a.shape[0]
    d = a.shape[1]
    c = binomial_coefficient(n, 2)

    out = numpy.zeros( (c, d) )

    l = 0
    r = l + n - 1
    for sl in range(1, n): # no point1 - point1!
        out[l:r] = a[:n-sl] - a[sl:]
        l = r
        r += n - (sl + 1)
    return out

rawDescription: Pairwise displacement vectors among set of points


code:
print([item for item in count_dict if count_dict[item] == maxi])
# ['goose', 'duck']

rawDescription: Without using Counter(), how to find most common element in a list?


code:
D = np.vstack((A,B[np.newaxis,:,:]))
print(D.shape)

rawDescription: concatenating two multidimensional arrays in numpy

description: Concatenating two multidimensional arrays in numpy


rawDescription: slice in python, is a copy or just a pointer

description: Slice in python, is a copy or just a pointer


code:
df = pd.read_csv("mwe.csv", index_col=0)
df.index = pd.DatetimeIndex(df.index)

rawDescription: Weird behavior specifying date limits with pandas


rawDescription: Python: Why does list import using quotation marks, how can I avoid this/get rid of them?


code:
def meshgrid(x,y):
    """
    Return coordinate matrices from two coordinate vectors.

    Parameters
    ----------
    x, y : ndarray
        Two 1-D arrays representing the x and y coordinates of a grid.

    Returns
    -------
    X, Y : ndarray
        For vectors `x`, `y` with lengths ``Nx=len(x)`` and ``Ny=len(y)``,
        return `X`, `Y` where `X` and `Y` are ``(Ny, Nx)`` shaped arrays
        with the elements of `x` and y repeated to fill the matrix along
        the first dimension for `x`, the second for `y`.

    See Also
    --------
    index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
                         using indexing notation.
    index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
                         using indexing notation.

    Examples
    --------
    >>> X, Y = np.meshgrid([1,2,3], [4,5,6,7])
    >>> X
    array([[1, 2, 3],
           [1, 2, 3],
           [1, 2, 3],
           [1, 2, 3]])
    >>> Y
    array([[4, 4, 4],
           [5, 5, 5],
           [6, 6, 6],
           [7, 7, 7]])

    `meshgrid` is very useful to evaluate functions on a grid.

    >>> x = np.arange(-5, 5, 0.1)
    >>> y = np.arange(-5, 5, 0.1)
    >>> xx, yy = np.meshgrid(x, y)
    >>> z = np.sin(xx**2+yy**2)/(xx**2+yy**2)

    """
    x = asarray(x)
    y = asarray(y)
    numRows, numCols = len(y), len(x)  # yes, reversed
    x = x.reshape(1,numCols)
    X = x.repeat(numRows, axis=0)

    y = y.reshape(numRows,1)
    Y = y.repeat(numCols, axis=1)
    return X, Y

rawDescription: Numpy meshgrid in 3D

description: Numpy meshgrid in 3D


code: ['regard- ed', 'com- pared']

rawDescription: How to catch words that ends with dash and its following word? Regex

description: Catch words that ends with dash and its following word? Regex


code:
import re
re.sub(r'|'.join(map(re.escape, replace_list)), '', words)

rawDescription: Most efficient way to remove multiple substrings from string?


code: return '%s| %s|'%(tokens[0],'|'.join(["'%s',%s"%(word,words.count(word)) for word in set(words)]))

rawDescription: How can I read and group this CSV data?

description: Read and group this CSV data


code:
disparray = myarray + (arange(6) * .2)[:,None]
plot(X.flatten(), disparray.flatten(), '.')

rawDescription: Python plot values at nodes in meshgrid

description: Python plot values at nodes in meshgrid


code:
import Tkinter as tk

button = {}

def toggle_text(button_number):
    print(button_number)

    if (button[button_number][1] == "On"):
        button[button_number][0].configure(text = "Coil %d is Off" %button_number)
        button[button_number][1]='Off'
    else:
        button[button_number][0].configure(text = "Coil %d is On" % button_number)
        button[button_number][1]='On'

root = tk.Tk()
root.title("Click the Buttons to change the state of the coil")

for i in range(1,13):
    button[i]  = [tk.Button(text="Coil %d is On" %i ,
                           width=50,
                           command=lambda i=i: toggle_text(i)), "On"]
    button[i][0].grid(row = i, column = 1)

root.mainloop()

rawDescription: How to change text of Tkinter button initilised in a loop

description: Change text of Tkinter button initilised in a loop


code:
def diff(loc):
    return [y-x for x,y in zip((0,) + loc, loc)]

rawDescription: Python list of combinations of positions


code:
guess = (-1, 0.1, 0)
popt, pcov = optimize.curve_fit(func, xData, yData, guess)

rawDescription: Why does scipy.optimize.curve_fit not fit to the data?


rawDescription: pandas python - round() not behaving correctly

description: Pandas python - round() not behaving correctly


code: i = element_frame[['n1', 'n2', 'n3', 'n4']].isin(node_list).any(axis=1)

rawDescription: Trim Pandas DataFrame based on values in list


code:
import sympy
from sympy import *
a = Symbol('a')
b = Symbol('b')
c = Symbol('c')
eval('5*a+6*b')
eval('5*a+6*b') + eval('2*a+3*b+9*c')

rawDescription: Python string processing based on the numeric part: '5a+6b' + '2a+3b+9c' = '7a+9b+9c'


code:
def dict_keys_without(d,excludes_set):
    return (k for k in d if k not in excludes_set)

rawDescription: Python - Looping Over Specific Variables in a Dictionary


code:
def foo(x):
    if not x:
        return x+2

rawDescription: How about 'empty if statement' in python


rawDescription: why this regular expression returns empty

description: Why this regular expression returns empty


code:
newlist = []
sublist = []
for i in biglist:
    sublist.append(i)
    if i[2] == 10:
        newlist.append(sublist)
        sublist = []

rawDescription: Python - How do I split a nested list into further list?


rawDescription: how to create dict inside one more dict, without overwriting old data

description: Create dict inside one more dict, without overwriting old data


code:
CURRENT_DIR= '/Users/brandizzi/Documents/software/netunong'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': CURRENT_DIR+ '/database.db', # <- The path
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

rawDescription: Where is the sqlite database file created by Django?


code: from __future__ import unicode_literals

rawDescription: Python 2.7, Appengine Data Store & Unicode


rawDescription: How do I find the square root of the negative integer -16 or the numbers that it is a multiple of with a while loop

description: Find the square root of the negative integer -16 or the numbers that it is a multiple of with a while loop


code: pos_tag([porter.stem(word) for word in word_tokenize(sent)])

rawDescription: Confused about priority between stemmer and pos tagger


code:
word = 'AMERICANS'
lemmatized = wnl().lemmatize(word.lower())
if word.istitle():
    word = lemmatized.capitalize()
elif word.upper()==word:
    word = lemmatized.upper()
else:
    word = lemmatized
# word = 'AMERICAN'

rawDescription: nltk lemmatizer doesn't know what to do with the word Americans

description: Nltk lemmatizer doesn't know what to do with the word Americans


code:
import flask

app = flask.Flask(...)
app.json_encoder = MyJSONEncoder

rawDescription: How to convert all Decimals in a Python data structure to string?

description: Convert all Decimals in a Python data structure to string