code:
for i in Wells:
    #
    #...
    #
    xys_bot.append( ((x.max() - x.min())/2., 15) )
    xys_top.append( ((x.max() - x.min())/2., zone) )
    if i > 0:
        # bottom line
        p = ConnectionPatch(xyA = xys_bot[i-1], xyB = xys_bot[i],
               coordsA='data', coordsB='data',
               axesA=fig.axes[i-1], axesB=ax,
               arrowstyle='-')
        ax.add_artist(p)
        # top line
        p = ConnectionPatch(xyA = xys_top[i-1], xyB = xys_top[i],
               coordsA='data', coordsB='data',
               axesA=fig.axes[i-1], axesB=ax,
               arrowstyle='-')
        ax.add_artist(p)

plt.draw()
plt.show()

rawDescription: Draw a line correlating zones between multiple subplots in matplotlib


code:
import sys

for word in sys.argv[1:]:
  if word in dictionary:
    print(word, ':', dictionary[word])
  else:
    print(word, "not found in dictionary.")

rawDescription: zConvert an HTML file into a Python dictionary

description: ZConvert an HTML file into a Python dictionary


code:
def rd(x):
    if len(x)<2: #if my string is 1 or less character long leave it untouched
        return x
    elif x[0]==x[1]:
        return rd(x[1: ])
    else:
        return x[0]+rd(x[1: ])

rawDescription: Contradictory outputs in simple recursive function


rawDescription: can argparse store positional number arguments as simple variables?

description: Can argparse store positional number arguments as simple variables


code:
class Alphabet:
    def change(self, word):
        return word + 'Z'

rawDescription: Where to implement python classes in Django?


code:
socket = imp.load_module('socket_original', *imp.find_module('my_socket_module'))
socket_monkey = imp.load_module('socket_patched',*imp.find_module('my_socket_module'))

def alternative_implementation(blah, blah):
    return 'Happiness'

socket_monkey.original_function = alternative_implementation

import my_sub_module

rawDescription: How to make a copy of a python module in runtime?

description: Make a copy of a python module in runtime


code:
def factorial(n):
    i = n
    while i > 1:
        i -= 1
        n *= i
    return n

rawDescription: Custom non-recursive factorial function refuses further input after execution


code: a, b = C.reshape(2)

rawDescription: Loops to minimize function of arrays in python


code:
import numpy as np
f = lambdify(x, integrate(x**2+2,x), "numpy")
f(np.arange(10))

rawDescription: Evaluate integral from sympy as lambda function


code:
pagination +='
%(current)s
' % \
                     {'link': link, 'current_link': current_link, 'current': current_link}

rawDescription: String formatting in python isn't working as expected


code:
def update_bar(self, to_add_number):
    while True:
        time.sleep(0.5)
        value = self.value() + to_add_number
        self.setValue(value)
        if value > 50:
            self.change_color("yellow")
        QtGui.qApp.processEvents()
        if (value >= self.maximum()):
            break
    self._active = False

rawDescription: Python: QtGui.QProgressBar Color

description: Python: QtGui.QProgressBar Color


rawDescription: Pandas: groupby and return mean value of a non-numeric variable


code:
def create_random_chromosomes(genes):
    chromosomes = set()
    randomgenes = genes[:]
    while len(chromosomes) < 2000:
        random.shuffle(randomgenes)
        chromosomes.add(tuple(randomgenes))
    return list(chromosomes)

rawDescription: python random.shuffle() in a while loop

description: Python random.shuffle() in a while loop


rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
from System import Type, Activator
Activator.CreateInstance(Type.GetTypeFromProgID(com_type_name))

rawDescription: How to import COM into Ironpython?

description: Import COM into Ironpython


rawDescription: How to remove the ?q= from search query url

description: Remove the ?q= from search query url


code: counters[0] | counters[1] | counters[2] | ...

rawDescription: Union of many Counters

description: Union of many Counters


code:
import json
json.dumps( {'vld_id':1,'vls_error':2,'something_else':True} )

rawDescription: Passing a Python list using JSON and Django


code:
sites = ["XLOC_008369", "XLOC_008369"]
pattern = '|'.join(sites)
mask = df[8].str.contains(pattern)

rawDescription: How can I replace a column given a specific condition in python?

description: Replace a column given a specific condition in python


code:
import csv
from collections import defaultdict

with open('in.csv') as f:
    r = csv.reader(f)
    d = defaultdict(list)
    for row in r:
        d[row[0]].append(row[1:])
print(d)

rawDescription: Converting CSV data to list in dictionary


code: fast_colors = dict((key, value.load()) for key, value in colors_dict.items())

rawDescription: PIL? Extract all pixels of a given RGB value


code:
config = shelve.open(pastaConfig + '\\config.db')
ultimaRev = getconfig( 'ultimaRev', 'Digite a nova revisão: ')
ultimoIso = getconfig( 'ultimoIso', 'Digite o tag do' )
pastaIsometricosSpooler = getconfig('pastaIsometricosSpooler', 'Digite o caminho da' )
config.close()

rawDescription: (Python) Shelve + try: how to search for a key and set it if it doesn't exists without repeating code?


code:
def get_y():
     t = 0
     while t <= Tc:
         y = -0.5 * g * t**2 + h
         yield y
         t += step

rawDescription: How to plot real-time graph, with both axis dependent on time?

description: Plot real-time graph, with both axis dependent on time


rawDescription: Python: Read a list with tree depth level and output a tree like nested list


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

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

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


rawDescription: Python lxml - find parent of comment

description: Python lxml - find parent of comment


code:
class PDF(object):
  def __init__(self, pdf, size=(200,200)):
    self.pdf = pdf
    self.size = size

  def _repr_html_(self):
    return '<iframe src={0} width={1[0]} height={1[1]}></iframe>'.format(self.pdf, self.size)

  def _repr_latex_(self):
    return r'\includegraphics[width=1.0\textwidth]{{{0}}}'.format(self.pdf)

rawDescription: View pdf image in an iPython Notebook

description: View pdf image in an iPython Notebook


code:
mydict = {}
RoR = RoR + 1

mydict["C{0}R{1}".format(CoC, RoR)] = int(input("What is your row {0} Column {1} number?:  ".format(RoR, CoC)))

rawDescription: How to vary an object's name in a Python 3 loop?

description: Vary an object's name in a Python 3 loop


code:
a = ['ok.py', 'hello.py']
all_sizes = get_file_sizes('/home/zurelsoft/my_files', a)

rawDescription: How to add all the elements inside loop in Python?

description: Add all the elements inside loop in Python


code:
lines = """am writing a Python script that will take words in a text file and convert them into numbers (my own, not ASCII, so no ord function).
I have assigned each letter to an integer and would like each word to be the sum of its letters' numerical value.
The goal is to group each word with the same numerical value into a dictionary.
I am having great trouble recombining the split words as numbers and adding them together"""

from collections import defaultdict

d = defaultdict(list)
for line in lines.splitlines():
    for word in line.split():
        d[sum(l_n.get(ch,0) for ch in word)].append(word)

rawDescription: How would I convert words to numbers in python 3 (own keys and values)?


rawDescription: Reducing an axis with numpy

description: Reducing an axis with numpy


rawDescription: Where does Python store the name binding of function closure?


code:
from PySide import QtGui
import sys

class MainWindow(QtGui.QMainWindow):
  def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.input_widget = InputWidget(self)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.input_widget)
        self.setLayout(self.layout)
        self.setCentralWidget(self.input_widget)

class InputWidget(QtGui.QWidget):
    def __init__(self, parent):
        super(InputWidget, self).__init__(parent)

        self.grid_layout = QtGui.QGridLayout()
        self.labels = ["amp", "more text", "blabla"]

        self.text_edits = []
        self.qlabels = []

        for row, label in enumerate(self.labels):
            label = QtGui.QLabel(label)
            self.qlabels.append(label)
            self.grid_layout.addWidget(label, row, 0)
            text_edit = QtGui.QTextEdit()
            self.text_edits.append(text_edit)
            self.grid_layout.addWidget(text_edit, row, 1)

        self.grid_layout.setColumnStretch(0, 0)
        self.grid_layout.setColumnStretch(1, 2)

        self.setLayout(self.grid_layout)

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

rawDescription: How do I size QLayout based on proportionality?

description: Size QLayout based on proportionality


rawDescription: Exclude matched string python re.findall


code:
import bs4

xml = "Your bare XML String"
soup = bs4.BeautifulSoup(xml)
test_apps = soup.findChildren("app", {"name": "test"})
for app in test_apps:
    app["name"] = "delete me"

with open("filename.xml", "w") as f:
    f.write(str(soup))

rawDescription: How to to search a key in an xml and replace it's value with Python?

description: To search a key in an xml and replace it's value with Python


code: df.fillna({'Auto_name':'Autobiographer', 'AutoCount':0, 'Stu_name':'Student', 'StudentCount':0})

rawDescription: Adding/inserting values in pandas dataframe based on 1 or more columns


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

r = np.random.random(100)

a = 1.
a_max = 1.
a_step = 0.01
a = np.arange(a_step-.3, a_max, a_step)
a.shape
#(129,)
a = a[:,None] #adds a new axis, making this a column vector, same as: a = a.reshape(-1,1)
a.shape
#(129, 1)
(a*r).shape
#(129, 100)
loga = np.log(1 + a*r)
loga.shape
#(129,100)
mloga = loga.mean(axis=1) #take the mean along the 2nd axis where `a` varies
mloga.shape
#(129,)

plt.plot(a, mloga)
plt.show()

rawDescription: Plot parametric mean in Python

description: Plot parametric mean in Python


code:
class Item(object):
    def __init__(self):
        if type(self) is Item:
            raise NotImplementedError("Item must be subclassed.")

    def __setattr__(self, name, value):
        if name not in self.fields:
            raise AttributeError("Invalid attribute name.")
        else:
            self.__dict__[name] = value

class MyItem(Item):
    fields = ("foo", "bar", "baz")

rawDescription: Ruby like DSL in Python

description: Ruby like DSL in Python


code:
...
b.print_board()

rawDescription: Underscores in method names [silly mistake]


code:
print(soup.p)
#
This text is my

rawDescription: BeautifulSoup: How to replace value in an element with an element tag?


code: ','.join('0x' + s[i:i+2] for i in range(0, len(s), 2))

rawDescription: Python - Splitting up a string into a list of paired chars


code:
import codecs
with codecs.open(filename,'r',encoding='utf8') as f:
    text = f.read()
# process Unicode text
with codecs.open(filename,'w',encoding='utf8') as f:
    f.write(text)

rawDescription: Python reading from a file and saving to utf-8


code:
import sys, time
while True:
    for i in range( 4 ):
        sys.stdout.write( '\r' + ( '.' * i ) + '   ' )
        sys.stdout.flush()
        time.sleep( 0.5 )

rawDescription: How can I make an indeterminate progress bar in a Python console app?

description: Make an indeterminate progress bar in a Python console app


code:
def get_ind(a,ind):
    if len(ind)==1:
        return a[0]
    return get_ind(a[ind[0]],ind[1:])

rawDescription: Changing value of variable in list using indices from another list


code: regex.findall(r'[\p{Cf}\p{L}]+', text)

rawDescription: Tokenizing non English Text in Python

description: Tokenizing non English Text in Python


rawDescription: Python Phonebook

description: Python Phonebook


code:
def numpy_gcd(a, b):
    a, b = np.broadcast_arrays(a, b)
    a = a.copy()
    b = b.copy()
    pos = np.nonzero(b)[0]
    while len(pos) > 0:
        b2 = b[pos]
        a[pos], b[pos] = b2, a[pos] % b2
        pos = pos[b[pos]!=0]
    return a

numpy_gcd(np.array([98]), np.array([42]))
98/14, 42/14

rawDescription: Does Python have a function to reduce fractions?


code: ['BETA0', 'BETA1', 'BETA2', 'BETA3', 'SVEN1F01', 'SVEN1F04', 'SVEN1F09', 'SVENF01', 'SVENF02', 'SVENF03', 'SVENF04', 'SVENF05', 'SVENF06', 'SVENF07', 'SVENF08', 'SVENF09', 'SVENF10', 'SVENF11', 'SVENF12', 'SVENF13', 'SVENF14', 'SVENF15', 'SVENF16', 'SVENF17', 'SVENF18', 'SVENF19', 'SVENF20', 'SVENF21', 'SVENF22', 'SVENF23', 'SVENF24', 'SVENF25', 'SVENF26', 'SVENF27', 'SVENF28', 'SVENF29', 'SVENF30', 'SVENPY01', 'SVENPY02', 'SVENPY03', 'SVENPY04', 'SVENPY05', 'SVENPY06', 'SVENPY07', 'SVENPY08', 'SVENPY09', 'SVENPY10', 'SVENPY11', 'SVENPY12', 'SVENPY13', 'SVENPY14', 'SVENPY15', 'SVENPY16', 'SVENPY17', 'SVENPY18', 'SVENPY19', 'SVENPY20', 'SVENPY21', 'SVENPY22', 'SVENPY23', 'SVENPY24', 'SVENPY25', 'SVENPY26', 'SVENPY27', 'SVENPY28', 'SVENPY29', 'SVENPY30', 'SVENY01', 'SVENY02', 'SVENY03', 'SVENY04', 'SVENY05', 'SVENY06', 'SVENY07', 'SVENY08', 'SVENY09', 'SVENY10', 'SVENY11', 'SVENY12', 'SVENY13', 'SVENY14', 'SVENY15', 'SVENY16', 'SVENY17', 'SVENY18', 'SVENY19', 'SVENY20', 'SVENY21', 'SVENY22', 'SVENY23', 'SVENY24', 'SVENY25', 'SVENY26', 'SVENY27', 'SVENY28', 'SVENY29', 'SVENY30', 'TAU1', 'TAU2']

rawDescription: AttributeError when extracting data from a URL in Python


code:
with open('textfile2.txt') as f:
   words = [line.strip() for line in f]

with open('textfile1.txt') as f:
   for line in f:
      if line.split(' ')[-1].strip() in words:
         print(line)

rawDescription: Search one text file for values of another and then print that line


code:
sett = lambda t, idx, val: tuple((v if i != idx else val) for i,v in enumerate(t))
l = [(0,) * 3] * 4
l
l[1] = sett(l[1], 2, 42)
l

rawDescription: Modify only a specific tuple in python (incomprehensible)


code:
import numpy as np

class AutoArray2(np.ndarray):
    def __new__(cls, input_array):
        # Input array is an already formed ndarray instance
        # We first cast to be our class type
        obj = np.asarray(input_array).view(cls)
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
    def __setitem__(self, coords, value):
        print("HERE")

a = np.array([[1,2],[2,3]])
b = AutoArray2(a)
b[0,0] = 1

rawDescription: numpy python class calling wrong __setitem__

description: Numpy python class calling wrong __setitem__


code:
import selenium
from selenium import webdriver
from selenium.common.exceptions    import StaleElementReferenceException
from selenium.common.exceptions    import WebDriverException
from selenium.common.exceptions    import TimeoutException as SeleniumTimeoutException
from selenium.webdriver.support.ui import WebDriverWait

url = "http://seekingalpha.com/symbol/IBM/transcripts"

selenium_browser = webdriver.Firefox()
selenium_browser.set_page_load_timeout(30)

selenium_browser.get(url)

selenium_browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
elem = selenium_browser.find_element_by_css_selector("div #transcripts_show_more div#more.older_archives")

old_count = len(selenium_browser.find_elements_by_xpath("//div[@id='headlines_transcripts']//li"))
elem.click()

try:
    WebDriverWait(selenium_browser, 10).until(lambda driver: len(driver.find_elements_by_xpath("//div[@id='headlines_transcripts']//li")) != old_count)
except StaleElementReferenceException:
    pass
except SeleniumTimeoutException:
    pass
print(selenium_browser.page_source.encode("ascii", "ignore"))

rawDescription: Selenium - Python bindings - Detect new AJAX data


code: assign = var("varname") + oneOf("= *=")("assign_op") + expr("varvalue")

rawDescription: Evaluating nested variables with pyparsing for a DSL


rawDescription: How can I implement a fuzzy search across each value of a dictionary in a multiple dictionary list?

description: Implement a fuzzy search across each value of a dictionary in a multiple dictionary list


code:
from itertools import chain

def condense(*lists):
    # remember original positions
    positions = {}
    for pos, item in enumerate(chain(*lists)):
        if item not in positions:
            positions[item] = pos

    # condense disregarding order
    sets = condense_sets(map(set, lists))

    # restore order
    result = [sorted(s, key=positions.get) for s in sets]
    return result if len(result) != 1 else result[0]

def condense_sets(sets):
    result = []
    for candidate in sets:
        for current in result:
            if candidate & current:   # found overlap
                current |= candidate  # combine (merge sets)

                # new items from candidate may create an overlap
                # between current set and the remaining result sets
                result = condense_sets(result) # merge such sets
                break
        else:  # no common elements found (or result is empty)
            result.append(candidate)
    return result

rawDescription: Replace list of list with "condensed" list of list while maintaining order


code:
import inspect

class A:
  def a(self):
    print("A.a()")
    B().b()

class B:
  def b(self):
    print("B.b()")
    stack = inspect.stack()
    the_class = stack[1][0].f_locals["self"].__class__
    the_method = stack[1][0].f_code.co_name
    print("  I was called by {}.{}()".format(str(the_class), the_method))

A().a()

rawDescription: How to get the caller class name inside a function of another class in python?

description: Get the caller class name inside a function of another class in python


code:
from bs4 import BeautifulSoup
soup=BeautifulSoup('text See full summary')
soup.find('a', text='See full summary')['href']

rawDescription: Match href value with a regular expression


code:
conditions = (And(...), ...)
Or(*conditions)

rawDescription: How can i have more than 255 arguments in Z3py function?

description: Have more than 255 arguments in Z3py function


rawDescription: How can I get the key_name of the entry in Model() on GAE for Python?

description: Get the key_name of the entry in Model() on GAE for Python


code:
def file_stuff():
    nodes = []
    X = []
    Y = []
    with open('Offices.txt') as input_data:
        for line in input_data:
           n, x, y = line.split(',')
           nodes.append(n)
           X.append(int(x))
           Y.append(int(y))

rawDescription: Reading text file line by line in Python and storing into struct as coordinates for graphing


code:
def initialer(name, splitter=' '):
    words = name.split(splitter)
    return u''.join(zip(*words)[0])

rawDescription: How can i use "str.find" (python) to locate the next character after a space or " "?

description: Use "str.find" (python) to locate the next character after a space or " "


code:
import lxml.etree as ET
data = """<?xml version="1.0" ?>
<zAppointments reminder="15">
    <appointment>
        <subject>Bring pizza home</subject>
    </appointment>
    <appointment>
        <subject>Bring hamburger home</subject>
    </appointment>
    <appointment>
        <subject>Check MS Office website for updates</subject>
  </appointment>
</zAppointments>"""
root = ET.fromstring(data)
root.xpath("//subject[contains(., 'home')]/text()")

rawDescription: Parsed a XML file using lxml based of text string


code:
def dict_of_means(d):
    return {k:sum(v)*1.0/v.count() for k, v in d.items()}

rawDescription: How do you sort a list which is inside a dictionary?

description: Sort a list which is inside a dictionary


rawDescription: Cython and overloaded c++ constructors

description: Cython and overloaded c++ constructors


rawDescription: Merging records in a Numpy structured array


code:
from collections import defaultdict

sums = defaultdict(int)

with open(filename) as f:
    for line in f:
        col1, col2, rest = line.split(None, 2)
        sums[col1] += int(col2)

rawDescription: Summation of specific items in a nested list


code:
import bisect

# Define searchable (word, value) tuples for every word in the file.
# I'm assuming your files are sorted, but if not, sort this list (SLOW!!)
words = [(w[1], w[0]) for w in (line.strip().split() for line in f if line)]

# Binary search for the word and return its associated value.
def get_value(word):
    idx = bisect.bisect_left(words, (word,None)) # Tuples compare element-wise
    if idx != len(words) and words[idx][0] == word:
        return words[idx][1]
    raise ValueError('word not found')

rawDescription: Python Binary Search for Dictionary

description: Python Binary Search for Dictionary


code:
class PersonForm(forms.ModelForm):
    class Meta:
        model = Person

    def clean(self):
        statuses = self.cleaned_data.get('status')
        if status.count() > 3:
            raise ValidationError("Person can not have more than 3 statuses")

rawDescription: Need help on Django Modelling

description: Need help on Django Modelling


rawDescription: Pandas: Grouping DataFrame by hundreds

description: Pandas: Grouping DataFrame by hundreds


rawDescription: Connecting to remote PostgreSQL database with SQLAlchemy using SSH tunneling with public key and passphrase, all that from a Windows machine


code:
p = dict(template)
p['thing1'] = 1
template
p

rawDescription: How to create copies of a python object that are not linked to original object?

description: Create copies of a python object that are not linked to original object


code: msg['to'] = "someone@somesite.com"

rawDescription: Why field TO is empty after sending emails from list?


code:
import re
infilename = 'myfile.fasta'
outfilename = 'myfile_nodots.fasta'
regex = re.compile("[.-]+")

with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
    for line in infile:
        outfile.write(regex.sub("", line))

rawDescription: remove periods from fasta file using python

description: Remove periods from fasta file using python


rawDescription: How do I avoid text between {{ }}

description: Avoid text between {{ }}


code:
class ClassCode(QtGui.QWidget, Ui_ClassCode):
    def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()):
        QtGui.QWidget.__init__(self, parent, f)

        self.setupUi(self)

rawDescription: PyQt4 - Custom widget class structure?

description: PyQt4 - Custom widget class structure


rawDescription: How can I make x=y in terms of value and not memory?

description: Make x=y in terms of value and not memory


rawDescription: Splitting list of python dictionaries by repeating dictionary key values


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

x, label, y = np.genfromtxt('tmp.txt', dtype=int, unpack=True)

ux, uidx, uinv = np.unique(x, return_index=True, return_inverse=True)
max_width = np.bincount(x).max()
bar_width = 1/(max_width + 0.5)

locs = x.astype(float)
shifted = []
for i in range(max_width):
    where = np.setdiff1d(uidx + i, shifted)
    locs[where[where<len(locs)]] += i*bar_width
    shifted = np.concatenate([shifted, where])

plt.bar(locs, y, bar_width)

rawDescription: How to draw bar in python

description: Draw bar in python


code: numberOfEvens = sum([1 if k%2==0 else 0 for k in sequence])

rawDescription: Find the Number of even intergers in a sequence


rawDescription: averaging elements in a matrix with the corresponding elements in another matrix (in python)

description: Averaging elements in a matrix with the corresponding elements in another matrix (in python)


code:
with open('data.csv','a') as out:
     starting = True
     for x, y in zip(arrayForInitialSpots, arrayForChosenSpots):
          for item in (x + y):
              if not starting:
                 out.write(", ")
                 starting = False
              out.write(item + ", ")

rawDescription: Python and CSV: Output everything to one line


code:
ItemInstance.objects.filter(tv_series_id=item.pk).annotate(
    null_ids=Count('id')
).order_by('-null_ids', 'id')

rawDescription: Order by NULL then id asc

description: Order by NULL then id asc


code: [[x_o_r(z) for z in zip(list(a), list(b))] for a in x for b in x]

rawDescription: Python - Result returns generator instead of list (comprehension)


code:
# Format numpy.ndarray object representations
if np_arrays and issubclass(typ, ndarray):
    write('array(dtype:' + str(object.dtype))
    write('; shape: ' + str(object.shape) + ')')
    return

rawDescription: Pretty print and substitute numpy arrays


code:
from hurry.filesize import size, si
size(11000, system=si)
size(198283722, system=si)

rawDescription: Better way to convert file sizes in Python


code:
import wx #For graphics' interface
import os #For operating system compatibility

class TextPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(wx.WHITE)

        self.control = wx.TextCtrl(self, style = wx.TE_MULTILINE) #Text area with multiline

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.control, 1, wx.EXPAND)
        self.SetSizer(sizer)

class GraphicsPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(wx.BLACK)

class TopPanel(wx.Panel):

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

        main_sizer = wx.BoxSizer(wx.HORIZONTAL)

        text = TextPanel(self)
        main_sizer.Add(text, 1, wx.EXPAND)

        graphics = GraphicsPanel(self)
        main_sizer.Add(graphics, 1, wx.EXPAND)

        self.SetSizer(main_sizer)

class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):

        #SETUP
        wx.Frame.__init__(self, parent, wx.ID_ANY, title = "MyTitle", size = (550,300))
        self.dirname=''

        self.top_panel = TopPanel(self)

        #CREATE
        self.create_status_bar()
        self.create_menu_bar()

# FUNCTIONS
# ------------------------------------------------------------------------------
    def create_status_bar(self):
        self.CreateStatusBar() #A Statusbar at the bottom of the window

    def create_menu_bar(self):

    # File Menu
        filemenu= wx.Menu()

        menuOpen = filemenu.Append(wx.ID_OPEN, "&Open", "Open file to edit")
        filemenu.AppendSeparator()
        menuSave = filemenu.Append(wx.ID_SAVE, "&Save", "Save the file")
        menuSaveAs = filemenu.Append(wx.ID_SAVEAS, "Save &As", "Save the file with a new name")
        filemenu.AppendSeparator()
        menuExit = filemenu.Append(wx.ID_EXIT, "E&xit", "Terminate communication and close window")

    #The Menu Bar
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") #Adding the "File" menu to the 'menuBar'
        self.SetMenuBar(menuBar)  #Adding the 'menuBar' to the Frame content

    #Event binding
        self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
        self.Bind(wx.EVT_MENU, self.OnSave, menuSave)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, menuSaveAs)

# EVENTS
# ------------------------------------------------------------------------------
    def OnExit(self, event):
        self.Close(True) #Close the frame

    def OnOpen(self, event):
        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname, self.filename), 'r')
            self.panelA.control.SetValue(f.read())
            f.close()
        dlg.Destroy()

    def OnSave(self, event):
        f = open(os.path.join(self.dirname, self.filename), 'w')
        f.write(self.panelA.control.GetValue())
        f.close()

    def OnSaveAs(self, event):
        file_choices = "TXT (*.txt)|*.txt"
        dlg = wx.FileDialog(self, message = "Save file as...", defaultDir = os.getcwd(), defaultFile = self.filename, wildcard = file_choices, style = wx.SAVE)

        if dlg.ShowModal() == wx.ID_OK:
            f = open(os.path.join(dlg.GetDirectory(), dlg.GetFilename()), 'w')
            f.write(self.panelA.control.GetValue())
            f.close()

# RUN!
# ------------------------------------------------------------------------------
if __name__ == '__main__':
    app = wx.PySimpleApp(False)
    app.frame = MainWindow(None, wx.ID_ANY, "tSock - Adaptation Technologies")
    app.frame.Show()
    app.MainLoop()

rawDescription: Two panels side by side (one with TextCtrl) - wxPython


code:
import  numpy as np

l = np.array(l)

a = l[:2]

l[0] = 10

print(l)
print(a)

rawDescription: Create alias of part of a list in python


code:
import numpy as np
import matplotlib.pyplot as plt
a=np.random.randint(0,20,20)
b=np.random.randint(0,20,20)
plt.close()
plt.plot(a,'*-')
plt.plot(b,'*-')
difference=a-b
cross=(np.sign(difference*np.roll(difference,1))<1)[1:]
plt.plot(np.arange(.5,19),10* cross, 'd')

rawDescription: What is the easiest way to detect a cross-over in values of 1d list?


rawDescription: Python method for storing list of bytes in network (big-endian) byte order to file (little-endian)


code: soup.find("span",{"data-caption":" Bed"}).replace is None

rawDescription: BS4 grabbing the contents of a tag with an unusual attribute


rawDescription: xor matrix multiplication for AES mix column stage

description: Xor matrix multiplication for AES mix column stage


code:
import matplotlib.pyplot as plt

vals = [1, 100, 14, 76, 33] # random data, aligned to `x_indices`
fig, ax1 = plt.subplots(1,1)
ax1.plot(x_indices, vals)
ax2 = ax1.twiny() # Remark: twiny will create a new axes
                 # where the y-axis is shared with ax1,
                 # but the x-axis is independant - important!
ax2.set_xlim(ax1.get_xlim()) # ensure the independant x-axes now span the same range
ax2.set_xticks(x_indices) # copy over the locations of the x-ticks from the first axes
ax2.set_xticklabels(x_percents) # But give them a different meaning

rawDescription: Adding secondary X-axis with user-defined list of coordinates


code:
inc = np.core.rec.fromarrays(result)
all_ind = np.core.rec.fromarrays(np.indices(data.shape).reshape(2,-1))
exc = np.setdiff1d(all_ind, inc)
data[exc['f0'], exc['f1']] = np.nan

rawDescription: set the elements not included by np.where as np.nan

description: Set the elements not included by np.where as np.nan


code:
from myapp.admin_helper import ModelAdminCustom

class MyModelAdmin(ModelAdminCustom):
    pass

admin.site.register(MyModel, MyModelAdmin)

rawDescription: Admin site uses default database in Django 1.6


code:
country = [u'USA']
country = str(country[0])
country

rawDescription: Python turn list values into String

description: Python turn list values into String


code:
from modules import foo

# when code from modules.py is required
foo()

rawDescription: Make python module not load/run itself unless it is a an "import"


code:
g = df.groupby('DATE')
key = g.groups.keys()[0]
key
g.get_group(key.astype('i8'))

rawDescription: Python Pandas: Groupby date, and accessing each group by timestamp


code:
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = all_words.keys()[:2000]

rawDescription: NLTK Naive bayes Classifier wierd results


code:
def test_plot_square1():
    x, y = [0, 1, 2], [0, 1, 2]
    line, = plot_square(x, y)
    x_plot, y_plot = line.get_xydata().T
    np.testing.assert_array_equal(y_plot, np.square(y))

rawDescription: How can I write unit tests against code that uses matplotlib?

description: Write unit tests against code that uses matplotlib


rawDescription: numpy array multiplication slower than for loop with vector multiplication?

description: Numpy array multiplication slower than for loop with vector multiplication


code: myTableView.setColumnHidden(0, True) # again assuming ID is the first column

rawDescription: Data in the qtableview's vertical header?


code:
with open('data', 'rb') as f, open('newdata', 'wb') as g:
    g.write('<ROOT>{}</ROOT>'.format(f.read()))

rawDescription: PYTHON : How to add root node to an XML

description: PYTHON : How to add root node to an XML


rawDescription: Using grouby for counting

description: Using grouby for counting


code:
sentence = ['This','is','a','sentence']
sentence = [sentence[0]] + [' '+word for word in sentence[1:]]
sentence

rawDescription: Python: How to change each element of a list in place


code:
class MyItem(QListWidgetItem):
    def __init__(self, path, parent=None):
        self.path = path

        import os
        filename = os.path.basename(self.path)
        super().__init__(filename)

rawDescription: How to get the file name and show it on Qlistwidget?

description: Get the file name and show it on Qlistwidget


code: for _ in xrange(nIterations): y = f(y)

rawDescription: Iteration in a single line

description: Iteration in a single line


code:
import wx

class Cartesian(wx.Frame):
    def __init__(self, parent=None, id=-1, title=""):
        wx.Frame.__init__(self, parent, id, title, size=(640, 480))

        self.panel = wx.Panel(self)
        self.panel.Bind(wx.EVT_PAINT, self.OnPaint)

    def OnPaint(self, event):
        dc = wx.PaintDC(event.GetEventObject())
        dc.Clear()
        dc.SetPen(wx.Pen(wx.BLACK))
        dc.DrawLine(320, 0, 320, 480)
        dc.DrawLine(0, 240, 640, 240)

app = wx.App(False)
frame = Cartesian()
frame.Show()
app.MainLoop()

rawDescription: Drawing a Cartesian plane in wxPython

description: Drawing a Cartesian plane in wxPython


code: [x[i:i+size_of_new] for i in range(0,len(x),size_of_new)]

rawDescription: Python long list separated

description: Python long list separated


code:
cashflow = 2*np.ones(6)
cashflow[-1] +=100
cashflow
np.npv(0.01, cashflow)

rawDescription: Basic Financial Library for Python

description: Basic Financial Library for Python


code:
myDict = {}
path = ('newEnv','newProj','newComp')
reduce(lambda d, k: d.setdefault(k, {}), path, myDict)

rawDescription: Creating dictionary using list/tuple elements as key


code:
with open("temp.txt", "w") as f:  # with automatically closes your files
    my_l = [x.replace(".jpg", "").rsplit("_", 1) for x in glob.glob("*.jpg")]
    for l in my_l:
        f.write(str(l).replace(",", ""))

rawDescription: Save file list into text file using python


code:
counter={}
for c in "<text xx will xx be xx pasted xx here>":
    counter[c] = counter.get(c,0)+1

"".join(k for k,v in counter.items() if v<8)

rawDescription: what is a way to match any char that appears less than a given number of times with regex python?

description: What is a way to match any char that appears less than a given number of times with regex python


code:
df = df.set_index(['ticker', 'date']).sort_index()
df

rawDescription: Speeding up group-wise differencing in Pandas


code:
xx = np.linspace(0, 1, 10000)
yy = [sse(x0, x, y) for x0 in xx]
plot(xx, yy)

rawDescription: python curve_fit doesn't work with stiff model

description: Python curve_fit doesn't work with stiff model


code:
del data['no','unique']
del data['yes','unique']
pd.concat([data['no'],data['yes']],axis=1,keys=['no','yes'])

rawDescription: Modify describe function to remove and add columns


code:
data={t[0]:t[1:] for t in zip(*reader)}
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}

rawDescription: Read columns into separate lists

description: Read columns into separate lists


code:
import sys
from PyQt4 import QtGui,QtCore

class myTable(QtGui.QTableWidget):
    def __init__(self,parent=None):
        super(myTable,self).__init__(parent)
        self.setColumnCount(2)

    def add_item(self,name):
        #new row
        row=self.rowCount()
        self.insertRow(row)

        #button in column 0
        button=QtGui.QPushButton(name)
        button.setProperty("name",name)
        button.clicked.connect(self.on_click)
        self.setCellWidget(row,0,button)

        #text in column 1
        self.setItem(row,1,QtGui.QTableWidgetItem(name))

    def on_click(self):
        # find the item with the same name to get the row
        text=self.sender().property("name")
        item=self.findItems(text,QtCore.Qt.MatchExactly)[0]
        print("Button click at row:",item.row())

if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    widget = myTable()
    widget.add_item("kitten")
    widget.add_item("unicorn")
    widget.show()
    sys.exit(app.exec_())

rawDescription: PyQt4 - Using a QItemDelegate to display widget in a QListView


code:
for word in wordlist[:]:
    if any(f in word for f in filters):
        wordlist.remove(word)

rawDescription: Two Lists of strings: remove strings from list A that contain any string from list B?


code:
indexes = (next(group)[0] - 1 for key, group in
                groupby(enumerate(myList), key=itemgetter(1)))

next(indexes)
indexes = list(indexes)

rawDescription: Get index from a list where the key changes, groupby


code: serversocket.bind(('', 111))

rawDescription: Python instant messaging program fails to connect with errno 111


code:
import random

name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0

for question_num in range(1, 11):
    ops = ['+', '-', '*']
    rand=random.randint(1,10)
    rand2=random.randint(1,10)
    operation = random.choice(ops)
    maths = eval(str(rand) + operation + str(rand2))
    print('\nQuestion number: {}'.format(question_num))
    print ("The question is",rand,operation,rand2)

    d=int(input ("What is your answer:"))
    if d==maths:
        print ("Correct")
        score=score+1
    else:
        print ("Incorrect. The actual answer is",maths)

rawDescription: Python maths quiz random number

description: Python maths quiz random number


code: pairs

rawDescription: A Confusing task

description: A Confusing task


code:
from itertools import takewhile
array = takewhile(lambda x: x != "b", array)
# then if array must be a list (we can already iterate through it)
array = list(array)

rawDescription: Delete array values in python

description: Delete array values in python


code:
def func2():
    list1=[]
    list2=[]
    value=10
    if somePredicate():
        (list3,list4)=func3(value)
        return list1, list2, list3, list4
    else:
        return list1, list2, None, None

rawDescription: Returning function values based on argument?


rawDescription: Pandas table lookup

description: Pandas table lookup


code:
import re

def regexp(lo, hi):
    fmt = '%%0%dd' % len(str(hi))
    return re.compile('(%s)' % '|'.join(fmt % i for i in range(lo, hi+1)))

rawDescription: python: number range to regex matching string

description: Python: number range to regex matching string


code:
A[:] = [A[i] for i in new_order]
for row in A:
    row[:] = [row[i] for i in new_order]

rawDescription: Rearranging Matrix Elements with Numpy

description: Rearranging Matrix Elements with Numpy


code:
class Course(Entity):
    ...
    assistants = ManyToMany('Professor', inverse='courses_assisted',
                            local_colname='course_id', remote_colname='prof_id',
                            ondelete='cascade')

rawDescription: SQLAlchemy/Elixir - querying to check entity's membership in a many-to-many relationship list


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

def main():
    data = [np.random.random((2, 3)) for _ in range(5)]
    fig, ax = plt.subplots()
    plot_polygons(data, alpha=0.5, ax=ax)
    plot_verts(data, marker='^', color='black', ax=ax)
    plt.show()

def plot_polygons(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.fill(x, y, **kwargs) for x, y in data]
    return artists

def plot_verts(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.scatter(x, y, **kwargs) for x, y in data]
    return artists

main()

rawDescription: What is the best way of combining two independent plots with matplotlib?


rawDescription: Modifying a list outside of recursive function in Python


code: lbl["text"] = grav

rawDescription: Update Tkinter Label

description: Update Tkinter Label


code: f = get_functions(20)

rawDescription: How to copy define function to make 'n' variations of it? (Python)

description: Copy define function to make 'n' variations of it? (Python)


code:
from datetime import datetime
d = datetime.now()
d
print(d)
print(d.strftime('%Y-%m-%d %H:%M:%S'))

rawDescription: Python Timenow Without Milliseconds?

description: Python Timenow Without Milliseconds


code:
np.random.seed(3)
n=14000000
df = pd.DataFrame({'X' : np.random.randint(2000000, size=n),
                   'Y' : np.random.randint(2000000, size=n)})

rawDescription: Creating a permutation, with restrictions


code:
from uniseg.graphemecluster import grapheme_cluster_breakables
sum(grapheme_cluster_breakables('בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָאָרֶץ'))
from uniseg.graphemecluster import grapheme_clusters
list(grapheme_clusters('בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַיִם, וְ  הָאָרֶץ'))
len(list(grapheme_clusters('בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַי , ואֵת הָאָרֶץ')))

rawDescription: How do you get the display width of combined Unicode characters in Python 3?

description: Get the display width of combined Unicode characters in Python 3


code:
last_call_time = -delay # to be sure that motor_do can be called the first time
# "On Windows, [time.clock] returns wall-clock seconds elapsed since the first call to this
# function, as a floating point number, based on the Win32 function QueryPerformanceCounter()
# The resolution is typically better than one microsecond." (python 2.7 doc)
# i.e. close to 0 on first call of time.clock()

while True:
    data = read_sensors()
    command = process(data)
    motor_try(command)

def motor_try(command):
    global last_call_time

    current_time = time.clock()
    # on win that works, on unix... you may want to take a look at the NB

    elapsed = current_time - last_call_time
    if elapsed >= delay:
        motor_do(command)
        last_call_time = current_time

rawDescription: How to multithread/multiprocess just one instance of a particular function in Python?

description: Multithread/multiprocess just one instance of a particular function in Python


code: np.where(df.values == rowmax[:,None])

rawDescription: Find all indices of maximum in Pandas DataFrame


code:
import sys
getattr(sys.stdout, 'buffer', sys.stdout)

rawDescription: Writing bytes to standard output in a way compatible with both, python2 and python3


code:
import sys
from cx_Freeze import setup, Executable

base = None
if (sys.platform == "win32"):
    base = "Win32GUI"    # Tells the build script to hide the console.

rawDescription: How to stop a python program executable from opening a cmd shell?

description: Stop a python program executable from opening a cmd shell


rawDescription: Python partitions excluding numbers already been together


code:
keys = ['audio', 'video', 'sensor', 'backup']

SETTINGS = {
    'mode_1': dict.fromkeys(keys, True),
    'mode_2': dict.fromkeys(keys, False),
}

rawDescription: DRYly represent a list of settings objects


code:
pairs = {}
for i in range(len(word)):
    pair = word[i:i+n]
    pair += '$' * (n - len(pair))
    pairs[pair] = pairs.get(pair, 0) + 1

pairs

rawDescription: Create a dictionary of all letter transitions from a previous dictionary of words?


rawDescription: Reverse ForeignKey lookup

description: Reverse ForeignKey lookup


rawDescription: Points, Vectors, Dot Product & Cross Product of python


code:
from contextlib import contextmanager
@contextmanager
def file_or_stdout(file_name):
    if file_name is None:
        yield sys.stdout
    else:
        with open(file_name, 'w') as out_file:
            yield out_file

rawDescription: Fallback to stdout if no file name provided


code:
def iter_preorder(self):
    yield self
    # check for folderishness here if a non-folderish
    # node may have children as well
    for x in self.children:
        for y in x.iter_preorder():
            yield y

rawDescription: Loop through a bunch of folderish content, which may be itself folderish?


code: ['Eric Theodore Cartman', 'DOB: July 1', 'Respect My Authroitah!', 'Mooom!', 'Big-boned', 'Politically incorrect', 'Knit-cap!']

rawDescription: How to Store Rows from CSV File into Python and Print Data with HTML


code:
def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '''),
            ('"', '"'),
            ('>', '>'),
            ('<', '<'),
            ('&', '&')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s

unescaped = html_decode(my_string)

rawDescription: How do I perform HTML decoding/encoding using Python/Django?

description: Perform HTML decoding/encoding using Python/Django


code:
from calendar import monthrange
monthrange(2012, 2)

rawDescription: Get Last Day of the Month in Python

description: Get Last Day of the Month in Python


code: map(sum, mylist)

rawDescription: Summing a tuple in a list, in python

description: Summing a tuple in a list, in python


code:
from pybrain.datasets            import ClassificationDataSet
from pybrain.utilities           import percentError
from pybrain.tools.shortcuts     import buildNetwork
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.structure.modules   import SoftmaxLayer

from pylab import ion, ioff, figure, draw, contourf, clf, show, hold, plot
from scipy import diag, arange, meshgrid, where
from numpy.random import multivariate_normal

means = [(-1,0),(2,4),(3,1)]
cov = [diag([1,1]), diag([0.5,1.2]), diag([1.5,0.7])]
n_klass = 2
alldata = ClassificationDataSet(2, 1, nb_classes=n_klass)
for n in xrange(400):
    for klass in range(n_klass):
        input = multivariate_normal(means[klass],cov[klass])
        alldata.addSample(input, [klass])

rawDescription: Library in python for neural networks to plot ROC, AUC, DET


code: parts = map(lambda x: float(x), parts)

rawDescription: Delete unusable characters or data in archive with python


rawDescription: python:organising a text file of users scores into a list

description: Python:organising a text file of users scores into a list


code: merged.columns = [col[-1] for col in merged.columns.str.split('\\')]

rawDescription: Changes to a Merged CSV file not saving

description: Changes to a Merged CSV file not saving


code: df.groupby('request_type').latency.resample('T', how=lambda x: x.quantile(0.99))

rawDescription: How do I group by one or more dimensions in a time series with Pandas?

description: Group by one or more dimensions in a time series with Pandas


code:
a = np.arange(12).reshape(3,4)
a1 = sparse.csr_matrix(a)

np.dot(a, a.T)
a1 * a.T
a*a
a1.multiply(a1)
etc

rawDescription: Dot product sparse matrices

description: Dot product sparse matrices


code:
import Tkinter

root = Tkinter.Tk(  )
root.title("8 Puzzle Game")

Tkinter.Label(root, text= '4', borderwidth=25 ).grid(row=1,column=1)
Tkinter.Label(root, text= ' ', borderwidth=25 ).grid(row=1,column=2)
Tkinter.Label(root, text= '3', borderwidth=25 ).grid(row=1,column=3)
Tkinter.Label(root, text= '2', borderwidth=25 ).grid(row=2,column=1)
Tkinter.Label(root, text= '8', borderwidth=25 ).grid(row=2,column=2)
Tkinter.Label(root, text= '5', borderwidth=25 ).grid(row=2,column=3)
Tkinter.Label(root, text= '7', borderwidth=25 ).grid(row=3,column=1)
Tkinter.Label(root, text= '6', borderwidth=25 ).grid(row=3,column=2)
Tkinter.Label(root, text= '1', borderwidth=25 ).grid(row=3,column=3)

def mainprg():

    Tkinter.Label(root, text= '4', borderwidth=25 ).grid(row=1,column=1)
    Tkinter.Label(root, text= '8', borderwidth=25 ).grid(row=1,column=2)
    Tkinter.Label(root, text= '3', borderwidth=25 ).grid(row=1,column=3)
    Tkinter.Label(root, text= '2', borderwidth=25 ).grid(row=2,column=1)
    Tkinter.Label(root, text= ' ', borderwidth=25 ).grid(row=2,column=2)
    Tkinter.Label(root, text= '5', borderwidth=25 ).grid(row=2,column=3)
    Tkinter.Label(root, text= '7', borderwidth=25 ).grid(row=3,column=1)
    Tkinter.Label(root, text= '6', borderwidth=25 ).grid(row=3,column=2)
    Tkinter.Label(root, text= '1', borderwidth=25 ).grid(row=3,column=3)

    root.after(1000, mainprg1)

B = Tkinter.Button(root, text = "Run", command = mainprg)
B.grid(row = 4, column = 1)

def mainprg1():
    Tkinter.Label(root, text= '4', borderwidth=25 ).grid(row=1,column=1)
    Tkinter.Label(root, text= '8', borderwidth=25 ).grid(row=1,column=2)
    Tkinter.Label(root, text= '3', borderwidth=25 ).grid(row=1,column=3)
    Tkinter.Label(root, text= '2', borderwidth=25 ).grid(row=2,column=1)
    Tkinter.Label(root, text= '5', borderwidth=25 ).grid(row=2,column=2)
    Tkinter.Label(root, text= ' ', borderwidth=25 ).grid(row=2,column=3)
    Tkinter.Label(root, text= '7', borderwidth=25 ).grid(row=3,column=1)
    Tkinter.Label(root, text= '6', borderwidth=25 ).grid(row=3,column=2)
    Tkinter.Label(root, text= '1', borderwidth=25 ).grid(row=3,column=3)

    root.after(1000, mainprg2)
def mainprg2():
    Tkinter.Label(root, text= '4', borderwidth=25 ).grid(row=1,column=1)
    Tkinter.Label(root, text= '8', borderwidth=25 ).grid(row=1,column=2)
    Tkinter.Label(root, text= '3', borderwidth=25 ).grid(row=1,column=3)
    Tkinter.Label(root, text= '2', borderwidth=25 ).grid(row=2,column=1)
    Tkinter.Label(root, text= '5', borderwidth=25 ).grid(row=2,column=2)
    Tkinter.Label(root, text= '1', borderwidth=25 ).grid(row=2,column=3)
    Tkinter.Label(root, text= '7', borderwidth=25 ).grid(row=3,column=1)
    Tkinter.Label(root, text= '6', borderwidth=25 ).grid(row=3,column=2)
    Tkinter.Label(root, text= ' ', borderwidth=25 ).grid(row=3,column=3)

    root.after(1000, mainprg3)

root.mainloop()

rawDescription: Display a series of interfaces with one click of Run button


code: soup.find_all(["a", "div"], class_=["div1", "a1"])

rawDescription: I want to search div and <a> with specified class using beautifulsoup


code:
a = ['a','b','c','d','e']
b = ['a','b','c','f','g']

exclude = set(b)
new_list = [x for x in a if x not in exclude]

new_list

rawDescription: Finding difference between two very large lists


rawDescription: How to get leap seconds from gps epoch for current date in python

description: Get leap seconds from gps epoch for current date in python


code:
toprint = set()
for x in xrange(sheet.nrows):
    ...
    if james[n] == newton[i]:
        toprint.add(path[n])

for name in sorted(toprint):
    print(name)

rawDescription: Dealing with Nested Loops in Python - Options?


code:
curr = df.ix[df.index.quarter == 4]
prev = df.ix[df.index.quarter == 4].shift()
curr/prev

rawDescription: Pandas select the year end quarters in a DF


code:
from fractions import Fraction
Fraction("10.25")
x = Fraction("10.25")
x**100

rawDescription: Handling very large numbers

description: Handling very large numbers


code:
import flask
# You want to automatically generate the token and store it somewhere on the server (database for example)
flask.session['some_token'] = some_token

rawDescription: Flask: How to store credentials in session and retrieve them?


code:
"""Formatter for generating usage messages and argument help strings.

Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""

rawDescription: Can I pass on options from optparse to argparse?

description: Pass on options from optparse to argparse


rawDescription: Sticking two pictures together in python


code:
def get_siblings(l):
    for a in l:
        for b in l:
            if a < b: # this tests the elements' memory addresses,
                      # so we don't get duplicate pairs or test
                      # elements against themselves
                if a.getparent() == b.getparent():
                    yield (a, b)

rawDescription: Determine if two html elements are siblings


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

class Writer(object):
    logfile = codecs.open("test.log", "w", 'utf-8')

    def createXML(self, dict):
        xml_string = ''
        for key, value in dict.iteritems():
            self.logfile.write(u'\nkey = {0}\n'.format(key))
            if (isinstance(value, basestring)):
                self.logfile.write(u'basestring\n')
                self.logfile.write(u'value = {0}\n\n'.format( value))
            else:
                self.logfile.write(u'value = {0}\n\n'.format( value ))

            xml_string += u'<{0}>{1}</{0}>'.format(key, value )

        return xml_string

rawDescription: Decoding utf-8 in Django while using unicode_literals in Python 2.7


code: func(*parameters)

rawDescription: Storing Python function parameters as a variable to call later


code:
def blink(rect, canvas):
    ...
    # call this function again in a second to
    # blink forever. If you don't want to blink
    # forever, use some sort of flag or computation
    # to decide whether to call blink again
    canvas.after(1000, blink, rect, canvas)

rawDescription: Tkinter, executing functions over time

description: Tkinter, executing functions over time


rawDescription: Return all the values of a specific index number


rawDescription: How to add multiple QPushButtons to a QTableView?

description: Add multiple QPushButtons to a QTableView


rawDescription: python gather together ascii and utf-8 stuff

description: Python gather together ascii and utf-8 stuff


code: import ctypes

rawDescription: Python: simple 'if' statement to tell you if the user has no windows maximized


rawDescription: Performing Photoshop's "Luminosity" filter programmatically


rawDescription: How to index pandas DataFrames by selecting times in a particular interval?

description: Index pandas DataFrames by selecting times in a particular interval


code:
cookies = r.cookies
r = requests.get('http://www.content.alternative.ac.nz/index.php/alternative/article/view/176/202', cookies=cookies)

rawDescription: python urllib2, passworded content and a null response

description: Python urllib2, passworded content and a null response


code: pd.expanding_apply(a, lambda x: cumsum_limit(x))

rawDescription: Reset cumsum if over limit (python)

description: Reset cumsum if over limit (python)


rawDescription: Finding max value of float in a string - regex


code: nums = [map(int, line.split()) for line in f]

rawDescription: How do I use a specific line of a text file in python?

description: Use a specific line of a text file in python


code:
def f():
    pass

g = h = k = m = f  # You created 4 new sticky labels that refer to a single function

class A():
    pass

g = h = k = m = A  # Reusing same 4 labels, all refer to one class

a = ()
g = h = k = m = a  # Reusing same 4 labels, all refer to one instance

rawDescription: Python: pass by reference

description: Python: pass by reference


code:
types_ = {}
def registerType ( dtype , cls ) :
    types_[dtype] = cls
def RandomizableT ( dtype ) :
    return types_[dtype]

rawDescription: Is there a way to get ad-hoc polymorphism in Python?


code:
from nltk import pos_tag
sent1 = 'get me now'.split()
sent2 = 'run fast'.split()
def imperative_pos_tag(sent):
    return pos_tag(['He']+sent)[1:]

imperative_pos_tag(sent1)
imperative_pos_tag(sent2)

rawDescription: NLTK identifies verb as Noun in Imperatives


code: pd.concat([l, r], axis=1)

rawDescription: Merging dataframes with duplicate indices


code:
def normalize(term):
    #do stuff -- i.e., lower; stem; strip punctuation; etc.
    pass
word_list_one = [normalize(word) for word in text_doc.split()]
word_list_two = [normalize(word) for word in other_text_doc.split()]

# if you know the longest of your lists, then you can create a dictionary of ones and zeros from the two lists.
word_dict = dict([(word,1) if word in word_list_one else (word,0) for word in word_list_two])
# that's it.  in the above code, word_list_two should be the longer of your two lists (assuming I understand your code properly)
# Note: someone with more python experience could definitely improve my code.  I just wanted show you another option.

rawDescription: Vectorizing LIst of Unique Words into 0 or 1 using Python


code:
if __name__ == '__main__':
    MyTests = Tests()
    log_file = 'log_file.txt'
    f = open(log_file, "w")
    runner = unittest.TextTestRunner(f)
    unittest.main(defaultTest='MyTests.suite', testRunner=runner)

rawDescription: how to add dozen of test cases to a test suite automatically in python

description: Add dozen of test cases to a test suite automatically in python


rawDescription: Automatization issue

description: Automatization issue


code:
for i in data.find():
    a = [element['total'] for element in i['counts']]
    P.plot(a, label=somename)
P.legend()
P.show()

rawDescription: Iterating through graph labels

description: Iterating through graph labels


rawDescription: Python, all possible combinations of numbers betweens 2 lists


code:
i = 0
end = 10

while i < end:
    # NOTE: do something with i here

    if i == 5:
        i += 3
    i += 1

rawDescription: How to jump some steps when use python's for statement

description: Jump some steps when use python's for statement


code:
import matplotlib.pyplot as plt
plt.style.use('ggplot')

rawDescription: In Jupyter, how can I use the matplotlib ggplot style by default?


rawDescription: Python Variables Referecing - unexpected behavior with zip


code: sorted(l, key=scores.get)

rawDescription: Sort a list by a key and get the value out without recomputing


code:
import pandas as pd
import numpy as np
import treetaggerwrapper
import multiprocessing as mp

input_file = 'new_corpus.csv'
output_file = 'output2.csv'

def postag_string_mp(s):
    '''
    Returns tagged text for string s.
    "pool_tagger" is a global name, defined in each subprocess.
    '''
    if isinstance(s, basestring):
       s = s.decode('UTF-8')
    return pool_tagger.tag_text(s)

''' Reading in the file '''
all_lines = []
with open(input_file) as f:
    for line in f:
        all_lines.append(line.strip().split('|', 1))

df = pd.DataFrame(all_lines[1:], columns = all_lines[0])

''' Multiprocessing '''

# Number of processes can be adjusted for better performance:
nproc = mp.cpu_count()

# Function to be run at the start of every subprocess.
# Each subprocess will have its own TreeTagger called pool_tagger.
def init():
    global pool_tagger
    pool_tagger = treetaggerwrapper.TreeTagger(TAGLANG='en')

# The actual job done in subprcesses:
def run(df):
    return df.apply(postag_string_mp)

# Splitting the input
lst_split = np.array_split(df['content'], nproc)

pool = mp.Pool(processes = nproc, initializer = init)
lst_out = pool.map(run, lst_split)
pool.close()
pool.join()

# Concatenating the output from subprocesses
df['POS-tagged_content'] =  pd.concat(lst_out)

# Format fix:
def fix_format(x):
    '''x - a list or an array'''
    # With encoding:
    out = list(tuple(i.encode().split('\t')) for i in x)
    # and without:
    # out = list(tuple(i.split('\t')) for i in x)
    return out
df['POS-tagged_content'] = df['POS-tagged_content'].apply(fix_format)

df.to_csv(output_file, sep = '|')

rawDescription: Optimizing function computation in a pandas column?


code: popularSearchEngine = input("What is the most popular search engine? ")

rawDescription: How to insert an answer into python

description: Insert an answer into python


code:
VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
if db in VALID_DB:
   ...

rawDescription: Python dictionary optimize this script

description: Python dictionary optimize this script


code: C.grad_foo + C.grad_bar + C.grad_baz

rawDescription: Efficient calculation on a pandas dataframe


code:
import cv2
import numpy as np

#######   training part    ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

rawDescription: Simple Digit Recognition OCR in OpenCV-Python


code:
with ix.searcher() as searcher:
    query = QueryParser("content", ix.schema).parse("somesearchstring")
    results = searcher.search(query)
    print(results)

rawDescription: Whoosh Functionality

description: Whoosh Functionality


rawDescription: Reading the same filename from multiple locations


code:
import ctypes

def bitarray_to_ctypes_byte_buffer(data):
    """Convert a BitArray instance to a ctypes array instance"""
    ba = bytearray(data.bytes)
    ba_len = len(ba)
    buffer = (ctypes.c_uint8 * ba_len).from_buffer(ba)
    return buffer

rawDescription: How can I convert a BitString to a ctypes Byte Array?

description: Convert a BitString to a ctypes Byte Array


code:
bigger_array = np.zeros((4,4), dtype=np.int32)
select_mask = ~masked_smaller_array.mask
select_mask
bigger_array[2:4, 2:4][select_mask] = smaller_array[select_mask]
bigger_array

rawDescription: How to replace only part of a numpy array's values with those of another array?

description: Replace only part of a numpy array's values with those of another array


code:
import pandas as pd
df = pd.DataFrame({'a': ['x', 'y', 'x', 'y'],
                   'x': [1, 2, 3, 4]})

df.groupby('a').apply(myfun)

rawDescription: What is pythonic way to do dt[,y:=myfun(x),by=list(a,b,c)] in R?


code:
list_choices = {}
for i in obj:
    list_choices.setdefault(i.area.region.id, []).append([i.id, i.name])

rawDescription: how do i turn for loop iterator into a neat pythonic one line for loop

description: Turn for loop iterator into a neat pythonic one line for loop


rawDescription: Running external program through python terminal


rawDescription: Can I use a variable string to refer to a list?

description: Use a variable string to refer to a list


code:
class EqltByGene(object):
    #

    def serialize(self):
        return {
            'gene_id': self.gene_id,
            'gene_symbol': self.gene_symbol,
            'p_value': self.p_value,
        }

rawDescription: Flask jsonify a list of objects

description: Flask jsonify a list of objects


code:
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
conn, addr = sock.accept()
conn.sendall(pickle.dumps({'somedictionary':data}))

rawDescription: Pass variable between python scripts on different computers.


code:
for line in in_file:
    try:
        donation = float(line)
    except ValueError:
        continue

rawDescription: How to read numbers in a text file for python?

description: Read numbers in a text file for python


rawDescription: How to merge two JSONs

description: Merge two JSONs


code: self.methodB(execute_anyways=True) #Now, the flag would have the default value of None, and would execute.

rawDescription: Reusing code from a method which performs a flag check


code:
for item in mdcArray:
    required_files = glob.glob("{0}/*/QqTest.txt".format(item))
    # process files here

rawDescription: Read file in unknown directory

description: Read file in unknown directory


code:
import re

string = """**
asdf**adsfds
**
**
 **   """
temp = 'specialuniquestring'
string = re.sub(r'(\s*)\*\*(\s*)', r'\1%s\2' % temp, string)
string = string.replace('**', '+++')
string = string.replace(temp, '**')
print(string)

rawDescription: How to find some string by regex but when special string doesn't adjoin?

description: Find some string by regex but when special string doesn't adjoin


code: 'I do not like this novel, no, I do not.'

rawDescription: Python: finding the two words following a key word


code:
df.plot(x=df[[col for col in df.columns if 'Value' in col]].min(axis=1),
        y=['bnw_Percent', 'php_Percent', 'mtgp_Percent'],
        title='Frequency Distribution of Fuzzy Accumulated Values')

rawDescription: Defining x ticks in pandas

description: Defining x ticks in pandas


code: word_set = set(your_string.split())

rawDescription: Python: Jaccard Distance using word intersection but not character intersection


code:
def powerset_generator(i):
    for subset in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
        yield set(subset)

rawDescription: Python: powerset of a given set with generators


code:
import Queue
q = Queue.Queue()
q.put("a")
q.put("b")
q.put("c")
q.put("d")
q.queue[2]
q.queue[3]
with q.mutex:  # Always acquire the lock first in actual usage
  q.queue[3]

rawDescription: Cancel a task execution in a thread and remove a task from a queue


code: f(*lst)

rawDescription: Is there a way to delist a list in python?


code:
ints = [5,3,6,1]
sorted(ints, reverse=True)

rawDescription: Sorting Variables in Python?

description: Sorting Variables in Python


code:
import re
strs= "This is my test the string to match the stuff"
p = re.compile(" the ")
re.findall(p,strs)
var1,var2=re.findall(p,strs)
var1,var2

rawDescription: How can i grab the matched regex pattern in python

description: Grab the matched regex pattern in python


code:
for i, val in enumerate(itertools.islice(lst, 2, None)):
    print(i, val) # would begin with 1 3, then 2 4, …

rawDescription: For count from 2

description: For count from 2


code:
import threading
import time
import sublime
import sublime_plugin

"""
The command just creates and runs a thread.
The thread will do all the work in the background.

Note that in your Thread constructor, you will need to pass in an
instance of your Command class to work with in your thread.
"""
class ExampleCommand(sublime_plugin.TextCommand):

    def run(self, edit):

        exampleThread = ExampleThread(self, edit)
        exampleThread.start()

"""
Extend the Thread class and add your functionality in
the run method below.

One thing to remember when moving your code over is
you need to use self.cmd instead of self.
"""
class ExampleThread(threading.Thread):

    """
    Remember to pass in the parameters you need
    in this thread constructor.
    """
    def __init__(self, cmd, edit):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.edit = edit

    """
    Add your functionality here.

    If you need to access the main thread, you need to
    use sublime.set_timeout(self.callback, 1).

    In my example here, you can't call insert text into the editor
    unless you are in the main thread.

    Luckily that is fast operation.

    Basically, time.sleep(3) is a slow operation and will block, hence it
    is run in this separate thread.
    """
    def run(self):
        time.sleep(3)
        sublime.set_timeout(self.callback, 1)

    """
    This is the callback function that will be called to
    insert HelloWorld.

    You will probably need to use this to set your status message at
    the end. I'm pretty sure that requires that you be on main thread
    to work.
    """
    def callback(self):
        self.cmd.view.insert(self.edit, 0, "Hello, World!")

rawDescription: Python threading in for loop

description: Python threading in for loop


code:
FilesToSearch  = []
for fname in os.listdir(search_folder):
    FilesToSearch.append(search_folder + '\\' + fname)

rawDescription: Searching logs, outputting lines before and after match


code:
from sqlalchemy import Column, Integer, Unicode, create_engine
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite://')
Base = declarative_base(bind=engine)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(60))

Base.metadata.create_all()

rawDescription: In Sqlalchemy, if i add an object using session.add() and flush it, session.query() does not give that object, why?


code:
for element in iterable:
    spam(element)

it = iterator(iterable)
while True:
    try:
        element = next(it)
    except StopIteration:
        break
    else:
        spam(element)

rawDescription: Trying to return numbers in a list

description: Trying to return numbers in a list


code:
for item in (values[index] for index in indices):
    print(item + ' ' + item)

rawDescription: Extract list from given list and given indices


code:
class Foo(object):
    spam = 2
    def __init__(self, a = 'init'):
        self.a = a

rawDescription: which to use: class variables versus classmethod?

description: Which to use: class variables versus classmethod


code:
import numpy
from matplotlib import pyplot as plt

width, height = 300, 500

xs = numpy.arange(width)
ys = numpy.arange(height)
data = numpy.dstack(numpy.meshgrid(xs, ys))

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


code:
hello_lbl = Label(root, text="")
hello_lbl.grid(row=4, columnspan=2)

rawDescription: Tkinter: Instatiate Object with Button

description: Tkinter: Instatiate Object with Button


rawDescription: ctime, atime, and mtime - How to interpret them?

description: Ctime, atime, and mtime - How to interpret them


code: imtag = re.match(r'<img.*?>', line).group(0)

rawDescription: how do i return a string from a regex match in python

description: Return a string from a regex match in python


code:
lowerBounds = a[...,:-1]
upperBounds = a[...,1:]

rawDescription: Calculating new entries in array based on entries from another array in python


code:
def some_func(x):
    return x > 5

filter(some_func, iterable)

rawDescription: Regarding the use of filter()

description: Regarding the use of filter()


code: ticket_form = TicketForm(request.user)

rawDescription: Django model form with selected rows

description: Django model form with selected rows


code:
def __setattr__(self, name, value):
    if not hasattr(self, name):
        raise AttributeError('''Can't set attribute "{0}"'''.format(name))
    # Or whatever the base class is, if not object.
    # You can use super(), if appropriate.
    object.__setattr__(self, name, value)

rawDescription: How to make class immutable in python?

description: Make class immutable in python


code:
from collections import OrderedDict
d= OrderedDict()

import fileinput
import os

with open("joined.txt","w") as f:
    for line in fileinput.input(os.listdir("path_to")):
        spl = line.strip().split(",")
        d.setdefault(spl[0],[])
        d[spl[0]] += spl[1:]
    for k,v in d.items():
        f.write("{} {}\n".format(k,",".join(v)))

rawDescription: Python side-by-side merge of comma-delimited text files


code:
result = result.set_index(['SUM(DAYS)', 'MONTH'], append=True)
result = result.unstack('MONTH')
result = result.reset_index(['SUM(DAYS)'])

rawDescription: Pandas multiple index with multiple aggregate functions


code:
a = "aa"
b = 1
c = { "b":2 }
d = [3,"c"]
e = (4,5)
letters = [a, b, c, d, e]
def EmptyVar(lst):
    return [type(i)() for i in lst]

EmptyVar(letters)

rawDescription: Empty a variable without destroying it

description: Empty a variable without destroying it


code:
def my_func(data):
    if isinstance(data, basestring):
        with open(data, 'rb') as f:
            return my_func(f)
    ...

rawDescription: How can I pass a .txt file as a function parameter

description: Pass a .txt file as a function parameter


code:
@asynchronous
@gen.engine
def post(self):
    fetch_response = yield gen.Task(async_fetch, ...)
    mail_response = yield gen.Task(async_mail, ...)
    self.render(...)

rawDescription: chaining asynchronous operations before writing to client (python - tornado)

description: Chaining asynchronous operations before writing to client (python - tornado)


code:
'hello'.isspace()
'\n'.isspace()

rawDescription: Delete a blank line from a file using python


rawDescription: how do I make a list of tuples from a string?

description: Make a list of tuples from a string


rawDescription: Optimizing Python distance calculation while accounting for periodic boundary conditions


code: index = yearSeconds / (60*60*6) # / 60 sec/min * 60 min/hour * 6 hours

rawDescription: Writing NetCDF time variable from start of year


code:
{ "_id" : ObjectId("5343aeb5efbdb94c3647c8df"), "field" : "BBB" }
{ "_id" : ObjectId("5343aebbefbdb94c3647c8e0"), "field" : "aaa" }
{ "_id" : ObjectId("5343aebfefbdb94c3647c8e1"), "field" : "AAA" }

rawDescription: Serializing MongoDB find() return into non-anonymous JSON array, using PyMongo


code:
for link in links:
    cont = requests.get(link).content
    soup = BeautifulSoup(cont)
    css = r.search(link)
    if not css:
       continue
    css = css.group()
    yield [p.text for p in soup.select(css)]

rawDescription: Why does my webcrawler not follow into the next link containing keywords


code:
import pandas as pd
import difflib as diff
#Read the CSV
df = pd.read_csv('datac.csv')
#Create a new column 'diff' and get the result of comparision to it
df['diff'] = df.apply(lambda x: diff.SequenceMatcher(None, x[0].strip(), x[1].strip()).ratio(), axis=1)
#Save the dataframe to CSV and you could also save it in other formats like excel, html etc
df.to_csv('outdata.csv',index=False)

rawDescription: Comparing two columns of a csv and outputting string similarity ratio in another csv


code:
import requests
import tempfile

from django.core import files

# List of images to download
image_urls = [
    'http://i.thegrindstone.com/wp-content/uploads/2013/01/how-to-get-awesome-back.jpg',
]

for image_url in image_urls:
    # Steam the image from the url
    request = requests.get(image_url, stream=True)

    # Was the request OK?
    if request.status_code != requests.codes.ok:
        # Nope, error handling, skip file etc etc etc
        continue

    # Get the filename from the url, used for saving later
    file_name = image_url.split('/')[-1]

    # Create a temporary file
    lf = tempfile.NamedTemporaryFile()

    # Read the streamed image in sections
    for block in request.iter_content(1024 * 8):

        # If no more file then stop
        if not block:
            break

        # Write image block to temporary file
        lf.write(block)

    # Create the model you want to save the image to
    image = Image()

    # Save the temporary image to the model#
    # This saves the model so be sure that is it valid
    image.image.save(file_name, files.File(lf))

rawDescription: Download a remote image and save it to a Django model


rawDescription: Is it possible to make Python interpret a script line by line and generate output as if from an interactive shell?


code:
class Agent(Thread):
    mylock = Lock()
    def write_result(self):
        with self.mylock:
            ...

rawDescription: Multithreaded Resource Access - Where Do I Put My Locks?


code: open('%s.log'%hname, 'w').writelines([line.decode('ascii') for line in open('%s_tmp.log' %hname) if 'word' in line])

rawDescription: python line strip \n and write line

description: Python line strip \n and write line


rawDescription: Extract content with BeautifulSoup and Python


code: data = {'name': 'Karatepig', 'score': 10}

rawDescription: Reading/Writing/Appending using json module


code: dict((myTuple[1], {'index': index}) for index, myTuple in enumerate(l))

rawDescription: Is there a way in Python to index a list of containers (tuples, lists, dictionaries) by an element of a container?


rawDescription: multiple conditioned slicing (pandas dataframe)

description: Multiple conditioned slicing (pandas dataframe)


code:
from enum import Enum
MyEnum = Enum('MyEnum', 'APPLE BANANA WALRUS')
MyEnum.BANANA

rawDescription: What's the cleanest way to set up an enumeration in Python?


code:
def run(self):
    worker = SocketServerListen()
    thread = QThread()
    worker.moveToThread(thread)
    worker.finished.connect(self.workerFinished)
    worker.error.connect(self.workerError)

    thread.started.connect(worker.run)
    thread.start()
    thread.exec_()
    self.thread = thread
    self.worker = worker

rawDescription: Socket server not responding when in thread


rawDescription: Python string, find specific word, then copy the word after it


code: return conditional

rawDescription: Which Python Conditional Return Statement Is The Most Pythonic?


code: df.filter(like='Length', axis=1)

rawDescription: Identifying multiple columns by name in Pandas


rawDescription: Generator to merge sorted dictionary-like iterables


code:
instance_a = raw_input('set instance a')
instance_b = raw_input('set instance b')
run(tests[instance_a], tests[instance_b])

rawDescription: Execute a function with an instance based on user input (in conjunction with a class) [Python]


code:
pattern=re.compile(r'(?<=\bdata-id=")\d+(?=")')
s = 'data-id="48859672"'
pattern.search(s).group()

rawDescription: How could I get a part of a match string by RegEx in Python?


code:
from bs4 import BeautifulSoup
from urllib.request import urlopen

url = urlopen('http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01')

content = url.read()

soup = BeautifulSoup(content)

results = {}

for table in soup.find_all('table', class_='scores'):
    for row in table.find_all('tr'):
        scores = []
        name = None
        for cell in row.find_all('td', class_='yspscores'):
            link = cell.find('a')
            if link:
                name = link.text
            elif cell.text.isdigit():
                scores.append(cell.text)
        if name is not None:
            results[name] = scores

for name, scores in results.items():
    print('%s: %s' % (name, ', '.join(scores)))

rawDescription: Associating the correct teams with the correct score values


code:
tuple1 = ("a", "b", "c")
tuple2 = ("y", "z")
tuple1 + tuple2  # This creates a new tuple object
tuple1  # tuple1 is unaffected
tuple2  # tuple2 is also unaffected

rawDescription: Beginning with two separate tuples, how to make one non-nested tuple?


code:
c = a
c *= b

rawDescription: What is this operator *= -1

description: What is this operator *= -1


code: grid = np.logical_and(rev_count[None, :] >= revbin[:-1, None], rev_count[None, :] < revbin[1:, None])

rawDescription: Python: Binning one coordinate and averaging another based on these bins


code:
from itertools import product

for digit, pos in product('1234', range(len(letters))):
    s = list(letters)
    s[pos] = digit
    print(''.join(s))

rawDescription: Change one character at a time in a string, don't change the string?


code:
p = re.compile(r"QChar\((0x[a-fA-F0-9]*)\)")

def qcharToUnicode(s):
    return p.sub(lambda m: '"' + chr(int(m.group(1),16)) + '"', s)

rawDescription: In Python, are function-level assignments evaluated at each function call?


rawDescription: Python: Split a list into smaller jsons based on another list


code: reduce(operator.mul, map(len, a), 1)

rawDescription: Multiply lengths of all sub-lists in list


code:
pca = RandomizedPCA(n_components=3)
pca.fit(X)
pca.transform(z)

rawDescription: what is the difference between 'transform' and 'fit_transform' in sklearn

description: What is the difference between 'transform' and 'fit_transform' in sklearn


rawDescription: Python 2.7 - Take two JSON's and combine the string field values together and add int fields


code:
from collections import OrderedDict
section_dict = OrderedDict((sec, {}) for sec in sections)

rawDescription: Create many empty dictionary in Python

description: Create many empty dictionary in Python


code: zip(*np.where(N == N.max()))

rawDescription: Python find list of surrounding neighbours of a node in 2D array


code: questions = [('Enter name of boy', 'nameb') , ('Enter place', 'place'),...]

rawDescription: Python- Simple random selector

description: Python- Simple random selector


code: (prev_item['path'], item['path'])

rawDescription: Double assignment in python

description: Double assignment in python


rawDescription: Slicing a DataFrame

description: Slicing a DataFrame


code: setCallback(lambda param, data: myObj.callbackFunction(param, data), param="x")

rawDescription: Python callback working with functions but not methods


code:
def complement(dna):
    transtable = dna.maketrans('acgtnACGTN', 'tgcanTGCAN')
    return dna.translate(transtable)

print(complement('TGA'))

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


code: Out[14]: [u'dog', u'domestic dog', u'Canis familiaris']

rawDescription: Replacement by synsets in Python pattern packatge


code: on_press=lambda instance: self.SAVE_EDIT(instance, TEXT=t1.txt)

rawDescription: Give/get arguments in popup from "on_press"


code:
import itertools

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection, PolyCollection
import numpy as np

import cartopy.feature
from cartopy.mpl.patch import geos_to_path
import cartopy.crs as ccrs

fig = plt.figure()
ax = Axes3D(fig, xlim=[-180, 180], ylim=[-90, 90])
ax.set_zlim(bottom=0)

concat = lambda iterable: list(itertools.chain.from_iterable(iterable))

target_projection = ccrs.PlateCarree()

feature = cartopy.feature.NaturalEarthFeature('physical', 'land', '110m')
geoms = feature.geometries()

geoms = [target_projection.project_geometry(geom, feature.crs)
         for geom in geoms]

paths = concat(geos_to_path(geom) for geom in geoms)

polys = concat(path.to_polygons() for path in paths)

lc = PolyCollection(polys, edgecolor='black',
                    facecolor='green', closed=False)

ax.add_collection3d(lc)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Height')

plt.show()

rawDescription: 3D CartoPy similar to Matplotlib-Basemap


code: [int(d) for d in re.findall(r'\d+', versionstring)]

rawDescription: Cleanest way to obtain a list of the numeric values in a string


code: [[x for x in line] for line in a.split('\n')]

rawDescription: How can I transform a string into a matrix

description: Transform a string into a matrix


rawDescription: How to load a npz file in a non-lazy way?

description: Load a npz file in a non-lazy way


rawDescription: Python: matplotlib - Black and White Scatter


code:
blob_key = BlobKey.all().get()
blob = blobstore.get(blob_key)
if blob : blob.delete()
db.delete( blob_key )    # you don't need it anymore

file_name = files.blobstore.create( mime_type = 'text/csv')
with files.open(file_name, 'a') as f:
    f.write( your_content )

files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)

BlobKey( blob_key = str(blob_key) ).put()   # save the new key

rawDescription: GAE Python - Task to save CSV to same Blobstore element daily


code:
regex = re.compile(r'[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?\b|\.[0-9]+\b')
mynumerics = re.findall(regex,'The final bill is USD1,010.53 and you will earn 300 points. What about .25 and 123,456.12?')
mynumerics

rawDescription: Python 2.7.7 not working with RegEx

description: Python 2.7.7 not working with RegEx


rawDescription: Subsetting data in python

description: Subsetting data in python


code: function_in_library("Hello %s", ', '.join(my_args))

rawDescription: python - How to format variable number of arguments into a string?

description: Python - How to format variable number of arguments into a string


code:
for sub in l:
    sub[:] = map(float,(s.rsplit("(",1)[0] for s in sub))

print(l)

rawDescription: How to remove parenthesis from elements in a list (Python)

description: Remove parenthesis from elements in a list (Python)


code:
from collections import defaultdict

data = defaultdict(float)

for line in lst1+lst2:
    name, code, value = line.split(",")
    data[name, code] += float(value)

newlist = ['{},{},{}'.format(key[0], key[1], val) for key, val in sorted(data.items())]

rawDescription: python add two list and createing a new list

description: Python add two list and createing a new list


code:
dm_s_uniques = len(np.unique(dm_s))
logs = np.log10(10 * dm_p)
logs[logs == -np.inf] = 1
prox_mat = ((dm_w +  dm_s_uniques) / (dm_w.shape[0] * dm_s_uniques)) * logs

ps = np.reshape(ps, dm_w.shape)

rawDescription: Efficient way to iterate through numpy arrays in parallel and create a new resultant array


code:
def euclidean_dist4(x1, x2):
    assert(len(x1) == len(x2))

    x1 = np.array(x1)
    x2 = np.array(x2)

    diff = x1 - x2

    dot = np.dot(diff, diff)

    norm = np.sqrt(dot)

    return norm

rawDescription: How to vectorize array operations in Python

description: Vectorize array operations in Python


code:
stdout, stderr = p.communicate()
stdout
stderr
p.returncode

rawDescription: Python subprocess.Popen strange behavior


rawDescription: Python - Comparing lists

description: Python - Comparing lists


code:
import itertools
[x+y for x,y in itertools.zip_longest('12345','ab',fillvalue='*')]

rawDescription: Python list comprehension for loops

description: Python list comprehension for loops


code:
process(
    "Itali-am fat-o profug-us Lavini-a-que ven-it",
    "Italy-Fem:Sg:Acc fate-Neut:Sg:Abl fleeing-Masc:Sg:Nom Lavinian-Neut:Pl:Acc come:Perf-3-Sg:Indic:Act",
    "in flight [driven] by fate came to Italy and the Lavinian [shores]")

rawDescription: Using Python to count morphemes in a file & list them in columns


code:
with open('python_dictionary.json','a') as f:
    str = json.dumps(new_dictionary).replace('{', ',', 1)
    f.seek(-2,2)
    f.write(str)

rawDescription: Append to dictionary file in json, python


code:
ascii = ''.join(chr(x) for x in range(33, 127))
re.findall('([{}]+|[^{}]+)'.format(ascii, ascii), u"abc你好def啊")

rawDescription: python split a unicode string by 3-bytes utf8 character

description: Python split a unicode string by 3-bytes utf8 character


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

driver = webdriver.Firefox()
driver.maximize_window()
driver.get("http://store.nike.com/us/en_us/pw/mens-tops-t-shirts/7puZobp?ipp=120")

wait = WebDriverWait(driver, 10)

driver.find_element_by_xpath(
    "//div[@id='exp-gridwall-wrapper']/div[2]/div[2]/div[2]/div/div/div/div/div/div[3]/div[2]/p").click()

# opening size dropdown
size_button = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".exp-pdp-size-and-quantity-container a.exp-pdp-size-dropdown")))
actions = ActionChains(driver)
actions.move_to_element(size_button).click().perform()

# selecting size
size = wait.until(EC.visibility_of_element_located((By.XPATH, "//li[contains(@class, 'nsg-form--drop-down--option') and normalize-space(.) = 'S']")))
actions = ActionChains(driver)
actions.move_to_element(size).click().perform()

# adding to cart
driver.find_element_by_id("buyingtools-add-to-cart-button").click()

# checkout
checkout_button = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".checkout-button")))
actions = ActionChains(driver)
actions.move_to_element(checkout_button).click().perform()

rawDescription: selenium fails when adding to cart, how to click on a javascript button?

description: Selenium fails when adding to cart, how to click on a javascript button


code:
print(list(set(a).difference(b))[:3])
[3, 5, 7]

rawDescription: How to get n elements of a list not contained in another one?

description: Get n elements of a list not contained in another one


code: next(i for i, x in enumerate(text.split('\n')) if x and re.search(pattern, x))

rawDescription: Given a list of strings, how to locate position of first string matching substring using RegEx?


rawDescription: Python: Understanding how 'return' works within a class (Learn Python Hard Way, exercise 43)


code: c

rawDescription: how to get the value stored in the hex file location in python?

description: Get the value stored in the hex file location in python


code:
ix
df["id"].values[ix]

rawDescription: convert indices into corresponding pandas dataframe values

description: Convert indices into corresponding pandas dataframe values


code:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from kivy.app import App

class Test(App):
    pass

Test().run()

rawDescription: Forcing a Kivy widget's orientation to be landscape/portrait


code:
"".join(
  # if i is between A and Z change it to between a and z
  [chr(ord(i)+32) if 65<= ord(i) <= 90
  # otherwise leave it as is
  else i for i in a])

rawDescription: How to make letters in a string lowercas, Python

description: Make letters in a string lowercas, Python


code:
import urllib2 as urllib

page = urllib.urlopen('http://www.someurl.com/blah.xml')
with open('output.xml', 'w') as f:
  f.write(page.read())

rawDescription: How to download content from a webpage every few seconds with python?

description: Download content from a webpage every few seconds with python


code:
COMPANY = ''.join(list(lines[30]))              \
            .replace(",", "").replace("\n", "") \
            .split(" : ")

rawDescription: How can I set a variable to a value multiple times in one line?

description: Set a variable to a value multiple times in one line


rawDescription: Sort inter-dependant elements of a dictionary


code:
def do_something(a,b,c,d):
    print("{0} {1} {2} {3}".format(a,b,c,d))

a = [1,2,3,4]
do_something(*a)

rawDescription: pointer in python?

description: Pointer in python


code:
df = df2.join(df1, on='Id_a')
df = df.rename(columns = {'value' : 'value_a'})

df = df.join(df1, on='Id_b')
df = df.rename(columns = {'value' : 'value_b'})

rawDescription: How to extract values of one dataframe with values of other dataframe in pandas?

description: Extract values of one dataframe with values of other dataframe in pandas


rawDescription: Match embedded Documents by Regular expression with Mongoengine


code:
class Damage:

    def __init__(self, modifier=0, die_sides=6):
        self.modifier = modifier
        self.die_sides = die_sides

    def damage(self):
        return randint(1, self.die_sides) + self.modifier

shortsword = Damage(1)

damage = shortsword.damage()

rawDescription: Storing the value of a randomly generated integer


rawDescription: Detection of concurrent event appearances - pandas and DataFrame, but possibly pure-python related


code:
import logging
import webapp2
from google.appengine.api import mail
from google.appengine.ext.webapp.mail_handlers import BounceNotification
from google.appengine.ext.webapp.mail_handlers import BounceNotificationHandler

class LogBounceHandler(BounceNotificationHandler):
    def receive(self, bounce_message):
        mail.send_mail(to='ajai@qburst.com', sender='ajai@qburst.com', subject='Bounced email',
                       body=str(self.request))
        logging.info('Received bounce post ... [%s]', self.request)
        logging.info('Bounce original: %s', bounce_message.original)
        logging.info('Bounce notification: %s', bounce_message.notification)

class BounceHandler(webapp2.RequestHandler):
    def post(self):
        bounce = BounceNotification(self.request.POST)
        logging.info('Bounce original: %s', bounce.original)
        logging.info('Bounce notification: %s', bounce.notification)

app = webapp2.WSGIApplication([
    ('/_ah/bounce', LogBounceHandler),
], debug=True)

rawDescription: Is it possible to receive email bounce notifications for google app engine - python?


code:
user_name = ""
while len(user_name) == 0:   # While the user_name var is empty
    user_name = raw_input('Enter a user name: ')  # Prompt the user to enter a name, and assign to the user_name var

rawDescription: How to stop a user from hitting enter on a Python Command Line program?

description: Stop a user from hitting enter on a Python Command Line program


code:
from bs4 import BeautifulSoup
import re
import csv

doc = """

  July 1

  Top Gun

  "Location: Millennium Park"

  "Amenities: Please be a volleyball tournament..."

  Captain Phillips

  "Location: Montgomery Ward Park"

  July 2

  The Fantastic Mr. Fox

  "Location: Somewhere"

  "Amenities: Something something"

"""

soup = BeautifulSoup(doc.replace("
", "
"))

data = []

for date in soup.find_all("strong"):
    sibling = date.next_sibling
    while sibling and sibling.name != "strong":
        if sibling.name == "em":
            title = sibling
            location = title.find_next("br").next
            extra = location.find_next("br").next

            row = []
            row.append(date.text)
            row.append(title.text)
            row.append(re.findall('(?<=:)[^"]*', location)[0])
            extra_val = re.findall('(?<=:)[^"]*', extra)
            if len(extra_val):
                row.append(extra_val[0])

            data.append(row)

        sibling = sibling.next_sibling

with open('foo.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(data)

rawDescription: Utilizing BeautifulSoup on a completely flat HTML hierarchy


code: del lst[4:]

rawDescription: Most pythonic way to truncate a list to N indices when you can't guarantee the list is at least N length?


code:
class Victim(object):
    @Decor
    def sum(self, a, b):
        return a + b

v = Victim()
v.sum
v.sum.func

rawDescription: Callable object decorator applied to method doesn't get self argument on input


code:
class Foo:
    def __init__(self):
        self.x = dict()

    def add(self):
        self.x[1] = 'a'  # add something to our dict

    def redefine(self):
        self.x = {2:'b', 3:'c'}  # reassign our dict

rawDescription: self variables not being stored in python?

description: Self variables not being stored in python


code:
import os
data_csv_filename = os.path.join(
    os.path.dirname(__file__), 'bar', 'data.csv')
with open(data_csv_filename) as data_csv_file:
    ...

rawDescription: How to use an external, static data file in a script hosted on Google App Engine?

description: Use an external, static data file in a script hosted on Google App Engine


code:
# foo.py
class Foo(object):
   def method(self):
       return 'foo!'

# bar.py
class Bar(object):
    def method(self):
       return 'bar!'

# call_method.py
def go(object_with_method):
    print(object_with_method.method())

# driver.py
import call_method
import foo
import bar

call_method.go(Foo())  # call the method on a foo instance
call_method.go(Bar())  # call the method on a bar instance

rawDescription: When does a passed class instance require an import in python


code:
import pandas as pd

ids = [1,2,3,3,4,4,5,6]
cols = ['a', 'a', 'p', 'sp', 'n', 'sn', 'b', 'c']

df = pd.DataFrame({'Id':ids, 'Col':cols})

counts = df['Id'].value_counts()
values = [x for x in counts.index if counts[x]>1]
result = []
for e in values:
    vals = df[df['Id'] == e].Col.value_counts().index.values
    result.append((e, vals))

rawDescription: Modifying Python DataFrame rows with duplicates


code:
import numpy as np
import pandas as pd

import numpy as np

rawDescription: Converting pandas column to string w/o scientific notation


code:
SC = SimpleClass()
setattr(SC, 'your_new_attribute_name', 'test')

rawDescription: Method that applies to instance of a class in python // Apply a method to an instance of a class in python


code:
X = X.reshape((np.prod(X.shape),))
Y = Y.reshape((np.prod(Y.shape),))

rawDescription: How to create matrix of points by X, Y coordinate in Python?

description: Create matrix of points by X, Y coordinate in Python


code:
class Child(models.Model):
    parent = models.ForeignKey(Parent, related_name='children')

for child in parent.children.filter(some_field=True):
    do_something()

rawDescription: Django backwards relation

description: Django backwards relation


code: _constructor_sliced = Series

rawDescription: What does _constructor do in DataFrame class


code:
for person in os.listdir(top_level_folder):
    inbox = os.path.join(top_level_folder, person, 'inbox')
    sent = os.path.join(top_level_folder, person, 'sent')

    for file in os.listdir(inbox):
        pass # Do something

    for file in os.listdir(sent):
        pass # Do something

rawDescription: Only enumerate files in folders with specific names


code:
import calendar

for day,abbr in zip(calendar.day_name,calendar.day_abbr):
    paragraph = paragraph.replace(day,abbr)

rawDescription: shorten the weekdays from texts

description: Shorten the weekdays from texts


code:
class A:
    def __init__(self):
        super().__init__()
        print("A")

class B:
    def __init__(self):
        super().__init__()
        print("B")

class C(A,B):
    def __init__(self):
        super().__init__()

rawDescription: Call constructor in multiple derived classes


rawDescription: Blurring images containing text using Python Imaging Library


code:
class A(object):
    def __init__(self):
        self.version = '1.0'
        self.login = 'logged in'
        self.login_message = 'hello logger'
        property_attrs = {'logout': {'1.0': 'logged out',
                                     '2.0': 'logged out 2.0'},
                          'logout_message': {'1.0': 'goodbye logger',
                                             '2.0': 'goodbye logger 2.0'}}
        for name, value in property_attrs.items():
            setattr(self.__class__, name, property(lambda x: value[x.version]))

rawDescription: python global decorator for class attributes

description: Python global decorator for class attributes


rawDescription: Python Lists/ Tuples in terms of sorting


rawDescription: remove pytz timezone

description: Remove pytz timezone


code:
with open(your_config_file) as config_file:
    _config.write(your_config_file)

rawDescription: Python - How to change the name of a section use configparser?


code:
def __getattribute__(self, attr):
    try:
        return object.__getattribute__(self, attr)
    except AttributeError: # attr must be a fieldname
        pass
    fielddict = ndarray.__getattribute__(self, 'dtype').fields
    try:
        res = fielddict[attr][:2]
    except (TypeError, KeyError):
        raise AttributeError("record array has no attribute %s" % attr)
    return self.getfield(*res)
    ...

rawDescription: Namedtuple in Numpy

description: Namedtuple in Numpy