code:
list1 = [1,True,"high",42,"low"]
list2 = [1,False,"low",42,"low"]
map(lambda x,y: 1 if x == y else 0, list1, list2)
sum(map(lambda x,y: 1 if x == y else 0, list1, list2))

rawDescription: calculate the distance of data on specific column using python language

description: Calculate the distance of data on specific column using python language


rawDescription: Pandas: Get value of mutliple sorting/grouping query


rawDescription: Is it possible to do fill forward with DataFrame.mul() fill_value?


code: store.select(group, where = [ 'field_1000=foo', 'field_1001>0' ])

rawDescription: "Large data" work flows using pandas

description: "Large data" work flows using pandas


rawDescription: wxPython: How to make a TextCtrl fill a Panel

description: WxPython: How to make a TextCtrl fill a Panel


rawDescription: Keyboard interruptable blocking queue in Python


code:
from urllib import request
from bs4 import BeautifulSoup
soup = BeautifulSoup(request.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)").read())
[tag['href'] for tag in soup.select('p a[href]')]

rawDescription: How to find all links in all paragraphs in Beautiful Soup

description: Find all links in all paragraphs in Beautiful Soup


code: ADMIN_ENABLED = False

rawDescription: How can I disable Django's admin in a deployed project, but keep it for local development?

description: Disable Django's admin in a deployed project, but keep it for local development


code:
with open("sth.bin", "rb") as f:
    numbers = [
        struct.unpack('d', chunk)[0]
        for chunk in iter(lambda: f.read(8), "")
    ]

rawDescription: Python read binary: how to unpack a large number of numbers?


rawDescription: Accessing / modifying submatrix of sparse scipy matrix


code:
import sys
print(sys.path)

rawDescription: how to place ".py" file into the search path of your python installation

description: Place ".py" file into the search path of your python installation


code:
c = Counter()
c += Counter('aaabbbcccddd eee fff ggg')
c
c += Counter('aaabbbccc')

rawDescription: Count frequency of letters in a text file


code:
def findGerm(x):
    for ix in xrange(1, len(x)+1):
        if x == x[:ix]*(len(x)//ix):
            return x[:ix]

rawDescription: How can I implement a function that reduces a list to the minimum set of elements that are repeated in the list?

description: Implement a function that reduces a list to the minimum set of elements that are repeated in the list


rawDescription: Regexp split string with additional conditions


code:
# first way
sorted = df.sort(['type', 'value'], ascending = [True, False])

first = sorted.groupby('type').first().reset_index()

rawDescription: Pandas, how to filter a df to get unique entries?


code:
class Manga_site(object):

    def __init__(self,homepage,collection_page,base_manga_page,manga_title = ""):
        self.homepage = homepage
        self.collection_page = collection_page
        self.base_manga_page = base_manga_page
        self.manga_title = manga_title

class Mangacanblog(Manga_site):

    def __init__(self,manga_title):
        super(Mangacanblog, self).__init__(bloglink, collectionpagelink, basepagelink, manga_title.lower())

rawDescription: python inheritance __init__ confusion

description: Python inheritance __init__ confusion


rawDescription: Python: numpy.var yields unknown number

description: Python: numpy.var yields unknown number


code:
class Note2(object):
    def __init__(self, name, value): self.name, self._size = name, value
    def _set_size(self, value): self._size = value
    size = property(lambda x: x._size+1, _set_size)
    def __repr__(self): return str(self.size) #simple trick to gain visual access to .size

class Notebook2(object):
    def __new__(cls, *notes):
        notebook = object.__new__(cls)
        notebook._notes = {note.name: note.size for note in notes}
        for note in notes: setattr(notebook, note.name, note)
        return notebook

memo1, report1 = Note2("memo", 5), Note2("report", 20)
notebook1 = Notebook2(memo1, report1)
print(notebook1.memo, notebook1.report) # 6 21
memo2, report2 = Note2("memo", 35), Note2("report", 40)
notebook2 = Notebook2(memo2, report2)
print( notebook2.memo, notebook2.report) # 36 41
print(notebook1.memo, notebook1.report) # 6 21
notebook1.memo.size += 16
print(notebook1.memo) # 23
print(memo1) # 23, Notice this will also set the original objects value to the new value as well
notebook1.memo += 15 # TypeError: unsupported operand type(s) for +=: 'Note2' and 'int' - It is true without making it as a property does make it less effective to work with

rawDescription: Adding properties dynamically using functions created dynamically


rawDescription: Parsing a CS:GO language file with encoding in Python


rawDescription: Celey + Python ignores update_state calls


code:
minor_ticks = []
for i in range(min_exponent, max_exponent):
    for j in range(2,10):
         minor_ticks.append(i+np.log10(j))

plt.gca().set_yticks(minor_labels, minor=True)

rawDescription: Aspect ratio in semi-log plot with Matplotlib


code:
def foo ():
    ''' But do not remove this #1 docstring
    '''

    pass

rawDescription: python regex to remove comments

description: Python regex to remove comments


code:
import numpy as np
from sklearn import datasets
from sklearn.metrics import  pairwise

iris = datasets.load_iris()

X = iris.data
Y = iris.target

# dividing X by classes {0,1,2} to perform intra-distances
X0 = X[np.where(Y==0)]
X1 = X[np.where(Y==1)]
X2 = X[np.where(Y==2)]

sim0_intra = pairwise.pairwise_distances(X0, metric='euclidean')
sim1_intra = pairwise.pairwise_distances(X1, metric='euclidean')
sim2_intra = pairwise.pairwise_distances(X2, metric='euclidean')

rawDescription: Python - Intra similarity

description: Python - Intra similarity


code:
class LineOfOnesChecker(object):

    _DIAG_INDICES = (lambda i: i, lambda i: -i - 1)

    def __init__(self, matrix):
        self._matrix = matrix
        self._len_range = range(len(self._matrix))

    def has_any(self):
        return self.has_row() or self.has_col() or self.has_diag()

    def has_row(self):
        return any(all(elem == 1 for elem in row)
                   for row in self._matrix)

    def has_col(self):
        return any(all(self._matrix[i][j] == 1 for i in self._len_range)
                   for j in self._len_range)

    def has_diag(self):
        return any(all(self._matrix[transf(i)][i] == 1 for i in self._len_range)
                   for transf in self._DIAG_INDICES)

rawDescription: Check for pattern recursively

description: Check for pattern recursively


code:
x = np.arange(5)
x[:, None]

rawDescription: Shortest Syntax To Use numpy 1d-array As sklearn X


code:
from scrapy.contrib.loader import XPathItemLoader
response.body
from scrapy.contrib.loader import XPathItemLoader
xl = XPathItemLoader(response=response, item={'image': ''})
xl
xl.get_xpath('//style', re=r"background-image.*/([^/]+)'")
xl.add_xpath('image', '//style', re=r"background-image.*/([^/]+)'")
xl.load_item()

rawDescription: How to extract background-url from css definition with scrapy

description: Extract background-url from css definition with scrapy


code: ax = df[['original', 'new']].groupby(df['by column']).boxplot(figsize=(12,6))

rawDescription: pandas boxplot: swap box placement for comparison

description: Pandas boxplot: swap box placement for comparison


code:
timeit.timeit('r(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8]); r=q.rotate', number=1000000)
timeit.timeit('r(-1)', setup='import collections; q = collections.deque([0,1,2,3,4,5,6,7,8]); r=q.rotate', number=100000000)

rawDescription: Python array manipulation

description: Python array manipulation


code:
from pprint import pprint

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

url ='http://courses.it-tallaght.ie/'

driver = webdriver.Firefox()
driver.get(url)

courses = {}
for department_link in driver.find_elements_by_css_selector("div#homeProgrammes a[onclick]"):
    department = department_link.text

    # open department
    department_link.click()

    # grab a list of courses
    overlay = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'ProgrammeListForDepartment')))
    courses[department] = [course_link.text for course_link in overlay.find_elements_by_css_selector("ol > li > a")]

    # close department
    overlay.find_element_by_link_text("close").click()

pprint(courses)

driver.close()

rawDescription: Scrape a lightbox overlay using Selenium, Beautiful Soup in Python


rawDescription: Return a list of words on a line but ignore certain whitespace


code:
raw = raw_input('Filename: ')
ip = raw_input('Host: ')
command = 'tcpdump -c5 -vvv -w {0} {1}'.format(raw, ip)   # the command goes here
subprocess.call(command.split(), shell=False)   # call subprocess and pass the command as a list using split

rawDescription: Subprocess Variables

description: Subprocess Variables


code:
from collections import defaultdict

def merge_final_values(values):
    mergeddict = defaultdict(list)
    for group in values:
        mergeddict[group[:-1]].append(group[-1])
    return [(k + (tuple(v),) if len(v) > 1 else k + tuple(v))
                for k, v in mergeddict.iteritems()]

test = [(1, 2, 'R'), (1, 3, 'S'), (1, 2, 'S'), (2, 3, 'S')]

print(merge_final_values(test))

rawDescription: merge two tuples with same key

description: Merge two tuples with same key


code: postTtlLbl = Label(postTtlFrame, text="Page title:").grid(row=0, column=0)

rawDescription: Issues with layout management in Tkinter Python application


code:
my_codons = 'atgaaaccaaag'
codons = [my_codons[i:i+3] for i in range(0,len(my_codons),3)]
codons
codons.count('aaa')

rawDescription: count the number of a certain triplet in a file (DNA codon analysis)

description: Count the number of a certain triplet in a file (DNA codon analysis)


code:
import re
converter = re.compile(r"\?P<.*?>")

def recursive_parse(urlpatterns, lst):
    for pattern in urlpatterns:
        obj = {
            "pattern": converter.sub("", pattern.regex.pattern)
        }
        if hasattr(pattern, "name") and pattern.name is not None:
            obj["name"] = pattern.name
        if hasattr(pattern, "namespace"):
            obj["namespace"] = pattern.namespace

        if hasattr(pattern, "url_patterns"):
            if "urls" not in obj:
                obj["urls"] = []
            recursive_parse(pattern.url_patterns, obj["urls"])

        lst.append(obj)

def generate_paths(urlpatterns):
    paths = []
    recursive_parse(urlpatterns, paths)
    return paths

rawDescription: Django get url regex by name

description: Django get url regex by name


code:
def is_subtitled_3d(showtimes):
  return showtimes.filter(
    language=LANGUAGE_SUBTITLED,
    type_vip__isnull=True,
    type_3d=1,
    type_gtmax__isnull=True,
    type_xd__isnull=True
  )

rawDescription: Modify Django QuerySet object after it has been created


code:
from textwrap import TextWrapper
w = TextWrapper(16, break_long_words=True)
w.wrap("this_is_a_really_long_word")
w = TextWrapper(16, break_long_words=False)
w.wrap("this_is_a_really_long_word")

rawDescription: Python - split sentence after words but with maximum of n characters in result


rawDescription: Getting argument list in a Boost:Python function


code:
pattern1 = re.compile('[^0-9a-zA-Z]+')
pattern2 = re.compile('\s+')
for k in range(len(titles)):
    #remove all non-alphanumeric characters
    s = re.sub(pattern1,' ',titles[k])

    #remove extra white space
    s = re.sub(pattern2,' ', s).strip()

rawDescription: String substitution performance in python


code: players = [player[0] for player in playerPars]

rawDescription: Using a for loop to select items and put them into a list


text: Man I like me some @twitterapi

Twitter API

screen_name: twitterapi

source: web

fakekurrik

profile_sidebar_fill_color: ffffff

description: I am just a testing account, following me probably won't gain you very much

time_zone: Pacific Time (US & Canada)

screen_name: fakekurrik

rawDescription: How to stream twitter mentions with tweepy?

description: Stream twitter mentions with tweepy


code:
# for colored console but not file
logger.infoc('Colored message')
# for normal
logger.info('Normal message')

rawDescription: How to decorate console logger messages in Python?

description: Decorate console logger messages in Python


code:
class SparseTable(object):

    def __init__(self, iterable):
        d = {}
        col_label_set = set()
        for row_label, col_label, value in iterable:
            try:
                subdict = d[row_label]
            except KeyError:
                subdict = {}
                d[row_label] = subdict
            subdict[col_label] = value
            col_label_set.add(col_label)
        self.d = d
        self.col_label_set = col_label_set

    def tabulate(self, row_writer, corner_label=u"", missing=u""):
        d = self.d
        col_labels = sorted(self.col_label_set)
        row_labels = sorted(d.iterkeys())
        orow = [corner_label] + col_labels
        row_writer(orow)
        for row_label in row_labels:
            orow = [row_label]
            subdict = d[row_label]
            for col_label in col_labels:
                orow.append(subdict.get(col_label, missing))
            row_writer(orow)

if __name__ == "__main__":

    import sys

    test_data = u"""
    3277,4733,54.1
    3278,4741,51.0
    3278,4750,28.4
    3278,4768,36.0
    3278,4776,50.1
    3278,4784,51.4
    3279,4792,82.6
    3279,4806,78.2
    3279,4814,36.4
    """.splitlines(True)

    def my_writer(row):
        sys.stdout.write(u"\t".join(row))
        sys.stdout.write(u"\n")

    def my_reader(iterable):
        for line in iterable:
            line = line.strip()
            if not line: continue
            splat = line.split(u",")
            if len(splat) != 3:
                raise ValueError(u"expected 3 fields, found %d" % len(splat))
            yield splat

    table = SparseTable(my_reader(test_data))
    table.tabulate(my_writer, u"A/B", u"....")

rawDescription: Script to convert Huge Three column table into table


code:
box1 = AddDirTo('box1.txt') #note: you did close box1's quote on your question
cupcake = Button(donut,text = "Box #1", command = open(box1))

rawDescription: Retrieve multiple files from same directory


code:
b = map(obj.getDateTimeStat,data)
next(b)
next(b)
next(b)
next(b)
next(b)
next(b)

rawDescription: Python: Map calling a function not working


code: matching_accounts = [sender['sender'] for sender in snaps if sender['media_type'] == 3]

rawDescription: Filtering results in python, I need one variable but only if based on another


code:
from itertools import izip, chain
def partition(alist, indices):
    pairs = izip(chain([0], indices), chain(indices, [None]))
    return (alist[i:j] for i, j in pairs)

rawDescription: Split a list into parts based on a set of indexes in Python


code:
class PerUserAuthorization(Authorization):
  def apply_limits(self, request, object_list):
    if request and hasattr(request, 'user'):
        if request.user.is_authenticated():
            object_list = object_list.filter(user=request.user)
            return object_list

    return object_list.none()

rawDescription: django and backbone.js questions

description: Django and backbone.js questions


code:
class MyClass(object):
    # This works (fast)
    query = text(str(select(...).where(...).order_by(text('distance')).limit(text('1'))))
    ...

    @classmethod
    def issue_query(cls, **params):
        cls.engine.execute(cls.query, params)

rawDescription: Is there a way to make SQLAlchemy pre-compile a query?


code:
def iterate_strings(n):
    if n <= 0:
        yield ''
        return
    for c in string.ascii_lowercase:
        for s in iterate_strings(n - 1):
            yield c + s

rawDescription: increasing string size through loop

description: Increasing string size through loop


code:
"This is a string with an \"escaped quote\" inside it"
""
"data"

rawDescription: Correctly parsing string literals with python's re module


code:
from __future__ import print_function
from collections import Counter
from collections import defaultdict
import random

mylist=[1,1,1,1,1,1,2,3,2,2,2,2,3,3,4,5,5,5,5]*10

def s1(mylist):
    return {k:mylist.count(k) for k in set(mylist)}

def s2(mlist):
    return Counter(mylist)

def s3(mylist):
    mydict=dict()
    for index in mylist:
        mydict[index] = mydict.setdefault(index, 0) + 1
    return mydict

def s4(mylist):
    mydict={}.fromkeys(mylist,0)
    for k in mydict:
        mydict[k]=mylist.count(k)
    return mydict

def s5(mylist):
    mydict={}
    for k in mylist:
        mydict[k]=mydict.get(k,0)+1
    return mydict

def s6(mylist):
    mydict=defaultdict(int)
    for i in mylist:
        mydict[i] += 1
    return mydict

def s7(mylist):
    mydict={}.fromkeys(mylist,0)
    for e in mylist:
        mydict[e]+=1
    return mydict

if __name__ == '__main__':
    import timeit
    n=1000000
    print(timeit.timeit("s1(mylist)", setup="from __main__ import s1, mylist",number=n))
    print(timeit.timeit("s2(mylist)", setup="from __main__ import s2, mylist, Counter",number=n))
    print(timeit.timeit("s3(mylist)", setup="from __main__ import s3, mylist",number=n))
    print(timeit.timeit("s4(mylist)", setup="from __main__ import s4, mylist",number=n))
    print(timeit.timeit("s5(mylist)", setup="from __main__ import s5, mylist",number=n))
    print(timeit.timeit("s6(mylist)", setup="from __main__ import s6, mylist, defaultdict",number=n))
    print(timeit.timeit("s7(mylist)", setup="from __main__ import s7, mylist",number=n))

rawDescription: efficient way to count the element in a dictionary in Python using a loop

description: Efficient way to count the element in a dictionary in Python using a loop


rawDescription: Click on buttons with images

description: Click on buttons with images


code:
pool = multiprocessing.Pool(processes=6)
try:
    results = pool.map(analysis.analyze, paths)
finally:
    pool.close()
    pool.join()

rawDescription: How to pass variables in parent to subprocess in python?

description: Pass variables in parent to subprocess in python


code:
df = np.asarray(x - y)                # the difference between the images
dst = np.sqrt(np.sum(df**2, axis=1))  # their euclidean distances

rawDescription: Euclidean distances between several images and one base image


code: w = vars(numpy)[window](11)

rawDescription: accessing module-level functions in Python if their name is stored in a variable

description: Accessing module-level functions in Python if their name is stored in a variable


code:
x = ["age", "Bonkers", "cheese"]
x.sort()
x
str.lower("Bonkers")
x.sort(key=str.lower)
x

rawDescription: Custom sort order of list

description: Custom sort order of list


code:
class Breakfast(object):
    pass

class HealthyBreakfast(object):
    def __init__(self, spam):
        self.spam, self.eggs = spam, 0

class NormalBreakfast(object):
    def __init__(self, spam, eggs):
        self.spam, self.eggs = spam, eggs

rawDescription: Multiple constructors in python, using inheritance


rawDescription: Access individual elements of an array of several arrays, Python


code:
flistC11 = glob.glob('ES*')
for fname in flistC11:
    # ...something...
    np.savetxt('{0}.dat'.format(fname), np.c_[strain_percent, es_avg, es_std])

rawDescription: How to make file name a variable using np.savetxt in python?

description: Make file name a variable using np.savetxt in python


code:
from functools import wraps

def register_gw_method(method_or_name):
    """Cool!"""
    def decorator(method):
        if callable(method_or_name):
            method.gw_method = method.__name__
        else:
            method.gw_method = method_or_name
        @wraps(method)
        def wrapper(*args, **kwargs):
            method(*args, **kwargs)
        return wrapper
    if callable(method_or_name):
        return decorator(method_or_name)
    return decorator

rawDescription: Python - making decorators with optional arguments


code:
details = {}
questions = [("gender", "What is your gender?"), ("age", "How old?"), ("name", "What is your name?")]
response = ""
while response not in ("bye", "cya"):
    for detail, question in questions:
        response = input(question)
        if response in ("bye", "cya"):
            break
        details[detail] = response
    print(details)

rawDescription: How to make a while loop exit when user enters a certain string?

description: Make a while loop exit when user enters a certain string


code:
def remainder(a,b):
    if a<b: #trivial: remainder = a - b*0 = a
        return a
    else: #reduce the problem to a simple one
        return remainder(a-b, b)

rawDescription: how to compute a%b recursively?

description: Compute a%b recursively


code:
def find_one(query, string):
    if query in string:
        return [query]
    return []

rawDescription: If thing exists, do something with thing


code: frequency = bisect(AISmessages[messageIndex:], message+86400)

rawDescription: Binary search to find last element in sorted list that is less then specific value


code:
class Test:
    some_dict = {}
Test.some_dict[Test] = True

rawDescription: class __init__ (not instance __init__)

description: Class __init__ (not instance __init__)


code: wx.Panel.__init__(self, parent)

rawDescription: Use class variable in another class

description: Use class variable in another class


code: Person.__init__(self, name, phone)

rawDescription: Inheritance of attributes in python using _init_


rawDescription: Django: Saving multiple ManyToMany fields within a transaction


rawDescription: Any pretty python string formatting for a counter?


code:
labels = [date.isoformat() for date in (start + oneday*i for i in xrange(0,470))]
labels = labels[::7]
plt.xticks(x_data[::7], labels, rotation='vertical')

rawDescription: Converting Integer (Day Count) X Axis to Months


rawDescription: Get a random boolean in python?

description: Get a random boolean in python


code:
import os
import time
os.environ['TZ'] = tz
time.tzset()

rawDescription: Quickly parse Python datetime in a non-local timezone, adjusting for daylight savings


code:
class Queue:
    def __init__(self, maxsize=0):
        ...
        self.mutex = threading.Lock()
        self.not_empty = threading.Condition(self.mutex)
        self.not_full = threading.Condition(self.mutex)
        self.all_tasks_done = threading.Condition(self.mutex)
        self.unfinished_tasks = 0

rawDescription: Does the multi-threaded support of Queue exhibit overthread even when used for just one thread?


code:
def __getitem__(self, i):
    if i >= len(self):
        raise IndexError("Index out of range.")

    current = self.head
    for _ in xrange(i):
        current = current.next

    return current

rawDescription: How would a linked list be faster in iteration? with __iter__ and __next__ or with __getitem__?


code:
from bbfreeze import Freezer
f = Freezer("project_name", includes=("selenium","SendKeys",)) #list problem packages here to manually include
f.addScript("project_name_script.py")
f()    # starts the freezing process

rawDescription: Python GUI2Exe Application Standalone Build (Using Py2Exe)


rawDescription: Horizontal analysis by generating list using while-loop


rawDescription: plot single row of 2d numpy array against 1d list

description: Plot single row of 2d numpy array against 1d list


code:
ch = (input('Veuillez entrer une liste des valeurs separees par virgules: '))
inverse(ch)
print(inverse(ch))

rawDescription: How to return a list with brackets?

description: Return a list with brackets


code:
from pyspark.sql import Row
from pyspark.mllib.linalg import DenseVector

row = Row("gender", "foo", "bar")

df = sc.parallelize([
  row("0", 3.0, DenseVector([0, 2.1, 1.0])),
  row("1", 1.0, DenseVector([0, 1.1, 1.0])),
  row("1", -1.0, DenseVector([0, 3.4, 0.0])),
  row("0", -3.0, DenseVector([0, 4.1, 0.0]))
]).toDF()

rawDescription: Encode and assemble multiple features in PySpark


code: print(l.swapcase().replace("2", "")*2)

rawDescription: Removing numbers.

description: Removing numbers.


rawDescription: Count to zero then Count up

description: Count to zero then Count up


rawDescription: How can I check if a list exist in a dictionary of lists in the same order

description: Check if a list exist in a dictionary of lists in the same order


rawDescription: How do you set a variable number of regex expressions?

description: Set a variable number of regex expressions


code:
class Base2(Base1):
    @classmethod
    def setUpClass(cls):
        print('setupClass - this is Base2')
        super(Base2, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        print('tearDownClass - this is Base2')
        super(Base2, cls).tearDownClass()

rawDescription: could setUpClass extended in unnitest framework?

description: Could setUpClass extended in unnitest framework


code:
import re
p = re.compile(r',? ?\bclass="(?![ab]")[^"]+"')
test_str = "class=\"a\", class=\"b\", class=\"ab\", class=\"body\", class=\"etc\"\nclass=\"b\", class=\"ab\", class=\"body\", class=\"etc\", class=\"a\"\nclass=\"b\", class=\"ab\", class=\"body\", class=\"a\", class=\"etc\""
result = re.sub(p, '', test_str)
print(result)

rawDescription: Delete substring not matching regex in Python


code: df = pd.DataFrame(d)

rawDescription: Python creating Covariance matrix from List


code:
from scipy.stats import f_oneway
t, p =  f_oneway(*data.values())
p

rawDescription: How to calculate p-value for two lists of floats?

description: Calculate p-value for two lists of floats


code:
xcoord = x[int((x.size/3)*2)]
ycoord = y[int((x.size/3)*2)] / 2
plt.text(xcoord,ycoord,"Text")

rawDescription: Plotting a curve with different background colors in python


code:
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['v'] = 1
d['b'] = 1
d

rawDescription: How to preserve the item order in a Python dictionary?

description: Preserve the item order in a Python dictionary


code:
from tornado.testing import gen_test

class HandlerTest(testing.AsyncHTTPTestCase):
    def get_app(self):
        return web.Application([('/', Handler)])

    def get_new_ioloop(self):
        return tasyncio.AsyncIOMainLoop()

    @gen_test
    def test_put(self):
        response = yield self.http_client.fetch(self.get_url('/'), method='PUT')
        self.assertEqual(b'spam', response.body)

rawDescription: Can only perform GET requests in Tornado test


code:
def rec(current_item):
    if type(current_item) == list:
        for items in current_item:
            for item in rec(items):
                yield item
    elif type(current_item) == int:
        yield current_item

rawDescription: Flattening a list which consist of integer and list


code: [field.name for field in model._meta.fields if not field.primary_key]

rawDescription: Get all fields except one

description: Get all fields except one


code: args, unknown = parser.parse_known_args()

rawDescription: Python argparse ignore unrecognised arguments


code: p = Process(target=produce)

rawDescription: deadlock because of blocking Queue.get() method

description: Deadlock because of blocking Queue.get() method


code:
def check_names(dirpath, file_name):
    check = False
    new_name = None
    first_check = re.match("^\d\d - ", file_name)
    second_check = re.match("^\d\d ", file_name)
    if first_check or second_check:
        check = True
        if first_check:
            new_name = file_name[first_check.span()[1]:]
        else:
            new_name = file_name[second_check.span()[1]:]
        old_path = os.path.join(dirpath, file_name)
        new_path = os.path.join(dirpath, new_name)
        shutil.move(old_path, new_path)
    return check, new_name

def get_old_file(check, a_file):
    if not check[0]:
        old_file = a_file
    else:
        old_file = check[1]
    return old_file

def move_music(source_dir, destination, dirpath, a_file):
    check = check_names(dirpath, a_file)
    dir_name = os.path.split(dirpath)[-1]
    if dir_name != source_dir:
        check_folders(destination, dir_name)
        if os.path.join(source, dir_name) not in COPIED_DIRECTORIES:
                path = os.path.join(source, dir_name)
                COPIED_DIRECTORIES.append(path)
        old_file = get_old_file(check, a_file)
        old_path = os.path.join(dirpath, old_file)
        new_path = os.path.join(destination , dir_name)
        shutil.move(old_path, new_path)

    else:
        old_file = get_old_file(check, a_file)
        old_path = os.path.join(dirpath, old_file)
        shutil.move(old_path, destination)

def check_move(source, destination, file_extension, sub_string):
    source_dir = os.path.split(source)[-1]
    for dirpath, dirnames, filenames in os.walk(source):
        for a_file in filenames:
            if (a_file.endswith(file_extension)
                and sub_string in a_file):
                move_music(source_dir, destination, dirpath, a_file)

rawDescription: Cleaner way to move renamed files when walking over directory


code:
class obj:
    def __del__(self):
         global _ref
         _ref = self
         return

rawDescription: How to make an object indestructible even with force deletion?

description: Make an object indestructible even with force deletion


code:
import re
import csv
with open("in.txt") as f:
    lines = [re.sub('\s(?=\d\d,)',",",x).split() for x in f if x.strip()]
    zipped = zip(*lines)
    with open("out.csv","w") as f1:
        wr = csv.writer(f1)
        wr.writerows(zipped)

rawDescription: Transpose a text file to csv using Python


code:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
# do something with out, err, or don't bother altogether.

rawDescription: How to just call a command and not get its output

description: Just call a command and not get its output


code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 9988))
s.listen(1)

while True:
    conn, addr = s.accept()
    data = conn.recv(1024)
    conn.close()
    my_function_that_handles_data(data)

rawDescription: How to get a python script to listen for inputs from another script

description: Get a python script to listen for inputs from another script


code:
import ruamel.yaml

yaml_str = """\
first_name: Art
occupation: Architect  # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...
"""

data = ruamel.yaml.round_trip_load(yaml_str)
data.insert(1, 'last name', 'Vandelay')

print(ruamel.yaml.round_trip_dump(data))

rawDescription: Can I insert a line into ruamel.yaml's CommentedMap?

description: Insert a line into ruamel.yaml's CommentedMap


code:
def git_commit_all(message):
    return subprocess.check_output(['git', 'commit', '-am', message])

rawDescription: Python: GIT commit programmatically

description: Python: GIT commit programmatically


code:
for line in p.stdout:
  ...

rawDescription: Getting realtime output using subprocess


code:
# Filters for active and inactive rows
active_row_names = ['Moving','Playing','Using Phone']
active_filter = [row in active_row_names for row in df.index]
inactive_filter = [not row for row in active_filter]

active = df.loc[active_filter].sum()       # Sum of 'active' rows as a Series
active  = pd.DataFrame(active).transpose() # as a dataframe, and fix orientation
active.index=["active"]                    # Assign new index name

# Keep the inactive rows as they are, and replace the active rows with the
# newly defined row that is the sum of the previous active rows.
df = df.loc[inactive_filter].append(active, ignore_index=False)

rawDescription: Pandas df sum rows based on index column


code:
msg = resp.info()
msg.getheaders('Set-Cookie')

rawDescription: Using mimetools.Message in urllib2.urlopen


code:
for item in List1:
    print(item.split(None, 1))

rawDescription: Breaking List value with space delimiter - Python


code: screen.blit(cars[change], (0.0))

rawDescription: Using a String to Call a Variable in Python 3.3 with Pygame


rawDescription: Deleting consonants from a string in Python


code: [[row[key] for row in myList] for key in keylist]

rawDescription: How to convert list of dictionaries into list of lists

description: Convert list of dictionaries into list of lists


code:
class MembershipInline(admin.TabularInline):
    model = Todo.tags.through

    def get_formset(self, request, obj=None, **kwargs):
        request.saved_user_pk = obj.user.pk  # Not sure if it can be None
        return super().get_formset(request, obj, **kwargs)

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'tag':
            kwargs['queryset'] = Tag.objects.filter(user__pk=request.saved_user_pk)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: Limit choices and validate django's foreign key to related objects (also in REST)


code:
from gi.repository import Gtk
from os.path import abspath, dirname, join

WHERE_AM_I = abspath(dirname(__file__))

class MyApp(object):

    def __init__(self):
        # Build GUI
        self.builder = Gtk.Builder()
        self.glade_file = join(WHERE_AM_I, 'test.glade')
        self.builder.add_from_file(self.glade_file)

        # Get objects
        go = self.builder.get_object
        self.window = go('window')
        self.myliststore = go('myliststore')
        self.mycombobox = go('mycombobox')

        # Initialize interface
        colors = [
            ['#8C1700', 'Redish'],
            ['#008C24', 'Greenish'],
            ['#6B6BEE', 'Blueish'],

        ]
        for c in colors:
            self.myliststore.append(c)
        self.mycombobox.set_active(0)

        # Connect signals
        self.builder.connect_signals(self)

        # Everything is ready
        self.window.show()

    def main_quit(self, widget):
        Gtk.main_quit()

    def combobox_changed(self, widget, data=None):
        model = widget.get_model()
        active = widget.get_active()
        if active >= 0:
            code = model[active][0]
            print('The code of the selected color is {}'.format(code))
        else:
            print('No color selected')

if __name__ == '__main__':
    try:
        gui = MyApp()
        Gtk.main()
    except KeyboardInterrupt:
        pass

rawDescription: add combobox in glade with python and GObject

description: Add combobox in glade with python and GObject


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelmin, argrelmax

#Generate some example signal
res = 1000
x = np.linspace(0,2*np.pi,res)
y = np.sin(x)
plt.plot(x,y)

#Take a number of discrete steps
Nsteps = 10
skip = x.shape[0]/Nsteps

#Get local minimum and maximum in blocks for whole set of data
xstep = []; ystep =[]
for rec in range(0,x.shape[0],skip):
    srt = rec
    end = rec+skip-1
    if (y[srt] > y[end]):
        indx = argrelmax(y[srt:end],mode='wrap')[0]
    elif (y[srt] < y[end]):
        indx = argrelmin(y[srt:end],mode='wrap')[0]

    xstep.append(x[srt+indx])
    ystep.append(y[srt+indx])

#Plot location of min/max
plt.plot(xstep,ystep,'o')

#Plot the step graph
plt.step(xstep, ystep)

plt.show()

rawDescription: Finding discrete logic levels in a waveform


code:
x = {1,2,3,-1}
x
[_ for _ in x]
x = {1,2,3,0}
x
[_ for _ in x]
import collections
isinstance(x, collections.Iterable)

rawDescription: How can I tell if a structure in Python has order?

description: Tell if a structure in Python has order


code: map(sum, zip(a, b, c))

rawDescription: Adding tuples to produce a tuple with a subtotal per 'column'


code:
import subprocess
dir(subprocess)
subprocess.__all__

rawDescription: Is there a way to access parent modules in Python


code: print(a)

rawDescription: Python string contains byte array

description: Python string contains byte array


code:
text = re.sub(r"\n\n", somespecialsequence, text);
text = re.sun(r"\s*\n", " ", text);
text = re.sub(r"\s+", " ", text);
text = re.sub(somespecialsequence, "\n\n", text);

rawDescription: Matching previously defined groups in python


code:
users = session.query(User).\
              options(subqueryload_all(User.attempts, UserAttempt.challenge)).all()

rawDescription: SQLAlchemy Many-To-Many performance

description: SQLAlchemy Many-To-Many performance


code:
def m(df):
    #resample column Timestamp by 100ms, convert bak to integers
    df['Timestamp'] = df['Timestamp'].astype('timedelta64[ms]')
    df['i'] = 1
    df = df.set_index('Timestamp')
    df1 = df[[]].resample('100ms', how='first').reset_index()
    df1['Timestamp'] = (df1['Timestamp'] / np.timedelta64(1, 'ms')).astype(int)
    #felper column i for merging
    df1['i'] = 1
    #print df1

    out = df1.merge(df,on='i', how='left')
    out1 = out[['Timestamp', 'Sign_1']][(out.Timestamp >= out.S_time1) & (out.Timestamp <= out.End_Time_1)]
    out2 = out[['Timestamp', 'Sign_2']][(out.Timestamp >= out.S_time2) & (out.Timestamp <= out.End_time_2)]

    out1 = out1.rename(columns={'Sign_1':'Bin_time'})
    out2 = out2.rename(columns={'Sign_2':'Bin_time'})

    df = pd.concat([out1, out2], ignore_index=True).drop_duplicates(subset='Timestamp')
    df1 = df1.set_index('Timestamp')
    df = df.set_index('Timestamp')
    df = df.reindex(df1.index).reset_index()
    #print df.head(10)

rawDescription: Python pandas resampling

description: Python pandas resampling


code:
count=capture.getvalue().count('\n')-1 #you should do a count so that you don't add a newline at the end
html_message = template %{"text":capture.getvalue().replace('\n', "<br>\n", count)}

rawDescription: direct Python output to text file and html

description: Direct Python output to text file and html


code:
class Post(models.Model):
    category = models.ForeignKey(Category, verbose_name=_('Community'))

rawDescription: how to change the name of the field displaying in my form

description: Change the name of the field displaying in my form


code:
h = 5
for i in xrange(0, 4 * h, h):
    values = [(6, i, x) for x in xrange(2, 17, 2)]
    for j in starmap(lambda x, y, z:(x, y, z, (x * y) + z), values):
        print('(%d * %d) + %d = %d' % j)

    print('')

rawDescription: Iterations With Unequal Steps

description: Iterations With Unequal Steps


code:
from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')
PROGRAM_DAT     = open('program.dat').read()
CLIENT_SECRETS  = open('client_secrets.json').read()

setup(windows=[{'script': "program.py",
            'other_resources': [
                 (u'PROGRAM_DAT', 1, PROGRAM_DAT),
                 (u'CLIENT_SECRETS', 2, CLIENT_SECRETS)
            ]
           }],
            options = {'py2exe': {'bundle_files': 1, 'compressed': True, "includes" : ['apiclient','httplib2','oauth2client',
                    'uritemplate']}
           },

           zipfile = None
 )

rawDescription: py2exe - Create single executable file out of a folder

description: Py2exe - Create single executable file out of a folder


rawDescription: Python's barchart equivalent in R

description: Python's barchart equivalent in R


code:
aX, aY = player.pos
bX, bY = enemy.pos
distance = abs(aX - bX) + abs(aY - bY)

rawDescription: Movement in 2D Map in Python

description: Movement in 2D Map in Python


code:
df = pd.DataFrame({"Name": ["A","B","C","D"]})
df
df["Name"].isin(eligible_players) # remember, this will be [10, 20, 30]
df["Name"].isin(eligible_players.index)
df["Name"].isin(eligible_players.index).sum()

rawDescription: Problems with isin pandas

description: Problems with isin pandas


code:
not str2
not string

rawDescription: Assigning empty value or string in Python


rawDescription: How do I Auto-Name Each Subsequent .CSV File of Scraped Date?


rawDescription: Python Use Regex Sub Multiple Times in 1 Pass


rawDescription: Python can not get links from web page

description: Python can not get links from web page


code:
item = treeWidget.currentItem() # one way
item = treeWidget.itemAt(centerOfTree) # another way

# either save the text value or whatever the custom
# identifying value is of your item
text = item.text()

rawDescription: Remembering Scroll value of a QTreeWidget in PyQt


code:
import itertools
list(set(itertools.chain(a, b, c)))

rawDescription: Select unique value in many lists in python


rawDescription: Python: Convert '3.5' to integer

description: Python: Convert '3.5' to integer


code:
timeit(set(a) & set(b))
timeit(set(a).intersection(b))
timeit([x for x in a if x in b])

rawDescription: compare if an element exists in two lists

description: Compare if an element exists in two lists


code: x + y

rawDescription: Create an array from n copies of subarray in python


code:
with futures.ThreadPoolExecutor(1) as executor:
    f1 = executor.submit(someClass.doSomething)
    f2 = executor.submit(someClass.doSomethingElse)
    futures.wait((f1, f2))
    f3 = executor.submit(someClass.doSomethingElser, f1.result(), f2.result())
    result = f3.result()

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

description: Call a function on a running Python thread


code:
def WeekCombo(request):
    fweeks = []
    cursor = connections['nocdb'].cursor()
    for start, end in WeeklyReports().FourWeeks(2013, 48):
        cursor.execute("""
            SELECT DISTINCT (p.name) AS platform,
                COUNT(e.id ) AS count
            FROM event e, lu_platform p
            WHERE e.platform_id = p.id
            AND e.sourcetype_id = 1
            AND e.event_datetime BETWEEN %s AND %s
            AND e.sender_id  NOT IN ( 759, 73 )
            GROUP BY p.name
            ORDER BY p.name""", [start, end] )
        fweeks.extend(cursor.fetchall())
    fweeks = zip(fweeks)
    return render_to_response('form.html', {'fweeks': fweeks},
                              context_instance=RequestContext(request))

rawDescription: fetchall for loop multiple list to one

description: Fetchall for loop multiple list to one


rawDescription: PyQT -- How can you make a QTreeview uneditable but also selectable?


code: gender = getattr(person, attr_name)

rawDescription: Why should I ever use "getattr()"?

description: Why should I ever use "getattr()"


rawDescription: Python Data Model Document : an unbound user-defined method and a class method object


code:
import wx
from xlwt import *

w = Workbook()
ws1 = w.add_sheet('sheet 1')

class MyFrame(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,'Button to Excel', size = (300,300))
        panel=wx.Panel(self)

        extBtn = wx.Button(panel, label="Exit",pos=(100,150))
        extBtn.Bind(wx.EVT_BUTTON, self.onClose)

        btn = wx.Button(panel,label = "Mem 1",pos=(100,100))
        btn.Bind(wx.EVT_BUTTON, self.onButton)

    def onClose(self, event):
        w.save('a.xls')
        self.Close()

    def onButton(self,event):
        btn = event.GetEventObject()
        lbl = btn.GetLabel()
        ws1.write(0, 0, lbl)

if __name__ == '__main__':
    app=wx.PySimpleApp()
    frame=MyFrame(parent=None,id=-1)
    frame.Show()
    app.MainLoop()

rawDescription: wxpython how to display button label into xlwt

description: Wxpython how to display button label into xlwt


code:
import re

a = {'b': {'c': True}}

in_ = 'a.b.c'
match = re.match(
    r"""(?P<dict>      # begin named group 'dict'
          [^.]+        #   one or more non-period characters
        )              # end named group 'dict'
        \.             # a literal dot
        (?P<keys>      # begin named group 'keys'
          .*           #   the rest of the string!
        )              # end named group 'keys'""",
    in_,
    flags=re.X)

d = vars()[match.group('dict')]
for key in match.group('keys'):
    d = d.get(key, None)
    if d is None:
        # handle the case where the dict doesn't have that (sub)key!
        print("Uh oh!")
        break
result = d

# result == True

rawDescription: parse a dot seperated string into dictionary variable

description: Parse a dot seperated string into dictionary variable


code:
import numpy
a = numpy.array([[1,2],[3,4],[5,6]])
numpy.savetxt("foo.csv", a, delimiter=',', header="A,B", comments="")

rawDescription: Save multiple arrays to a csv file with column names


code:
def send_email_action(modeladmin, request, queryset):
    whatever_you_want_to_do_with_request_and_queryset
send_email.short_description = 'Send email'

class MyModelAdmin(admin.ModelAdmin):
    ...
    actions = [
        send_email_action
    ]

rawDescription: Django Admin Customizing

description: Django Admin Customizing


code:
query = DBSession.query(CompleteBloodCount).\
    join(PrimateToMetricBlock, PrimateToMetricBlock.metricblock_id == MetricBlock.id)

rawDescription: SQLAlchemy: One-Way Relationship, Correlated Subquery


rawDescription: Faster string assignment using Numpy

description: Faster string assignment using Numpy


code:
import inspect
def caller_globals():
    # The frame of the caller of the function calling caller_globals.
    caller_frame = inspect.currentframe().f_back.f_back
    return caller_frame.f_globals

rawDescription: globals() of imported functions

description: Globals() of imported functions


code:
class Bunch(yaml.YAMLObject):
    yaml_tag = u'!Bunch'
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        return '{c}({a})'.format(
            c = self.__class__.__name__,
            a = ', '.join(
                ['='.join(map(str,item)) for item in self.__dict__.items()]))
tag_names = ['define', 'action']
namespace = {}
for name in tag_names:
    namespace[name] = type(name, (Bunch,), {'yaml_tag':u'!{n}'.format(n = name)})

definitions = {"one" : 1, "two" : 2, "three" : 3}
actions = {"run" : "yes", "print" : "no", "report" : "maybe"}
text = yaml.dump_all([namespace['define'](**definitions),
                      namespace['action'](**actions)],
                     default_flow_style = False,
                     explicit_start = True)
print(text)

rawDescription: Python dictionaries into yaml documents using PyYaml


rawDescription: pip: upgrade package without upgrading particular dependency

description: Pip: upgrade package without upgrading particular dependency


code:
for sub_array in A:
    sub_array[...] = 0

rawDescription: how to set on zero 3d numpy array?

description: Set on zero 3d numpy array


rawDescription: python callback vs node callback point to point comparisons

description: Python callback vs node callback point to point comparisons


code:
A
B
A.searchsorted(B,side='right')-1
A.searchsorted(A,side='right')-1 # With itself

rawDescription: Find the indices of the lowest closest neighbors between two lists in python


rawDescription: Construct Pandas DataFrame with dict in form - index: list of row values


code:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.dir", download_dir)
fp.set_preference("browser.download.manager.showWhenStarting", False)

fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")

driver = webdriver.Firefox(firefox_profile=fp)

rawDescription: How to emulate Firefox "Save File" -> OK in Python

description: Emulate Firefox "Save File" -> OK in Python


rawDescription: Give a list of nums... Add every 2 numbers (ex: 1,2,3,4 -> 3, 7)?


code: a[np.argmin(a[:, 1])]

rawDescription: Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row


code:
a1
a2
[item for item in itertools.chain(a1, a2)]

rawDescription: How to merge item in list

description: Merge item in list


code:
top = Toplevel()
top.title("Result")

rawDescription: Python Tkinter. Cant apply theme for second window of program


rawDescription: What does python sys.intern do, and when should it be used?


code:
from mock import MagicMock

class YesMan(object):
    def __eq__(self, other):
        return True

anything = YesMan()

mock = MagicMock()
mock(x=123, y=456)
mock.assert_called_once_with(x=anything, y=456)

rawDescription: How to test for the second parameter of a mocked method?

description: Test for the second parameter of a mocked method


code:
print(new.foo)
# None

rawDescription: Use class variables as instance vars?

description: Use class variables as instance vars


code:
from functools import partial

y = partial(x, whatever)

rawDescription: python function with arguments assigned to a variable

description: Python function with arguments assigned to a variable


code:
windows = []
win32gui.EnumWindows(lambda hwnd, resultList: resultList.append(win32gui.GetWindowText(hwnd)),windows)
#enumerates all the windows open from the top down
[i for i in windows if "Microsoft Excel" in i].pop(0)
#this one is closest to the top

rawDescription: Get name of active Excel workbook from Python


rawDescription: Pythonic way to shuffle stacks

description: Pythonic way to shuffle stacks


code:
text = REPLACE_1.sub(r'REPLACE_1', str(row[0]))
text = REPLACE_1.sub(r'REPLACE_1', text)
# ..
text = REPLACE_99.sub(r'REPLACE_99', text)
text = REPLACE_100.sub(r'REPLACE_199', text)

rawDescription: List of compiled regexes in Python

description: List of compiled regexes in Python


code:
import functools

class Memoize(object): #inherit object
    def __init__(self, function):
        self.function = function
        self.memoized = {}
    def __call__(self, *args): #don't accept kwargs you don't want.
        # I removed "hash = args" because it shadowed a builtin function and
        # because it was untrue--it wasn't a hash, it was something you intended for
        # Python to hash for you.
        try:
            return self.memoized[args]
        except KeyError:
            self.memoized[args] = self.function(*args)
            return self.memoized[args]
    def __get__(self, obj, type):
        if obj is None: #We looked up on the class
            return self

        return functools.partial(self, obj)

rawDescription: add a decorate function to a class

description: Add a decorate function to a class


code:
with open(filename, encoding=character_encoding) as file:
    unicode_character_count = sum(len(line) for line in file)

rawDescription: Calculate bytes of the unicode character in python


code:
def StorePassEvent(self, event):
    self.StorePass()

rawDescription: Implementing a Password Dialog with Tkinter


code:
c
type(c)
type(c[0])

rawDescription: Convert list of numpy.float64 to float in Python quickly


rawDescription: Python: list vs. np.array: switching to use certain attributes


code:
items=['foo', 'tri', 'baz']

s = ''
for i, item in enumerate(items):
    if i == len(items) - 1:
        s += 'and {}'
    else:
        s += '{}, '

print(s.format(*items))

rawDescription: Python3 - print a string from a list, seperated by commas with an 'and' before the last item in a list


code:
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('example.cfg')
config.getfloat('Section', 'my_option') # returns 12.2

rawDescription: "Standard" way of creating config file suitable for Python and Java together


code:
def __init__(self, created=None):
    self.created = created or datetime.now()

rawDescription: Python class with datetime.now() when instantiated


rawDescription: pandas: column formatting issues causing merge problems

description: Pandas: column formatting issues causing merge problems


code: clean = open('thefile.txt').read().replace('\n', '')

rawDescription: Simple python/Regex problem: Removing all new lines from a file


code: va['decade'] = (va['contest_id'].apply(lambda x: x[:2])).astype('category')

rawDescription: Years to Decades

description: Years to Decades


code:
import unittest
from amdfilter import *

class FilterTest(unittest.TestCase):
    def testRemoveTimeStampAttribute(self):
        input = '<?xml version="1.0"?><ComponentMain><Component timeStamp="2014"></Component></ComponentMain>'
        output = amdfilter(input)
        expected = '<ComponentMain><Component /></ComponentMain>'
        self.assertEqual(expected, output)

rawDescription: Filtering XML in Python

description: Filtering XML in Python


code: list(map(list, map(range, lst[:-1], lst[1:])))

rawDescription: Generate ranges between pairs of consecutive values


code:
strp = timeit.timeit("t=time.strptime(s, '%H:%M');mins=t.tm_hour * 60 + t.tm_min", "import time; s='02:40'", number=100000)/100000
strp
strp/parsetime

rawDescription: Parsing hh:mm in Python

description: Parsing hh:mm in Python


rawDescription: Pandas - Replace Integers with Floats

description: Pandas - Replace Integers with Floats


code: pyversion('path/to/python')

rawDescription: Sending JSON data over WebSocket from Matlab using Python Twisted and Autobahn


code:
name = 'repo_'
i = 0
repo_list = {}
items = get_items() # defined elsewhere

for item in os.listdir(dirpath):
    i = i + 1 # this was just to add a custom name to the repos located
    repo_name = name + str(i)
    path_to_repo = os.path.join(dirpath, item)

    repo = pygit2.discover_repository(path_to_repo)
    repo_list[item] = repo

rawDescription: Using pygit2's discover_repository to locate multiple repositories in a directory


code: df["industry"] = pd.Series(d)

rawDescription: Add a new column to pandas data frame from dictionary


code: fun = (lambda x: x + 1) if x < y else (lambda x: x - 1)

rawDescription: Calling lambda-created functions returns functions?


code:
import glob
import csv
from datetime import datetime

with open("combined_files_csv", "wb") as outfile:
    writer = csv.writer(outfile, delimiter=",")
    for csvfilename in glob.glob(r"C:\mydirectory\*.csv"):
        with open(csvfilename, "rb") as infile:
            reader = csv.reader(infile, delimiter=",")
            for row in reader:
                startdate = datetime.strptime(row[3], "%Y-%m-%d")
                enddate = datetime.strptime(row[2], "%Y-%m-%d")
                delta = enddate - startdate # difference in days
                row[0:0] = [str(delta)]
                row.append(csvfilename)
                writer.writerow(row)

rawDescription: Need to do a math operation on every line in several CSV files in Python


code:
df[0].apply(lambda v: '_'.join(v.split('_')[1:]))
df[0] = df[0].apply(lambda v: '_'.join(v.split('_')[1:]))

rawDescription: split string column by "_", drop the preceding text, recombine str by "_" in pandas

description: Split string column by "_", drop the preceding text, recombine str by "_" in pandas


rawDescription: cluster points after KMeans clustering (scikit learn)

description: Cluster points after KMeans clustering (scikit learn)


code:
A
A.ravel()[np.random.choice(A.size, c, replace=False)] = np.nan
A

rawDescription: Create sample numpy array with randomly placed NaNs


code:
from django.forms.widgets import ClearableFileInput
import os
# missing imports
from django.utils.safestring import mark_safe
from cgi import escape
from django.utils.encoding import force_unicode

class ShortNameClarableFileInput(ClearableFileInput):
    def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = u'%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'%s'
                                        % (escape(value.url),
                                           escape(force_unicode(os.path.basename(value.url))))) # I just changed this line
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)

rawDescription: Django : customizing FileField value while editing a model


code:
import itertools
import matplotlib.pyplot as plt

def myfun(data, ax):
    ax.plot(*data)

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
para = [
    [[[1,2,3],[1,2,3]],ax1],
    [[[1,2,3],[3,2,1]],ax2],
]
list(itertools.starmap(myfun, para)) # list is need to iterator to be consumed.
plt.show()

rawDescription: Is it possible to plot within user-defined function with python and matplotlib?


code:
url(r'^(?P<project_slug>[\w-]+)/add_todo/$',
    views.ProjectDetailToDoForm.as_view(),
    name='add_todo',
),
...

rawDescription: Django - Query to retrieve pk from other model


code:
#!/usr/bin/env python
from subprocess import check_output

result = check_output("date")

rawDescription: Use NamedTemporaryFile to read from stdout via subprocess on Linux


code: print(repr(vocab))

rawDescription: iterate through unicode strings and compare with unicode in python dictionary

description: Iterate through unicode strings and compare with unicode in python dictionary


code:
class Searchform(ElasticsearchForm):
  q = forms.Charfield(required=False)

  def get_index(self):
    return 'your_index'

  def get_type(self):
    return 'your_model'

  def prepare_query(self):
    if not self.cleaned_data['q']:
      q = "*"
    else:
      q = str(self.cleaned_data['q'])

    return {
      "query": {
        "query_string": {
          "query": q
        }
      }
    }

  def search(self):
    esp = ElasticsearchProcessor(self.es)
    esp.add_search(self.prepare_query, page=1, page_size=25, index=self.get_index(), doc_type=self.get_type())
    responses = esp.search()
    return responses[0]

rawDescription: Indexing/Searching "complex" JSON in elasticsearch


rawDescription: Pythonic way to check logics

description: Pythonic way to check logics


rawDescription: Find common rows of 2 dataframe for 2 columns


code:
s = set()
for counter in counters.values():
    for key in counter:
        s.add(key)

rawDescription: Python map() dictionary values

description: Python map() dictionary values


code:
stringData = infile.read()
stringData = stringData.strip()
stringData = stringData.split()

infileData = []

for item in stringData:
    infileData.append(int(item))

rawDescription: python using data from a list, where by you call the data from its index number

description: Python using data from a list, where by you call the data from its index number


rawDescription: How to work with data from NBA.com?

description: Work with data from NBA.com


code: final

rawDescription: how to combine 3 complex data frames in pandas

description: Combine 3 complex data frames in pandas


code:
import pandas as pd
df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})
df
df[df < 0] = 0
df

rawDescription: How to replace all Negative Numbers in Pandas DataFrame for Zero

description: Replace all Negative Numbers in Pandas DataFrame for Zero


rawDescription: Get values from multiple entries after entry duplication


code: pd.crosstab(rows=dates, cols=log)

rawDescription: Pivot on log event category and group by day


rawDescription: get python class parent(s)

description: Get python class parent(s)


code:
lead_color_name = 'true black'

one_list = [{'true black': ['AA1', ['BB']]}, {'white': ['AA2', ['CC1', 'CC2']]}]

non_lead_colors = [x for x in one_list if lead_color_name not in x]

lead_color = [x for x in one_list if lead_color_name in x][0][lead_color_name]

end_list = []
end_list.append(lead_color[0])
end_list.extend(lead_color[1])
for x in non_lead_colors:
    end_list.extend(list(x.values())[0][1])
print(end_list)

rawDescription: Selecting only some values from dictionaries in list


code:
import threading
import queue

def console(q, lock):
    while 1:
        input()   # Afther pressing Enter you'll be in "input mode"
        with lock:
            cmd = input('> ')

        q.put(cmd)
        if cmd == 'quit':
            break

def action_foo(lock):
    with lock:
        print('--> action foo')
    # other actions

def action_bar(lock):
    with lock:
        print('--> action bar')

def invalid_input(lock):
    with lock:
        print('--> Unknown command')

def main():
    cmd_actions = {'foo': action_foo, 'bar': action_bar}
    cmd_queue = queue.Queue()
    stdout_lock = threading.Lock()

    dj = threading.Thread(target=console, args=(cmd_queue, stdout_lock))
    dj.start()

    while 1:
        cmd = cmd_queue.get()
        if cmd == 'quit':
            break
        action = cmd_actions.get(cmd, invalid_input)
        action(stdout_lock)

main()

rawDescription: Constantly looking for user input in Python


code:
def realign_polar_xticks(ax):
    for theta, label in zip(ax.get_xticks(), ax.get_xticklabels()):
        theta = theta * ax.get_theta_direction() + ax.get_theta_offset()
        theta = np.pi/2 - theta
        y, x = np.cos(theta), np.sin(theta)
        if x >= 0.1:
            label.set_horizontalalignment('left')
        if x <= -0.1:
            label.set_horizontalalignment('right')
        if y >= 0.5:
            label.set_verticalalignment('bottom')
        if y <= -0.5:
            label.set_verticalalignment('top')

rawDescription: python + matplotlib: how to insert more space between the axis and the tick labels in a polar chart?

description: Python + matplotlib: how to insert more space between the axis and the tick labels in a polar chart


rawDescription: How to read columns of varying length from a text file in NumPy using genfromtxt()?

description: Read columns of varying length from a text file in NumPy using genfromtxt()


code:
# Here pointsToAdd is not 30, but the value inputed by the user
strengthPoints += pointsToAdd
# Here strengthPoints == pointsToAdd == the value from the input
pointsToAdd -= strengthPoints
# Here pointsToAdd == 0

rawDescription: While loop in python not working

description: While loop in python not working


code:
magnitude_below_20 = x['Apparent Magnitude'] < 20
dec_above_m10 = x['Dec'] > -10*u.degree
# Get every row that satisfies both conditions:
x_from_comb_condition = x[magnitude_below_20 & dec_above_m10]
# or using the numpy-ufunc (gives the same result):
x_from_comb_condition = x[np.logical_and(magnitude_below_20, dec_above_m10)]

rawDescription: How to index observable coordinates in an astropy Table

description: Index observable coordinates in an astropy Table


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

rawDescription: Python 2d grid : Assigning values to coordinates in the grid


code:
from string import ascii_lowercase as letters
dic = {letters[j]:float(val) for j, val in enumerate(astr.split(' '))}

rawDescription: Solving a task in cosmology using Python 2.7.5


code:
int('fff',16)
da_number = 'fff'
int(da_number, 16)

rawDescription: putting a variable inside of quotes in python

description: Putting a variable inside of quotes in python


code:
value  = int('0x01010000',16)
apple  = 0x01000000
orange = 0x00010000
banana = 0x00000100
bool(value & apple) # tests if apple is part of the value
value |= banana     # adds the banana flag to the value
value &= ~orange    # removes the orange flag from the value

rawDescription: Python hexadecimal comparison

description: Python hexadecimal comparison


code:
from setuptools import setup
from setuptools.command.install import install
from distutils.command.build_py import build_py
import os

class InstallReadsScriptDir(install):
    def run(self):
        self.distribution._x_script_dir = self.install_scripts
        install.run(self)

class BuildConfiguresScriptDir(build_py):
    def run(self):
        build_py.run(self)
        if self.dry_run:
            return
        script_dir = self.distribution._x_script_dir  # todo: check exists
        target = os.path.join(self.build_lib, 'mypackage', 'scriptdir.py')
        with open(target, 'w') as outfile:
            outfile.write('path = """{}"""'.format(script_dir))

setup(
    name="MyPackage",
    version='0.0.1',
    packages = ['mypackage'],
    entry_points = {
        'console_scripts': [
            'footest = mypackage:main',
        ],
    },
    cmdclass= {
        'install': InstallReadsScriptDir,
        'build_py': BuildConfiguresScriptDir,
    },
)

rawDescription: Get entry point script file location in setuputils package?


code:
df = pd.DataFrame(np.random.randint(0, 10, size=(5, 3)), columns=list('abc'))
df
df.to_csv('d:/temp/test.csv', index=False)
(df+100).to_excel('d:/temp/test.xlsx', index=False)

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


rawDescription: Python Drawing ASCII Map

description: Python Drawing ASCII Map


code:
for i,l in enumerate(open(the_file)):
   f = open('new_file_%i.csv' % i, 'w')
   f.write(l)
   f.close()

rawDescription: csv rows into separate txt files?

description: Csv rows into separate txt files


code: "My name is " + name + " and I'm " + str(round(age,2)) + " metres tall"

rawDescription: Basic decrement loop - PYTHON

description: Basic decrement loop - PYTHON


code:
from kivy.clock import Clock
from functools import partial
Clock.schedule_interval(self.update, 2)

rawDescription: Using while loop in Pycharm and Kivy

description: Using while loop in Pycharm and Kivy


code:
outfile=open("out.txt","w")

# First you need to write the header row
outfile.write("\t")
for line2 in open("file2.txt","r"):
    outfile.write(line2.strip() + "\t")
outfile.write("\n")

# You never do anything useful with record, so don't build it
#record=[]

# Open file1 and file2, not file2 and file2, and don't reuse the name line
for line1 in open("file1.txt","r"):
    # You need also need to write the header column
    outfile.write(line1.strip() + "\t")
    #record.append(line)
    for line2 in open("file2.txt","r"):
        # Don't try to compare the string to a list iterator, compare it
        # to the string from the other file.
        if line1==line2:
            # You can't pass write multiple arguments like print, just
            # put the two strings together
            outfile.write("1\t")
        else:
            # Indentation matters in Python
            outfile.write("0\t")
        # next is a function that gets the next value from an iterator;
        # just referring to that function by name doesn't do anything
        #next
    # Don't forget to end each line
    outfile.write("\n")

# You should always close files, but _especially_ writable files
outfile.close()

rawDescription: comparing two files using python to get a matrix

description: Comparing two files using python to get a matrix


code:
indices = set([0, 7, 12, 25])
s = "i like stackoverflow and python"
print("".join(c.upper() if i in indices else c for i, c in enumerate(s)))

rawDescription: change some lowercase letters to uppercase in string

description: Change some lowercase letters to uppercase in string


rawDescription: Shorten the IF condition for 2 variables (same comparison)


code:
import web

urls = (
    '/(.*)', 'hello'
)

app = web.application(urls, globals(), autoreload=False)
application = app.wsgifunc()

class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'

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

rawDescription: Web.py Apache mod_wsgi url rewrite

description: Web.py Apache mod_wsgi url rewrite


code:
x = {1: 2}
dict(x, **{2: 3})
dict(x, foo_bar='spam_eggs')
dict(x, foo='spam', bar='eggs', **{2: 3, 42: 81})
x  # not changed, copies were made

rawDescription: Is it possible to copy and update a python dictionary in a single chained expression?


rawDescription: merging 2D slices into 3D volume in python

description: Merging 2D slices into 3D volume in python


code: unwrapped = login_user.__wrapped__

rawDescription: In Python 3 how can I patch a function inside a module for unit testing?


rawDescription: For loop item unpacking

description: For loop item unpacking


rawDescription: My code works for a single list but not for a nested list. I need to improve it in means of functionality


code:
# Replace convenience down with…

# Verify row totals.
for (r, row) in enumerate(grid[:-1]):
    assert sum(row[:-1]) == row[-1], 'row {}'.format(r)

# Verify column totals.
for (c, col) in enumerate(zip(*grid)[:-1]):
    assert sum(col[:-1]) == col[-1], 'col {}'.format(c)

rawDescription: python coding sum the rows and columns of a grid

description: Python coding sum the rows and columns of a grid


code:
def get_ticket_available_product(self, date_select, client_id, quantity):
    client = Client.objects.get(id=client_id)
    prodCount = Product.objects.filter(client=client_id,status='Active').values_list('id', flat=True)
    for id in prodCount:
        prodAvailable = Ticket.objects.get_ticket_sum_quantity(id, date_select)
        prodAvailable = prodAvailable - quantity
        if prodAvailable < 0:
            data = {'id':id}
        else :
            data = {'id':id}
            data = data['id']
            yield data
    return

rawDescription: how to return the looped values in a method in python/django that no using array

description: Return the looped values in a method in python/django that no using array


code:
import subprocess
file_to_show = "/Applications/iTunes.app"
subprocess.call(["open", "-R", file_to_show])

rawDescription: Python "show in finder"

description: Python "show in finder"


code:
import commands
# Caps Lock is off.
commands.getoutput('xset q | grep LED')[65]
# Setting Caps Lock on now.
commands.getoutput('xset q | grep LED')[65]

rawDescription: Python - How to get current keylock status?


code:
import numpy as np
np.identity(5)
np.identity(5)+np.ones([5,5])
np.identity(5) == np.identity(5)+np.ones([5,5])

rawDescription: Comparing two dictionaries with numpy matrices as values


code:
results = {}
for val in vals:
    i = some_request_to_server(val)
    results.setdefault(i, []).append(val)

rawDescription: python dictionary with list as values

description: Python dictionary with list as values


code: p.add_argument('duration', type = int, nargs='?', help = 'Duration of downtime (minutes), 15 if not specified', default=15)

rawDescription: Change number of mandatory arguments depends on option (argparse)


code:
from pprint import pprint
pprint(data)

rawDescription: Parse a webpage with BeautifulSoup4

description: Parse a webpage with BeautifulSoup4


rawDescription: Iterate over same list twice and avoid duplicates in python


code:
import json
import datetime
your_json_value = '''\
{
  "boolean": true,
  "null": null,
  "number": 123,
  "values": [
    [
      "95",
      "2011-12-04"
    ],
    [
        "90",
        "2011-10-03"
    ]
  ]
}
'''
for _, date in data['values']:
    date = datetime.datetime.strptime(date, '%Y-%m-%d').date()
    print('{:%a %d %B %Y}'.format(date))

rawDescription: JSON value parse with Python

description: JSON value parse with Python


code: data = [[row[0]]+row[1].tolist() for row in data]

rawDescription: Writing Multiple Rows to CSV using Numpy Arrays without Brackets?


code: python3 /home/pi/myfiles/windowtest.py

rawDescription: tkinter not importable from terminal but works in Python 3 shell on Raspberry Pi

description: Tkinter not importable from terminal but works in Python 3 shell on Raspberry Pi


code:
# in the spider
def parse_pdf(self, response):
    i = MyItem()
    i['body'] = response.body
    i['url'] = response.url
    # you can add more metadata to the item
    return i

# in your pipeline
def process_item(self, item, spider):
    path = self.get_path(item['url'])
    with open(path, "wb") as f:
        f.write(item['body'])
    # remove body and add path as reference
    del item['body']
    item['path'] = path
    # let item be processed by other pipelines. ie. db store
    return item

rawDescription: Should I create pipeline to save files with scrapy?


code:
xxxd - 4
xxxa - 1,3,2
xxxb - 2
xxxc - 3

rawDescription: how to get unique values set from a repeating values list

description: Get unique values set from a repeating values list


code:
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)

rawDescription: Login after creating a user with formwizard-django


code:
parser = argparse.ArgumentParser(...)
parser.convert_arg_line_to_args = convert_arg_line_to_args

rawDescription: using fromfile_prefix_chars with multiple arguments (nargs="*")

description: Using fromfile_prefix_chars with multiple arguments (nargs="*")


code:
hashes(1)
hashes(4)

rawDescription: python nested loop print spaces between two characters every repeat

description: Python nested loop print spaces between two characters every repeat


code:
from django.db import models
from polymorphic import PolymorphicModel

class ModelA(PolymorphicModel):
    field1 = models.CharField(max_length=10)

class ModelB(ModelA):
    field2 = models.CharField(max_length=10)

class ModelC(ModelB):
    field3 = models.CharField(max_length=10)

rawDescription: Django Inheriting from classes

description: Django Inheriting from classes


code:
a=(u'master',)
str(a[0])
'master'

rawDescription: Select Postgresql Schemas in Python, output not as expected


code:
from itertools import product

maximumDigits = 2
digits = '1234'
for l in range(1, maximumDigits + 1):
    for n in product(digits, repeat=l):
        print(''.join(n))

rawDescription: Creating correct for-loop/iteration for a unique list


code:
from collections import Counter

tweets = data['results']
count = Counter(tw['from_user_name'] for tw in tweets)
tweets.sort(key=lambda tw: count[tw['from_user_name']], reverse=True)

rawDescription: Python extract top user name from json

description: Python extract top user name from json


rawDescription: How can I encode and decode percent-encoded (URL encoded) strings in Python?

description: Encode and decode percent-encoded (URL encoded) strings in Python


code:
i = s.head(file_url)
urlpath = i.url

rawDescription: How to get redirected URL without downloading file

description: Get redirected URL without downloading file


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(yourhtml)
languages = [s.get_text().strip() for s in soup.find_all('span', class_=True)]

rawDescription: Why isn't this regexp working

description: Why isn't this regexp working


code:
print(len(refs))
print(refs)

rawDescription: In Python, how do I determine if an object still exists?


rawDescription: IndexError: too many indices for array. Numpy array with 42 features not homogeneous


code: f= commands.output('zcat '+ file)

rawDescription: line or string?

description: Line or string


code:
def admin_thumbnail(self):
    return u'<img src="%s" />' % (self.image.url)
admin_thumbnail.short_description = 'Thumbnail'
admin_thumbnail.allow_tags = True

rawDescription: How to show image in django admin

description: Show image in django admin


code:
from operator import itemgetter
sorted(my_numpy_array,key=itemgetter(1))

rawDescription: How to group rows in a numpy 2d matrix based on column values?

description: Group rows in a numpy 2d matrix based on column values


code:
hp_history = [10]

def initial_health():
    return hp_history[0]

def cur_health():
    return hp_history[-1]

def affect_health(delta):
    hp_history.append(cur_health() + delta)
    return cur_health()

rawDescription: How do I keep track of score increments in Python?

description: Keep track of score increments in Python


code:
class Paid(models.Model):
     user=models.ForeignKey(User)
     eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True)

     def __init__(self):
         super(Paid, self).__init__()
         self.eyw_transactionref = str(uuid.uuid4())

     def __unicode__(self):
        return self.user

rawDescription: Generate unique id in django from a model field


code:
str1 = 'my best test ever!'
str2 = 'best'
for i, char in enumerate(str1):
    if str2[0] == char:
        print("found first instance of letter at, ", i)
        print(str2 == str1[i:i + len(str2)])

rawDescription: Recreating builtin s.find('substring') function


code:
def test_list_change_2(lst):
    lst[:-1] = ["the very last one"]
    lst[:] = lst[::-1]

string_list = ["first", "another one"]
test_list_change(string_list)
print (string_list)
['the last one', 'the very last one']

rawDescription: python: changing list value in sub-routine

description: Python: changing list value in sub-routine


code: [dictionary[key][1] for key in ('key1', 'key2', 'key3')]

rawDescription: Python: Pulling data out of dictionary like a 2D array


code:
df['date'] = pd.to_datetime(df['date'])
df['set'] = (df['date'].diff().fillna(0) <= 0).cumsum()

rawDescription: Reshaping two-column data using pandas pivot


rawDescription: Create python dictionary from text using regex to distinguish between specific sections


code:
object = bpy.data.objects['OBJECT']
object.select = True

rawDescription: Blender 2.6: Select object by name through Python


code: isinstance(u'hello', (basestring, str, unicode))

rawDescription: How to compare inheritance with several classes?

description: Compare inheritance with several classes


code:
[GetVitalStats]
SourceUrl=ftp.myhost.com
SourceType=FTP

Destination=Host=mydbserver; Database=somedb
SourceType=Postgres

rawDescription: Get remote text file, process, and update database - approach and scripting language to use?


code:
soup = BeautifulSoup.BeautifulSoup()
soup.feed('this is some text')
soup.findAll('a', href=True)[0]['href']
soup.findAll('a', href=True)[0].text

rawDescription: Beautiful Soup to Find and Regex Replace text 'not within  '


code:
dmin =1
ncenter =0
for n in pos:
    x,y = pos[n]
    d = (x-0.5)**2+(y-0.5)**2
    if d<dmin:
        ncenter = n
        dmin = d

rawDescription: Networkx Random Geometric Graph limit nodes within radius r


rawDescription: Sorting a list of dictionaries based on the order of values of another list


code: new_index = pd.Index(np.arange(250, 3500), name='temp')

rawDescription: Inserting rows into dataframe by reindexing


code: global best

rawDescription: Python global variable changes itself.... Why?


code:
with inplace(csvfilename, 'rb') as (infh, outfh):
    reader = csv.reader(infh)
    writer = csv.writer(outfh)

    for row in reader:
        row += ['new', 'column']
        writer.writerow(row)

rawDescription: Add columns to CSV while writing the CSV


rawDescription: Finding time intervals per day from a list of timestamps in Python


code: finder3.apply_ngram_filter(lambda w1, w2, w3: u').' in [w1,w2,w3])

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
dim_array = np.ones((1,a.ndim),int).ravel()
dim_array

rawDescription: multiply numpy ndarray with 1d array along a given axis

description: Multiply numpy ndarray with 1d array along a given axis


code: '  -- Checking connectivity from [1, 2, 3] to [4, 5, 6]'

rawDescription: How can I print each list item, in a single line of code?

description: Print each list item, in a single line of code


code:
def circle(symbol):

    def lines1(inner):
        def wrapper():
            print(symbol * 20)
            inner()
            print(symbol * 20)
        return wrapper

    def lines2(inner):
        def wrapper():
            print(symbol * 7 + ' ' * 6 + symbol * 7)
            inner()
            print(symbol * 7 + ' ' * 6 + symbol * 7)
        return wrapper

    def lines3(inner):
        def wrapper():
            print(symbol * 4 + ' ' * 12 + symbol * 4)
            inner()
            print(symbol * 4 + ' ' * 12 + symbol * 4)
        return wrapper

    def lines4(inner):
        def wrapper():
            print(symbol * 2 + ' ' * 16 + symbol * 2)
            inner()
            print(symbol * 2 + ' ' * 16 + symbol * 2)
        return wrapper

    def lines5():
        print(symbol + ' ' * 18 + symbol)
        print(symbol + ' ' * 18 + symbol)

    lines1(lines2(lines3(lines4(lines5))))()

rawDescription: How can I pass input to a function, then have it use that input across 5 internal functions that are chaining each other?

description: Pass input to a function, then have it use that input across 5 internal functions that are chaining each other


code:
def pickline(thestring, whatline):
    return thestring.splitlines()[whatline]

rawDescription: Trying to use enumerate() on a string with lines not surrounded by quotes in Python


code:
from __future__ import print_function
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

rawDescription: How to print to stderr in Python?

description: Print to stderr in Python


rawDescription: Write the digits of a number into an array


code:
class Foo(object):
    def __init__(self):
        self.text = "Hello World"  # has to be created first, so Bar.__init__ can reference it
        self.bar = Bar(self)

class Bar(object):
    def __init__(self, parent):
        self.parent = parent
        self.newText = parent.text

foo = Foo()

rawDescription: Getting container/parent object from within python


code:
import random

print("Pick a number from 1-50")

randomNumber = random.randint(1,50)
correct = False

while not correct:
    try:
        userInput = int(input("Insert your number here. "))
    except ValueError:
        print("That is not a Number!")
        continue
    if randomNumber == userInput: # Let's check this first!
        print ("YOU WIN!!!")
        break # We use break b/c changing correct would still run rest of loop

    acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
    guess_error = userInput - randomNumber
    i = 0
    while abs(guess_error) > acceptable_ranges[i]: # see how close they are
        i += 1
    if guess_error < 0: # let's figure out where they need to go
        next_guess_direction = "higher"
    else:
        next_guess_direction = "lower"

    print (("You are within %i: Please guess %s")
           %(acceptable_ranges[i], next_guess_direction))

rawDescription: How do I make my program check whether user input is within 5,10,15,20, etc of the random integer?

description: Make my program check whether user input is within 5,10,15,20, etc of the random integer


code:
from requests import Session # we can just import Session, no need to import the entire requests

s = Session() # new session

page_signed_out = s.get('http://www.surfline.com/home/index.cfm') # gets signed out page, this will set eventual cookies that may be needed later

s.post("http://www.surfline.com/myaccount/inc_login_handler.cfm", {"username":"myemail@example.com", "password":"mypassword", "rememberMe":"true", "top_login":"true"}) # does the actual login, if successful this will set a session cookie

page_signed_in = s.get('http://www.surfline.com/home/index.cfm') # good, we're logged in

rawDescription: How to stay logged into a website using a Python script (requests library)?

description: Stay logged into a website using a Python script (requests library)


code:
with open('file1.bin', 'rb') as f:
    myArr = bytearray(f.read(32678))

rawDescription: Create binary file in python

description: Create binary file in python


code:
# Tuples are in the form
# (Link Title, URL, Is Selected?, Sub Menu Items)
# And sub menu items are tuples in the form
# (Link Title, URL, Is Selected?)
navigation = [("1st Data Source", "/some/url", true, []),
    ("2nd Data Source", "/some/url/2", false, [("A", "/a", false)]),
    ("3rd Data Source", "/some/url/3", false, [("B", "/b", false),("C", "/c", false)])]

rawDescription: Structuring jinja/flask templates with multiple child templates?


code: showinfo(title="Blah", message="Look ma - No hands!")

rawDescription: Label does not update on button click

description: Label does not update on button click


rawDescription: quick way to convert a list of lists (ie from scipy.spatial.KDTree.query_ball_tree) to an array of pairs?

description: Quick way to convert a list of lists (ie from scipy.spatial.KDTree.query_ball_tree) to an array of pairs


code:
import pickle

# Write to file.
file = open("data.pkl", "wb")
pickle.dump(image1, file)
pickle.dump(image2, file)
file.close()

# Read from file.
file = open("data.pkl", "rb")
image1 = pickle.load(file)
image2 = pickle.load(file)
file.close()

rawDescription: pickling a python image object

description: Pickling a python image object


code:
import collections

class MyArray (collections.OrderedDict):
    def __init__ (self, values):
        super(MyArray, self).__init__ ((v.id, v) for v in values)
    def __rawgetitem (self, key):
        return super (MyArray, self).__getitem__ (key)
    def __getitem__ (self, key):
        if not hasattr (key, '__iter__'):
            key = (key, )
        return MyArray (self.__rawgetitem (k) for k in key)
    def __repr__ (self):
        return 'MyArray({})'.format(', '.join('{}: {}'.format(k, self.__rawgetitem(k)) for k in self.keys()))

rawDescription: Accessing numpy array based on attribute of object


code:
def overlapping_sublists(l, n, overlap=1, start=0):
    while start <= len(l) - n:
        yield l[start:start+n]
        start += n - overlap

rawDescription: python generate sublist with offset and condition

description: Python generate sublist with offset and condition


code: matching = [s for s in some_list if "abc" in s]

rawDescription: Check if a Python list item contains a string inside another string


rawDescription: Efficiently drop dataframe rows where *index* contains nulls (NaT)


code: st = ['path/to/somewhere?id=6&name=Test', 'path/to/list?date=05222014&type=cal']

rawDescription: Replace resulting values with python split method


rawDescription: How to coarse grain xy coordinates

description: Coarse grain xy coordinates


code:
tar = tarfile.open(fname + ".tar.gz", 'w:qz')
os.chdir('/home/user')
tar.add("file.txt")
tar.close()

rawDescription: How to compress a file with shutil.make_archive in python?

description: Compress a file with shutil.make_archive in python


code:
# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class Scrapy1Spider(CrawlSpider):

    name = "musiker"
    allowed_domains = ["musiker-board.de"]
    start_urls = ['http://www.musiker-board.de/forum/'
             ]
    rules = (
        Rule(LinkExtractor(allow=[r'forum/\w+']), follow=True),
        Rule(LinkExtractor(allow=[r'threads/\w+']), callback='parse_item'),
    )

    def parse_item(self, response):
        self.logger.info('response.url=%s' % response.url)

rawDescription: Scrapy: Following Links with regular Expression


code:
def min(a, b):
    return a if a < b else b

rawDescription: How to compare words in two lists according to same order in python?(I have def a function)

description: Compare words in two lists according to same order in python?(I have def a function)


code:
d = '0101010000' * 2000 # create a 20,000 long string of 1s and 0s
d_array = np.fromstring(d, 'int8') - 48 # 48 is ascii 0. ascii 1 is 49

rawDescription: numpy/pandas: How to convert a series of strings of zeros and ones into a matrix

description: Numpy/pandas: How to convert a series of strings of zeros and ones into a matrix


rawDescription: String parsing in Python with various unique cases


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

from django.core import management
from django.core.mail import mail_admins

class Command(BaseCommand):

    def inner_run(self, *args, **options):
        expired_items = Model.objects.filter(expiry_date__lte=datetime.datetime.now())
        message = some_message_formatter(expired_items)

        mail_admins(subject='Alerts on my Project!', message=message)

rawDescription: Create alerts in django application

description: Create alerts in django application


code:
yournumber = 87.28197
"{0:.3f}".format(yournumber)
"%.3f" % yournumber

rawDescription: Formatting display of numbers in Python 3


code: [word.translate(None, string.punctuation) for word in wordList]

rawDescription: Python NLTK not taking out punctuations correctly


code:
4
9
15
22
22 # this is the return value; previous output is from `print()`

rawDescription: Python recursive function that retain variable values


code:
a = np.arange(9).reshape(3,3)
b = np.transpose(a)
a
b
b[0,1] = 100
b
a

rawDescription: NumPy Matrix operation without copying

description: NumPy Matrix operation without copying


code:
logic = GameLogic()
game = Gui(logic)
game.mainloop()

rawDescription: How to properly organize this code?

description: Properly organize this code


code: [[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur']]

rawDescription: How to create a nested list from an object?

description: Create a nested list from an object


code: opener.open(request, timeout=0.01)

rawDescription: Python urllib2 setting timeout

description: Python urllib2 setting timeout


code:
with open("savegame", "wb") as f:
    pickle.dump(foo, f)

rawDescription: how to make save / load game functions in pygame?

description: Make save / load game functions in pygame


code:
#list_perms.py
import itertools

def combinePermutations(perms):
    a = min(min(p) for p in perms)
    b = max(max(p) for p in perms)
    d = {i:i for i in range(a,b+1)}
    for p in perms:
        pairs = zip(sorted(p),p)
        for i,j in pairs:
            d[i] = j
    return tuple(d[i] for i in range(a,b+1))

def permute(cell):
    return [p for p in itertools.permutations(cell)]

def listGoodPerms(cells):
    products = itertools.product(*(permute(cell) for cell in cells))
    return [combinePermutations(perms) for perms in products]

#to test:
myCells = [(1,4), (2,3,5), (6,7)]
for p in listGoodPerms(myCells): print(p)

rawDescription: generate a list of permutations that preserve a given partitioning (context: Graph Isomorphism)

description: Generate a list of permutations that preserve a given partitioning (context: Graph Isomorphism)


code:
provider = wx.SimpleHelpProvider()
wx.HelpProvider_Set(provider)

rawDescription: wxPython: Context dialog popup

description: WxPython: Context dialog popup


code:
mydist = Disk()
mydist.test1 = "value"
# And so on

rawDescription: How to create a object of variables, and return it, in Python?

description: Create a object of variables, and return it, in Python


code:
def foo(*args, **kwargs):
    call_args = ['scp', '-r', '-i']
    call_args.extend(args)
    call_args.extend(arg for item in kwargs.items() for arg in item)
    subprocess.check_output(call_args)

rawDescription: Additional processing of arugments for a function in Python


code:
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

rawDescription: Which element are we currently at in a "for x in y:" loop


code:
# loop on all the files
for num in range(1,1000):

    cfile = open ( 'c%u.dat'%num, mode='r')

    # find the specific line
    for line in cfile:
        if line[0]=='@':

            # open the determined file and add the line
            dfile = open( 'determined_c%u_send.dat'%num, mode='a')
            dfile.write( line[1:-1] )
            dfile.close()

    cfile.close()

rawDescription: Bash or Python or Awk to match and modify files


code:
import time
from threading import Timer

class ProgressMeter:
    def __init__(self):
        self._k = 0
        self._timer = 0

    # insert above methods with indentation as same level as __init__(self):

rawDescription: Python, calculating the status of computation slows down the computation itself


code:
import warnings
warnings.simplefilter('always')
from dir1.dir2.module_sub import sub2
sub2(1, 2)
from dir1.module_3 import add3
add3(1, 2, 3)

rawDescription: How to "fake" a module safely in a Python package


code:
def score(s, d):
    return avg([d[x][0] for x in s.lower().split() if x in d])

rawDescription: List comprehension with averages

description: List comprehension with averages


code: myDict = dict(zip(myList[::2], myList[1::2]))

rawDescription: converting a simple list to a dictionary (in python)

description: Converting a simple list to a dictionary (in python)


rawDescription: Explain this python string operation s[:6][::-1]


code: hosts = jdict['list']

rawDescription: Convert JSON to Python Array

description: Convert JSON to Python Array


rawDescription: Count the number of results

description: Count the number of results


code: l3 = partition(l2, new_len)

rawDescription: python list average over bin sizes

description: Python list average over bin sizes


code:
t = type('test', (object,), {})()
t

rawDescription: Creating an empty object in Python

description: Creating an empty object in Python


rawDescription: Pandas: Impute NaN's

description: Pandas: Impute NaN's


code:
# importee.py
def call_me(parameter):
    print(parameter)

rawDescription: Is there a way to get importer's variable in importee?


rawDescription: Create DataFrame from another DataFrame.describe() - Pandas


code: {key:value for key,value in ...}

rawDescription: how to pythonically pass arguments to methods of subclassed widgets?

description: Pythonically pass arguments to methods of subclassed widgets


rawDescription: Python: Slicing a String based on Indicies and character


code:
frame = pd.DataFrame()
frame['Date'] = pd.Series()
frame['Date'] = frame['Date'].astype(object).fillna(user_input)

rawDescription: How do I fill a column with a user inputted value?

description: Fill a column with a user inputted value


code:
[]   # Normal list didn't work, the appended '1' didn't make it to the main process
[1]  # multiprocessing.Manager() list works fine

rawDescription: Python/Multiprocessing : Processes does not seem to start


code:
dt = datetime.datetime.fromtimestamp(946652400)
OFFSET = datetime.timedelta(hours=-9)
adjusted_dt = dt + OFFSET

rawDescription: Getting datetime from binary

description: Getting datetime from binary


rawDescription: Python 2.7 rounding vs Python 3

description: Python 2.7 rounding vs Python 3


code:
test.py
import sys

def main(args = sys.argv):
    ans = int(args[1])**int(args[1])
    with open('test.out', 'w') as fout:
        fout.write(str(ans))

rawDescription: Using sys.argv from another .py file - python


code:
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])
win = MyDialog()
win.show()
app.exec_()   #after this try to close the dialog, it wont close bu minimize

rawDescription: How do I catch a pyqt closeEvent and minimize the dialog instead of exiting?

description: Catch a pyqt closeEvent and minimize the dialog instead of exiting


rawDescription: How to find where Python class is defined

description: Find where Python class is defined


code:
post_set = set(tuple(x) for x in post.itervalues())
pre_set = set(tuple(x) for x in pre.itervalues())

items_in_only_one_set = post_set ^ pre_set

rawDescription: fast data comparison in python

description: Fast data comparison in python


rawDescription: Groupby and Multi indexing

description: Groupby and Multi indexing


code:
from django.utils.safestring import mark_safe
from django.template import Template, Context
Template("{{ name }}").render(Context({'name': mark_safe('<b>Brad</b>')}))

rawDescription: How to prevent auto escape in Django templates?

description: Prevent auto escape in Django templates


code:
def __init__(self, parent, controller):
    ...
    # button commands don't have an event but sometimes you use these callbacks for both .bind and buttons
    # so having event=None makes it work for both.
    def go_next(event=None):
        self.changePage(True)

    next = ttk.Button(innerFrame, text = "Next", command = go_next)
    next.grid(row=2, sticky="E")

    def go_back(event=None):
        self.changePage(False)

    back = ttk.Button(innerFrame, text = "Back", command = go_back)
    back.grid(row=2, sticky="W")

    ...

rawDescription: tkinter - Going Back and Forth Between Frames Using Buttons

description: Tkinter - Going Back and Forth Between Frames Using Buttons


code:
add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('username', 'password1', 'password2', 'first_name', 'last_name')}
    ),
)

rawDescription: django: Add user popup. Missing fields (first_name, last_name)

description: Django: Add user popup. Missing fields (first_name, last_name)


code:
f = open(filename)
# do something
f.close()

rawDescription: How to load a Python dict from a textfile into a variable

description: Load a Python dict from a textfile into a variable


code: subprocess.call(['echo', 'hello'])

rawDescription: File gets created, but subprocess call says no such file or directory


code:
grouped = df.groupby(['Game', df.Player.map(kind)]).sum()
grouped

rawDescription: How to generate continuous record from incomplete data in Pandas Dataframe

description: Generate continuous record from incomplete data in Pandas Dataframe


code:
import shlex
import logging
import subprocess
from StringIO import StringIO

def run_shell_command(command_line):
    command_line_args = shlex.split(command_line)

    logging.info('Subprocess: "' + command_line + '"')

    try:
        command_line_process = subprocess.Popen(
            command_line_args,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )

        process_output, _ =  command_line_process.communicate()

        # process_output is now a string, not a file,
        # you may want to do:
        # process_output = StringIO(process_output)
        log_subprocess_output(process_output)
    except (OSError, CalledProcessError) as exception:
        logging.info('Exception occured: ' + str(exception))
        logging.info('Subprocess failed')
        return False
    else:
        # no exception was raised
        logging.info('Subprocess finished')

    return True

rawDescription: Run subprocess and print output to logging


rawDescription: Finding the minimum of each column of a CSV file using python