code:
class Foo:
    def __init__(self):
        import os
        self.number = 1
        self.module = os
        self.class_ = Exception
        self.function = dir

f = Foo()

rawDescription: Multiple dot syntax in python and matplotlib


code: rddData = sc.textFile("gs://storage-bucket/your-input-data", minPartitions=200)

rawDescription: Dataproc Pyspark job only running on one node


code: print('You wrote {} words!'.format(len(input("Enter some text, I will tell you how many words you wrote!: ").split())))

rawDescription: How to count how many words are in a text string inputted by the user in python

description: Count how many words are in a text string inputted by the user in python


code:
p = 'foo+*bar'
import re
re.escape(p)

rawDescription: How to escape special regex characters in a string?

description: Escape special regex characters in a string


code:
sns.set(font_scale=5)  # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))

rawDescription: How can I change the font size using seaborn FacetGrid?

description: Change the font size using seaborn FacetGrid


code:
class Parent(object):
    @property
    def fieldname(self):
        """returns a tuple"""
        return (1, 10)

class Child(Parent):
    @property
    def fieldname(self):
        """returns a tuple"""
        return self._config.get(
            'fieldname',
            super(Child, self).fieldname)

child = Child()
child._config = {}
child.fieldname
child._config['fieldname'] = ('foo', 'bar')
child.fieldname

rawDescription: accessing value of a python @property

description: Accessing value of a python @property


code:
class CheckableQueue(Queue.Queue): # or OrderedSetQueue
    def __contains__(self, item):
        with self.mutex:
            return item in self.queue

rawDescription: Check if element is already in a Queue

description: Check if element is already in a Queue


code:
bags_closed = Shipment.objects.filter(bags__status__exact='close',
                                      bags__time__range=[start_time,end_time],
                                      pptls__pptl_id__exact = 147)\
                              .distinct('bags').count()

rawDescription: how to get unique values in Django models?

description: Get unique values in Django models


rawDescription: Why Python need rich comparison?

description: Why Python need rich comparison


code: df.groupby(['A', 'B']).mean()

rawDescription: Python Pandas- how to unstack a pivot table with two values with each value becoming a new column?


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Iterate an iterator by chunks (of n) in Python?


code:
#!/usr/bin/env python
# vim:fileencoding=utf-8:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Last modified: 2015-05-24 12:28:45 +0200
#
# To the extent possible under law, Roland Smith has waived all
# copyright and related or neighboring rights to gitdates.py. This
# work is published from the Netherlands. See
# http://creativecommons.org/publicdomain/zero/1.0/

"""For each file in a directory managed by git, get the short hash and
data of the most recent commit of that file."""

from __future__ import print_function
from multiprocessing import Pool
import os
import subprocess
import sys
import time

# Suppres annoying command prompts on ms-windows.
startupinfo = None
if os.name == 'nt':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

def main():
    """
    Entry point for gitdates.
    """
    checkfor(['git', '--version'])
    # Get a list of all files
    allfiles = []
    # Get a list of excluded files.
    if '.git' not in os.listdir('.'):
        print('This directory is not managed by git.')
        sys.exit(0)
    exargs = ['git', 'ls-files', '-i', '-o', '--exclude-standard']
    exc = subprocess.check_output(exargs, startupinfo=startupinfo).split()
    for root, dirs, files in os.walk('.'):
        for d in ['.git', '__pycache__']:
            try:
                dirs.remove(d)
            except ValueError:
                pass
        tmp = [os.path.join(root, f) for f in files if f not in exc]
        allfiles += tmp
    # Gather the files' data using a Pool.
    p = Pool()
    filedata = [res for res in p.imap_unordered(filecheck, allfiles)
                if res is not None]
    p.close()
    # Sort the data (latest modified first) and print it
    filedata.sort(key=lambda a: a[2], reverse=True)
    dfmt = '%Y-%m-%d %H:%M:%S %Z'
    for name, tag, date in filedata:
        print('{}|{}|{}'.format(name, tag, time.strftime(dfmt, date)))

def checkfor(args, rv=0):
    """
    Make sure that a program necessary for using this script is available.
    Calls sys.exit when this is not the case.

    Arguments:
        args: String or list of strings of commands. A single string may
            not contain spaces.
        rv: Expected return value from evoking the command.
    """
    if isinstance(args, str):
        if ' ' in args:
            raise ValueError('no spaces in single command allowed')
        args = [args]
    try:
        with open(os.devnull, 'w') as bb:
            rc = subprocess.call(args, stdout=bb, stderr=bb,
                                 startupinfo=startupinfo)
        if rc != rv:
            raise OSError
    except OSError as oops:
        outs = "Required program '{}' not found: {}."
        print(outs.format(args[0], oops.strerror))
        sys.exit(1)

def filecheck(fname):
    """
    Start a git process to get file info. Return a string containing the
    filename, the abbreviated commit hash and the author date in ISO 8601
    format.

    Arguments:
        fname: Name of the file to check.

    Returns:
        A 3-tuple containing the file name, latest short hash and latest
        commit date.
    """
    args = ['git', '--no-pager', 'log', '-1', '--format=%h|%at', fname]
    try:
        b = subprocess.check_output(args, startupinfo=startupinfo)
        data = b.decode()[:-1]
        h, t = data.split('|')
        out = (fname[2:], h, time.gmtime(float(t)))
    except (subprocess.CalledProcessError, ValueError):
        return None
    return out

if __name__ == '__main__':
    main()

rawDescription: Get time of last commit for Git repository files via Python?


code:
url(r'^users/(?P<pk>[0-9]+)/workouts/get/$',
        WorkoutList.as_view(serializer_class=WorkoutSerializer), name='list'),

rawDescription: unbound method get_queryset() must be called with WorkoutList instance as first argument (got nothing instead)

description: Unbound method get_queryset() must be called with WorkoutList instance as first argument (got nothing instead)


rawDescription: trouble extracting elements to list from string

description: Trouble extracting elements to list from string


code:
if nomer in DATA:
    print(globals()[nomer])

rawDescription: Search element in list and print property element


code:
for i in range(len(rows) - 2, -1, -1):
    for j in range(i + 1):
        rows[i][j] += max([rows[i + 1][j], rows[i + 1][j + 1]])

rawDescription: Strange For Loop

description: Strange For Loop


rawDescription: Combine words with nearest index

description: Combine words with nearest index


code:
d = c.x       # getter again
d[1] = 4

rawDescription: Python property on a list

description: Python property on a list


code:
#!/usr/bin/env python
import sys
for line in sys.stdin:
    line = line.strip()
    cols = line.split("\t")
    orig_line = "\t".join(cols[1:])
    # do stuff...

rawDescription: Input split for Map function in Hadoop

description: Input split for Map function in Hadoop


code:
def addword(theIndex, word, pagenumber):
    if word in theIndex:
        theIndex[word].append(pagenumber)
    else:
        theIndex[word] = [pagenumber]

rawDescription: python backports for some methods

description: Python backports for some methods


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

np.random.seed(0)

index = pd.date_range('2013-1-1 00:00', '2013-12-31  23:00', freq='1h')
df = pd.DataFrame(np.random.rand(len(index),2),index=index, columns=['A','B'])
df2 = df.groupby(lambda x: x.month).agg({'A' : [np.mean, np.sum], 'B': np.mean})

fig = plt.figure()
ax = df2[('A', 'sum')].plot(kind="bar", alpha=0.7)
plt.xticks(rotation=0)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(),df2[('B', 'mean')],marker='o', c='navy', linewidth=4)

rawDescription: Plot specific column after DataFrame aggregation


code:
def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
                                                  ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # "if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class ThreadWithExc(threading.Thread):
    '''A thread class that supports raising exception in the thread from
       another thread.
    '''
    def _get_my_tid(self):
        """determines this (self's) thread id

        CAREFUL : this function is executed in the context of the caller
        thread, to get the identity of the thread represented by this
        instance.
        """
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        # TODO: in python 2.6, there's a simpler way to do : self.ident

        raise AssertionError("could not determine the thread's id")

    def raiseExc(self, exctype):
        """Raises the given exception type in the context of this thread.

        If the thread is busy in a system call (time.sleep(),
        socket.accept(), ...), the exception is simply ignored.

        If you are sure that your exception should terminate the thread,
        one way to ensure that it works is:

            t = ThreadWithExc( ... )
            ...
            t.raiseExc( SomeException )
            while t.isAlive():
                time.sleep( 0.1 )
                t.raiseExc( SomeException )

        If the exception is to be caught by the thread, you need a way to
        check that your thread has caught it.

        CAREFUL : this function is executed in the context of the
        caller thread, to raise an excpetion in the context of the
        thread represented by this instance.
        """
        _async_raise( self._get_my_tid(), exctype )

rawDescription: Is there any way to kill a Thread in Python?


code:
lines
lines[0]
lines[1]
lines[2]

rawDescription: How can I return specific lines in python 2.7 by using f.readline()

description: Return specific lines in python 2.7 by using f.readline()


code:
class IntRange(object):
    def __init__(self, start, stop=None):
        if stop is None:
            start, stop = 0, start
        self.start, self.stop = start, stop

    def __call__(self, value):
        value = int(value)
        if value < self.start or value >= self.stop:
            raise argparse.ArgumentTypeError('value outside of range')
        return value

rawDescription: Python's argparse choices constrained printing


code:
def flatten(obj):
    if obj is None:
        return None
    elif hasattr(obj, '__dict__') and obj.__dict__:
        return dict([(k, flatten(v)) for (k, v) in obj.__dict__.items()])
    elif isinstance(obj, (dict,)):
        return dict([(k, flatten(v)) for (k, v) in obj.items()])
    elif isinstance(obj, (list,)):
        return [flatten(x) for x in obj]
    elif isinstance(obj, (tuple,)):
        return tuple([flatten(x) for x in obj])
    else:
        return obj

rawDescription: Pythonic way to "flatten" object hierarchy to nested dicts?


code:
from io import StringIO    # version < 2.6: from StringIO import StringIO

buffer = StringIO()
buffer.writelines(mylist)
buffer.seek(0)

session.storlines("...", buffer)

rawDescription: Is there a simple way to make lists behave as files (with ftplib)


code:
from two_types_of_methods import A
a=A('RTT')
a.connect('myserv.com')
a.send('myserv.com')
a.read('myserv.com')
a.log('myserv.com')
b=A()
b.connect('myserv.com')
b.send('myserv.com')
b.read('myserv.com')
b.log('myserv.com')

rawDescription: Deciding which class method to be called according to class initiatiation parameters


code:
from itertools import groupby

while len(sequences) < 10:
    random.shuffle(order)

    if order in sequences:
        continue

    if all(len(list(group)) < 4 for _, group in groupby(order)):
        sequences.append(order[:])

rawDescription: Limit the number of repeats in pseudo random python list


code:
class MyModel(models.Model):
    image = models.ImageField(upload_to='images')

rawDescription: Extend image field to allow pdf ( django )


code:
import pandas as pd
import itertools

rawDescription: Pandas data-frame creation as permutations of 2 series?


code:
class Test(object):
    config = None

    def __init__(self):
        self.config = {}

    def __setattr__(self, key, value):
        if self.config is None:
            # set config directly
            super(Test, self).__setattr__(key, value)
            return
        self.config[key] = value

    def __getattr__(self, key):
       return self.config[key]

rawDescription: Using Python to create a dictionary with setters and getters


code:
# In your application setup code:
@app.after_request
def add_served_by_flask_header(response):
    response.headers["X-Served-By-Flask"] = "true"
    return response

rawDescription: flask templates: nginx cache or serve static assets called in jinja markups

description: Flask templates: nginx cache or serve static assets called in jinja markups


code:
def sumVectors(classB_infile, classA_infile, outfile):
    class_dictA = {}

    with open(classA_infile, "rb") as opened_infile_A:
        for line in opened_infile_A:
            items = line.split()
            classA, feat, valuesA = items[:3]
            class_dictA[feat.strip()] = float(valuesA)

    class_dictB = {}

    with open(classB_infile, "rb") as opened_infile_B:
        for line in opened_infile_B:
            items = line.split()
            classB, feat, valuesB = items[:3]
            class_dictB[feat.strip()] = float(valuesB)

    ####outfile
    with open(outfile, "wb") as output_file:
        for key in class_dictA:
            if key in class_dictB:
                weight = class_dictA[key] + class_dictB[key]
                outstring = "\t".join([classA + "-" +  classB, key, str(weight)])
            else:
                weight = class_dictA[key]
                outstring = "\t".join([classA + "-" +  classB, key, str(weight)])
            output_file.write(outstring + "\n")

        for key in class_dictB:
            if key not in class_dictA: # if key was in A it was processed already
                weight = class_dictB[key]
                outstring = "\t".join([classA + "-" + classB, key, str(weight)])
                output_file.write(outstring + "\n")

rawDescription: summing vectors in Python

description: Summing vectors in Python


rawDescription: How to Modify a String in wx.StaticText?

description: Modify a String in wx.StaticText


code: a=str(raw_input('Enter The String To revers'))

rawDescription: enter n numbers to control the enter of the map or array

description: Enter n numbers to control the enter of the map or array


code: my_string = my_string.rsplit('+', 1)[0]

rawDescription: Python: Iterate over string with while loop


code:
def attrcls(cls):
    cls._attrdict={}
    for methodname in cls.__dict__:
        method=cls.__dict__[methodname]
        if hasattr(method,'_attr'):
            cls._attrdict[getattr(method,'_attr')]=methodname
    return cls

def attr(key):
    def wrapper(func):
        class Property(object):
            def __get__(self,inst,instcls):
                return func(inst)
            def __init__(self):
                self._attr=key
        return Property()
    return wrapper

@attrcls
class Info(object):
    @attr("Version")
    def version(self):
        return 3
    def __getitem__(self,key):
        if key in self._attrdict:
            return getattr(self,self._attrdict[key])

rawDescription: Python decorator class to transform methods to dictionary items


rawDescription: reinterpret signed long as unsigned in Python

description: Reinterpret signed long as unsigned in Python


code:
centers.shape
centers

rawDescription: Dividing a square into N smaller squares and finding center coordinates of the N smaller squares


code:
if __name__ == '__main__':
    import xmlrunner
    unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))

rawDescription: Python unittests in Jenkins?

description: Python unittests in Jenkins


code: set(['JUNKIE', 'DEALER', 'BUBBLES'])

rawDescription: Get specific words in a string

description: Get specific words in a string


code: [[x['field2'], x['field1']] for x in l]

rawDescription: Turning a list of dictionaries into a list of lists


code: matrix = [[0] * 10 for x in range(10)]

rawDescription: Initializing an n-dimensional matrix elegantly in Python


code:
import pprint
pprint.pprint(merge(*a))

rawDescription: Merge duplicate entries in array of dict


code: set(B) <= set(A)

rawDescription: Compare List with different number of items


code:
for key in set2 - set1:
    print(key, dict2[key])

rawDescription: python3 + Set function: how to get key and values from dictionary performing set operation

description: Python3 + Set function: how to get key and values from dictionary performing set operation


code:
audio /= np.max(np.abs(audio),axis=0)
image *= (255.0/image.max())

rawDescription: How to normalize a NumPy array to within a certain range?

description: Normalize a NumPy array to within a certain range


code:
Records = [{'Name':'Kelvin','Price': 0},{'Name': 'Michael','Price':10}]
[i for i in Records if i['Price'] != 0]

rawDescription: Delete multiple dictionaries in a list

description: Delete multiple dictionaries in a list


rawDescription: Eliminating series of .replace() calls in Python


code:
i_set = { frozenset(row.items()) for row in incoming_rows }
a_set = { frozenset(row.items())  for row in available_row }
(i_set - a_set)

rawDescription: Finding difference between two list of dictionary in Python


code:
A.__module__
B.__module__

rawDescription: Limit which classes in a .py file are importable from elsewhere


rawDescription: Equivalent of os.getpardir()?

description: Equivalent of os.getpardir()


code: result = re.sub(r'(?i)test', 'XXXX', 'TeSt')

rawDescription: Case insensitive Python regular expression without re.compile


code:
import numpy as np
from scipy import signal

# Add some padding to limit the periodic extension effect
padlen = int(np.floor(0.1*len(x)))
y = np.pad(x, (0,padlen), mode='edge');
# Compute the envelope
envelope = np.abs(signal.hilbert(y));
# Truncate to the original signal length
envelope = envelope[:-padlen]

rawDescription: Determining the event location on an oscillatory signal


code:
string = 'Volume 2                      RAW    Partition      8 MB  Healthy\n K:\XYZ\\'
string2 = 'Volume 2         NEW VOLUME   FAT    Partition      8 MB  Healthy\n    H:\XYZ\\'

rawDescription: Find Character in string and assign it to variable


code: final_list = []

rawDescription: Trouble splitting text without using split()


rawDescription: How to get atributes and operator from function

description: Get atributes and operator from function


code:
from PIL import Image
import numpy
img=Image.open(pathtoimage)
imgarray=numpy.array(img)

rawDescription: Python 3.5.1 from PixelAcces Objects to CSV dataset


code:
for idx, el in enumerate(your_list):
    if satisfies_condition(el):
        return your_list[:idx]

rawDescription: Find the first N elements of a list, until a condition is satisfied


code:
person = {
  'name': 'Joe',
  'age':  '35',
  'speak': lambda: 'o hai i am joe',
}

rawDescription: Javascript-style object methods in Python?


rawDescription: Time complexity of casting lists to tuples in python and vice versa


rawDescription: Pandas dataframe add a field based on multiple if statements


code:
s = 'refs/heads/'
[i.split()[1][len(s):] for i in l if s in i]

rawDescription: What is the most pythonic way to extract branch names from a remote-ls list?


code:
info = {}
rows = table.findAll("th")
for headercell in rows:
    valuecell = headercell.findNextSibling('td')
    if valuecell is None:
        continue
    header = ''.join([unicode(t).strip() for t in headercell.findAll(text=True)])
    value = ''.join([unicode(t).strip() for t in valuecell.findAll(text=True)])
    info[header] = value

rawDescription: Parsing HTML page using beautifulsoup

description: Parsing HTML page using beautifulsoup


code:
def seconds(time_str):
    end_time = datetime.datetime.strptime(time_str,'%H:%M:%S')
    delta = end_time - datetime.datetime.strptime('0:0:0','%H:%M:%S')
    return delta.total_seconds()

df_SOF1.D_Time = df_SOF1.D_Time.apply(seconds)

rawDescription: timedelta csv pandas

description: Timedelta csv pandas


code:
bits = []
for separator in separators:
    first, _, s = s.partition(separator)
    bits.append(first)
bits.append(s)

rawDescription: Using Python: to split long string, by given ‘separators’


rawDescription: pyparsing: Nested countedArray?

description: Pyparsing: Nested countedArray


code:
import re
re.sub(r'\bvar\b', '###', expr)

rawDescription: Replace variable in expression

description: Replace variable in expression


code: handle = Entrez.efetch(db='nuccore', id=key, rettype='fasta')

rawDescription: Access sequence element from fasta record using Biopython Entrez


code:
count = dlist.count(y)
index = dlist.index(y)
print ("\nThis word appears",count,"times.")
print ("\nThis word appears in the places",index)

rawDescription: How do I display an item which is in the list multiple times?

description: Display an item which is in the list multiple times


code:
list_of_dicts = [{'name': 'Rob', 'phoneNumbers': [{'phone': '123-3214', 'type': 'home'}, {'phone': '456-3216', 'type': 'work'}]}]
[dict(contact, phoneNumbers=[
    dict(phone_dict, phone=phone_dict['phone'].replace('-', ''))
    for phone_dict in contact['phoneNumbers']])
 for contact in list_of_dicts]
for contact_dict in list_of_dicts:
    for phone_dict in contact_dict['phoneNumbers']:
        phone_dict['phone'] = phone_dict['phone'].replace('-', '')
list_of_dicts

rawDescription: Updating a value in a dictionary inside a dictionary


code:
events2 = EventQueue()
foo1 = Foo(4)
bar1 = Bar(4, 2)

events2.push(lambda: foo1.update_value(1.5))
events2.push(lambda: bar1.print_alt_value(foo1.value))
events2.push(lambda: bar1.print_alt_value(foo1.return_bah()))

events2.process_next()
events2.process_next() # 36.0
events2.process_next() # 54.0

rawDescription: Passing objects around an event queue in Python


code: dic2 = {key: {k: v for sublist in value for k, v in sublist} for key, value in dic1.items()}

rawDescription: Converting a nested tuples into nested dictionaries


code:
def addTwo(x):
    return x+2

addTwo(2)

rawDescription: What does "lambda" mean in Python, and what's the simplest way to use it?


code:
def reversable(decorator):
    def wrapper(func):
        ret = decorator(func) # manually apply the decorator
        ret.decorated = func # save the original function
        return ret
    return wrapper

rawDescription: Is it possible to use reflection to examine a function's decorators in Python 2.5?


code:
# Default Django settings for project.
from project.settings import *

DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
ALLOWED_HOSTS = []
MEDIA_ROOT = ''
STATIC_ROOT = ''

rawDescription: Duplication of settings for multi-site django setup


code:
def polar_to_rect(theta, r):
    return (r*cos(theta), r*sin(theta))

rawDescription: Mixing Matplotlib patches with polar plot?


code:
class POIView(ModelView):
    can_create = True
    form_overrides = dict(location=WTFormsMapField)
    form_args = dict(
        way=dict(
            geometry_type='Polygon', height=500, width=500
        )
    )
    column_formatters = dict(tags=lambda v, c, m, p: (u', '.join(u"=".join([k, v]) for k, v in m.tags.items())),
                             )

    def __init__(self, session, **kwargs):
        super(POIView, self).__init__(POI, session, **kwargs)

    def scaffold_form(self):
        form_class = super(POIView, self).scaffold_form()
        form_class.way = WTFormsMapField()
        form_class.tags = MySelect2TagsField("Tags",None)
        return form_class

rawDescription: AdminModelConvertor for Geometry Field (LON/LAT)


code:
ts
ts.resample('t', how='mean')

rawDescription: Better way to aggregate timestamped data?


code:
from bs4 import BeautifulSoup
soup1 = BeautifulSoup('[words]	')
soup1.find('td', class_='prodSpecAtribute').contents[0]
soup2 = BeautifulSoup('[words]	')
soup2.find('td', class_='prodSpecAtribute').contents[0]

rawDescription: Regex in Python for html

description: Regex in Python for html


code:
#! /usr/bin/env python3
from safetkinter import *
from tkinter.constants import *
import socket
import sys

class MultichatClient(Frame):

    after_handle = None

    def __init__(self, master, remote_host):
        super().__init__(master)
        self.message_area = ScrolledText(self, width=81, height=21,
                                         wrap=WORD, state=DISABLED)
        self.message_area.grid(sticky=NSEW, columnspan=2)
        self.send_area = Entry(self)
        self.send_area.bind('<Return>', self.keyPressed)
        self.send_area.grid(sticky=EW)
        b = Button(self, text='Send', command=self.mouseClicked)
        b.grid(row=1, column=1)
        self.send_area.focus_set()
        try:
            self.remote = socket.create_connection((remote_host, 8989))
        except socket.gaierror:
            print('Could not find host {}.'.format(remote_host))
        except socket.error:
            print('Could not connect to host {}.'.format(remote_host))
        else:
            self.remote.setblocking(False)
            self.after_handle = self.after_idle(self.dataready)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

    @classmethod
    def main(cls, args):
        root = Tk()
        root.title('MultichatClient version 1.0')
        m = cls(root, args[0])
        m.grid(sticky=NSEW)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.mainloop()
        return 1

    def dataready(self):
        try:
            s = self.remote.recv(1 << 12).decode()
        except socket.error:
            pass
        else:
            self.message_area['state'] = NORMAL
            self.message_area.insert(END, s)
            self.message_area['state'] = DISABLED
            self.message_area.see(END)
        self.after_handle = self.after(100, self.dataready)

    def destroy(self):
        if self.after_handle:
            self.after_cancel(self.after_handle)
        super().destroy()

    def mouseClicked(self, e=None):
        self.remote.sendall(self.send_area.get().encode() + b'\r\n')
        self.send_area.delete(0, END)

    keyPressed = mouseClicked

if __name__ == '__main__':
    sys.exit(MultichatClient.main(sys.argv[1:]))

rawDescription: Send/sync variable/text over LAN in Python 3


code:
def ignoreargs(func, count):
    @functools.wraps(func)
    def newfunc(*args, **kwargs):
        return func(*(args[count:]), **kwargs)
    return newfunc

rawDescription: Python counterpart to partial for ignoring an argument


code:
from bs4 import Tag, NavigableString

def tag_clone(self):
    copy = type(self)(None, self.builder, self.name, self.namespace,
                      self.nsprefix)
    # work around bug where there is no builder set
    # https://bugs.launchpad.net/beautifulsoup/+bug/1307471
    copy.attrs = dict(self.attrs)
    for attr in ('can_be_empty_element', 'hidden'):
        setattr(copy, attr, getattr(self, attr))
    for child in self.contents:
        copy.append(child.clone())
    return copy

Tag.clone = tag_clone
NavigableString.clone = lambda self: type(self)(self)

rawDescription: clone element with beautifulsoup

description: Clone element with beautifulsoup


code: self.pixmap = QtGui.QPixmap.fromWinHBITMAP(self.bitmapFromHIcon(large[0]), 2)

rawDescription: Best way to extract .ico from .exe and paint with PyQt?

description: Extract .ico from .exe and paint with PyQt


code:
# With an array the matrix multiply like this
matrix_product = array.dot(vector)

# With a matrix it look like this
matrix_product = matrix * vector

rawDescription: Values of Variables Matrix NumPy

description: Values of Variables Matrix NumPy


rawDescription: Extract a value out of n

description: Extract a value out of n


code:
class AllList(list):
    """list which can be called in order to be used as a __all__-adding decorator"""
    def __call__(self, obj):
        """for decorators"""
        self.append(obj.__name__)
        return obj

rawDescription: Modifying module globals using externally defined function


code:
acceptedChars = set(string.digits + "[]()+-/*^=!<>" + string.letters)
newL = ''.join([ x for x in l if x in acceptedChars])

rawDescription: Is digit, aplha or math symbol

description: Is digit, aplha or math symbol


code:
element = driver.find_element_by_xpath("/html/body/div[1]/div[5]/table/tbody/tr/td[1]/div[1]/div[1]/div/div/form/textarea")
element.send_keys("suvrit")
element.submit()  # it would find the parent form and submit it

rawDescription: Selenium using python

description: Selenium using python


code:
csum = occupations.cumsum()
n = csum[-1]
np.arange(n) + np.repeat(idx_unique_objIDs - csum + occupations, occupations)

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
# This window just has a button to make all of the tabs in separate processes
class MainWindow(QtGui.QMainWindow):
    process_signal = QtCore.pyqtSignal()
    def __init__(self, parent = None):
        ## snipped
        pass

    # Here we open several tabs and put them in different processes
    def open_tabs(self):
        for i in range(0, 10):
            # this is just some random data for the objects
            X = np.arange(1240.0/1350.0, 1240./200., 0.01)
            Y = np.array(np.e**.2*X + np.sin(10*X)+np.cos(4*X))
            # Here the special tab is created
            temp_special_object = special_object(str(i), X, Y)
            new_tab = Special_Tab(self.main_tab_widget, temp_special_object)
            self.main_tab_widget.addTab(new_tab, str(i))
            # this part works fine without the .start() function
            self.tabs_list.append(new_tab)
        return
    # This appears to be where the problem lies because this should initialize all of the processes
    def process_tabs(self):
        for tab in self.tabs_list:
            tab.start_computation()

        return
    # This should be the 'slot' which the signal is communicating to
    def update_GUI(self, special_object):
        pass

rawDescription: Tabs with long processes in GUI all calling the same instance? [EDITED-QThread and QObject for passing objects to GUI]


code:
cursor.execute(query,
    (destination, source, protocol, version, header_length, ttl, protocolEGP, target, source_port, destination_port, length, data))

rawDescription: Python formatting string escape

description: Python formatting string escape


code:
a = [True, True, True]
b = [True, True, False]

rawDescription: Python list of booleans comparison gives strange results


code:
a1 = np.array([1, 2, 3])
a2 = np.array([4, 5, 6])
a3 = np.array([7, 8, 9])

np.savez("test", A=a1,B=a2,C=a3)
a = np.load("test.npz")

d = dict(zip(("data1{}".format(k) for k in a), (a[k] for k in a)))
print(d)

rawDescription: Loading arrays from npz files in pythhon


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)

        self.s1 = tk.Frame(self, background="pink", width=200, height=200)
        self.s2 = tk.Frame(self, background="blue", width=200, height=200)
        self.s3 = tk.Frame(self, background="bisque", width=200, height=200)

        self.s1.grid(row=0, column=0, sticky="nsew")
        self.s2.grid(row=0, column=1, sticky="nsew")
        self.s3.grid(row=1, column=0, columnspan=2, sticky="nsew")

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)

        # now create the search section
        self.searchSection(self.s1)

    def searchSection(self, parent):
        l = tk.Label(parent, text="Search :", bg='grey')
        self.searchField = tk.Entry(parent)
        self.search = tk.Menubutton(parent, text="Search", bg="grey")
        self.search.menu = tk.Menu(self.search, tearoff = 0)
        self.search['menu'] = self.search.menu
        self.SearchType1Var = tk.IntVar()
        self.search.menu.add_checkbutton(label="SearchType1",
                                         variable = self.SearchType1Var)

        l.grid(row=0, column=0, columnspan=2, sticky='w')
        self.searchField.grid(row=1, column=0, sticky="ew")
        self.search.grid(row=1, column=1, sticky="ew")

        parent.grid_columnconfigure(0, weight=1)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Python - using grid layout to format a window


code:
def recAlphaCount(s):
    if len(s) == 0:
        return 0
    return int(s[0].isalpha()) + recAlphaCount(s[1:])

rawDescription: Resetting a counter after recursion

description: Resetting a counter after recursion


rawDescription: extracting data from .txt file using python

description: Extracting data from .txt file using python


code:
import itertools
map(sum,itertools.izip_longest(a,b,fillvalue = 0))

rawDescription: Element wise addition of two unequal lists in python


code:
indices = np.abs(differences).argmin(axis=0)
residual = np.diagonal(differences[indices,])

rawDescription: NumPy: Vectorize finding closest value in an array for each element in another array


rawDescription: Python regex split but put end part of regex match back into string?


rawDescription: Scrapy adds %0A to URLs, causing them to fail


code: m_screen.after(3000, scale_screen(event = None))

rawDescription: Pausing from within a tkinter function

description: Pausing from within a tkinter function


code: user_id = user_email = []

rawDescription: double assign in python results in identical lists even when different operation is done. Why?

description: Double assign in python results in identical lists even when different operation is done. Why


code: "1","a","the big bad, string"

rawDescription: How to escape comma in string Python 2.7 in a .csv file

description: Escape comma in string Python 2.7 in a .csv file


code:
b = "".join(mul(*b) for b in a)
dict_a = {e[0]: b.count(e) for e in b}

rawDescription: How to merge value of key when I have a list-tuple object

description: Merge value of key when I have a list-tuple object


code: pprint({action: {direction: [(duration, (i * len(directions) + j, x)) for x in frames] for j, direction in enumerate(directions) } for i, action in enumerate(actions)})

rawDescription: How to find the iteration index in this loop

description: Find the iteration index in this loop


code: user_rel_id = (4,[course_ids])

rawDescription: Filling Many2many field (odoo 8)

description: Filling Many2many field (odoo 8)


code:
import os
os.rename(source, destination)

rawDescription: Cut and Paste a File or Directory in Python


code:
from unipath import Path

BASE_DIR = Path(__file__).ancestor(2)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR + '/project/design/',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

rawDescription: Render template located in a unregistered folder in Django


code: ignore = set(ignore)

rawDescription: Optimise comparison between two lists, giving indices that differ


code: df.ix[0, 'COL_NAME'] = x

rawDescription: Set value for particular cell in pandas DataFrame with iloc


rawDescription: Comparing 2 numpy arrays

description: Comparing 2 numpy arrays


code: wrapee(param1, *stuff, **kargs)

rawDescription: Preserving argument default values while method chaining


code:
nums = xrange(100000000)
-1 in nums

rawDescription: Why is my threading/multiprocessing python script not exiting properly?


code:
import re
with open('myfile', 'r') as f:
    f = f.read()
    # use matches_a or matches_b depending on what you actually want
    matches_a = re.findall(r'<([^=]+=\"[^"]+\")>', f)
    matches_b = re.findall(r'<[^=]+=\"([^"]+)\">', f)

rawDescription: How would I search a .txt file for something between <> python


rawDescription: What is the syntax to insert one list into another list in python?


code:
# Replace any rows that do exist with the cur_df version
result.update(df4)

rawDescription: Pandas concatenate, with no duplicate indices or columns


code:
players = list(xrange(np.size(score, 0)))
players
excludes = [2,3]
players_to_include = [p for p in players if p not in excludes]
players_to_include
score[players_to_include, 1]

rawDescription: slice numpy array by column except for 1 row

description: Slice numpy array by column except for 1 row


code: filtersToCheck = value.split(',')

rawDescription: Getting a list from a config file with ConfigParser in Python


rawDescription: Python: Finding multiple roots of nonlinear equation


code:
zeroth_ifd[pyxif.ZerothIFD.Artist] = args.artist
zeroth_ifd[pyxif.ZerothIFD.Copyright] = args.copyright

exif_ifd[pyxif.ExifIFD.PixelXDimension] = size[0]
exif_ifd[pyxif.ExifIFD.PixelYDimension] = size[1]

exif_bytes = pyxif.dump(zeroth_ifd, exif_ifd, gps_ifd)

im.save(output_path, "JPEG", quality=85, exif=exif_bytes)

rawDescription: Write EXIF-data from TIF (read with exifread) to JPEG-file using PIL (Pillow)


code:
tagslinks_assoc = Table(
    'tagslinks', Base.metadata,
    Column('tagid', Integer, ForeignKey('tags.tagid'), primary_key=True),
    Column('linkid', Integer, ForeignKey('links.linkid'), primary_key=True)
)

rawDescription: database for tags - updating many-to-many tables with unique columns

description: Database for tags - updating many-to-many tables with unique columns


code:
original = ['state1', ',', 'state2,st6']
[[item] for string in original for item in string.split(',') if item]

rawDescription: How to separate strings in a list in python?

description: Separate strings in a list in python


rawDescription: Split strings on whitespaces, but do not remove them


code:
distances = [dist(e1, e2) for lst1, lst2 in permutations(d.values(), 2)
             for e1, e2 in chain.from_iterable(product(lst1, lst2))]

rawDescription: Finding Interfaces

description: Finding Interfaces


code: s = np.concatenate(([s0], s0 * np.cumprod(z[0:-1])))

rawDescription: Efficient Way to Recursively Multiply

description: Efficient Way to Recursively Multiply


code:
import matplotlib
matplotlib.use('TkAgg') # do this before importing pylab
import time
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

def animate():
    origin = 'lower'
    delta = 0.025

    x = y = arange(-3.0, 3.01, delta)
    X, Y = meshgrid(x, y)
    Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    Z = 10 * (Z1 - Z2)

    CS1 = ax.contourf(
        X, Y, Z,
        levels = linspace(Z.min(), Z.max(), 10),
        cmap=cm.bone,
        origin=origin)

    for i in range(10):
        tempCS1 = contourf(
            X, Y, Z,
            levels = linspace(Z.min(), Z.max(), 10),
            cmap=cm.bone,
            origin=origin)
        del tempCS1
        fig.canvas.draw()
        time.sleep(0.1)
        Z += x/10

win = fig.canvas.manager.window
fig.canvas.manager.window.after(100, animate)
plt.show()

rawDescription: How to visualize scalar 2D data with Matplotlib?

description: Visualize scalar 2D data with Matplotlib


code: output = Sample.objects.get(pk=1)

rawDescription: Django Query Set Results

description: Django Query Set Results


rawDescription: Map string positions to list positions

description: Map string positions to list positions


code:
with open("file_b", "r") as fb:
    all_lines_except_header = numpy.loadtxt(fb, skiprows=1)

rawDescription: combining two csv files python

description: Combining two csv files python


code:
import math

class DecimalIndexing:
    def __init__(self, n):
        self.n = n
    def __len__(self):
        return int(math.floor(math.log10(self.n)+1))
    def __getitem__(self, i):
        if isinstance(i, slice):
            return [self[x] for x in range(i.start, i.stop, i.step or 1)]
        else:
            return (self.n/(10**i))%10
    def __iter__(self):
        for i in xrange(len(self)):
            yield self[i]

rawDescription: Find sequences of digits in long integers efficiently


rawDescription: Python removing duplicate lines

description: Python removing duplicate lines


code:
tree_info = [['5', 'Child 2', '3'],
             ['1', 'Grandparent', 'root'],
             ['4', 'Child 1', '3'],
             ['3', 'Parent 2', '1'],
             ['2', 'Parent 1', '1'],
             ['6', 'Child 3', '2']
             ]

children = {}
names = {}

for node_id, name, parent in tree_info:
    children.setdefault(parent, []).append(node_id)
    names[node_id] = name

q = [('root', -1)]
while q:
    parent, depth = q.pop()
    if parent != 'root':
        print(' ' * depth + names[parent])

    if parent in children:
        for child in children[parent]:
            q.append((child, depth+1))

rawDescription: print out an indented node tree in python from a list of list

description: Print out an indented node tree in python from a list of list


code:
def run(self):
    global running
    self.isRunning = 1

rawDescription: Confusion with python global variables, pygame event


rawDescription: Find the edges of a numpy array that 95% data within them


code:
import pandas as pd

sensor1 = pd.DataFrame({"p1":[5,2,3], "ObservationID":[22, 31, 14]})
sensor2 = pd.DataFrame({"p2":[1,1,0], "ObservationID":[22, 31, 14]})

# first, set index column to be unique
sensor1_indexed = sensor1.set_index(["ObservationID"])
sensor2_indexed = sensor2.set_index(["ObservationID"])

sensors = pd.concat([sensor1_indexed, sensor2_indexed], axis=1)

rawDescription: Append data in pandas

description: Append data in pandas


code: statusbar.push(1, "Almost done...")

rawDescription: How do I add children to a StatusBar in Glade3?

description: Add children to a StatusBar in Glade3


code:
import Tkinter as tk

root = tk.Tk()
temp_f_number = tk.DoubleVar()
temp_c_number = tk.DoubleVar()

tk.Label(root, text="F").grid(row=0, column=0)
tk.Label(root, text="C").grid(row=0, column=1)

temp_f = tk.Entry(root, textvariable=temp_f_number)
temp_c = tk.Entry(root, textvariable=temp_c_number)

temp_f.grid(row=1, column=0)
temp_c.grid(row=1, column=1)

update_in_progress = False

def update_c(*args):
    global update_in_progress
    if update_in_progress: return
    try:
        temp_f_float = temp_f_number.get()
    except ValueError:
        return
    new_temp_c = round((temp_f_float - 32) * 5 / 9, 2)
    update_in_progress = True
    temp_c_number.set(new_temp_c)
    update_in_progress = False

def update_f(*args):
    global update_in_progress
    if update_in_progress: return
    try:
        temp_c_float = temp_c_number.get()
    except ValueError:
        return
    new_temp_f = round(temp_c_float * 9 / 5 + 32, 2)
    update_in_progress = True
    temp_f_number.set(new_temp_f)
    update_in_progress = False

temp_f_number.trace("w", update_c)
temp_c_number.trace("w", update_f)

root.mainloop()

rawDescription: Python Tkinter update when entry is changed


code:
Food  # sorbet
Person # man
Person # shirt
Food # meal
Vehicle # formula
Food # steak

rawDescription: Python - reading complex lines of text into dictionary


code:
import numpy as np
A = np.array([5, np.nan, np.nan, np.nan, np.nan, 10])
np.isnan(A)
~np.isnan(A)
A[~np.isnan(A)]
A[~np.isnan(A)].mean()

rawDescription: Get mean value avoiding nan using numpy in python


code:
from getData import getData
status, description, data = getData()

# Print the values
print("STATUS:", status)
print("DESCRIPTION:", description)
print("DATA:", data)

rawDescription: PHP calling Python, returning multiple values


code:
x = "Python is the best programming language"
x.split()[::-1]

Out [2]: ['language', 'programming', 'best', 'the', 'is', 'Python']

rawDescription: Reversing a string in python (WORD by WORD)


code:
def sort(names, rank):
    lst=[]
    for x in range(0, len(names)):
        lst.append((int(rank[x]), names[x]))
    lst.sort(key=lambda x: (-x[0],len(x[1]), ord(x[1][0])) )
    newArr = []
    for z in range(0, len(lst)):
        row = lst[z]
        newArr.append(row[1] + " " + str(row[0]))
    return newArr

rawDescription: Sort by name and rank

description: Sort by name and rank


code:
N = 3000000
r1 = np.random.multivariate_normal(M1, C1, N)
r2 = np.random.multivariate_normal(M2, C2, N)

h1, rx, ry = np.histogram2d(r1[:, 0], r1[:, 1], bins=50, range=[[-2, 2], [-2, 2]])
h2, _, _ = np.histogram2d(r2[:, 0], r2[:, 1], bins=50, range=[[-2, 2], [-2, 2]])

rx, ry = np.broadcast_arrays(rx[:, None], ry[None, :])

fig, axes = pl.subplots(1, 3, figsize=(15, 5))
ax1, ax2, ax3 = axes.ravel()
for ax in axes.ravel():
    ax.set_aspect("equal")

ax1.pcolormesh(rx, ry, h1)
ax2.pcolormesh(rx, ry, h2)
ax3.pcolormesh(rx, ry, h1 > h2)

rawDescription: Plotting a Discriminant Function for Normal Densities via Matplotlib


code: ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

rawDescription: Good ways to sort a queryset? - Django

description: Good ways to sort a queryset? - Django


code:
import csv
import os

outputfile = inputfile + '.tmp'
with open(inputfile, 'rb') as inf, open(outputfile, 'wb') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf, delimiter='|')
    writer.writerows(reader)
os.remove(inputfile)
os.rename(outputfile, inputfile)

rawDescription: Pipe delimiter file, but no pipe inside data


code: max_each = {key: max(value) for key, value in class_1.items()}

rawDescription: working out an average of the values in a dictionary

description: Working out an average of the values in a dictionary


code: from __future__ import print_function

rawDescription: Customize compile function in python?

description: Customize compile function in python


code:
x = np.random.randn(10)

# this writes the array out to 6 decimal places
np.savetxt('six_dp.txt', x, fmt='.6f')

# this writes the same array to 3 decimal places
np.savetxt('three_dp.txt', x, fmt='.3f')

rawDescription: Apply round off setting to whole notebook


code: t, z, y, x = np.indices(temp.shape)

rawDescription: Python numpy grid transformation using universal functions


rawDescription: Pandas DatetimeIndex vs to_datetime discrepancies


code:
import csv

# import
data = {}
with open('userdata.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        a = iter(row[1:])
        data[row[0]] = dict(zip(a, a))

# export
with open('userdata_exported.csv', 'w') as f:
    writer = csv.writer(f)
    for key, values in data.items():
        row = [key] + [value for item in values.items() for value in item]
        writer.writerow(row)

rawDescription: Importing/Exporting a nested dictionary from a CSV file


code:
def tracelog(log):

    def real_decorator(func):
        @wraps(func)
        def inner(*args, **kwargs):
            log.debug('entered {0} called with args={1}, kwargs={2}'.format(func.func_name, *args, **kwargs))
            func(*args, **kwargs)
            log.debug('exited {0}'.format(func.func_name))
        return inner
    return real_decorator

rawDescription: Python : Automatic debug logs when control goes inside/outside function


code: df.columns = df.columns.droplevel(1)

rawDescription: Flatten / Remove hierarchical column headers


code: counter[i] = counter.get(i, 0) + 1

rawDescription: Python Counter doesn't count

description: Python Counter doesn't count


rawDescription: Method to get two separate lists after parsing output


code:
# Load first array.
bigarray = numpy.load(filenames[0]);
# Add a new axis to make it 3D.
bigarray = bigarray[numpy.newaxis,...];
# Load rest of arrays.
for i in range(1,len(filenames)):
    bigarray = numpy.append(bigarray, numpy.load(filenames[i])[numpy.newaxis,...], axis=0);

rawDescription: Import array files with numpy

description: Import array files with numpy


rawDescription: pandas get all columms without one

description: Pandas get all columms without one


code:
class Debtors(sqlimport.Exact):
    def startDocument(self):
        self.table = 'debiteuren'
        self.address = None

    def startElement(self, name, att):
        sqlimport.Exact.startElement(self, name, att)

        if self.curPath(True) == ' > '.join(self.stdpath):
            self.thisrow = {}
            self.thisrow['debiteur'] = att.get('code').strip()
        elif self.curPath() == 'Name':
            self.getValue = 'naam'
        elif self.curPath() == 'Phone':
            self.getValue = 'telefoon1'
        elif self.curPath() == 'ExtPhone':
            self.getValue = 'telefoon2'
        elif self.curPath() == 'Contacts > Contact > Addresses > Address':
            if att.get('type') == 'V':
                self.address = 'Contacts > Contact > Addresses > Address '
        elif self.address is not None:
            if self.curPath() == self.address + '> AddressLine1':
                self.getValue = 'adres1'
            elif self.curPath() == self.address + '> AddressLine2':
                self.getValue = 'adres2'
        else:
            self.getValue = None

if __name__ == '__main__':
    handler = Debtors(['Debtors', 'Accounts', 'Account'])
    parser = xml.sax.make_parser()
    parser.setContentHandler(handler)

    parser.parse(open('myfile.xml', 'rb'))

rawDescription: Parsing XML with Python xml.sax: How does one "keep track" of where in the tree you are?


code:
class Post(models.Model):
    pass

class Project(models.Model):
    posts = models.ManyToManyField(Post)

rawDescription: django return foreign key object from queryset?

description: Django return foreign key object from queryset


code: setattr(x, attr, 'magic')

rawDescription: How do you programmatically set an attribute in Python?

description: Programmatically set an attribute in Python


code: datetime.now() - df['Date']

rawDescription: Pandas Python: How to create lapse since today column?


rawDescription: python pyparsing string: A,b,b,b,A,b,b,b*

description: Python pyparsing string: A,b,b,b,A,b,b,b*


code:
words = "ABCD abcd AB55 55CD A55D 5555"
' '.join(s for s in words.split() if not any(c.isdigit() for c in s))

rawDescription: Python regex to remove all words which contains number


code:
class AbstractCustomerData( object ):
   """Generic features common to all customer data."""

rawDescription: Where to put rules for creating a map between two data sets?


code: df - df.shift(12)/ df

rawDescription: Calculating year over year growth by group in Pandas


rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code:
for i, label in enumerate(labels_class):
     labels_class[i] = 1 if (label == classifier) else 0

rawDescription: Modify actual element value in array numpy


code:
import re
def f(a):
  return a[::-1]
s = '\t  \t this  is a\tbanana   \n'
re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)

rawDescription: What's the most pythonic way to apply a function on every word in a string with multiple types of white space characters?


rawDescription: Regular Expression for single line comments


rawDescription: python - how to get the data from an plt.imshow()?

description: Python - how to get the data from an plt.imshow()


code:
def deco(wrapped_cls):
    @functools.wraps(wrapped_cls)
    class Wrapper(wrapped_cls):
        def __new__(cls, *args, **kwargs):
            ...
            return wrapped_cls(*args, **kwargs)
    return Wrapper

rawDescription: Why does decorating a class break the descriptor protocol, thus preventing staticmethod objects from behaving as expected?


code:
if var is 'stringone' or 'stringtwo':
    dosomething()

rawDescription: Python: How to check if a variable is equal to one string or another string


code:
US0837, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
PK273, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
US1549, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
USDM1120, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
US1563, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
US1420, {'Count': 3, 'State': 'DOWN', 'StateType': 'HARD'}
US1354, {'Count': 2, 'State': 'DOWN', 'StateType': 'HARD'}
US3033, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
FR0744, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
ID1135, {'Count': 2, 'State': 'DOWN', 'StateType': 'HARD'}
IL1308, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
VN1320, {'Count': 2, 'State': 'DOWN', 'StateType': 'HARD'}
US1118, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
VN373, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
US1565, {'Count': 1, 'State': 'DOWN', 'StateType': 'HARD'}
US1311, {'Count': 2, 'State': 'DOWN', 'StateType': 'HARD'}

rawDescription: How to parse nagios log file to count host down in a given log file?

description: Parse nagios log file to count host down in a given log file


code:
def main():
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__': main()

rawDescription: Saving connect statements pyqt when UI is still changing


code: (("b" in a) and ("z" in a)) in a and ("a" in a)

rawDescription: Python 2.7: Using reduce to verify that elements are in a list


code:
vecfunc = np.vectorize(MyClass.add5,otypes=[int])
vecfunc(myarray2)

rawDescription: Handling attributes of a class within a numpy array


code: final = str(self.lostfeatures).replace('[array([[','').replace(']], dtype=float32)', '')

rawDescription: Python strip() function - remove characters before/after string


code:
info = [
  [1, 'eth0', 'description'],
  [2, 'virbr0', 'description'],
  [3, 'qvb25f982e4-ae', 'description'],
  [4, 'tap25f982e4-ae', 'description'],
]

exclude = ('q','tap')
info = [i for i in info if not i[1].startswith(exclude)]

info

rawDescription: Somewhat complex list comprehension

description: Somewhat complex list comprehension


code:
def apply_indexed_fast(array, func_indices, func_table):
    func_argsort = func_indices.argsort()
    func_ranges = list(np.searchsorted(func_indices[func_argsort], range(len(func_table))))
    func_ranges.append(None)
    out = np.zeros_like(array)
    for f, start, end in zip(func_table, func_ranges, func_ranges[1:]):
        ix = func_argsort[start:end]
        out[ix] = f(array[ix])
    return out

rawDescription: Efficient algorithm for evaluating a 1-d array of functions on a same-length 1d numpy array


rawDescription: parse a date to utc unixtime

description: Parse a date to utc unixtime


code:
data = {}
with open('file.txt', 'r') as f:
    header, *descriptions = f.read().split('\n\n')
    for line in header.split('\n'):
        key, value = line.split(' : ')
        data[key.lower()] = value.rstrip()
    for description in descriptions:
        key, value = description.split('\n', 1)
        data[key[1:]] = value
print(data)

rawDescription: tokenizing and parsing with python

description: Tokenizing and parsing with python


code: print('\n'.join('CLL' + word.rstrip('|') for word in s.split('|CLL') if word))

rawDescription: Split String with Python Regexp

description: Split String with Python Regexp


rawDescription: Wilcard matching substring in Python

description: Wilcard matching substring in Python


code: wait = WebDriverWait(driver, 5, poll_frequency=0.1)  # default frequency is 0.5

rawDescription: make selenium driver wait until elements style attribute has changed

description: Make selenium driver wait until elements style attribute has changed


code:
def perform_distributed_processing(dbList, threads, processor_factory):
    with ProcessPoolExecutor(processes=threads) as executor:
        fs = (executor.submit(processor_factory, db) for db in dbList)
        yield from map(Future.result, as_completed(fs))

rawDescription: Multiprocessing with python3 only runs once


code:
data.json
{
  "person": {
    "name": "Jhon Dow",
    "address": "London",
    "age": 26,
    "isMarried": true,
    "brothersNames": [
      "Kim",
      "David",
      "Ron"
    ]
  },
  "animal": {
    "type": "Lion",
    "name": "Simba",
    "age": 10
  }
}

rawDescription: how to Change dictionary values in python file

description: Change dictionary values in python file


code:
df = pd.DataFrame(np.random.randint(1, 5, (10, 2)), columns=list('ab'))
df
df.a.rank()  # there are several 2s (which have rank 5)
df.a.rank(method='first')

rawDescription: create new rank column in python , or use sort and reset index rank - how to?

description: Create new rank column in python , or use sort and reset index rank - how to


code:
from itertools import groupby
from operator import itemgetter

grouped = [list(g) for p, g in groupby(inputlist, key=itemgetter('person_id'))]

rawDescription: Group list of dictionaries to list of list of dictionaries with same property value


code:
context = decimal.Context(prec=1000)
decimal.setcontext(context)

rawDescription: How to define a decimal class holding 1000 digits in python?

description: Define a decimal class holding 1000 digits in python


code:
def callback(spider, reason):
    stats = spider.crawler.stats.get_stats()  # stats is a dictionary

    # write stats to the database here

    reactor.stop()

def run_spider(spider):
    settings = get_project_settings()
    crawler = Crawler(settings)
    crawler.signals.connect(callback, signal=signals.spider_closed)
    crawler.configure()
    crawler.crawl(spider)
    crawler.start()
    log.start()
    reactor.run()

run_spider(spider)

rawDescription: How to get stats from a scrapy run?

description: Get stats from a scrapy run


rawDescription: Plotting a horizontal line on multiple subplots in python using pyplot


code:
currenttime = strftime('%H:%M:%S')
print ("""23:40:00 to 23:50:00 | %s""" % (currenttime))
sleep(1)

rawDescription: Complete a task during certain time frames within a python script


code:
#y.py
def func():
    print(lol)

rawDescription: What are all the ways to add an object to the local scope in Python?


code:
from collections import namedtuple
Record = namedtuple("MyNamedTuple", ["ID", "Value", "Name"])
tuplePi = (1, 3.14, "pi")
Record(*tuplePi)
Record._make(tuplePi)

rawDescription: How to cast tuple into namedtuple?

description: Cast tuple into namedtuple


code:
proc = subprocess.Popen("third_party.exe",
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT, bufsize=1)

rawDescription: Python subprocess output on windows?

description: Python subprocess output on windows


rawDescription: Removing spaces from astring within a CSV in python


code: fig.suptitle(r'H$_{\rm two}$ Emission from GJ832')

rawDescription: Force LaTeX font to match default matplotlib font


rawDescription: Print letters not in string

description: Print letters not in string


code:
def rec(currentObject):
    if isinstance(currentObject, list):
        return "".join([rec(item) for item in currentObject])
    elif isinstance(currentObject, dict):
        return "".join([rec(item) for item in currentObject.values()])
    elif isinstance(currentObject, str) or isinstance(currentObject, unicode):
        return currentObject
    else:
        raise TypeError("Unexpected type : {}".format(type(currentObject)))

rawDescription: Python:How to recursively store all the value of hash of hash into a string ?


code:
df = df.reset_index()
df['CompanyName']

rawDescription: KeyError in Dataframe

description: KeyError in Dataframe


code:
with open('test.txt') as x:
    for line in x:
        # By this point, line is set to the first line
        # the file cursor has advanced just past the first line
        print(x.read())
        # the above prints everything after the first line
        # file cursor reaches EOF, no more lines to iterate in for loop

rawDescription: Reading from a text file with python - first line being missed


rawDescription: Verifying If key or value exists in dictionary, works for char and fails for number


code:
from sqlalchemy.sql.expression import desc, asc
session.query(Shots) \
    .filter_by(event_id=event_id) \
    .order_by(asc(Shots.user_id))

rawDescription: How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?

description: Model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)


rawDescription: Reverse Y-Axis in PyPlot

description: Reverse Y-Axis in PyPlot


rawDescription: All combinations fourteen item array

description: All combinations fourteen item array


code: print >> outputfile, value1, "NOMINAL" if isinstance(value1, str) else "NUMERIC"

rawDescription: Pythonic way to make string dependend on type of variable


code:
from flask import Flask, Response
import random
import time

app = Flask(__name__)
def eventStream():
    # will send simple SSE style responses
    while True:
        waittt = random.random()
        time.sleep(waittt)
        yield "data: {}\n\n".format(str(waittt))
# This route works fine :)
@app.route('/streamroute')
def stream():
    return Response(eventStream(), mimetype="text/event-stream")

# This route doesn't work :(
app.add_url_rule('/stream', 'stream', stream)
app.run(debug=True)

rawDescription: Python Flask : Route vs add_url_rule, SSE


code: targetText2 = text.select(".Book-Title- + .Text")

rawDescription: Beautiful Soup 4 CSS sibling selector

description: Beautiful Soup 4 CSS sibling selector


code:
A = [[],[],[],[]]
for i in range(x.shape[0]):
    for j in range(x.shape[1]):
        A[0].append('node(%s,%s)'%(i,j))
        A[1].append(i)
        A[2].append(j)
        A[3].append(x[i,j])

rawDescription: Creating NxM indices from a Python array


code:
from itertools import product
s = "10000101"
all_poss = product(*(['1', '!'] if c == '1' else [c] for c in s))
for x in all_poss:
    print(''.join(x))

rawDescription: How do I iterate through all sub-combinations of 1's and !'s?

description: Iterate through all sub-combinations of 1's and !'s


code: rows = soup.select('.chart-wide tr')

rawDescription: Python BeautifulSoup webcrawling: Getting text that doesn't have links or class tags


rawDescription: Generic way to create nested dictionary from flat list in python


code:
from functools import wraps
def set_return_type(typeobj):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            return typeobj(func(*args, **kwargs))
        return wrapper
    return decorator

rawDescription: A decorator-creating class

description: A decorator-creating class


code: df.loc[df.Name == 'Pigeon', 'Category']

rawDescription: Accessing Another Column By Value ,Pandas


code: lambda seq: [lambda: el for el in seq]

rawDescription: Weird lambda behaviour in loops in python 2.7, anybody has a clue?


code: br_record[0].id == 36

rawDescription: Retrieve "id" as list from browse record of many2many field?


code:
final_output = {}
flat_dict = flatten(original_dict)
for key in needed_keys:
    for k in flat_dict:
        if k.endswith(key):
            final_output[key] = flat_dict[k]
            break
    if not key in final_output:
        final_output[key] = None

rawDescription: Single dictionary of fewer keys from a multi level dictionary


code: dict(islice(mydict.iteritems(), 0, 2))

rawDescription: In Python how to obtain a partial view of a dict?


code: d = {'None': 'None' for _ in range(100000)}

rawDescription: Initialising a large dict with unknown keys? Is there a better way than this?


rawDescription: What's a variable in a inner function definition in python?


rawDescription: Inserting an element in list, at exact location, without array sizing in Python?


rawDescription: Why can't Python understand integers in word form?


code: (cl != cl.shift()) & cl

rawDescription: Pandas Label Sequences of 1 in a 0-1 valued Series


code:
s = '8255'
type(ast.literal_eval(s))

rawDescription: Double string to int

description: Double string to int


rawDescription: open file in finder or explorer on linux or unix

description: Open file in finder or explorer on linux or unix


rawDescription: What is a cell in the context of an interpreter or compiler?


code:
text = ''
while True: # change this condition.
    text += input('''Enter the paragraph :''')+'\n' #UPDATED. Appended a \n character.

rawDescription: Accept newline character in python

description: Accept newline character in python


code:
import os, fnmatch

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)

                yield filename

def find_files_to_list(directory, pattern):
    file_list = []
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                file_list.append(filename)

    return file_list

rawDescription: How to find files and save them to different folder in python

description: Find files and save them to different folder in python


code:
status = Status()
cherrypy.tree.mount(status, '/status', config)
cherrypy.tree.mount(status, '/', config)

rawDescription: CherryPy index path

description: CherryPy index path


code:
def print_board(game_state):
    """Prints the game board given the current game state"""

    print("1 2 3 4 5 6 7")
    for row in range(BOARD_ROWS):
        for col in range(BOARD_COLUMNS):
            if game_state.board[row][col] == connect_four.NONE:
                print('.', end=' ')
            elif game_state.board[row][col] == connect_four.RED:
                print('R', end=' ')
            elif game_state.board[row][col] == connect_four.YELLOW:
               print('Y', end=' ')

        print()

rawDescription: Printing a two dimensional list

description: Printing a two dimensional list


code:
for testy in collection.distinct('stores', {'dept': 'A'}):
    print(testy)

rawDescription: How to get distinct values from PyMongo

description: Get distinct values from PyMongo


code:
for f in self.engine.processMovie():
    c, s = dlg.Update(f, "Processing frame %d"%f)
    if not c: break

rawDescription: usage of generators as a progression notifier

description: Usage of generators as a progression notifier


code: Foo(a, b).bar((c, len(d)))

rawDescription: Inline Tuple Creation - Which is More Readable?


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

NPOINTS=100

def set_grid_cross(ax, in_back=True):
    xticks = ax.get_xticks()
    yticks = ax.get_yticks()
    xgrid, ygrid = np.meshgrid(xticks, yticks)
    kywds = dict()
    if in_back:
        kywds['zorder'] = 0
    grid_lines = ax.plot(xgrid, ygrid, 'k+', **kywds)

xvals = np.arange(NPOINTS)
yvals = np.random.random(NPOINTS) * NPOINTS

ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

ax1.plot(xvals, yvals, linewidth=4)
ax1.plot(xvals, xvals, linewidth=7)
set_grid_cross(ax1)
ax2.plot(xvals, yvals, linewidth=4)
ax2.plot(xvals, xvals, linewidth=7)
set_grid_cross(ax2, in_back=False)

plt.savefig('gridpoints.png')
plt.show()

rawDescription: Instead of grid lines on a plot, can matplotlib print grid crosses?


code:
dct = sorted(prob.items(), key=lambda x: x[1], reverse=True)
result = collections.OrderedDict(dct)

rawDescription: how can I sort dictionary whose key is tuple and value is int?

description: Sort dictionary whose key is tuple and value is int


code:
def basestate(base):
    return 1 if base == 0 else 0

rawDescription: How to make a function with a parameter?

description: Make a function with a parameter


code:
employee_one = Employee.objects.get(pk=1)
company_of_employee_one = employee_one.office.company

rawDescription: Django model relation

description: Django model relation


code:
settings = QtCore.QSettings(org_name, app_name)
main_win.restoreGeometry(settings.value('geometry'))
main_win.restoreState(settings.value('state'))
main_win._ui.dockWin.setFloating(settings.value('dockWin/isFloating')=='true')

rawDescription: Qt - pyside - saveGeometry() saveState()


code:
import subprocess

def create_grid(*commands):
    process = subprocess.Popen(
        ['grid.exe'],
        stdout=subprocess.PIPE,
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE)

    process.communicate('\n'.join(commands) + '\n')

if __name__ == '__main__':
    create_grid('grid.grd', 'yes', 'not really')

rawDescription: How to run executable from python and pass it arguments asked for?

description: Run executable from python and pass it arguments asked for


code:
from collections import OrderedDict

ordered_dictionary = [OrderedDict(zip(names, subl)) for subl in list_of_lists]

rawDescription: How to make ordered dictionary from list of lists?

description: Make ordered dictionary from list of lists


code: motif = re.compile('%s' % pattern)

rawDescription: Selecting item in a string from a starting point retrieved via regex (Python)


code:
def monthdict():
    return defaultdict(list)
data = defaultdict(monthdict)

data[year][month].append(day)

rawDescription: Which data structure to use in Python to store data like this?


code:
for i in range(n):
    if i % 3 == 0:
        x();
    elif i % 3 == 1:
        ...

rawDescription: Inside a range how can I internally count up to 3?


code: heapq.nlargest(10, xrange(len(l1)), key=lambda i: abs(l1[i] - l2[i]))

rawDescription: finding n largest differences between two lists

description: Finding n largest differences between two lists


code:
rawimage = kitty .get_image_data()
format = 'RGBA'
pitch = rawimage.width * len(format)
pixels = rawimage.get_data(format, pitch)

rawDescription: Get colour of specified pixel in window

description: Get colour of specified pixel in window


code:
class Z:
    def __init__(self):
        self.a, self.b, self.c = 1,2,3

    def it(self):
        for x in self.a, self.b, self.c:
            yield x

z = Z()
for x in z.it():
    if x == 1:
       x = 42 # z.a should be 42? - doesn't work!

rawDescription: Python: Assigning "through" an iterator

description: Python: Assigning "through" an iterator


rawDescription: understanding python variable assignment

description: Understanding python variable assignment


rawDescription: Logical OR on a subset of columns in a DataFrame


code:
for x,y in alist:
    if x == "Me" and y:
        if flag:
            tempcount += 1
            initiated = True
        else:
            tempcount = 1
            flag = True
    if x == "Me" and not y and flag and initiated:
        tempcount += 1
    if x == "Partner" and y and flag and initiated:
        permcount.append(tempcount)
        flag = False
    if x == "Partner" and not y and flag and initiated:
        permcount.append(tempcount)
        flag = False

rawDescription: Python 2.7: Evaluating pairs in a 2D Python Array


code:
for lst in input:
    for i in range(len(lst)):
        if lst[i] not in item_node:
            item_node[lst[i]] = []
            if i == 0:
                output.append(lst[i])
                output.append(item_node[lst[i]])
            else:
                item_node[lst[i-1]].append(lst[i])
                item_node[lst[i-1]].append(item_node[lst[i]])
Out[54]: ['a', ['b', ['c', [], 'd', []], 'e', []]]

rawDescription: python - going from a stack trace to a tree

description: Python - going from a stack trace to a tree


code:
lst = ['a b d', 'a b e', 'c d j', 'w x y', 'w x z', 'w x k']
def remove_starts(lst):
    seen = []
    for elem in lst:
        if elem.startswith(tuple(seen)):
            continue
        yield elem
        seen.append(elem[:4])
list(remove_starts(lst))

rawDescription: remove later strings starting with a certain thing in a list python

description: Remove later strings starting with a certain thing in a list python


code:
_bar = Foo()
foo = _bar.__enter__()
print ('Hello World!')
_bar.__exit__()
del _bar # This will call __del__ because _bar is the only reference

rawDescription: Why is __del__ called at the end of a with block?


code: set(dir()) - set(dir(__builtins__)) - {'__builtins__'}

rawDescription: Is there a way to see the variables declared in a session in Python?


rawDescription: Cumulative counts in NumPy without iteration


rawDescription: Special Character Pattern Matching in Python


code:
passwords = {'foo':'vlTTdhML', 'bar':'xneoYb2c', 'baz':'wnkyVsBI'}
username, password = queue, passwords[queue]

rawDescription: python, replace if/elif with dictionary

description: Python, replace if/elif with dictionary


code:
class SomeTable(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    date = Column(String)
    time = Column(String)

    @hybrid_property
    def datetime(self):
        # @todo: add python parsing of date and time to produce the result
        str_value = self.date + self.time
        return datetime.strptime(str_value, "%d/%m/%Y%H:%M:%S")

    @datetime.expression
    def datetime(cls):
        # @note: query specific value
        dt_column =(func.substr(cls.date, 7) + "-" +
                    func.substr(cls.date, 4, 2) + "-" +
                    func.substr(cls.date, 1, 2) + " " + cls.time)
        dt_column = func.datetime(dt_column)
        return dt_column

...
qry = session.query(SomeTable)
qry = qry.filter(SomeTable.datetime <= datetime(2013, 1, 1, 23, 59, 59))

rawDescription: Converting string to date timestamp in SQLAlchemy


code: indexes = [i for i, t in enumerate(zip(a, b, c)) if any(e > max_limit for e in t)]

rawDescription: Make this simple for/if block more pythonic


code:
def test(message):
    return message + message

testanon = lambda message: message + message

rawDescription: Performance gain using anonymous functions?


code:
results = []
todo = [1,2,3,4,5]
for arg in todo:
    res = process.apply_async(args=(arg))
    results.append(res)

all_results = [res.get() for res in results]

rawDescription: Suggestions on distributing python data/code over worker nodes?


code:
while True:
    pos = data.find('_')
    if pos < 0:
        break
    data = data[:pos-2] + data[pos+1:]

rawDescription: how to remove and add character/integer in python?

description: Remove and add character/integer in python


code: filter(None, ["1", 0, " ", "", None, True, False, "False"])

rawDescription: Tkinter - Only show filled values of an array in a OptionMenu


code:
x.newer_field
y.newer_field

rawDescription: Does django (python) reuse object?

description: Does django (python) reuse object


code: split_string("foo.,.bar", ".,")

rawDescription: How can I simplify this function?

description: Simplify this function


code:
subs = {
        "Houston": "HOU",
        "L.A. Clippers": "LAC",

    }
rev_subs = { v:k for k,v in subs.iteritems()}
[rev_subs.get(item,item)  for item in my_lst]

rawDescription: How to replace elements in a list using dictionary lookup

description: Replace elements in a list using dictionary lookup


rawDescription: How can I change values for a section of a numpy array?

description: Change values for a section of a numpy array


code:
def __init__(self, *options):
    for name in options:
        self.__dict__[name] = name

rawDescription: Receiving Arguments via Pointers in Python


code:
import ast
result = ast.literal_eval("['A', 'B', 'C', 'D', 'E']")
type(result)
result

rawDescription: How to convert list lookalike into a list?

description: Convert list lookalike into a list


code:
sorted(['2', '2', '3', 'A'], key=lambda x: RANKS.index(x))
sorted(['10',"K","J","Q"], key=lambda x: RANKS.index(x))

rawDescription: Sort Python list by dict key,value

description: Sort Python list by dict key,value


rawDescription: Python list subtraction operation

description: Python list subtraction operation


rawDescription: Python program don't run

description: Python program don't run


rawDescription: Iterate through rows in pandas dateframe in a cleaner way using .iterrows() and keep track of rows inbetween specific values


code:
def replacement():
  o = open("file.txt","a") #file.txt will be the file containing the changed phrase
  for line in open("y.txt"):  #y.txt is the original file
    split_line = line.split()
    new_split_line = [maybe_replace(word) for word in split_line]
    new_line = ' '.join(new_split_line)
    o.write(new_line + '\n')
  o.close()

rawDescription: Python 3.2 Replace all words in a text document that are a certain length?


code:
import csv, heapq

filenames = ('B1.csv', 'B2.csv', 'B3.csv')

# Prepare the input streams
files = list(map(open, filenames))
readers = [iter(csv.reader(file)) for file in files]
headers = list(map(next, readers))
def model_and_row(row):
    return row[2], row
model_and_row_streams = [map(model_and_row, reader) for reader in readers]

# Merge them into the output file
with open('Bmerged.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    writer.writerow(headers[0])
    for _, row in heapq.merge(*model_and_row_streams):
        writer.writerow(row)

# Close the input files
for file in files:
    file.close()

rawDescription: Concatenate large files in sql-like way with limited RAM


code:
import inspect
import re

def handle_nested_parens(v):
   parens = 0
   output = ""
   for c in v:
       if c == ")":
           parens = parens - 1
           if parens < 0:
               return output
       output += c
       if c == "(":
           parens = parens + 1
   return output

def logger(v):
   currentframe = inspect.currentframe()
   code_context = inspect.getouterframes(currentframe,1)[1][4][0]
   variable = handle_nested_parens(re.sub(r".*logger\((.*)",r"\1", code_context))
   print("{0} => {1}".format(variable, v))

def testing(a):
   return(a)

def submain(a):
   ab = (1, 2, a)
   logger(testing(ab))
   return 15

def main():
   xyz = "hello"
   logger(xyz)
   logger(submain(xyz))

if __name__ == '__main__':
    a = 5
    logger(a)
    main()

rawDescription: In a Python function, Is there a way to tell the argument's variable name on the caller side?


rawDescription: Print two presorted lists into one output file in python


rawDescription: Ask user and print a list

description: Ask user and print a list


code:
for content in abstracts:
    items.append(ItemWidget(content, globalvisibility[:]))

rawDescription: Incomprehensible behaviour of class variables


code:
def mbox(msg, b1='OK', b2='Cancel', frame=True, t=False, entry=False):
    """Create an instance of MessageBox, and get data back from the user.
    msg = string to be displayed
    b1 = text for left button, or a tuple (<text for button>, <to return on press>)
    b2 = text for right button, or a tuple (<text for button>, <to return on press>)
    frame = include a standard outerframe: True or False
    t = time in seconds (int or float) until the msgbox automatically closes
    entry = include an entry widget that will have its contents returned: True or False
    """
    msgbox = MessageBox(msg, b1, b2, frame, t, entry)
    msgbox.root.mainloop()
    # the function pauses here until the mainloop is quit
    msgbox.root.destroy()
    return msgbox.returning

rawDescription: Correct way to implement a custom popup tkinter dialog box


code:
seqmap = sequify(itertools.imap)
seqmap(int, (1.2, 2.3))
sequify(itertools.ifilter)(lambda x: x>0, (-2, -1, 0, 1, 2))

rawDescription: `map`-like function preserving sequence-type


code: text = re.sub('\n ','\n', text)

rawDescription: Python: re.sub changes nothing

description: Python: re.sub changes nothing


code:
sticks = np.random.randint(0, dim, size=(num_sticks, 4)).astype(np.int32)
img = np.zeros((dim, dim), dtype=np.int32)

rawDescription: Directly "plot" line segments to numpy array


code: LHS = (DiffusionTerm(coeff = diffusion_coefficient))

rawDescription: Space dependent diffusion in fipy

description: Space dependent diffusion in fipy


code:
import two
def main(argv):
    opts, _ = getopt.getopt(argv, 'hs', ['--strict='])
    for opt, _ in opts:
        if opt in ('-s', '--strict'):
            config.strict = True

    two.foo(s=config.strict)

rawDescription: Command line argument as default to a function defined in another module


code:
dict_stuff = {}
for key, value in stuff:
    dict_stuff.setdefault(key, []).append(value)

rawDescription: What's the cleanest (most Pythonic) way of creating a dictionary with list values from a sequence?


rawDescription: Group together arbitrary date objects that are within a time range of each other


code:
def toggleLeds(self, interrupt=False):
    if interrupt:
        self.after_cancel(self.after_id)
    # Existing code follows

rawDescription: Python Tkinter use to emulate blinking with interaction of multiple buttons


code:
from math import sqrt
def close_triangle2(n):
    m=int(0.5*(-1+sqrt(1+8*n))) #solve it for the explicit formula
    tan0=(m*m+m)/2              #the closest one is either this
    tan1=(m*m+3*m+2)/2          #or this
    if (n-tan0)>(tan1-n):
        return tan1-n
    else:
        return n-tan0

rawDescription: Fastest way to find nearest triangle number?


code:
a = [[0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 1, 0, 1]]
for elem in a:
    for i, bit in enumerate(elem):
        r = random.random()
        if r < prob:
            elem[i] = 1 - bit

rawDescription: Flip 1s to 0s and viceversa in string elements


code:
def compareValues():
        number = randrange(10)
        if number >= 5:
             yield "%s: Greater than or equal to 5: %d  "%(t.name, number)
        else:
             yield "%s: Less than 5: %d  "%(t.name, number)

rawDescription: Confusion regarding the output of threads in python


code:
from django.conf import settings

from storages.backends.s3boto import S3BotoStorage

class S3StaticStorage(S3BotoStorage):

    def __init__(self, *args, **kwargs):
        kwargs['bucket']  = settings.AWS_STATIC_BUCKET_NAME
        super(S3StaticStorage, self).__init__(*args, **kwargs)

rawDescription: How can I use django-storages for both media and static files?

description: Use django-storages for both media and static files


code: plt.subplots_adjust(left=0.2, top=0.8)

rawDescription: Matplotlib table only

description: Matplotlib table only


code:
csdxy, fcsd = plt.csd(s1, s2, nfft, 1./dt)
plt.ylabel('CSD (db)')
plt.title('cross spectral density between signal 1 and 2')
plt.tight_layout()
show()

rawDescription: How to use the cross-spectral density to calculate the phase shift of two related signals

description: Use the cross-spectral density to calculate the phase shift of two related signals


code: {k: v for d in lst for k, v in d.iteritems()}

rawDescription: Python - Convert list of single key dictionaries into a single dictionary


code:
import tldextract
url = 'http://stackoverflow.com/questions/27805952/scrapy-set-depth-limit-per-allowed-domains'
tldextract.extract(url).registered_domain

rawDescription: Scrapy set depth limit per allowed_domains


code:
a = np.loadtxt('stack.txt', delimiter=',',usecols=(1,2,3,4),
        skiprows=1, dtype=[('Attribute 1', float),
                           ('Attribute 2', float),
                           ('Attribute 3', float),
                           ('Attribute 4', float)])

rawDescription: Recomended way to create a matrix containing strings in python


code:
with open("wfield.txt") as fp:
    rows = (dict(entry.split("=",1) for entry in row.strip().split("|")) for row in fp)
    df = pd.DataFrame.from_dict(rows)

rawDescription: Read flat file to DataFrames using Pandas with field specifiers in-line


rawDescription: Sqlalchemy "double layer" query

description: Sqlalchemy "double layer" query


code: fields = ('id', 'model')

rawDescription: Django-piston: How can I get app_label + model_name?


code:
#Pickle Example

# Save a dictionary into a pickle file.
import pickle

favorite_color = { "lion": "yellow", "kitty": "red" }

pickle.dump( favorite_color, open( "save.p", "wb" ) )

# Load the dictionary back from the pickle file.

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }

rawDescription: Reading and writing variables from file

description: Reading and writing variables from file


code: from __future__ import print_function

rawDescription: Print statements without new lines in python?


code:
parse('foo "bar baz" "bob" ')
parse('foo "bar b-&&az" "bob" ')
parse('foo "bar" ')
parse('"foo" bar ')
parse('foo"bar baz" "bob" ')
parse('&&')

rawDescription: Extracting ALL matches of a nested regular expression in python


code:
jj=[j for j,_ in chain(*vectors)]
data=[d for _,d in chain(*vectors)]
ii
jj
data
A=sparse.csr_matrix((data,(ii,jj)))  # coo style input
A.A

rawDescription: scipy csr_matrix from several vectors represented as list of sets

description: Scipy csr_matrix from several vectors represented as list of sets


code:
{'addition': u'News', 'name': u'Spaced'}
{'addition': u'Game', 'name': u'Angry Birds'}
{'addition': u'for all games', 'name': u'Cheats'}
{'addition': u'for all games', 'name': u'Cheats'}
{'addition': u'for all games', 'name': u'Cheats'}
{'addition': u'for all games', 'name': u'Cheats'}

rawDescription: Matching regex groups (with or's) and special characters with Python's re module


rawDescription: Apply multiple functions with map

description: Apply multiple functions with map


code:
def get_items(s):
    s_coo = s.tocoo()
    return set(zip(s_coo.row, s_coo.col))

rawDescription: Check if scipy sparse matrix entry exists


code:
groupby(a, [0])
groupby(a, [1])

rawDescription: How do I get the indexes of unique row for a specified column in a two dimensional array

description: Get the indexes of unique row for a specified column in a two dimensional array


code:
from affine import Affine
fname = '/path/to/raster.tif'

rawDescription: How to I get the coordinates of a cell in a geotif?


code:
import timeit
all = """l = list(range(100))
rl = list(reversed(range(100)))
"""
tim = all + """def gt(nums, n):
    if not nums:
        return False
    return max(nums) > n"""
gnibbler = all + """def gt(nums, n):
    return any(x>n for x in nums)"""
burhan = all + """def gt(nums, n):
  return max(nums) > n if nums else False"""
# Test with the condition being False:
timeit.timeit(setup=tim, stmt="gt(l, 100)")
timeit.timeit(setup=gnibbler, stmt="gt(l, 100)")
timeit.timeit(setup=burhan, stmt="gt(l, 100)")
timeit.timeit(setup=tim, stmt="gt(rl, 100)")
timeit.timeit(setup=gnibbler, stmt="gt(l, 100)")
timeit.timeit(setup=burhan, stmt="gt(l, 100)")
# Now what if the condition is True?
timeit.timeit(setup=tim, stmt="gt(l, 98)")
timeit.timeit(setup=gnibbler, stmt="gt(l, 98)")
timeit.timeit(setup=burhan, stmt="gt(l, 98)")
timeit.timeit(setup=tim, stmt="gt(rl, 98)")
timeit.timeit(setup=gnibbler, stmt="gt(rl, 98)")
timeit.timeit(setup=burhan, stmt="gt(rl, 98)")

rawDescription: Check if the list is empty

description: Check if the list is empty


code:
from lxml import etree
root = etree.Element('{http://www.w3.org/2000/svg}svg')
g = etree.SubElement(root, '{http://www.w3.org/2000/svg}g', id='layer-id')

rawDescription: python lxml inkscape namespace tags

description: Python lxml inkscape namespace tags


code: c = signal.fftconvolve(a, numpy.fliplr(numpy.flipud(b)), 'valid')

rawDescription: Finding matching submatrices inside a matrix


code: print(o.hostname, o.path, o.query)

rawDescription: splitting a full url into parts

description: Splitting a full url into parts


code:
static_path = STATIC_ROUTES['static']
package, relative_path = static_path.split(':')
icon_path = pkg_resources.resource_filename(
    package, os.path.join(relative_path, 'favicon.ico'))

rawDescription: How to get file path of a add_static_view() in Pyramid

description: Get file path of a add_static_view() in Pyramid


code:
root = Tk()
app = App(root)
menubar = Menu(root)
root.configure(menu=menubar)

filemenu = Menu(menubar,tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Save", command=app.file_save)
filemenu.add_command(label='Open', command=app.open_file)
filemenu.add_command(label='Exit', command=root.quit)
root.mainloop()

rawDescription: Tkinter not open and save text file

description: Tkinter not open and save text file


code:
for row in a:
    drow = {cursor.description[i].name: row[i] for i in range(len(row))}
    print(row['ID'])

rawDescription: split database record into variables

description: Split database record into variables


code: file_contents = f.read()

rawDescription: How do I print the content of a .txt file in Python?

description: Print the content of a .txt file in Python


code:
{
    'name': 'FirstPerson',
    'children': [],
}

rawDescription: Recursively Collect Children in Python/Django


code:
import re
splitre = re.compile(".*?=(.*?)(?:(?=\s*?\S*?=)|(?=\s*$))")
with open("myFile.txt","r") as readfile, open("outFile.txt","w") as outfile:
    for line in readfile:
        def matchParens(text):
            count = 0
            for char in text:
                if char == ")":
                    count -= 1
                elif char == "(":
                    count += 1
                if count < 0:
                    break
            return count != 0 or text.count('"') % 2 != 0
        if any(matchParens(text) for text in splitre.findall(line)):
            outfile.write(line)

rawDescription: Determine if a line has parenthesis or quotes that are not closed in python


code:
@try_except(same, ValueError, "Please enter a valid integer!\n>>> ")
def get_int(prompt=">>> "):
    return int(input(prompt))

rawDescription: In a decorator how can I pass the function I'm decorating as an argument?


code:
df1 = DF_freqSpecies.replace(r'\s*\(\d+\.*\d*\)', '', regex=True)
df1.head()

rawDescription: Pandas DataFrame [cell=(label,value)], split into 2 separate dataframes


rawDescription: Insert textbox value into python mysql databse


code:
from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
    LEFT, DISABLED, NORMAL, RIDGE, END)

rawDescription: Wrapping lines with long class/attributes names in Python


rawDescription: python json dumps

description: Python json dumps


code:
def MyBar1():
    global EventType
    print("Event Type1")
    EventType=1

def MyBar2():
    global EventType
    print("Event Type2")
    EventType=2

rawDescription: I need a delegate class?

description: I need a delegate class


code:
import etltest
dir(etltest)

rawDescription: Received 'can't find '__main__' module in '<packageName>' with python package