rawDescription: Django Paginate by Year

description: Django Paginate by Year


code:
left_a = left.set_index('a')
right_a = right.set_index('a')

rawDescription: pandas left join and update existing column

description: Pandas left join and update existing column


code:
@register.filter(name='my_custom_filter')
def my_custom_filter(value):
    # here value is the value of your label
    # process it as you please then return the new value
    if value == 'changeme':
        return 'changed label'
    return value

rawDescription: Changing a form html name in a template

description: Changing a form html name in a template


code:
def everythird(l):
    ret = []
    for i in range(0, len(l), 3):
        ret.append(l[i])
    return ret

rawDescription: Python: How to return a list without modifying the original list using a while loop only?


code:
po:MusicSegment
po:SpeechSegment

rawDescription: Trouble accessing attribute after using BeautifulSoup's findAll


rawDescription: Remove tuples in a 2D numpy array that satisfy 2 conditions


code:
A_pairs = pairwise(flatten([re.split("[ ,]", item) for item in A]))
with open("output.csv", "wb") as f:
    csv.writer(f).writerows(A_pairs)

rawDescription: Writing a results to a .txt file using csv


code: ['is THAT what you mean, Mrs. Hussey?']

rawDescription: How to tweak the NLTK sentence tokenizer

description: Tweak the NLTK sentence tokenizer


code:
def find_all_paths(start, end, graph, visited=None):
    if visited is None:
        visited = set()

    visited |= {start}
    for node,link in graph[start].items():
        if node in visited:
            continue
        if node == end:
            yield [link]
        else:
            for path in find_all_paths(node, end, graph, visited):
                yield [link] + path

rawDescription: Python: How to find more than one pathway in a recursive loop when multiple child nodes refers back to the parent?


code:
from django.contrib.auth.decorators import login_required
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
    (r'^foo/$', login_required(direct_to_template), {'template': 'foo_index.html'}),
    )

rawDescription: How to require login for django generic views?

description: Require login for django generic views


code:
def getConfiguration(config_id):
    """ Signature:  getConfiguration(int): array<string>"""

    return ["feature_1", "feature_2"]

rawDescription: How to return multiple strings from a script to the rule sequence in booggie 2?

description: Return multiple strings from a script to the rule sequence in booggie 2


code:
left = max(r1.left, r2.left);
right = min(r1.right, r2.right);
top = max(r1.top, r2.top);
bottom = min(r1.bottom, r2.bottom);

rawDescription: How to make rect from the intersection of two?

description: Make rect from the intersection of two


code:
myregexps = [('AC1', r'(?:TGA[GA])+'), # list of (patname, regexp) pairs
             ('polyAT', r'[AT]{6,}'),
             ...
            ]

mypats = [(patname, re.compile(raw)) for patname, raw in myregexps]

rawDescription: More compact and/or elegent way to run multiple regex matches


code:
x = '"2","black,white","more","stuff"'
x
import shlex
y = shlex.shlex(x)
[i.strip('"') for i in y if i != ',']

rawDescription: Python Split With Delimiter In Field Value


code:
square_letter = {c: e for e in ['ABC','DEF','GHI'] for c in e}
square_number = {n: e for e in ['123','456','789'] for n in e}
def find_peers(square, _letter=square_letter, _number=square_number):
    """
    Returns list of strings of shared squares in the unit.
    Example: find_peers('A2') -> ['A1', 'A2', 'A3', 'B1' , ..., 'C3']
    """
    return cross_product(_letter[square[0]], _number[square[1]])

rawDescription: Pythonic way of returning an element of a list if a certain char is found in that element


code:
host, _, port = netloc.rpartition(':')
if ']' in port: host = netloc
host

rawDescription: Resolve host name of wss protocol with socket?


code:
class hookable(object):
  def __init__(self, fn):
    self.pre = []
    self.post = []
    self.fn = fn
  def add_pre(self, hook):
    self.pre.append(hook)
  def add_post(self, hook):
    self.post.append(hook)
  def __call__(self, *args, **kwargs):
    for hook in self.pre:
      hook(*args, **kwargs)
    ret = self.fn(*args, **kwargs)
    for hook in self.post:
      hook(*args, **kwargs)
    return ret

rawDescription: allow users to "extend" API functions

description: Allow users to "extend" API functions


rawDescription: Splitting a 16 bit int into two 8 bit ints in python


code: list(bytearray(b))

rawDescription: How does struct.unpack and struct.pack works?


rawDescription: Python Numpy matrix multiplication in high dimension


code:
version_1 = np.vstack(list(sorted({tuple(row) for row in list(itertools.combinations(a, 4))})))  # unique combinations, your way
version_2 = np.array(list(itertools.product((1, 11, 12, 13), repeat=4)))  # same result, but faster
assert (version_1 == version_2).all()

rawDescription: combination of numpy array satisfying condition

description: Combination of numpy array satisfying condition


code:
from django.db import models

class Upload(models.Model):
    name = models.CharField(max_length=100)
    file = models.FileField(upload_to="images")

rawDescription: Uploading csv file from url using django forms


code: sys.stdout = sys.__stdout__  # Restore stdout

rawDescription: How do I redirrect the output in web.py

description: Redirrect the output in web.py


code:
class Pool(object):
    def __init__(self, processes=None, initializer=None, initargs=()):
        ...
        self._terminate = Finalize(
            self, self._terminate_pool,
            args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
                  self._task_handler, self._result_handler, self._cache),
            exitpriority=15
            )

rawDescription: multiprocessing Pool.imap broken?

description: Multiprocessing Pool.imap broken


code: temp2 = temp.copy()

rawDescription: Force numpy array to physically match striding in memory


code: decode("1Dh", 3)

rawDescription: Converting a String to hex and calculate binary result in python


code:
B = A + A
B.nnz

rawDescription: Sparse Matrix Addition

description: Sparse Matrix Addition


rawDescription: How to make if-elif conditionals shorter for parsing

description: Make if-elif conditionals shorter for parsing


code:
for key in (set(myDict)-set(myList)):
    print(key+"\t"+myDict[key])

rawDescription: Python List Exclusions

description: Python List Exclusions


code:
class Select(object):
    def __get__(self,obj,objtype):
        x=objtype if obj is None else obj
        def select(where):
            print(x,where)
        return select
class Books(object):
    select=Select()

book = Books()
Books.select(where='asdf')
book.select(where='asdf')

rawDescription: The same method for class and instance

description: The same method for class and instance


code:
import socket
host = "" #Localhost
port = 12002
PACKET_SIZE=1024 # how many characters to read at a time
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((host,port))
sock.listen(5) # we should never have more than one client
def work_thread(client):
    while True: #continuously read and handle data
      data = client.recv(PACKET_SIZE)
      if not data:
          break # done with this client
      processData(data)

while True:
     client,addr = sock.accept() # your script will block here waiting for a connection
     t = threading.Thread(target=work_thread,args=(client,))
     t.start()

rawDescription: working with NMEA data sent to URL/IP

description: Working with NMEA data sent to URL/IP


rawDescription: Pickle doesn't take my registered custom type reduce function into account on python 2.6


code:
def TailedElement(tag,attrib=None,nsmap=None,tail=None,**extra):
        x = ET.Element(tag,attrib,nsmap,**extra)
        x.tail = tail
        return x

rawDescription: Adding a tail to lxml.etree.Element upon creation


code:
from locale import atof
import locale

locale.setlocale(locale.LC_ALL, 'de_DE')

mylist = ['23 text', '23.130', '12 text', '1.482 text', '3,250', "foo"]

def atof_try(x):
    try:
        return atof(x.split()[0])
    except ValueError:
        return float("inf")

rawDescription: Sort numeric lines with thousand separators


code:
def m():
 y = 1
 def test():
  y = y + 1
  return y
 test()
m()
dis.dis(m)
def l():
 li = [1]
 def test():
  li[0] = li[0] + 1
  return li
 test()
l()

rawDescription: python single integer variable between function

description: Python single integer variable between function


code:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

class MyRoundWidget(QWidget):

    def __init__(self, master=None):
        super(MyRoundWidget,self).__init__(master)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle("QLinearGradient Vertical Gradient ")
        self.setAttribute(Qt.WA_TranslucentBackground)

    def paintEvent(self, ev):
        painter = QPainter(self)
        painter.begin(self)
        gradient = QLinearGradient(QRectF(self.rect()).topLeft(),QRectF(self.rect()).bottomLeft())
        gradient.setColorAt(0.0, Qt.black)
        gradient.setColorAt(0.4, Qt.gray)
        gradient.setColorAt(0.7, Qt.black)
        painter.setBrush(gradient)
        painter.drawRoundedRect(self.rect(), 10.0, 10.0)
        painter.end()

def main():

    app     = QApplication(sys.argv)
    widget = MyRoundWidget()

    widget.show()
    widget.raise_()

    sys.exit(app.exec_())
if __name__ == '__main__':
    main()

rawDescription: round edges corner on a QWidget in PyQt

description: Round edges corner on a QWidget in PyQt


code:
class NoteResource(ModelResource):
    tags = fields.ToManyField('myapp.api.resources.TaggedItemResource',
                              'tags')
    class Meta:
        resource_name = 'notes'
        queryset = Note.objects.all()

rawDescription: Django tastypie including generic foreign key field results


code:
texdoc = []  # a list of string representing the latex document in python

# read the .tex file, and modify the lines
with open('test.tex') as fin:
    for line in fin:
        texdoc.append(line.replace('width=.5\\textwidth', 'width=.9\\textwidth'))

# write back the new document
with open('test.tex', 'w') as fout:
    for i in range(len(texdoc)):
        fout.write(texdoc[i])

rawDescription: Adding text into .tex file with python

description: Adding text into .tex file with python


rawDescription: Convert a hashcode to its binary representation


code:
import example
c=example.MyCppClass()
c.MyFunction()

rawDescription: Passing reference from Python to c++ function wrapped with swig for return value


rawDescription: Pandas: Convert Timestamp to datetime.date


rawDescription: Appending a column in a pandas DataFrame based on a different DataFrame


code:
from BeautifulSoup import BeautifulSoup as bs
markup = """Link1 Link2 or Link3
A bad link*
some text* update*
other text right before link click here"""
soup = bs(markup)
TAGS_TO_EXTRACT = ('a',)
for tag in soup.findAll():
  if tag.name in TAGS_TO_EXTRACT:
    tag.extract()
soup

rawDescription: Python filter list to remove certain links from html source code


code:
from abc import ABCMeta

class MyMeta(ABCMeta):
    def __init__(cls, name, bases, dct):
        super(MyMeta, cls).__init__(name, bases, dct)
        cls.allInstances = set()

rawDescription: inheritance of set class attribute in python

description: Inheritance of set class attribute in python


code:
a = [3, 4, 6]
' OR '.join('Case: {}'.format(i) for i in a)

rawDescription: Python: concatenate string and int in a loop


code: Data.resample(tframe, base=24)

rawDescription: Python Pandas, Resampling only specific hours


code:
import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True #Let TeX do the typsetting
plt.rcParams['text.latex.preamble'] = [r'\usepackage{sansmath}',r'\sansmath']
#Force sans-serif math mode
plt.rcParams['font.family'] = 'sans-serif' # ... for regular text
plt.rcParams['font.sans-serif'] = 'Helvetica' # Choose a nice font here

rawDescription: Matplotlib greek symbols differ in show() and savefig()


code:
class Point:
    pass

p = Point()
id(p)
hex(id(p))
p
hex(id(p)) in repr(p)
# the other direction

repr(p).rpartition(' ')[-1][:-1]
hexadecimal_id = repr(p).rpartition(' ')[-1][:-1]
int(hexadecimal_id, 16)
int(hexadecimal_id, 16) == id(p)

rawDescription: Object's unique identifier (translate from hexadecimal into decimal)


code:
def valid_pct(val):
    if val.endswith("%"):
       return float(val[:-1])/100
    else:
       try:
          return float(val)
       except ValueError:
          raise ValidationError(
              _('%(value)s is not a valid pct'),
                params={'value': value},
           )

rawDescription: Django percentage form field

description: Django percentage form field


code:
from collections import defaultdict

d = defaultdict(int)
d.default_factory = float
setattr(d, "default_factory", complex)

rawDescription: Giving attributes to an object in Python


code:
def buildProtocol(self, addr):
    """
    Create an instance of a subclass of Protocol.

    The returned instance will handle input on an incoming server
    connection, and an attribute "factory" pointing to the creating
    factory.

    Alternatively, C{None} may be returned to immediately close the
    new connection.

    Override this method to alter how Protocol instances get created.

    @param addr: an object implementing L{twisted.internet.interfaces.IAddress}
    """
    p = self.protocol()
    p.factory = self
    return p

rawDescription: How do Twisted python Factory and Protocol interfaces work?


code:
from math import radians, cos, sin, sqrt

# Constants defined by the World Geodetic System 1984 (WGS84)
A = 6378.137
B = 6356.7523142
ESQ = 6.69437999014 * 0.001

def geodetic2ecef(lat, lon, alt=0):
    """Convert geodetic coordinates to ECEF."""
    lat, lon = radians(lat), radians(lon)
    xi = sqrt(1 - ESQ * sin(lat))
    x = (A / xi + alt) * cos(lat) * cos(lon)
    y = (A / xi + alt) * cos(lat) * sin(lon)
    z = (A / xi * (1 - ESQ) + alt) * sin(lat)
    return x, y, z

def euclidean_distance(distance):
    """Return the approximate Euclidean distance corresponding to the
    given great circle distance (in km).

    """
    return 2 * A * sin(distance / (2 * B))

rawDescription: Python - how to speed up calculation of distances between cities


code:
class MyObj(object): # see note 0
    a = 23
    def __init__(self, b):
        self.b = b
    def __add__(self, other):
        return self.b + int(other)  # see note 1
    def a_add(self, other):
        return MyObj.a + other

rawDescription: Are python object functions singletons?

description: Are python object functions singletons


code:
import numpy as np

names=np.array(['H', 'B', 'D', 'A', 'I', 'C', 'F'])
a=np.array([[ 0.,   2.4,  6.1,  3.2,  5.2,  3.9,  7.1],
 [2.4,  0.,   4.1,  1.2,  3.2,  1.9,  5.1],
 [6.1,  4.1,  0.,   3.1,  6.9,  2.8,  5.2],
 [3.2,  1.2,  3.1,  0.,   4.,   0.9,  4.1],
 [5.2,  3.2,  6.9,  4.,   0.,   4.7,  7.9],
 [3.9,  1.9 , 2.8,  0.9,  4.7,  0.,   3.8],
 [7.1,  5.1,  5.2,  4.1,  7.9,  3.8,  0. ]])

def pptable(x_axis,y_axis,table):
    def format_field(field, fmt='{:,.2f}'):
        if type(field) is str: return field
        if type(field) is tuple: return field[1].format(field[0])
        return fmt.format(field)

    def get_max_col_w(table, index):
        return max([len(format_field(row[index])) for row in table])

    for i,l in enumerate(table):
        l.insert(0,y_axis[i])

    x_axis.insert(0,' ')
    table.insert(0,x_axis)
    col_paddings=[get_max_col_w(table, i) for i in range(len(table[0]))]
    for i,row in enumerate(table):
        # left col
        row_tab=[str(row[0]).ljust(col_paddings[0])]
        # rest of the cols
        row_tab+=[format_field(row[j]).rjust(col_paddings[j])
                for j in range(1,len(row))]
        print(' '.join(row_tab))

x_axis=['x{}'.format(c) for c in names]
y_axis=['y{}'.format(c) for c in names]

pptable(x_axis,y_axis,a.tolist())

rawDescription: How to generate a clean x and y axis for a numpy matrix?

description: Generate a clean x and y axis for a numpy matrix


code:
data = [
  {u'Pub.': u'Penguin Books',
   u'Auther': u'Edward de BONO',
   u'Sr. No.': u'1',
   u'Name of Book': u'Six Thinking Hats'
  },
  ...
]

rawDescription: Parsing of table from .docx file

description: Parsing of table from .docx file


code: board[pos] = player[0]

rawDescription: Tic Tac Cover up!! Can't get the program to work correctly


code:
paramnames = ['parameter1', 'parameter2', 'parameter3']
parameters = ['Hello', 'Stack', 'Overflow']

for name, value in zip(paramnames, parameters):
    example(**{name: value})

def example(parameter1="", parameter2="", parameter3=""):
    print(parameter1)
    print(parameter2)
    print(parameter3)

rawDescription: refer to specific parameter by object in array?

description: Refer to specific parameter by object in array


code:
someset = {1, 2, 3}
someset.discard({1})
someset.discard(2)
someset

rawDescription: Make a copy of a set and exclude one item


code: m_hat, residuals, rank, singular_vals = np.linalg.lstsq(x, y)

rawDescription: Better way to create fit functions with changing number of parameters in Python with Scipy curve_fit


code:
def flatten(input):
    for x in input:
        if isinstance(x, list):
            for y in flatten(x):
                yield y
        else:
            yield x

result = list(flatten(c))

rawDescription: iterate dynamically over sub lists and store its values

description: Iterate dynamically over sub lists and store its values


code:
import collections
my_dict = collections.defaultdict(int)
with open("your_document") as f:
    for line in f:
        my_dict[line] += 1

rawDescription: How do I count occurences of a unique label?

description: Count occurences of a unique label


code:
class MyClass(object):
    def __init__(self, a=None, b=None):
        self.a = a
        self.b = b

    @property
    def c(self):
        return self.a + self.b

o = MyClass()
o.a = 1
o.b = 2
assert o.c == 3
o.a = 2
assert o.c == 4

rawDescription: derived value in a python map

description: Derived value in a python map


code:
import ctypes
libdl = ctypes.CDLL("libdl.so")
libdl.dlclose.argtypes = [ctypes.c_void_p]
so = ctypes.PyDLL("./mini.so")
so.PyInit_mini.argtypes = []
so.PyInit_mini.restype = ctypes.py_object
mini = so.PyInit_mini()
mini.version
del mini
libdl.dlclose(so._handle)
del so

rawDescription: How to Reload a Python3 C extension module?

description: Reload a Python3 C extension module


rawDescription: Python subprocess: How to run a python script using a different intepreter than the main thread


code: ''.join([c * i for c, i in zip(A, choice)])

rawDescription: Python multiplication of two list

description: Python multiplication of two list


code:
# Specify a title for the plot
axes_list[i].set_title('test')

# Specify the axes size and position
axes_list[i].set_position([left, bottom, width, height])

# The affect of the above set_position can be seen by turning the axes frame on, like so:
axes_list[i].set_frame_on(True)

rawDescription: Subplot of tables in pylab

description: Subplot of tables in pylab


code: client.put(url, {'node':add_node}, headers = jsontype)

rawDescription: Python - Updating a JSON REST array

description: Python - Updating a JSON REST array


code: dct.get('c', 'not found')

rawDescription: Testing presence and non-emptyness of dict element


code:
def implicit(a):
    n = a.shape[0]
    m = np.zeros_like(a)
    m = - n*a.T + n*np.diag(a)[:,newaxis]
    m += (a.T[newaxis,...] - a[...,newaxis]).sum(1)
    return m

rawDescription: Numpy matrix operations

description: Numpy matrix operations


rawDescription: Combining different elements of array in Numpy while doing vector operations


code:
np.where((dists >= r) & (dists <= r + dr))
dists[np.where((dists >= r) & (dists <= r + dr))]

rawDescription: Numpy where function multiple conditions


code:
from nltk.book import *
from nltk.util import tokenwrap
from nltk.compat import Counter

word = 'monstrous'
num = 20

text1.similar(word)

wci = text1._word_context_index._word_to_contexts

if word in wci.conditions():
            contexts = set(wci[word])
            fd = Counter(w for w in wci.conditions() for c in wci[w]
                          if c in contexts and not w == word)
            words = [w for w, _ in fd.most_common(num)]
            # print(tokenwrap(words))

print(fd)
print(len(fd))
print(fd.most_common(num))

rawDescription: The similar method from the nltk module produces different results on different machines. Why?


code:
X_flattened = X.ravel()
Y_flattened = Y.ravel()

rawDescription: Vectorize python function

description: Vectorize python function


code: result = sum((-1)**i * 1.0/(2*i + 1) for i in xrange(s))

rawDescription: Plus and minus sequence in Python

description: Plus and minus sequence in Python


code:
import shlex
import random
from subprocess import Popen, PIPE

passphrase = '%030x' % random.randrange(16**30)
source_filename = '/tmp/somefile'
cmd = 'gpg --batch --symmetric --cipher-algo AES256 --passphrase-fd 0 --output - {}'.format(source_filename)

# error handling omitted
p = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE)
encrypted_data = p.communicate(passphrase.encode())[0]

# Decryption - should work for Python 2 & 3
import os

r, w = os.pipe()    # pipe for sending passphrase from parent to child
try:
    os.set_inheritable(r, True)
except AttributeError:      # new in version 3.4
    pass
cmd = 'gpg --batch --decrypt --passphrase-fd {}'.format(r)
p = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE, close_fds=False)
os.close(r)    # closes fd in parent, child needs it
f = os.fdopen(w, 'w')
f.write(passphrase + '\n')    # '\n' seems required for Python 2 ???
f.close()
decrypted_data, stderr = p.communicate(encrypted_data)

# check that data was successfully roundtripped
assert open(source_filename).read() == decrypted_data.decode()

rawDescription: Encrypt file with GPG in python 3 with subprocess


code: df=pd.read_csv("file.csv", sep=',\s+', quoting=csv.QUOTE_NONE, header=None, decimal=',', parse_dates=[0], encoding="mbcs")

rawDescription: Read csv (comma separated file) with values in quotation marks and comma as a decimal point


code:
import csv
with open('a.csv','r') as f , open('b.csv','w') as of:
    reader = csv.reader(f, delimiter=' ')
    writer = csv.writer(of, delimiter=' ')
    for lines in reader:
            key = lines.pop(0)
            for i in range(0,len(lines),2):
                    writer.writerow([key, lines[i], lines[i+1]])

rawDescription: Convert adjacency matrix to a csv file

description: Convert adjacency matrix to a csv file


code: [item.findtext("optional_element", default="") for item in tree.findall("item")]

rawDescription: Python XPath include missing elements

description: Python XPath include missing elements


code:
pButton = Button(root, text="Play", command="playButton")
pButton.grid(row=1)
pButton.config(image=PlayUp)

rawDescription: 'NoneType' object has no attribute 'config'


code:
# ./test.py emaillist.txt
zokomov@gmail.com

False
johnson9010@yahoo.com

False

rawDescription: Make python script to wait for return from module function


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

import http.server
import os
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

class SourceViewer(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        path = os.path.join(os.getcwd(), self.path[1:])
        if os.path.exists(path) and path.endswith('.py'):
            with open(path) as file:
                code = file.read()
                hl = highlight(code, PythonLexer(), HtmlFormatter(noclasses=True, linenos='table'))
                self.send_response(200)
                self.end_headers()
                self.wfile.write(bytes(hl, 'UTF-8'))
                return
        else:
            super().do_GET()

if __name__ == "__main__":
    server = http.server.HTTPServer(('localhost', 8080), SourceViewer)
    server.serve_forever()

rawDescription: pydoc-like program to browse content/code of Python files in a browser?

description: Pydoc-like program to browse content/code of Python files in a browser


rawDescription: Different intervals for Gauss-Legendre quadrature in numpy


code:
import win32com.client
oWS = win32com.client.Dispatch("WScript.Shell")
print("A", "mother starts child")
oEx = oWS.Exec("cscript ..\\vbs\\child.vbs")
while not oEx.Stdout.AtEndOfStream:
   print(oEx.Stdout.ReadLine())
print("B", "mother done")

rawDescription: Retrieving the command output of a hidden console?


rawDescription: how to variate a parameter in an equation python

description: Variate a parameter in an equation python


code:
dark = True
def isdark():
     return dark

if isdark():
    print('bt')
else:
     print('dasd')

rawDescription: Python3 defining room conditions

description: Python3 defining room conditions


code:
from timeit import timeit
timeit("s.rsplit('.', 1)[0]", "s = 'test.test1.test2'")
timeit("s.rpartition('.')[0]", "s = 'test.test1.test2'")

rawDescription: Remove the last part of string separated with dot in Python


code:
key = 1
base_url = 'www.xyz.com/'

rawDescription: Passing a parameter between python classes


code:
# Super-efficient version
#  for playing with million-digit palindromes

def str_lt(x, y):
    """
    Take two integer strings, `x` and `y`,
      return int(`x`) < int(`y`)
    """
    return len(x) < len(y) or x < y

def str_add_1(n):
    """
    Given an integer string `n`,
      return str(int(n) + 1)
    """
    # find the first non-9 digit, starting from the right
    for i in range(len(n) - 1, -1, -1):
        if n[i] != '9':
            return n[:i] + str(int(n[i]) + 1) + '0' * (len(n) - i - 1)
    # string was all 9s - overflow
    return '1' + '0' * len(n)

def next_palindrome(n):
    """
    For non-negative integer `n` (as int or str)
      find the first integer p such that p > n and p is palindromic
    Return str(p)

    Note: `n` must be well-formed, ie no leading 0s or non-digit characters
    """
    # Make sure n is a string
    if not isinstance(n, str):
        n = str(n)

    # There are three forms of palindrome:
    #           single digit,      x    (ab == '')
    #  even number of digits,   abba    ( x == '')
    #   odd number of digits,  abxba    ( x is single digit)
    #
    if len(n) == 1:
        # take care of single digit case
        return '11' if n == '9' else str_add_1(n)
    else:
        # There are six possibilites for p:
        #
        #  (1)  abqr   <  abba   -> p = abba
        #  (2)  abqr  >=  abba   -> p = a(b+1)(b+1)a   (with carries as needed)
        #  (3)  abqr  ==  9999   -> p = 10001          (carry results in overflow)
        #
        #  (4)  abxqr  < abxba   -> p = abxba
        #  (5)  abxqr >= abxba   -> p = ab(x + 1)ba    (with carries as needed)
        #  (6)  abxqr == 99999   -> p = 100001         (carry results in overflow)
        #
        # Find ab, x, qr
        half = len(n) // 2
        ab = n[     : half]
        x  = n[ half:-half]    # a 0- or 1-digit string
        qr = n[-half:     ]

        ba = ab[::-1]
        if str_lt(qr, ba):
            # solve cases (1) and (4)
            return "".join([ab, x, ba])

        if x == '9':
            # do manual carry from x
            ab1 = str_add_1(ab)
            ba1 = ab1[::-1]
            if len(ab1) > len(ab):
                # carry results in overflow - case (6)
                return ab1 + ba1
            else:
                # carry but no overflow - case (5)
                return "".join([ab1, '0', ba1])

        if x:
            # no carry - case (5)
            return "".join([ab, str_add_1(x), ba])

        # x == ''
        ab1 = str_add_1(ab)
        ba1 = ab1[::-1]
        if len(ab1) > len(ab):
            # carry results in overflow - case (3)
            return ab1[:-1] + ba1
        else:
            # no overflow - case (2)
            return ab1 + ba1

rawDescription: Speeding Up Python 3.4 Code

description: Speeding Up Python 3.4 Code


rawDescription: Python 2D array with same values

description: Python 2D array with same values


rawDescription: Python standard library function for rearranging a list


code:
def circle(x, y, ans):
    ...
    tr.write(ans, font=("Arial", 20))
    return something

C = [{}, {"rand": random.randint(1, 100)}, {"rand": random.randint(1, 100)}]
C[1]["circle"] = circle(150, 245, C[1]["rand"])
C[2]["circle"] = circle(245, 150, C[2]["rand"])

# C is now [None,
#           {"rand": *C1's random number*, "circle": *What circle returned*},
#           {"rand": *C2's random number*, "circle": *What circle returned*}]

rawDescription: Get a parameter

description: Get a parameter


code:
def sin(x, terms=4):
    ans = 0
    for n in range(terms):
        ans += (math.pow(-1, n)/math.factorial(2*n + 1)) * math.pow(x, 2*n + 1)
    return ans

rawDescription: Not Getting Correct Answer for sine & cosine in Python


code:
def sequences(x):
    it = iter(x)
    prev, temp = next(it), []
    while prev is not None:
        start = next(it, None)
        if prev + 1 == start:
            temp.append(prev)
        elif temp:
            yield tuple(temp + [prev])
            temp = []
        prev = start

rawDescription: Finding groups of increasing numbers in a list


code:
for i in xrange(limit1):
    l.append('First index: %d, Second index: %d' % (i, 2*i))
    l.append('First index: %d, Second index: %d' % (i, 2*i+1))

rawDescription: Iterate with 2 Indexes Variable in Python


rawDescription: Add 30 minutes to a time read from a text file and compare against current time


code: cols = list(header.columns.values) #a list with headers

rawDescription: Pandas - read_table read selected lines

description: Pandas - read_table read selected lines


code: mat[y][x].color = 'black'

rawDescription: I want to have a 2D list with value and color attributes in Python


code:
import decimal

def f1(x):
    ''' Definition by OP '''
    strprime = ""
    while x > 0:
        strprime += str(x%10)
        x //= 10
    return strprime

def digits(x):
    while x > 0:
        yield x % 10
        x //= 10

def f2(x):
    ''' Using string.join() to avoid repeated string concatenation '''
    return "".join((chr(48 + d) for d in digits(x)))

def f3(x):
    ''' Plain str() '''
    return str(x)

def f4(x):
    ''' Using Decimal class'''
    return decimal.Decimal(x).to_eng_string()

x = 2**100

if __name__ == '__main__':
    import timeit
    for i in range(1,5):
        funcName = "f" + str(i)
        print(funcName+ ": " + str(timeit.timeit(funcName + "(x)", setup="from __main__ import " + funcName + ", x")))

rawDescription: How can I convert an absolutely massive number to a string in a reasonable amount of time?

description: Convert an absolutely massive number to a string in a reasonable amount of time


code:
if a[flicker - 2] in vowels and a[flicker -1] in'r':
    final = str(a[:flicker-2])+'r'
    flicker = len(str(final))

if flicker < 6:
    final = 'My'+final

rawDescription: How to continue from the 'if' statement to the 'elif' in Python?

description: Continue from the 'if' statement to the 'elif' in Python


code:
def conv(s):
    try:
        return int(s)
    except ValueError:
        return s

data={}
with open(fn_in, 'rb') as fin:
    reader=csv.reader(fin, delimiter='\t')
    for row in reader:
        key=row[-1]
        data.setdefault(key, []).append([conv(row[2]), conv(row[3])])

maxes={}
mins={}
for k, li in data.items():
    maxes[k]=max(li, key=max)
    mins[k]=min(li, key=min)

with open(fn_out, 'wb') as fout, open(fn_in, 'r') as fin:
    reader=csv.reader(fin, delimiter='\t')
    writer=csv.writer(fout, delimiter='\t')
    for row in reader:
        key=row[-1]
        tr=[conv(row[2]), conv(row[3])]
        if tr==maxes[k]:
            tgt=max(tr)
            row[2:4]=[e+10 if e==tgt else e for e in tr]
        if tr==mins[k]:
            tgt=min(tr)
            row[2:4]=[e-20 if e==tgt else e for e in tr]

        writer.writerow(row)

rawDescription: Finding min() and max() of Python dictionary key-value pair complexes


rawDescription: Python - automating MySQL query: passing parameter


code:
for row in l:
    row.append(13)

rawDescription: Adding column In table with Python

description: Adding column In table with Python


code:
output = {index: row._asdict()
          for index, row
          in enumerate(DBSession.query(Client.id, Client.name)
                                .filter(q in Client.name))}

rawDescription: Create dictionary of a sqlalchemy query object in Pyramid


code:
def message(self, msg):
    if msg['type'] in ('normal', 'chat'):
        msg.reply("Thanks for sending:\n%s" % msg['body']).send()

rawDescription: Sleekxmpp Managing Stanzas

description: Sleekxmpp Managing Stanzas


code:
import sys

with open('/volumes/ramdisk/python.arch.log', 'a') as f:
    f.write('sys.maxsize = %s\n' % sys.maxsize)

rawDescription: Mac 10.8 + Python Scripts: How best to control the python architecture in scheduling?


code: k = lambda x: x[1]

rawDescription: Sorting or Finding Max Value by the second element in a nested list. Python


code:
class CounterThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.count = 0
        self.start()

    def run(self):
        while self.count < COUNTLIMIT:
            time.sleep(0.1)
            self.count += 0.1

        #Call function to turn off light here
        return

    def newSig(self):
        self.count = 0

rawDescription: How do I schedule a one-time script to run x minutes from now? (alternative for 'at')

description: Schedule a one-time script to run x minutes from now? (alternative for 'at')


code:
a = np.arange(10)
np.where(a > 5) # give me all indices where the value of a is bigger than 5
# a > 5 is a boolean mask like [False, False, ..., True, True, True]
# (array([6, 7, 8, 9], dtype=int64),)

rawDescription: Basics of numpy where function, what does it do to the array?


code:
from datetime import datetime
from dateutil import rrule
import pytz

def next_real_7am(dt):
    tzi = dt.tzinfo

    dt_naive = dt.replace(tzinfo=None)
    rr = rrule.rrule(freq=rrule.DAILY, byhour=7, dtstart=dt_naive)

    for ndt in rr:
        localize = getattr(tzi, 'localize', None)
        if tzi is not None and localize is not None:
            try:
                ndt = localize(ndt, is_dst=None)
            except pytz.AmbiguousTimeError:
                return min([localize(ndt, is_dst=True),
                            localize(ndt, is_dst=False)])
            except pytz.NonExistentTimeError:
                continue
        else:
            ndt = ndt.replace(tzinfo=tzi)

        return ndt

KWA = pytz.timezone('Pacific/Kwajalein')

dtstart = KWA.localize(datetime(1969, 9, 29, 18))
dt7 = next_real_7am(dtstart)

print(dt7.tzname())         # Should be MHT, before the transition

dtstart = KWA.localize(datetime(1993, 8, 19, 18))  # There was no 8/20 in this zone
dt7 = next_real_7am(dtstart)
print(dt7)                  # Should be 1993-8-21 07:00:00

rawDescription: How do I find the next 7am in a timezone

description: Find the next 7am in a timezone


code:
a
a=a.T
a

rawDescription: Flip x and y axes for Matplotlib imshow()


rawDescription: How to perform two inner joins in a queryset in Django

description: Perform two inner joins in a queryset in Django


rawDescription: I want to decorate a method in a class but without editing class.py -- details inside


code:
regex = re.compile('TOTAL:.*?C2(\n|$)', re.DOTALL)
regex.sub("XXX", content)

rawDescription: dealing with \n characters at end of multiline string in python

description: Dealing with \n characters at end of multiline string in python


code:
def transpose_matrix(matrix):
    zip(*matrix) # ignore result of computation
    return matrix # return argument unchanged

rawDescription: Transpose this matrix(python3)

description: Transpose this matrix(python3)


rawDescription: Pandas, move one of multi-index on top of multi-column indexes


code:
names_width = max(len(name) for name in namesList)
stock_width = max(len(stock) for stock in stockList)

rawDescription: Formatting Text in a Table in Python

description: Formatting Text in a Table in Python


rawDescription: I want a button on my website that will execute a python script


code:
cliproc.stdin.write("LIST objects OUTPUT csv NAME")
cliret = cliproc.stdout.readline()

rawDescription: Interactively writing/reading from an external program


rawDescription: Why I can't read anything with File.open in python when I open the file to write first?


code:
def my_function(dna):
    return 100 * len(dna.replace('A','').replace('T',''))/len(dna)

with open('rosalind.txt', 'r') as ros:
    with open('rosalind_clean.txt', 'w') as output:
        for line in ros:
            if line.startswith('>'):
                output.write('\n'+line.strip())
            elif line.strip():
                output.write(line.strip())

with open('rosalind_clean.txt', 'r') as ros:
    rosa = {line[1:].split(' ')[0]:my_function(line.split(' ')[1].strip()) for line in ros if line.strip()}
top_key = max(rosa, key=rosa.get)
print(top_key, rosa.get(top_key))

rawDescription: Wit's end with file to dict

description: Wit's end with file to dict


code:
for region, directory_ids in direct_dict.iteritems():
    for dir in directory_ids:
        def done_callback(result):
            pass  # process result...

        pool.apply_async(describe_with_directory_workspaces,
                         (region, dir, username),
                         done_callback)

rawDescription: Multithreading in python 2.7

description: Multithreading in python 2.7


code:
s = "%0 is a %1 %2"
args = ("Ram", "Good")
sub = re.sub(r"%\d+\b", lambda x: "{"+x.group()[1:]+"}", s,count=len(args)).format(*args)

print(sub)

rawDescription: String formatting : Replace "%0 %1 %2" with tuple with 0,1,2 indexes


rawDescription: django sort the query elements in a weekly monthly daily fashion

description: Django sort the query elements in a weekly monthly daily fashion


code:
for k in my_dict.keys():
    file_out.write("{0},\"{1}\",\"{2}\"\n".format(
        k,
        ','.join([x for x in my_dict[k][0]]),
        ','.join([x for x in my_dict[k][1]])
    ))

rawDescription: shorten csv file based on rules python

description: Shorten csv file based on rules python


code:
html_tags = [{i:map(lambda x: '@{}="{}"'.format(*x), j) if i=='attribs' else j for i,j in html_tags[0].items()}]
html_tags

rawDescription: How to do two-level nested map

description: Do two-level nested map


rawDescription: How can i query for objects in current year , current month in django

description: Query for objects in current year , current month in django


rawDescription: Fastest way to filter a numpy array by a set of values


code: print(smth, flush=True)

rawDescription: Python print on same line after sleep

description: Python print on same line after sleep


code:
from xml.etree import cElementTree as ET

from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context, loader

def xml_view(request):
    xmlData = """<?xml version="1.0" encoding="utf-8"?>
    <django-objects version="1.0">
    <object model="task.task" pk="4">
    <field name="name" type="CharField">foo</field>
    <field name="mission_id" type="IntegerField">1</field>
    <field name="parent_task_id" type="IntegerField">20</field>
    </object>
    <object model="task.task" pk="7">
    <field name="name" type="CharField">bar</field>
    <field name="mission_id" type="IntegerField">2</field>
    <field name="parent_task_id" type="IntegerField">10</field>
    </object></django-objects>"""

    xml = ET.fromstring(xmlData)

    fields = []
    for obj in xml.iter("object"):
        fields.append({'name': obj.find("field[@name='name']").text,
                       'mission_id': obj.find("field[@name='mission_id']").text,
                       'parent_task_id': obj.find("field[@name='parent_task_id']").text,
                       })

    t = loader.get_template('your_app/xml_view.html')
    c = Context({'elem_list': fields})
    return HttpResponse(t.render(c))

rawDescription: Translate xml string to Python list

description: Translate xml string to Python list


rawDescription: Return the closest value in a list

description: Return the closest value in a list


code:
beginPosit = tempans.index('007 A000000 Y')
endPosit = min([i for i, item in enumerate(tempans) if '008 ' in item])

rawDescription: Program Control-Flow in Python

description: Program Control-Flow in Python


rawDescription: Histogram which do not use bin intervals but concrete values


code:
def get_serial_port():
    return "/dev/"+os.popen("dmesg | egrep ttyACM | cut -f3 -d: | tail -n1").read().strip()

rawDescription: How to get arduino port with python

description: Get arduino port with python


code: decoded_clean_pk = clean_pk.decode('base64', 'strict')

rawDescription: Python: base64.b64decode() vs .decode?

description: Python: base64.b64decode() vs .decode


rawDescription: Python And Date Formats

description: Python And Date Formats


code:
scores = scores.reset_index()
#Plot a histogram with all scores:
scores.hist()
#Plot a histogram with specific cells:
cells = your_map['tissue_1']  #e.g. cells = ['LN18', 'DU145']
scores[scores.cell.isin(cells)].hist()
#or get the score array and input this to your plotting functions
score_array = scores[scores.cell.isin(cells)].score.values

rawDescription: Set DataFrame row index to a different column


code:
import pprint
pprint.pprint(alist)  # Assuming you only replaced the first element:

rawDescription: What does Python mean by printing "[...]" for an object reference?


rawDescription: python + matplotlib: how can I change the bar's line width for a single bar?

description: Python + matplotlib: how can I change the bar's line width for a single bar


code: block3[:] = np.rot90(block3.copy(),-1)

rawDescription: transpose/rotate a block of a matrix in python

description: Transpose/rotate a block of a matrix in python


rawDescription: How to edit audio files in Python?

description: Edit audio files in Python


code:
ip_vlan1 = jinja2.Template('10.10.{{id+100}}.5')
ip_vlan2 = jinja2.Template('10.11.{{2*id+1}}.6')
ip_vlan1.render(id=3)
ip_vlan2.render(id=5)

rawDescription: How to calculate value for a expression in a string, then return a new string?

description: Calculate value for a expression in a string, then return a new string


code:
def foobar_py(mixinsize, count, xs, mixins, acc):
    for i in xrange(count):
        k = xs[i]
        for j in xrange(mixinsize):
            acc[j+k] += mixins[i][j]

# covert NumPy arrays to lists
_xs = map(int,xs)
_mixins = [map(float,mixins[i,:]) for i in xrange(count)]
_acc = map(float,acc)

t6 = clock()
foobar_py(mixinsize, count, _xs, _mixins, _acc)
t7 = clock()
print("elapsed time with plain Python: %g ms" % (1000*(t7-t6),))

rawDescription: How to shove this loop into numpy?

description: Shove this loop into numpy


code:
import operator
values = sorted(d.items(), key=operator.itemgetter(1))

rawDescription: Ascending Sort of Float Dictionary Values


code: o = [int(idx == i) for idx, l in enumerate(input_seq) for _ in l]

rawDescription: Python map a value to each i-th sublist's element


rawDescription: Recursive "all paths" through a list of lists - Python


code:
@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    # Set the identity user object
    current_user = session.get('user', False)
    if not current_user:
        return False
    identity.user = current_user

    # Add the UserNeed to the identity
    if hasattr(current_user, 'id'):
        identity.provides.add(UserNeed(current_user.id))

    # Assuming the User model has a list of groups, update the
    # identity with the groups that the user provides
    if hasattr(current_user, 'groups'):
        groups = user.Group.query.filter(user.Group.users.any(id=current_user.id)).all()
        for group in groups:
            identity.provides.add(RoleNeed(group.name))

rawDescription: python group/user management packages

description: Python group/user management packages


code:
{'description': u'1 CD DVDRip - x264 AAC Stereo Audio English & Arabic Subtitles Specs: Format : Matroska File size : 701 MiB Duration : 2h 9mn Overall bit rate : 756 Kbps Encoded date : UTC 2015-04-14 21:26:04 Video Format : AVC Format/Info : Advanced Video Codec Format profile : [email protected] /* <![CDATA[ */!function(){try{var t="currentScript"in document?document.currentScript:function(){for(var t=document.getElementsByTagName("script"),e=t.length;e--;)if(t[e].getAttribute("cf-hash"))return t[e]}();if(t&&t.previousSibling){var e,r,n,i,c=t.previousSibling,a=c.getAttribute("data-cfemail");if(a){for(e="",r=parseInt(a.substr(0,2),16),n=2;a.length-n;n+=2)i=parseInt(a.substr(n,2),16)^r,e+=String.fromCharCode(i);e=document.createTextNode(e),c.parentNode.replaceChild(e,c)}}}catch(u){}}();/* ]]> */ Nominal bit rate : 687 Kbps Width : 640 pixels Height : 272 pixels Display aspect ratio : 2.35:1 Frame rate mode : Constant Frame rate : 23.976 fps Bit depth : 8 bits Scan type : Progressive Audio Format : AAC Format profile : LC Channel(s) : 2 channels Channel positions : Front: L R Sampling rate : 48.0 KHz Language : Hindi Subtitle Language : English & Arabic Chapters : YES SAMPLE Included A DDR Exclusive Release 1 posted by mard22 (2015-04-14 23:37:41) thankssssss 2 posted by harpreets088 (2015-04-15 04:09:57) Thanks 3 posted by j0k3r777 (2015-04-15 05:23:49) thank you dude 4 posted by DEVENDRA_SINGH140992 (2015-04-15 06:25:21) PLS UPLOAD Badlapur 2015 720p BRRIP magic mike xxl music community Flying Swords of Dragon Gate X-Art - Daphne, Katia ado.net sex Taylor Swift - I Knew You Were Trouble arremessa teu bumbum na vara dvd dava foxx interstellar urbin4hd ETTV adult ja rule mary j blige iyisin tabi the blacllist porn peter+andre+big+night Shyla.Stylez, Gianna Michaels you mad or nah x men first class 2011 zuma \u03bf\u03c4\u03b1\u03bd \u03b1\u03b3\u03b3\u03b5\u03bb\u03b7 \u03ba\u03bb\u03b5\u03bd\u03b5 \u03c0\u03b1\u03c0\u03b1\u03c1\u03b9\u03b6\u03bf\u03c5 mistresst truffle butter Nicki Minaj Joanna Angel, Small Hands, Scarlet LaVey ETRG 7 data recovery Hawaii.Five-0 doom 2005 xvid Rang Rasiya picasa39 el-nino-2014 vikings S02E06 souchon voulzy derriere les mots anime straponcum mukti bengali movie movie might med s02e13 The Night That Panic America riley jenner the flash scarface ft lil wayne & bun b forgot about me down teugu 50 cent \u0627\u0646\u0633 \u0643\u0631\u064a\u0645 \u0643\u0644 \u0627\u0644\u0639\u0645\u0631 \u0639\u062d\u0633\u0627\u0628\u0643 \u062a\u062d\u0645\u064a\u0644 YIFY big sean idfwu farrah flower software son of satiyamurti telugu full movie DDR jovanotti si alza il vento omar ruiz el americano 2015 hindi movies video mummyefaa blacked Jillian Janson Yellow Claw/Ayden - Till It Hurts Resident evil animated Monitoring',
     'name': u'Badlapur *2015* 1CD - x264 - DvDrip - AAC - MSubs [DDR] torrent',
     'size': u'708.25 MB',
     'url': 'http://extratorrent.cc/torrent/4140564/Badlapur+*2015*+1CD+-+x264+-+DvDrip+-+AAC+-+MSubs+%5BDDR%5D.html'}

rawDescription: Crawling extratorrent.cc using Scrapy

description: Crawling extratorrent.cc using Scrapy


code: new_re_df = [s.iloc[np.where(ts.astype(int) == int(i))] for i in ts]

rawDescription: Convert float Series into an integer Series in pandas


code:
import sklearn.feature_extraction
feature_dictionary = [{"feat1": 1.5, "feat10": 0.5}, {"feat4": 2.1, "feat5": 0.3, "feat7": 0.1}, {"feat2": 7.5}]

v = sklearn.feature_extraction.DictVectorizer(sparse=True, dtype=float)
v.vocabulary_ = {'feat0': 0, 'feat1': 1, 'feat2': 2, 'feat3': 3, 'feat4': 4, 'feat5': 5,
                 'feat6': 6,  'feat7': 7, 'feat8': 8, 'feat9': 9, 'feat10': 10}
v.feature_names_ = ['feat0', 'feat1', 'feat2', 'feat3', 'feat4', 'feat5', 'feat6', 'feat7',
                    'feat8', 'feat9', 'feat10']

X = v.transform(feature_dictionary)
print('v.vocabulary_ : {0} ; v.feature_names_: {1}'.format(v.vocabulary_, v.feature_names_))
print('X: \n{0}'.format(X))

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


code: find_element(By.ID, 'submit')

rawDescription: Selenium Webdriver Python page object MainPageLocators class why does it use an asterisk infront of the class name


code:
people = {}
people['john'] = Person('john')

def removePerson(personName):
    del people[personName]

removePerson('john')

rawDescription: How to give object away to python garbage collection?

description: Give object away to python garbage collection


code:
#!/usr/bin/env python3

def decorate(cls):
    print(cls)
    return cls

@decorate
class Foo: pass

rawDescription: Is it possible to decorate classes in Python?


code:
bytes(double_array)
double_array[:]

rawDescription: How to interpret a integer as a float

description: Interpret a integer as a float


code:
foo[:-2]  #return all items up to -2 index(i.e 0th index), so empty list
foo[:-1]
foo[:2]

rawDescription: Django slice template tag not working with negative indices


code:
# empty frame with desired index
rs = pd.DataFrame(index=df.resample('15min').iloc[1:].index)

# array of indexes corresponding with closest timestamp after resample
idx_after = np.searchsorted(df.index.values, rs.index.values)

# values and timestamp before/after resample
rs['after'] = df.loc[df.index[idx_after], 'Values'].values
rs['before'] = df.loc[df.index[idx_after - 1], 'Values'].values
rs['after_time'] = df.index[idx_after]
rs['before_time'] = df.index[idx_after - 1]

#calculate new weighted value
rs['span'] = (rs['after_time'] - rs['before_time'])
rs['after_weight'] = (rs['after_time'] - rs.index) / rs['span']
# I got errors here unless I turn the index to a series
rs['before_weight'] = (pd.Series(data=rs.index, index=rs.index) - rs['before_time']) / rs['span']

rs['Values'] = rs.eval('before * before_weight + after * after_weight')

rawDescription: Python regularise irregular time series with linear interpolation


code:
def func(df2):
    df1 = df2.reset_index(level=1, drop=True)
    columns = df1.loc['key1'].nlargest(2).index.tolist()
    columns.append(df1.loc['key2'][df.columns.difference(columns)].idxmax())
    return df1.loc['rtr', columns]

df.groupby(level=1).apply(func)

rawDescription: Sequential sorting in multi-indexed Pandas DataFrame


code: processedImage = foo.doSomething(image) # Where the argument "image" is a OpenCV numpy image.

rawDescription: Writing Python bindings for C++ code that use OpenCV


code:
def autolabel(rects):
    # Attach some text labels.
    for rect in rects:
        ax.text(rect.get_x() + rect.get_width() / 2.,
                rect.get_y() + rect.get_height() / 2.,
                '%f'%rect.get_height(),
                ha = 'center',
                va = 'center')

rawDescription: Y values on each stacked bar using matplotlib


code: np.sum((A - A.mean(0))*(B - B.mean(0)),0)/B.size

rawDescription: Covariance with a columns

description: Covariance with a columns


code: db.collection.distinct("_id", {"wishlist": ["feldon", "c15", "sp"]})

rawDescription: converting mongodb arrays into python arrays

description: Converting mongodb arrays into python arrays


code:
"""@package docstring
Documentation for this module.

More details.
"""

def func():
    """Documentation for a function.

    More details.
    """
    pass

rawDescription: Can I document Python code with doxygen (and does it make sense)?

description: Document Python code with doxygen (and does it make sense)


code:
t.data = u"The text\u0180content"
dom.parseString(e.toxml('utf8')).toxml('utf8')

rawDescription: How to ensure xml.dom.minidom can parse its own output?

description: Ensure xml.dom.minidom can parse its own output


rawDescription: Flask jsonify: key starting with digit

description: Flask jsonify: key starting with digit


rawDescription: exec a global variable from an extern module

description: Exec a global variable from an extern module


code:
g = gimp.GroupLayer(img)
pdb.gimp_image_insert_layer(img, g, None, 0)

rawDescription: GIMP Python-fu nested group layers

description: GIMP Python-fu nested group layers


code:
operator.delslice(a, b, c)
operator.__delslice__(a, b, c)

rawDescription: Check for [] operator

description: Check for [] operator


rawDescription: How to make python's argparse generate Non-English text?

description: Make python's argparse generate Non-English text


code:
import gc

def objects_by_id(id_):
    for obj in gc.get_objects():
        if id(obj) == id_:
            return obj

rawDescription: Why can't we access an object using its address in Python?


code:
tamil_letter_ma = "\u0bae"
marked_text = r"\a%s\bthe Tamil\cletter\dMa\e" % tamil_letter_ma
marked_text

rawDescription: python 3 raw unicode strings

description: Python 3 raw unicode strings


code:
class MyRandomSequence(tempfile._RandomNameSequence):
    characters = "xyz123"

tempfile._name_sequence = MyRandomSequence()
# make your temporary file

rawDescription: change character set for tempfile.NamedTemporaryFile

description: Change character set for tempfile.NamedTemporaryFile


code:
pprint.pprint(group_by_keys(dicts, ('type',)))

pprint.pprint(group_by_keys(dicts, ('type', 'color')))

rawDescription: How to group an array by multiple keys?

description: Group an array by multiple keys


code:
def f2(seq):
    near_equal = lambda x, y: abs(x - y) < 1.e-8
    checked = []
    for e in seq:
        if all([not near_equal(e, x) for x in checked]):
            checked.append(e)
    return np.asarray(checked)

rawDescription: Rounding in Python NumPy when adding nodes in Networkx


code:
list1
nlist
[list1[i] is nlist[i] for i in range(len(list1))]
list1[0]['newkey'] = 'value'
list1[0]
nlist[0]

rawDescription: Join list of dict with a dict in python

description: Join list of dict with a dict in python


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator

fig = plt.figure(1, [5,4])
ax = fig.add_subplot(111)

ax.plot( range(1,100) , range(1,100) ,  color='#aaaaff')
ax.set_xscale('log')
# This is default, so play with it
ax.xaxis.set_major_locator(LogLocator(base = 10.0))
plt.show()

rawDescription: xaxis numbers not printed on log-scale plot

description: Xaxis numbers not printed on log-scale plot


code: #! /usr/bin/python -u

rawDescription: SGE script: print to file during execution (not just at the end)?


code:
centroid = operator.itemgetter(1)
point = operator.itemgetter(0)

all_neighbours.sort(key = centroid)

rawDescription: Group list by values and keep both

description: Group list by values and keep both


code:
def f(x):
    c = common_helper_function(x)
    return a_complex_function(x,c), another_complex_function(x,c)

rawDescription: How to figure which returned values a function's call actually uses?

description: Figure which returned values a function's call actually uses


code:
['First line.',
 'Second line.',
 'The third line is a very long line, which I would like to somehow wrap; wrap at',
 '80 characters - or less, or more! ... can it really be done ??']

rawDescription: Wrap multiline string (preserving existing linebreaks) in Python?


code:
import numpy as np
import collections as c

# some arbitrary lookup table
a = c.defaultdict(int)
a[1] = 2
a[2] = 3
a[3] = 2
a[4] = 3

@np.vectorize
def func(x,y):
    # some arbitrary function
    return a[x] + a[y]

X,Y = np.mgrid[1:3, 1:4]
X = X.T
Y = Y.T

Z = func(X, Y)

rawDescription: How do I apply some function to a python meshgrid?

description: Apply some function to a python meshgrid


code:
from django.contrib.auth.models import User
from django.http import HttpResponse

def view_inside_a_view(request):
    return HttpResponse('hello %s' % request.user)

def view(request):
    # change to dummy user, or whoever
    request.user = User.objects.get(id=1)
    response = view_inside_a_view(request)
    return HttpResponse('rendered view: %s' % response.content)

rawDescription: Creating a fake request to render a view to a string in django


code: words_par.startswith("P1" or "P2" or "P3")

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
x[:] = np.where(mask, np.nan, r * np.cos(t))
y[:] = np.where(mask, np.nan, r * np.sin(t))

rawDescription: Log scale on radial contour plot with matplotlib


code: to_bits(b'Testing Temp "Testing"')

rawDescription: Binary I/O in Python

description: Binary I/O in Python


code:
# Add this line
from matplotlib.transforms import BlendedGenericTransform

# Edit the function call to use the BlendedGenericTransform
ax.legend(loc='upper center',
          ncol=7,
          labelspacing=-0.7,
          columnspacing=0.75,
          fontsize=8,
          handlelength=2.6,
          markerscale=0.75,
          bbox_to_anchor=(0.5, -0.05),
          bbox_transform=BlendedGenericTransform(fig.transFigure, ax.transAxes))

rawDescription: matplotlib: combine different figures and put them in a single subplot sharing a common legend

description: Matplotlib: combine different figures and put them in a single subplot sharing a common legend


code:
list1 = [4, 6, 4]
list2 = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

# Create an iterator for the list
it = iter(list2)

from itertools import islice
print([tuple(islice(it, item)) for item in list1])

rawDescription: How can I slice a list based on the lengths from another list?

description: Slice a list based on the lengths from another list


code:
# __init__.py
from school.student import Student
from school.classroom import ClassRoom
from school.teacher import Teacher

rawDescription: How to group mutliple modules into a single namespace?

description: Group mutliple modules into a single namespace


code:
s = 'Fuzzy wuzzy was a bear'
L = s.split()
# L == ['Fuzzy', 'wuzzy', 'was', 'a', 'bear']

rawDescription: Basic Slicing Review

description: Basic Slicing Review


code:
def to_dict(model):
    output = {}
    for key, prop in model._properties.iteritems():
        value = coerce(getattr(model, key))
        if value is not None:
            output[key] = value
    return output

rawDescription: Python StructuredProperty to dictionary

description: Python StructuredProperty to dictionary


code:
my_list = ["car", "bus", "car", "truck", "van", "bus", "truck"]
my_list[:] = ["bikes" if ele == "car" else ele for ele in my_list]

my_list
['bikes', 'bus', 'bikes', 'truck', 'van', 'bus', 'truck']

rawDescription: How to print the index values of two identical items in a list?

description: Print the index values of two identical items in a list


code:
from visual import sphere
s = sphere()

rawDescription: Visual module in python assign objects

description: Visual module in python assign objects


rawDescription: Split and append

description: Split and append


rawDescription: How to unquote a urlencoded unicode string in python?

description: Unquote a urlencoded unicode string in python


code: [here,none,none,none]

rawDescription: 2D Array Unintended Assignment Bug

description: 2D Array Unintended Assignment Bug


code:
class CustomMapping:
    def __getitem__(self, key):
        return str(len(key))
import string
url = "http://www.myserver.com/$abc/$foo_or_bar/$xy"
string.Template(url).substitute(CustomMapping())

rawDescription: How to dynamically parse python string templates?

description: Dynamically parse python string templates


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

# prepare random data
stats = -1, 1, 200
x = np.random.uniform(*stats)
y = np.random.uniform(*stats)
z = np.random.uniform(*stats)

# mask unwanted data
thresh = 0.4
mask = np.abs(z) <= thresh
x_ma = np.ma.masked_where(mask, x)
y_ma = np.ma.masked_where(mask, y)
z_ma = np.ma.masked_where(mask, z)

rawDescription: Matplotlib Scatter plot filter color (Colorbar)


code:
from ggplot import ggplot, geom_line, aes
import pandas as pd
df = pd.DataFrame({'a': range(10), 'b': range(5,15), 'c': range(7,17)})

df['x'] = df.index
df = pd.melt(df, id_vars='x')

ggplot(aes(x='x', y='value', color='variable'), df) + \
      geom_line()

rawDescription: Is it possible to plot multiline chart on Python ggplot?


code:
s = "Spot is a brown dog. Spot has brown hair. The hair of Spot is brown."
sum(s.count(x) for x in ("Spot", "brown", "hair"))

rawDescription: Counting occurrences of multiple strings in another string


code:
x = b'\xa3\x13\xa4;\xcb\xda\x1b\x1b,Ut\xde\xeb2\xb5\x84\xe5&\x85;'
binascii.hexlify(x).decode()

rawDescription: How to decode raw binary to hex

description: Decode raw binary to hex


rawDescription: Confused about an if statement in Learn Python the Hard Way ex41?


code:
hnday = {k:[hns[i].index(k)+1 for i in range(len(hns))] for k in keys}
hnday['a']
hnday['b']
hnday['c']

rawDescription: most pythonic way to use a value from a list as an index to another list

description: Most pythonic way to use a value from a list as an index to another list


code:
path_to_chromedriver = 'C:/python34/chromedriver/chromedriver.exe'
browser2 = webdriver.Chrome(executable_path = path_to_chromedriver)

rawDescription: ChromeDriver Quits Unexpectedly

description: ChromeDriver Quits Unexpectedly


rawDescription: Python, numpy : 3 dimensions broadcast

description: Python, numpy : 3 dimensions broadcast


code:
def __init__(self, parent):
    self._init_ctrls(parent)
    self.readInformation()

rawDescription: How do I load values into a wxPython app when it opens?

description: Load values into a wxPython app when it opens


code: plt.xticks(locs, map(lambda x: "%12.0f" % x, locs))

rawDescription: Is there a ready solution in matplotlib to plot times?


code:
for bad_char in special_chars:
    country = country.replace(bad_char, '')

rawDescription: Use an External file to replace special characters?


rawDescription: Check whether a string is alphabetical for languages other than english


rawDescription: How to make celery retry using the same worker?

description: Make celery retry using the same worker


code:
import numpy as np
import scipy as sp
import scipy.optimize

rawDescription: How do you stop the scipy.optimize.fmin function and start it again using the optimization history?

description: Stop the scipy.optimize.fmin function and start it again using the optimization history


code:
#!/usr/bin/env python
NORTH, S, W, E = (0, -1), (0, 1), (-1, 0), (1, 0) # directions
turn_right = {NORTH: E, E: S, S: W, W: NORTH} # old -> new direction

def spiral(width, height):
    if width < 1 or height < 1:
        raise ValueError
    x, y = width // 2, height // 2 # start near the center
    dx, dy = NORTH # initial direction
    matrix = [[None] * width for _ in range(height)]
    count = 0
    while True:
        count += 1
        matrix[y][x] = count # visit
        # try to turn right
        new_dx, new_dy = turn_right[dx,dy]
        new_x, new_y = x + new_dx, y + new_dy
        if (0 <= new_x < width and 0 <= new_y < height and
            matrix[new_y][new_x] is None): # can turn right
            x, y = new_x, new_y
            dx, dy = new_dx, new_dy
        else: # try to move straight
            x, y = x + dx, y + dy
            if not (0 <= x < width and 0 <= y < height):
                return matrix # nowhere to go

def print_matrix(matrix):
    width = len(str(max(el for row in matrix for el in row if el is not None)))
    fmt = "{:0%dd}" % width
    for row in matrix:
        print(" ".join("_"*width if el is None else fmt.format(el) for el in row))

rawDescription: creating a spiral array in python?

description: Creating a spiral array in python


rawDescription: Conditional indexing with Numpy ndarray

description: Conditional indexing with Numpy ndarray


code:
try:
    formatted = '{}ms'.format(delta.total_seconds() * 1000)
except AttributeError:
    formatted = '0ms'
return {'time_since_last': formatted}

rawDescription: Python logging module - time since last log


code:
import numpy as np

def using_explicit_dtype(filename):
    with open(filename, 'rb') as f:
        header = next(f).split()
        n = len(header)
        dtype = ['<i8', 'S16']+['<f8']*(n-2)
        dtype = zip(header, dtype)
        data = np.genfromtxt(f,
                             dtype=dtype,
                             usemask=True)
        return data

def using_default_dtype(filename):
    with open(filename, 'rb') as f:
        header = next(f).split()
        data = np.genfromtxt(f,
                             # filling_values=-1000,
                             # names=True,
                             # usemask=True,
                             dtype=float,
                             converters={0: int, 1: str})
        data.dtype.names = header
        return data

def using_pandas(filename):
    import pandas as pd
    df = pd.read_table('data', delim_whitespace=True, na_values='-')
    return df

rawDescription: Set one specific date type for reading in genfromtxt


code: list_dic = dict((k, []) for k in list_var)

rawDescription: Python - Initializing List variable from List elements


code:
inputready, outputready, exceptready = select.select(
    [proc.stdout, proc.stderr], # read list
    [proc.stdout, proc.stderr], # write list
    [proc.stdout, proc.stderr], # error list.
    0)                          # time out.

rawDescription: Asyncronous Bidirectional IO Redirection for a child process


code:
import numpy as np
X = np.random.randn(100, 20)
mask = np.arange(20) > 4

mpca = MaskedPCA(n_components=2, mask=mask)

transformed = mpca.fit(X).transform(X)

# check whether first five columns are equal
from numpy.testing import assert_array_equal
assert_array_equal(X[:, :5], transformed[:, :5])

rawDescription: pipeline with PCA on feature subset only in scikit-learn

description: Pipeline with PCA on feature subset only in scikit-learn


rawDescription: How to hide herokuapp.com site built in Django when the site is live

description: Hide herokuapp.com site built in Django when the site is live


code: G.add_edge(white, black, weight=5, color='blue')

rawDescription: what is the signification of ** in python (when not a mathematical expression)

description: What is the signification of ** in python (when not a mathematical expression)


code: def noop(*args, **kw): pass

rawDescription: Is there a standard Python function that takes any number of arguments and does nothing?


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

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim(-50, 50)
ax.set_ylim(-75, 75)
x = [-50, 0, 50]
y = np.array([-50, 0, 0])

ax.fill_between(x,y-30,y+30)

ax.grid()
plt.show()

rawDescription: Matplotlib: draw lines with width given in data coordinates


rawDescription: Representing graphs (data structure) in Python


rawDescription: Python unpack 2-dimensional list of named tuples


code:
def string_kernel(X, Y):
    R = np.zeros((len(x), len(y)))
    for x in X:
        for y in Y:
            i = int(x[0])
            j = int(y[0])
            # simplest kernel ever
            R[i, j] = data[i][0] == data[j][0]
    return R

clf = SVC(kernel=string_kernel)
clf.fit(X, ['no', 'yes', 'yes'])

rawDescription: How to use string kernels in scikit-learn?

description: Use string kernels in scikit-learn


rawDescription: Converting List of Float values into Dates


code:
import csv
from cStringIO import StringIO
sample = '1P|text "could" be\'tricky\n\'\\\\|T2P|or easy|'
input = LineTerminatorTranslator(StringIO(sample), 'T')
list(csv.reader(input, delimiter='P', quotechar='|'))

rawDescription: can I use the csv module when the end of record marker is not a new line?

description: Use the csv module when the end of record marker is not a new line


code: [[ObjectA, 9], [ObjectB, 14], [ObjectC, 8]]

rawDescription: Best way to remove/merge duplicates in this list?

description: Remove/merge duplicates in this list


code:
df = pd.DataFrame({
    1: {'agree': 1},
    2: {'disagree': 1},
    3: {'whatevs': 1},
    4: {'whatevs': 1}}).transpose()
df

rawDescription: Risks re changing NaN responses to zero in Python DataFrame


code:
import re
from operator import itemgetter as iget
with open('path/to/file') as infile:
    data = infile.read() # UGH
re_data = re.findall(r"([^\d\s]+)|([\d]+)", data)
dictionary = dict(zip( map(iget(0),re_data[0::2]),map(int,map(iget(1),re_data[1::2])) ))
# DOUBLE UGH. As a rule of thumb, if you're using three map
# functions in one line, REFACTOR.

rawDescription: From txt file to Python dictionary

description: From txt file to Python dictionary


code:
def createLambda(client):
    return lambda: client.returncode(CMD2) == 0
#...
passIf = createLambda(client)

rawDescription: Python Lambdas and Variable Bindings

description: Python Lambdas and Variable Bindings


code:
def does_segment_exist(seq, sublist):
    # seq and sublist must both be lists
    n = len(sublist)
    return sublist in (seq[i:i+n] for i in range(len(seq) + 1 - n))

rawDescription: Finding consecutive values within a list


rawDescription: Fastest way to retrieve newly registered users' instances in Django web app


code: i2 = DeleteSmallComponents[i1, 1000]

rawDescription: Square detection with aberrations in edges and 1 missing corner


code:
#straight from the docs
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

rawDescription: Python, inserting a boolean to a corresponding value


code: df1['Office'] = output['Office']

rawDescription: VLOOKUP Excel analog in pandas python

description: VLOOKUP Excel analog in pandas python


code:
def after_equals(s):
    return s.partition(' = ')[-1]
f = file('myfile.txt','w')
for k,s in zip(keyword, score):
  f.write('%s,%s\n' % (after_equals(k), after_equals(s)))
f.close()

rawDescription: Outputting to a file

description: Outputting to a file


code:
class FooBar(object):
    @requires_bar
    @requires_foo                 # You can chain as many decorators as you want
    def do_something_to_foo_and_bar(self):
        pass

rawDescription: Python decorators just syntactic sugar?

description: Python decorators just syntactic sugar


code:
from collections import Counter

c = Counter()

with open('file.txt') as f, open('outfile.txt', 'w') as out:
    for line in f:
        # In `if` and `elif`, use the current value of the counter
        # for the second column, default is 0.
        if '(*) Begin' in line:
            text = line.split(None, 2)[1]
            out.write('{}[{}]\n'.format(line.strip(), c[text]))
        elif '(*) End' in line:
            text = line.split(None, 2)[1]
            out.write('{}[{}]\n'.format(line.strip(), c[text]))
            # End found, so now increment the counter
            c[text] += 1
        else:
            out.write(line)

rawDescription: Index breaks in a set

description: Index breaks in a set


code: ["US" if any(item in US for item in p) else "Non-US" for p in place]

rawDescription: Check if items in one list exists in another list


code:
def rel_to_egg(f):
    my_dir = os.path.dirname(os.path.abspath(f))
    current = my_dir
    while not current.endswith('.egg'):
        current = os.path.dirname(current)
    return os.path.relpath(current, my_dir)

rawDescription: Python: How do i get the name of the current archive?


code:
import rpy2.rinterface as rinterface
rinterface.set_initoptions((b'rpy2', b'--no-save'))
rinterface.initr()
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects

rawDescription: QGIS: How to run R directly in python console?


rawDescription: How do I see the Python doc on Linux?

description: See the Python doc on Linux


code:
if player1.health > player1.max_health:
    player1.health = player1.max_health

rawDescription: Having a Function change variable in Python 3.4?


code: any(x in someDict for x in someList)

rawDescription: Optimize the performance of dictionary membership for a list of Keys


rawDescription: How to identify approximately (threshold defined) continuous non null data using pandas?

description: Identify approximately (threshold defined) continuous non null data using pandas


code:
smith = Person((c_ubyte * 8)(*b'Mr Smith'), 9)
bytes(smith.name).decode('ascii')

rawDescription: How to print c_ubyte_Array object in Python

description: Print c_ubyte_Array object in Python


code:
import os
os.path.join(os.path.expanduser('~'), '.programname')

rawDescription: Loading a config file from operation system independent place in python


rawDescription: Using recursion to reverse a dictionary around a value in python


code:
timestamp2 = datetime.datetime.strptime(line.split(' : ')[0].split(' Tag ')[0].replace('a.m.', 'AM'), "%d/%m/%Y %I:%M:%S %p")
timestamp2 - timestamp
print(timestamp2 - timestamp)

rawDescription: Python putting certain texts into a dictionary from a large string


code:
class Product(db.Model):

    tags = db.ListProperty(db.Category)
    category = db.CategoryProperty(verbose_name='Category')
    title = db.StringProperty(verbose_name='title')  # required
    text = db.TextProperty(verbose_name='text')

rawDescription: Google App Engine: Creating an Ecommerce website


rawDescription: How to write a calendar to excel?

description: Write a calendar to excel


code:
#!/usr/bin/kivy
import kivy
kivy.require('1.9.1')

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

Builder.load_string('''
<MyButton>:
    on_press: print('np' in self.properties())
''')

class MyButton(Button):
    pass

class MainApp(App):
    def build(self):
        mb1 = MyButton(text="mb1")
        mb2 = MyButton(text="mb2")
        mb1.apply_property(np=NumericProperty(100))

        layout = BoxLayout()
        layout.add_widget(mb1)
        layout.add_widget(mb2)
        return layout

if __name__ == '__main__':
    MainApp().run()

rawDescription: Dynamically adding properties with kivy discouraged – why?


code:
Distance = []
values=d["chr"]
for i,j in enumerate(values[:-1]):
    first,second=int(j[1]),int(values[i+1][0])
    diff = first - second # not sure if you want this or not
    x = range(first)
    y = range(second)
    distances = list(set(x) & set(y))
    Distance.append(distances)

rawDescription: Extract list of values in dictionary for comparison?


code: plus_three = map(lambda x: x+3, [1,2,3])

rawDescription: if annonymous, what is a call to python lambda?

description: If annonymous, what is a call to python lambda


code:
MyModel.objects.filter(
                       primaryid=1987
                      ).filter(
                       timestamp__gte=min_timestamp
                      ).exclude(
                       timestamp__gte=max_timestamp
                      ).values_list('valuefield', flat=True)

rawDescription: Django - SQL Query - Timestamp

description: Django - SQL Query - Timestamp


code:
@property
def s3_destination(self):
    return self.s3_destination

rawDescription: Using @property kicking off a recursive call somehow?


code:
pat ='(\x20+)(\x08+)'
repl = lambda m: m.group(1)[:-len(m.group(2))]

rawDescription: How to 'evaluate' backspaces in python?

description: 'evaluate' backspaces in python


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

# Read data from file into variables
cps, s_load, f_load, s_process, f_process, s_unload, f_unload = np.loadtxt('arena.txt', unpack=True)

# Plot a line for every line of data in your file
plt.hlines(cps, s_load, f_load, colors="red", lw=4)
plt.hlines(cps, s_process, f_process, colors="green", lw=4)
plt.hlines(cps, s_unload, f_unload, color="blue", lw=4)
plt.margins(0.1)
plt.show()

rawDescription: Python plot gantt chart

description: Python plot gantt chart


code:
import numpy as np
x = np.arange(10)
x[::-1].cumsum()[::-1]

rawDescription: Numpy.cumsum in reverse

description: Numpy.cumsum in reverse


code:
from django.core.files.storage import default_storage

f = default_storage.open(os.path.join('Data_Files', new_file), 'r')
data = f.read()
f.close()
print(data)

rawDescription: Opening a data file from the media directory in Django


rawDescription: Calculating the difference in dates in a Pandas GroupBy object


code:
A = zeros(D.shape)
i, j = I.T
A[i, j] = D[i, j]

rawDescription: How do I do this array indexing in numpy

description: Do this array indexing in numpy


code:
import os
import urllib

from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class MainHandler(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        self.response.out.write('')
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write("""Upload File: <input type="file" name="file">
 <input type="submit" name="submit" value="Submit"> </form>""")

        for b in blobstore.BlobInfo.all():
            self.response.out.write('
' + str(b.filename) + '')

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        self.redirect('/')

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, blob_key):
        blob_key = str(urllib.unquote(blob_key))
        if not blobstore.get(blob_key):
            self.error(404)
        else:
            self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)

def main():
    application = webapp.WSGIApplication(
          [('/', MainHandler),
           ('/upload', UploadHandler),
           ('/serve/([^/]+)?', ServeHandler),
          ], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
  main()

rawDescription: Upload files in Google App Engine

description: Upload files in Google App Engine


code: ''.join('{} {} {};'.format(v[0], v[1], k) for k,v in d.iteritems())

rawDescription: Python: How to create new variable in each iteration of a for loop?


code: assert json.dumps(d1, sort_keys=True) == json.dumps(d2, sort_keys=True)

rawDescription: python: is there a well-known function to normalize JSON representation of data?

description: Python: is there a well-known function to normalize JSON representation of data


rawDescription: Python. How to make list from another list by mark?


rawDescription: Using one Scrapy spider for several websites


code:
list_with_units=[str(value)+"'kg'" for value in list_without_units]
# print result: ["1'kg'", "2'kg'", "3'kg'"]

rawDescription: How to add units like kg or grams 'superficially ' in a list in python

description: Add units like kg or grams 'superficially ' in a list in python


code:
f.index = [[1,2,3],[1,2,3]]
f
f.apply(clean, axis=1).reindex(f.index)

rawDescription: Changing data in a dataframe with hierarchical indexing


code:
class ParserTest(unittest.TestCase):
    def setUp(self):
        self.parser = create_parser()

    def test_something(self):
        parsed = self.parser.parse_args(['--something', 'test'])
        self.assertEqual(parsed.something, 'test')

rawDescription: How do you write tests for the argparse portion of a python module?

description: Write tests for the argparse portion of a python module


code:
with open('dist.all.last') as inputfile:
    names = [line.split()[0] for line in inputfile if line.strip()]

rawDescription: Effectively parsing plain text

description: Effectively parsing plain text


code:
Aone = df.groupby('A').filter(lambda x: len(x) == 1)
Bone = df.groupby('B').filter(lambda x: len(x) == 1)
Aone.merge(Bone,on=['A','B'],how='inner')

rawDescription: Only allow one to one mapping between two columns in pandas dataframe


code:
import Tkinter as tk
import multiprocessing as mp
import tkFileDialog
import os
import Queue

sentinel = None

def long_running_worker(inputFilePath, outqueue):
    # Build a list of files in a directory
    fileList = os.listdir(inputFilePath)
    for filename in fileList:
        try:
            with open(os.path.join(inputFilePath, filename), 'r') as infile:
                # Update the status with the filename
                status_string = 'Status: Working on file: ' + str(filename)
                outqueue.put(status_string)
                for line in infile:
                    # Do some stuff here
                    pass
        except IOError:
            # You might get here if file is unreadable, you don't have read permission,
            # or the file might be a directory...
            pass
    # Put the sentinel in the queue to tell update_status to end
    outqueue.put(sentinel)

class App(object):
    def __init__(self, master):
        self.status = tk.StringVar()
        self.status.set("Status: Press 'Fix Files!'")
        self.statuslabel = tk.Label(
            master, textvariable=self.status, relief=tk.RIDGE, width=65,
            pady=5, anchor='w')
        bFixFiles = tk.Button(root, text='Fix Files!', command=self.startFixFiles)
        bQuit = tk.Button(root, text='Quit', command=root.destroy)
        self.statuslabel.grid(row=1, column=0, columnspan=2)
        bFixFiles.grid(row=0, column=0, sticky='e')
        bQuit.grid(row=0, column=1, sticky='e')

    def update_status(self, outqueue):
        try:
            status_string = outqueue.get_nowait()
            if status_string is not sentinel:
                self.status.set(status_string)
                root.after(250, self.update_status, outqueue)
            else:
                # By not calling root.after here, we allow update_status to truly end
                pass
        except Queue.Empty:
            root.after(250, self.update_status, outqueue)

    def startFixFiles(self):
        inputFilePath = tkFileDialog.askdirectory()
        # Start long running process
        outqueue = mp.Queue()
        proc = mp.Process(target=long_running_worker, args=(inputFilePath, outqueue))
        proc.daemon = True
        proc.start()
        # Start a function to check a queue for GUI-related updates
        root.after(250, self.update_status, outqueue)

root = tk.Tk()
root.title("FIX Files")
app = App(root)
root.mainloop()

rawDescription: Python / Tkinter status bar not updating correctly


rawDescription: Handle path name with backslash followed by numbers (Python)


code:
kw = Combine(Word(alphas + nums) + Literal(';'))('KEY')
body1 = delimitedList(OneOrMore(Word(alphas + nums)) +~kw)('Body')
g1 = OneOrMore(Group(kw + body1))

rawDescription: getting a grammar to read more than one keyword in the text

description: Getting a grammar to read more than one keyword in the text


code: json.dumps({'numbers': n, 'strings': s, 'x': x, 'y': y})

rawDescription: Python, writing things to json

description: Python, writing things to json


code:
import atexit

@atexit.register
def leaving():
    import datetime
    open("my.log", "w").write("I was closed at %s" % datetime.datetime.now())

rawDescription: Log the time a python script stopped?

description: Log the time a python script stopped


code:
"""
This app will show you small window with the randomly generated code that will confirm that reopened window is still the same app returned from background,
and the button allowing you to send it to background.
After you send it to background, wait 8 seconds and application will return to foreground again.
Too prove that the application is continuing its work in the background, the app will call wx.Bell() every second.
You should hear the sound while app is in the foreground and when it is in background too.

Merry Christmas and a happy New Year!
"""

import wx
import random, sys

if sys.platform=="darwin":
    from AppKit import NSBundle, NSApp, NSAutoreleasePool, NSApplicationActivationPolicyRegular, NSApplicationActivationPolicyProhibited

    # Use Info.plist values to know whether our process started as daemon
    # Also, change this dict in case anyone is later checking it (e.g. some module)
    # Note: Changing this dict doesn't change Info.plist file
    info = NSBundle.mainBundle().infoDictionary()

    def SendToBackground ():
        # Change info, just in case someone checks it later
        info["LSUIElement"] = "1"
        NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)

    def ReturnToForeground ():
        # Change info, just in case someone checks it later
        info["LSUIElement"] = "0"
        NSApp.setActivationPolicy_(NSApplicationActivationPolicyRegular)

else:
    # Simulate Mac OS X App - Info.plist
    info = {"LSUIElement": "0"} # Assume non background at startup
                                # If programmer chose not to display GUI at startup then she/he should change this before calling ReturnToForeground()
                                # To preserve consistency and allow correct IsDaemon() answer
    def SendToBackground ():
        info["LSUIElement"] = "1"

    def ReturnToForeground ():
        info["LSUIElement"] = "0"

def IsDaemon ():
    return info["LSUIElement"]=="1"

class Interface (wx.Frame):
    def __init__ (self):
        wx.Frame.__init__(self, None, -1, "Test", pos=(100, 100), size=(100, 100))
        wx.StaticText(self, -1, "Test code: "+str(random.randint(1000, 10000)), pos=(10, 10), size=(80, 20))
        b = wx.Button(self, -1, "DAEMONIZE ME", size=(80, 20), pos=(10, 50))
        wx.EVT_BUTTON(self, b.GetId(), self.OnDaemonize)
        self.belltimer = wx.Timer(self)
        wx.EVT_TIMER(self, self.belltimer.GetId(), self.OnBellTimer)
        self.belltimer.Start(1000)
        # On Mac OS X, you wouldn't be able to quit the app without the menu bar:
        if sys.platform=="darwin":
            self.SetMenuBar(wx.MenuBar())
        self.Show()

    def OnBellTimer (self, e):
        wx.Bell()

    def OnDaemonize (self, e):
        self.Show(False)
        SendToBackground()
        self.timer = wx.Timer(self)
        wx.EVT_TIMER(self, self.timer.GetId(), self.OnExorcize)
        self.timer.Start(8000)

    def OnExorcize (self, e):
        self.timer.Stop()
        ReturnToForeground()
        self.Show()
        self.Raise()

app = wx.App()
i = Interface()
app.MainLoop()

rawDescription: Python - How to make a daemon out of GUI Application on Mac OS X?


code:
class A(object):
    def __init__(self, value):
        self.value = value

    def is_safe(self):
        if value > 10:
            return False
        return True

    def increase_value(self, increment):
        if increment <= 0:
            raise ValueError("only positive increments are allowed")
        self.value += increment

rawDescription: What is the proper way to split a python module into submodules?


code:
data = []
if objects:
    keys = model_to_dict(objects[0]).keys()
    for object in objects:
        d = model_to_dict(object)
        data.append([d[key] for key in keys] + [object.storeID.StoreName])

rawDescription: Django loading dictionary values into JSON


rawDescription: Replacing items in a list one at a time

description: Replacing items in a list one at a time


code:
canvas.create_rectangle(x0, y0, x1, y1, tags="myRectangle")
canvas.delete("myRectangle")

rawDescription: How do I selectively delete drawings in Tkinter?

description: Selectively delete drawings in Tkinter


code: values = [''.join(td.xpath('.//text()').extract()) for td in Selector(response).xpath('//tbody/tr/td')]

rawDescription: Scrapy Xpath How should I handle missing data between tags in a table?


rawDescription: Easy way to test if each element in an numpy array lies between two values?


code:
_semaphores_rwlock = RWLock()
_semaphores = {}

def synchronized(name):
    def wrap(f):
        def inner(*args, **kwargs):
            lock = _semaphores_rwlock.reader()
            # If the named semaphore does not yet exist, create it.
            if name not in _semaphores:
                lock = _semaphores_rwlock.writer()
                _semaphores[name] = semaphore.Semaphore()

            sem = _semaphores[name]

            with sem:
                retval = f(*args, **kwargs)
            lock.release()
            return retval

rawDescription: Dynamically allocating and destroying mutexes?


code:
def fib(n): return n if n < 2 else fib(n - 2) + fib(n - 1)

fib(10)
import dis
dis.dis(fib)

description: Python Compilation/Interpretation Process


code:
class MyAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):

        # Set optional arguments to True or False
        if option_string:
            attr = True if values else False
            setattr(namespace, self.dest, attr)

        # Modify value of "input" in the namespace
        if hasattr(namespace, 'input'):
            current_values = getattr(namespace, 'input')
            try:
                current_values.extend(values)
            except AttributeError:
                current_values = values
            finally:
                setattr(namespace, 'input', current_values)
        else:
            setattr(namespace, 'input', values)

parser = argparse.ArgumentParser()
parser.add_argument('-a', nargs='+', action=MyAction)
parser.add_argument('-b', nargs='+', action=MyAction)
parser.add_argument('input', nargs='+', action=MyAction)

rawDescription: Multiple positional arguments with Python and argparse


code: np.einsum('ij,ij->i', data, mask)

rawDescription: Sum rows of numpy array where start index of each sum comes from another array


code: d.t = pd.to_datetime(d.t.str[:-6])

rawDescription: Ignore time offsets in Pandas Dataframe

description: Ignore time offsets in Pandas Dataframe


code:
from datetime import datetime

def is_third_friday(s):
    d = datetime.strptime(s, '%b %d, %Y')
    return d.weekday() == 4 and 14 < d.day < 22

rawDescription: Python: third Friday of a month

description: Python: third Friday of a month


code:
contacts = {}
for _ in range(10):
    pnumber = raw_input('Input number here: ')
    if pnumber not in contacts: #not sure how to do this
        name = raw_input("Input name for this number: ")
        contacts[pnumber] = name

rawDescription: Python - If string in dictionary, else add to dictionary and add index


code:
import threading

class Thread(threading.Thread):
    def __init__(self,callback,*args,**kwargs):
        self.__callback = callback
        threading.Thread.__init__(self,*args,**kwargs)
    def run(self):
        try:
            if self.__target:
                print('thread')
                _self = self.__kwargs.get('self',self.__args[0])
                self.__callback(_self, self.__target(*self.__args, **self.__kwargs))
        finally:
            # Avoid a refcycle if the thread is running a function with
            # an argument that has a member that points to the thread.
            del self.__target, self.__args, self.__kwargs

def background(callback):
    print('background')
    def wrapper(fun):
        print('wrapper')
        def inner(*args,**kwargs):
            print('inner')
            Thread(callback=callback,target=fun,args=args,kwargs=kwargs).start()
        return inner
    return wrapper

def spinner(fun):
    def inner(self,*args,**kwargs):
        self.show()
        result = fun(self,*args,**kwargs)
        self.hide()
        return result
    return inner

def spinner_hide(fun):
    def inner(self,*args,**kwargs):
        result = fun(self,*args,**kwargs)
        self.hide()
        return result
    return inner

def spinner_show(fun):
    def inner(self,*args,**kwargs):
        self.show()
        result = fun(self,*args,**kwargs)
        return result
    return inner

class A(object):
    @spinner_hide
    def my_function_callback(self,data):
        print('callback')
        print(data)
    @spinner_show
    @background(my_function_callback)
    def my_function(self, input):
        # do something here that takes long time
        print(input)
        output=input
        return output

    def show(self): print('showed')
    def hide(self): print('hidden')

a=A()
a.my_function('gogo')

rawDescription: Show Gtk Spinner while function running only


code:
if d.keys() != ['amount', 'name']:
    raise ValueError

rawDescription: python: what is best way to check multiple keys exists in a dictionary?

description: Python: what is best way to check multiple keys exists in a dictionary


code: ax = df2[('A', 'sum')].plot(kind="bar")

rawDescription: Plot specific column after DataFrame aggregation


code:
# create patterns here...
re_first = re.compile(...)
re_second = re.compile(...)
re_third = re.compile(...)

# create a list with them
regexes = [re_first, re_second, re_third]

# create the combined one
pattern_combined = '|'.join(x.pattern for x in regexes)

rawDescription: Pythonic way to concatenate regex objects


rawDescription: Having list of keys, get list/tuple of values from dict


code:
regex = re.compile(r'\b(?=[0-9U])(?:[0-9]+\s*U\.?S\.?D|U\.?S\.?D\s*[0-9]+)\b', re.I)

result = [x.strip(' USD.usd') for x in regex.findall(yourstring)]

rawDescription: Effective regex for multiple strings with characters and numbers


code:
for td in soup.find_all('td', {'data-tooltip': True}):
    print(td['data-tooltip'])

rawDescription: Extract Text from HTML Python (BeautifulSoup, RE, Other Option?)


rawDescription: Python Error with producing key of max of mins


code: if name is None: name = getattr(obj, '__qualname__', None)

rawDescription: Python multiprocessing Pool Interaction With Namespace At Creation


code:
from decorator import decorator
def substitute_args(arg_sub_dict):
  @decorator
  def wrapper(fun, arg):
    new_arg = arg_sub_dict.get(arg, arg)
    return fun(new_arg)
  return wrapper

rawDescription: Python Decorator 3.0 and arguments to the decorator


code:
#create flag filled with zeros with same shape as data
flag=numpy.zeros(data.shape)
#get bool array stating where data>=threshold
barray=data>=threshold
#everywhere where barray==True put a 1 in flag
flag[barray]=1

rawDescription: Huge difference between python and fortran difference for a small program


code:
from scipy.ndimage import label

# Label with scipy
labeled_array, num_features = label(my_np_array, structure = None, output = np.int)

# Set the threshold
thresh = 800

# Get the binned counts with "np.bincount" and check against threshold
matches = np.bincount(labeled_array.ravel())>thresh

# Get the IDs corresponding to matches and get rid of the starting "0" and
# "num_features", as you won't have those in "range(1, num_features)" either
match_feat_ID = np.nonzero(matches)[0]
valid_match_feat_ID = np.setdiff1d(match_feat_ID,[0,num_features])

# Finally, use "np.in1d" to do ORing operation corresponding to the iterative
# "big_zones += zone_array" operation on the boolean array "big_zones".
# Since "np.in1d"  works with 1D arrays only, reshape back to 2D shape
out = np.in1d(labeled_array,valid_match_feat_ID).reshape(labeled_array.shape)

rawDescription: Select size filtered elements in a large array (raster)


code:
import datetime
from Tkinter import * # from tkinter import *   # Python 3.x

root = Tk()
root.geometry('500x500')
frame = Frame(root)
frame.pack(side=BOTTOM, fill=BOTH)

label = Label(frame)
label.pack(side=RIGHT)
label['text'] = datetime.datetime.now().strftime('%H:%M:%S')
root.mainloop()

rawDescription: can we code time in text widget?

description: Can we code time in text widget


code:
df['C'] = (df.A.shift(-1) - df.A) / (df.B.shift(-1) - df.B)
df.loc[df.index.max(), 'C'] = df.loc[df.index.max(), 'A'] / df.loc[df.index.max(), 'B']
df.round(2)

rawDescription: join corresponding column to dataframe pandas

description: Join corresponding column to dataframe pandas


code:
class MyClass:
    var = 1
    print(MyClass.var)   # error: MyClass still doesn't exist.

rawDescription: How to reference a static attribute from within a class in Python?

description: Reference a static attribute from within a class in Python


rawDescription: Dumping memoization decorator cache to file


code: ''.join('%s %s\n' % o for o in a.items())

rawDescription: Python dict to user format string

description: Python dict to user format string


rawDescription: Python/Regex - Expansion of Parentheses and Slashes


code: [y.strip() for y in x.xpath('//dfn[.="B"]/..//text()') if y.strip()]

rawDescription: How to prevent infinite looping in Python while parsing with lxml?

description: Prevent infinite looping in Python while parsing with lxml


code:
import unicodedata
a = "बिक्रम मेरो नाम हो"
[unicodedata.name(c) for c in a]

rawDescription: Playing around with Devanagari characters


rawDescription: Count total bytes in a big file between two chars matching some rules by line


code:
import os
for filepath in filelist:
    dirpath = os.path.dirname(filepath)
    # Do something with `dirpath`

rawDescription: How do i get list of subdirectories contains specific file (ie. '__main__.py) using Python

description: Get list of subdirectories contains specific file (ie. '__main__.py) using Python


code:
class HierarchicCounter(object):
    def __init__(self, key, hierarchy):
        self.key = key
        self.hierarchy = hierarchy
        self.counts = defaultdict(int)
        self.subcounters = defaultdict(self._create_subcounters)

    def _create_subcounters(self):
        return {key: HierarchicCounter(key, hierarchy)
                for key, hierarchy in self.hierarchy.iteritems()}

    def count(self, line):
        key = self.key(line)
        if key is None:
            return
        self.counts[key] += 1
        for subcounter in self.subcounters[key].itervalues():
            subcounter.count(line)

rawDescription: Python parsing large text files and capturing multi-level data


code:
class Foo(object):
   def method(self): pass

a = Foo()
a.method()
setattr(a,'method',1)
a.method()

rawDescription: modify method only having the method's name and instance object

description: Modify method only having the method's name and instance object


rawDescription: Bulk import/load csv to sqlite using Python


code: [('Rami Eid', 'PERSON'), ('Stony Brook University', 'ORGANIZATION'), ('NY', 'LOCATION')]

rawDescription: Extract list of Persons and Organizations using Stanford NER Tagger in NLTK


code: np.sum((x - x[0])**2, axis=-1, keepdims=True)**0.5

rawDescription: How to get euclidean distance on a 3x3x3 array in numpy

description: Get euclidean distance on a 3x3x3 array in numpy


rawDescription: Python sum of N consecutive digits of a large number


code:
mydir = lambda a:[x for x in dir(a) if not x.startswith('_')]
mydir([])

rawDescription: How do I check the methods that an object has, in Python?

description: Check the methods that an object has, in Python