code:
cert = X509.load_cert("signer.pem")
decrypted = cert.get_pubkey().get_rsa().public_decrypt(StringSignature, 1)

rawDescription: How to get back a signed string (e.g. md5 hash) using a public-key (x509 certificate)

description: Get back a signed string (e.g. md5 hash) using a public-key (x509 certificate)


code:
new_cols = df.pop("probegene").str.split().apply(pd.Series)
new_cols.columns = ["probe","gene"]
df = df.join(new_cols)
df

rawDescription: How to split rows into two columns in Pandas

description: Split rows into two columns in Pandas


code:
cov = np.cov(a, b)
beta = cov[1, 0] / cov[0, 0]

rawDescription: Correlation between columns in DataFrame


code:
y=np.empty((4,),dtype=object)
for i in range(len(y)):
    y[i]=np.arange(i,2*i)

rawDescription: Simpler code to combine multiple lists into one array? I actually wish "lists" are still "lists" in that array


code:
import csv

with open('my_csv.txt', 'rb') as f:
    my_list = list(csv.reader(f))

rawDescription: Concatenate lines with similar key

description: Concatenate lines with similar key


code:
def divisorSums(n):
    dsums = [0] + [1]*n
    for k in xrange(2, n+1):
        for m in xrange(k, n+1, k):
            dsums[m] += k
    return dsums

rawDescription: How would I go about improving/making this run faster?


code:
import itertools

def process(lst):
    # Guard clause against empty lists
    if len(lst) < 1:
        return lst

    # use a dictionary here to work around closure limitations
    state = { 'prev': lst[0], 'n': 0 }

    def grouper(x):
        if x < state['prev']:
            state['n'] += 1

        state['prev'] = x
        return state['n']

    return [ list(g) for k, g in itertools.groupby(lst, grouper) ]

rawDescription: Python: Find monotonic sequences in a list


code:
import sh
FILENAME = 'inventory.txt'
print(sh.ls('-l', FILENAME, _err_to_out=True))

rawDescription: python command substitution for linux commands

description: Python command substitution for linux commands


code:
def getEpisode(filename):
    match = re.search(
        r'''(?ix)                 # Ignore case (i), and use verbose regex (x)
        (?:                       # non-grouping pattern
          e|x|episode|^           # e or x or episode or start of a line
          )                       # end non-grouping pattern
        \s*                       # 0-or-more whitespaces
        (\d{2})                   # exactly 2 digits
        ''', filename)
    if match:
        return match.group(1)

tests = (
    'Series Name s01e01.avi',
    'Series Name 1x01.avi',
    'Series Name episode 01.avi',
    '01 Episode Title.avi'
    )
for filename in tests:
    print(getEpisode(filename))

rawDescription: Using regex in python to get episode numbers from file name


code: dt = Symbol('dt', real=True)

rawDescription: Suppress the transpose of a symbol in sympy output when the symbol is a scalar


code:
# making a new linked list
class Train:
    def __init__(self):
        self.head_car = None

    def add_car(self, data):
        # make new car/node
        new_car = TrainCar()
        # add our data to the new car as desired
        new_car.data = data

        # This is where the magic happens! We're updating the reference inside
        # the node we just made to point to the last car we were on.
        # We are just adding a new car to the end of the train.
        new_car.next_car = self.head_car

        # Now we're setting the head car to be the one we just made!
        self.head_car = new_car

rawDescription: just another evil hangman quesiton

description: Just another evil hangman quesiton


code:
def extract_padding(self, s):
    return s, None

rawDescription: Scapy: Adding new protocol with complex field groupings


rawDescription: Is there a faster way to clean out control characters in a file?


code:
year = getuserselection()
heights = heights_per_year[int(year)]
max_height = max(a.itervalues())

rawDescription: Suggestions for improving my method for finding the max value


code:
def menuChoice():
    notepad = 1
    delayedPrint('\n')
    while True:
        choice = input('> ')
        if choice == "bench" and notepad < 2:
            moreDelayedPrint("You grab the notepad off the bench." + '\n')
            moreDelayedPrint("You flick through the pages, but don't notice anything written down." + '\n')
            notepad = notepad + 1
            optionMenu()
        elif choice == "bench" and notepad >= 2:
            moreDelayedPrint("You grab the notepad off the bench." + '\n')
            moreDelayedPrint("Aha! This time you notice a small scribble near the back of the     notepad." + '\n')
            moreDelayedPrint('It reads "3472\n')
            optionMenu()

rawDescription: Adding to local variables (integers) in Python


rawDescription: How to XOR hex values in a list with another fixed hex value


code:
pattern = re.compile(r'(?i)^%(regex)s/%(regex)s-(\d+)/%(regex)s/%(regex)s-(\d+)/$' % {'regex': r'([-.%\w]+)'})
s = 'united-states/boulder-21781/tool-%26-anchor/mulligan-21/'
match = pattern.match(s)
match.groups()

rawDescription: Regex in Django for URL with % or &

description: Regex in Django for URL with % or &


rawDescription: Create a subset of a DataFrame dependant on column name


code:
p = PrintThis()
p()
p.send(9)
p.send(10)
p()

rawDescription: Initializing Functions Like a Class

description: Initializing Functions Like a Class


code:
import time
from celery import Celery
from kombu import Queue, Exchange

class Config(object):
    BROKER_URL = "amqp://guest@localhost//"

    CELERY_QUEUES = (
        Queue(
            'important',
            exchange=Exchange('important'),
            routing_key="important",
            queue_arguments={'x-max-length': 10}
        ),
    )

app = Celery('tasks')
app.config_from_object(Config)

@app.task(queue='important')
def process_data(x):
    pass

rawDescription: Celery: how to limit number of tasks in queue and stop feeding when full?


code:
from functools import reduce
filters = [("a", False), ("b", True)]
reduce(lambda df, f: df[df.str.contains(f[0]) == f[1]], filters, df)
#outputs b2

rawDescription: Python Pandas: String Contains and Doesn't Contain


rawDescription: Verify all fields are entered correctly

description: Verify all fields are entered correctly


code:
import numpy as np, quaternions
a = np.array([np.quaternion(1,2,3,4), np.quaternion(5,6,7,8), np.quaternion(9,0,1,2)])
a.view(np.float).reshape(a.shape[0],4)

rawDescription: Creating new numpy scalar through C API and implementing a custom view


code:
def my_suspicious_method(*args):
    my_cool_object = somewhere.get_cool_inst()
    my_cool_object.populate_from_stuff(*args)
    # another thread received the same instance
    # and modified it
    # (my_cool_object is still local, but it's a reference to a shared object)
    return my_cool_object.result()

rawDescription: If I have an @staticmethod in my python webapp, do I need to protect it with threading.RLock()?


code:
stamps = [ Timestamp('20130101 09:01:01'),Timestamp('20130102 09:10:00') ]
stamps
ms_epoch = [ int(s.value/1e6) for s in stamps ]
ms_epoch

rawDescription: efficient way to make pandas.DatetimeIndex in Python

description: Efficient way to make pandas.DatetimeIndex in Python


rawDescription: Read (little endian) hex pair that represents a byte in python


code: neighbor_sets = [set(neis) for neis in g.get_adjlist()]

rawDescription: Get all disconnected pairs of nodes in a network


code:
def file_open(userPhrase=None):
    # file_open is lowercase and snake_case for PEP8
    # userPhrase=None to make it an optional argument

    filename = userPhrase if userPhrase is not None else \
               input("Enter file name (including extension): ")
    ...

rawDescription: Files won't be read in GUI program, only in shell


code:
from matplotlib import pylab
import numpy as np
data = np.random.randint(0,10, 1000)
bins = np.array([0,1,2,5,11])
values1, _ = pylab.histogram(data, bins, density = False)
print(values1)
# [ 97, 117, 278, 508]
values2, _ = pylab.histogram(data, bins, density = True)
print(values2)
# [ 0.097, 0.117, 0.09266667, 0.08466667]
bin_width = bins[1:] - bins[:-1]
print(values1 / np.sum(values1) / bin_width)
# [ 0.097, 0.117, 0.09266667, 0.08466667]

rawDescription: How to convert between different pylab.histogram results

description: Convert between different pylab.histogram results


code:
class A(object):
    def save(self):
        # fancy stuff
        pass

class B(A):
    def save(self):
        # misc stuff
        super(B, self).save()

class C(B):
    pass

c = C()
c.foo = 'whatever'
c.save()

# Re-defining the classes breaks the instance

class A(object):
    def save(self):
        # fancy stuff
        pass

class B(A):
    def save(self):
        # misc stuff
        super(B, self).save()

class C(B):
    pass

isinstance(c, C)
c.save()

# Fixing the issue by rebinding the class

c.__class__ = C
isinstance(c, C)
c.save()

rawDescription: Any way to manually fix operation of `super()` after IPython reload (avoiding TypeError)?


code:
import matplotlib.pyplot as plt
plt.figure()
plt.plot(src[[0,1,2,3,0], 0], src[[0,1,2,3,0], 1], '-')
plt.plot(data.T[0], data.T[1], 'o')
plt.figure()
plt.plot(dst.T[0], dst.T[1], '-')
plt.plot(data_local.T[0], data_local.T[1], 'o')
plt.show()

rawDescription: Transform irregular quadrilateral to rectangle in python matplotlib


code:
splits = 5
arr = np.sin(np.random.rand(100)) + np.arange(100)/50.0
cum_arr = arr.cumsum() / arr.sum()
idx = np.searchsorted(cum_arr, np.linspace(0, 1, splits, endpoint=False)[1:])
chunks = np.split(arr, idx)

rawDescription: Split array into equally weighted chunks based on order


code:
class MixedNumber(Fraction):
    def __init__(self, whole_number, fraction):
        num = whole_number * fraction.denominator + fraction.numerator
        super(MixedNumber,self).__init__(num,  fraction.denominator)

    def __str__(self):
        # assume positive fractions for demonstration only
        q, r = divmod(self.numerator,self.denominator)
        if r == 0:
            return str(q)
        elif q == 0:
            return super(MixedNumber,self).__str__()
        else:
            return '{} {}/{}'.format(q,r,self.denominator)

    def __repr__(self):
        q, r = divmod(self.numerator, self.denominator)
        return 'MixedNumber({},Fraction({},{}))'.format(q,r,self.denominator)

rawDescription: Python sub-classes

description: Python sub-classes


code:
import csv
import sys
from itertools import islice
sample = '''\
<data1>,<data2>
asdf,<data3>
asdf,<data4>
asdf,<data5>
<data6>,<data7>
asdf,<data8>

<data1>,<data2>
asdf,<data3>
asdf,<data4>
asdf,<data5>
<data6>,<data7>
asdf,<data8>

<data1>,<data2>
asdf,<data3>
asdf,<data4>
asdf,<data5>
<data6>,<data7>
asdf,<data8>
'''.splitlines()
reader = csv.reader(sample)
writer = csv.writer(sys.stdout)
for row in reader:
    while not row:
        # skip empty rows
        continue
    result = row
    for extra_row in islice(reader, 3):
        result.append(extra_row[1])
    result.extend(next(reader))
    result.append(next(reader)[1])
    writer.writerow(result)

rawDescription: CSV parsing and conversion

description: CSV parsing and conversion


rawDescription: Matching a variable with lists and printing list value


code:
doc = minidom.parse(sys.stdin)
# is equivalent to
doc = getattr(minidom, "parse")(sys.stdin)

rawDescription: Python metaprogramming for XML parsing

description: Python metaprogramming for XML parsing


code: BtnName = Tkinter.Button (RegBox, text="Back", command=back).pack()

rawDescription: Register username and password

description: Register username and password


code:
from sympy import *

t = symbols('t')

y = Function('y')(t)
y_ = Derivative(y, t)

sol = dsolve(y_ - y, y)

rawDescription: how to solve first-order linear differential equations analytically and numerically with sympy?

description: Solve first-order linear differential equations analytically and numerically with sympy


code:
def Leading_White_Space(input_str):
  for i, c in enumerate(input_str):
    if not c.isspace():
      return input_str[i:]

rawDescription: How to remove or strip off white spaces without using strip() function?

description: Remove or strip off white spaces without using strip() function


rawDescription: How can we fetch the elements of the list of specific index?


code:
import json
data = json.loads(string)

rawDescription: Working with JSON Nested in JSON Using Python/Pandas


code:
import sys
import os.path
sys.path[0]
os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6
os.path.join(sys.path[0], "path_to_libs")

rawDescription: How to get relative file path on Python 2.5?

description: Get relative file path on Python 2.5


rawDescription: Vectorizing feature hashing in python

description: Vectorizing feature hashing in python


code:
items = set(array2)
found = [i for i in array1 if i in items]

rawDescription: Python intersection of two lists keeping duplicates


code:
key_list = [5,6,6,1,6,1,6,1,1,2,1,2,1,2,2,1]
values_list = [13,14,15,10,16,11,17,12,12,13,13,14,14,15,16,17]
zipped_lists = zip(key_list, values_list)
sorted_zip = sorted(zipped_lists)
pattern = [5,6,6,6,6,1,1,1,1,1,1,2,2,2,2,1]
temp_dict = {}
for key, value in sorted_zip:
    if key not in temp_dict:
        temp_dict[key] = [value]
    else:
        temp_dict[key].append(value)

final_list = []
for i in pattern:
    final_list.append((i, temp_dict[i].pop(0)))

rawDescription: Aligning two lists with duplicate keys

description: Aligning two lists with duplicate keys


rawDescription: How to get chunks of elements from a queue?

description: Get chunks of elements from a queue


code:
class TimedButton(Button):
    """A simple ``Button`` subclass that produces an event at regular intervals
    when pressed.

    This class, when long-pressed, emits an ``on_time_slice`` event every
    ``time_slice`` milliseconds.

    :param long_press_interval: Defines the minimum time required to consider
                                the press a long-press.
    :type long_press_interval: int
    :param time_slice: The number of milliseconds of each slice.
    :type time_slice: int
    """

    def __init__(self, long_press_interval=550, time_slice=225, **kwargs):
        super(TimedButton, self).__init__(**kwargs)

        self.long_press_interval = long_press_interval
        self.time_slice = time_slice

        self._touch_start = None
        self._touch_uid = None
        self._long_press_callback = None
        self._slice_callback = None

        self.register_event_type('on_time_slice')
        self.register_event_type('on_long_press')

    def on_touch_down(self, touch):
        start_time = time.time()
        self._touch_start = start_time
        self._touch_uid = touch.uid

        def callback(dt):
            self._check_long_press(dt)

        Clock.schedule_once(callback, self.long_press_interval / 1000.0)
        self._long_press_callback = callback
        super(TimedButton, self).on_touch_down(touch)

    def _check_long_press(self, dt):
        delta = dt * 1000
        if delta > self.long_press_interval and self._touch_uid is not None:
            self.dispatch('on_long_press')
            self._long_press_callback = None
            def slice_callback(dt):
                self.dispatch('on_time_slice')

            Clock.schedule_interval(slice_callback, self.time_slice / 1000.0)

            self._slice_callback = slice_callback

    def on_touch_up(self, touch):
        end_time = time.time()
        delta = (end_time - (self._touch_start or 0)) * 1000
        Clock.unschedule(self._slice_callback)
        if (self._long_press_callback is not None and
                delta > self.long_press_interval):
            self.dispatch('on_long_press')
        self._touch_start = self._touch_uid = None
        self._long_press_callback = self._slice_callback = None
        super(TimedButton, self).on_touch_up(touch)

    def on_long_press(self):
        pass

    def on_time_slice(self):
        pass

rawDescription: Bind working at random times

description: Bind working at random times


code:
def last_index(xs, key):
    index = None
    for i in xrange(len(xs)-1, 0, -1):  # iterate from last item to first
        if xs[i] == key:
            index = i
            break  # found the rightmost index, exit the loop
    return index

rawDescription: How to get the last occurrence of list as output?

description: Get the last occurrence of list as output


code: foo(**args)

rawDescription: Get the order of parameters for python function?


rawDescription: Python generate from list instead of Genfromtext


caption: SublimeREPL

mnemonic: r

caption: Python

caption: Python - Anaconda

mnemonic: p

type: subprocess

cmd: /path/to/Anaconda/python -i -u

external_id: python

caption: IPython - Anaconda

SUBLIMEREPL_EDITOR: $editor

rawDescription: How Do I Setup SublimeREPL with Anaconda's interpreter?


code:
sample = '2014-07-28 16:46:39,221--sys.log--DEBUG--hello:61---hello world'
fields = ('asctime', 'name', 'levelname', 'funcName', 'message')
values = { k: v for k, v in zip(fields, sample.split('--', len(fields) - 1)) }
# and do some mending
values['funcName'], values['lineno'] = values['funcName'].split(':')
values['message'] = values['message'][1:]

rawDescription: Convert formatted log string back to LogRecord


code:
for f in args:
    process(f)

rawDescription: Modify python script to run on every file in a directory


code:
class Integer(object) :
    def __init__(self, val=0) :
        self._val = int(val)
    def __add__(self, val) :
        if type(val) == Integer :
            return Integer(self._val + val._val)
        return self._val + val
    def __iadd__(self, val) :
        self._val += val
        return self
    def __str__(self) :
        return str(self._val)
    def __repr__(self) :
        return 'Integer(%s)' %self._val

rawDescription: Creating my own "integer" object in Python


code:
S = []
for i in range(0,24):
    s = np.arange(i*100,i*100+60)
    s = list(s)
    S = S + s

rawDescription: To fill the missing data lines with pandas reindex function


code:
import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_suplot(111)
ax.contourf(x, y, z)
ax.colorbar()
plt.show()

rawDescription: Python reading X and Y values and assigning to Z specific X Y pairs


rawDescription: Obfuscated mandlebrot function - can someone deobfuscate it?


code:
quit = False

while not quit:
    d = input()
    print(d)
    if d == '': quit = True

rawDescription: Input() to Allow <Enter Key> to Insert New Line Instead Of Returning Out of the Code in Python 3.x


code:
import Tkinter as tk
root = tk.Tk()
root.withdraw()

rawDescription: How do I get rid of Python Tkinter root window?

description: Get rid of Python Tkinter root window


code: query._group_by = False

rawDescription: Is it possible to reset group_by items of a sqlalchemy query object in python?


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

x = np.array([821,576,473,377,326,300])
y = np.array([255,235,208,166,157,140])

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

Param=collections.namedtuple('Param','x0 y0 c k')
p_guess=Param(x0=600,y0=200,c=100,k=0.01)
p,cov,infodict,mesg,ier = optimize.leastsq(
    residuals,p_guess,args=(x,y),full_output=1,warning=True)
p=Param(*p)
xp = np.linspace(100, 1600, 1500)
print('''\
x0 = {p.x0}
y0 = {p.y0}
c = {p.c}
k = {p.k}
'''.format(p=p))

rawDescription: How to get RMSE from scipy.optimize.leastsq module

description: Get RMSE from scipy.optimize.leastsq module


code:
ne = (df1 != df2).any(1)
ne

rawDescription: Outputting difference in two pandas dataframes side by side - highlighting the difference


code:
from multiprocessing import Pool

def function_to_process_a(row):
    return row * 42 # or something similar

# replace 4 by the number of cores that you want to utilize
with Pool(processes=4) as pool:
    # The lists are processed one after another,
    # but the items are processed in parallel.
    processed_sublist_a = pool.map(function_to_process_a, sublist_a)
    processed_sublist_b = pool.map(function_to_process_b, sublist_b)
    processed_sublist_c = pool.map(function_to_process_c, sublist_c)
    processed_sublist_d = pool.map(function_to_process_d, sublist_d)

rawDescription: How to split python work between cores? (Multiprocessing lib)

description: Split python work between cores? (Multiprocessing lib)


rawDescription: Sort a numpy array by another array, along a particular axis


rawDescription: Python's re library's sub method "eating" capturing groups


code:
import  wx
class SimplePanel(wx.Panel):
    def __init__(self,parent,id,str_val):
        wx.Panel.__init__(self,parent,id,style=wx.SIMPLE_BORDER)
        self.sz = wx.BoxSizer()
        self.sz.Add(wx.StaticText(self,-1,str_val),0,wx.ALIGN_CENTER)
        self.SetSizer(self.sz)
class   MyCustomPanel(wx.Panel):
    def __init__(self,parent,id):

        wx.Panel.__init__(self,parent,id)
        self.sz =   wx.GridSizer(5,5,0,0)
        for i   in  range(25):
            self.sz.Add(SimplePanel(self,-1,str(i)),0,wx.GROW)
        self.SetSizer(self.sz)

if  __name__    ==  "__main__":
    a   =   wx.App(redirect=False)
    f1 = wx.Frame(None,-1)
    f   =   MyCustomPanel(f1,-1)
    #f.OnPaint(None)
    f1.Show()
    a.MainLoop()

rawDescription: How to make a Grid in wxPython?

description: Make a Grid in wxPython


code: d = { var: rest for var, equals, rest in (l.split(None, 2) for l in path_output) }

rawDescription: Using Python2.6 to Parse Bash Output

description: Using Python2.6 to Parse Bash Output


code:
import example
def test(fn, a1, expect=None):
    try:
        example.perform(fn, a1)
        assert(expect is None)
    except Exception as e:
        assert(isinstance(e, expect))

test(lambda x: 42, None)
test(lambda x, y=2: 42, None)
test(lambda x=1, y=2: 42, None)
test(lambda *args: None, None)
test(lambda: 42, None, ValueError)
test(lambda x, y: 42, None, ValueError)

class Mock:
    def method_no_arg(self): pass
    def method_with_arg(self, x): pass
    def method_default_arg(self, x=1): pass
    @classmethod
    def cls_no_arg(cls): pass
    @classmethod
    def cls_with_arg(cls, x): pass
    @classmethod
    def cls_with_default_arg(cls, x=1): pass

mock = Mock()
test(Mock.method_no_arg, mock)
test(mock.method_no_arg, mock, ValueError)
test(Mock.method_with_arg, mock, ValueError)
test(mock.method_with_arg, mock)
test(Mock.method_default_arg, mock)
test(mock.method_default_arg, mock)
test(Mock.cls_no_arg, mock, ValueError)
test(mock.cls_no_arg, mock, ValueError)
test(Mock.cls_with_arg, mock)
test(mock.cls_with_arg, mock)
test(Mock.cls_with_default_arg, mock)
test(mock.cls_with_default_arg, mock)

rawDescription: How to validated a boost::python::object is a function signature with an argument

description: Validated a boost::python::object is a function signature with an argument


code:
c = dict(a, cd=3, ed=5)
type(c)  #returns a dict

rawDescription: update method of python dictionary did not work

description: Update method of python dictionary did not work


code:
with astropy.io.fits.open(filename, mode='update') as hdus:
    hdus[0].add_checksum() # Fill in the arguments like you need them

rawDescription: Astropy add checksum to existing fits file


code:
import os

cwd = os.getcwd()
contents = os.listdir(cwd)

rawDescription: How to get only the subfolders of my cwd in python

description: Get only the subfolders of my cwd in python


code:
import re
text = "text, 1CTT, 2IR8, 35TR, 4T1R, smth else"
pattern = re.compile(r"[0-9][A-Z0-9]{3}")
pattern.findall(text)

rawDescription: define a regular expression in python

description: Define a regular expression in python


code:
datacursor(l, hover=True, point_labels=df['E'],
           formatter=lambda **kwargs: kwargs['point_label'][0])

rawDescription: How to show data labels when you mouse over data

description: Show data labels when you mouse over data


code:
coro = asyncio.sleep(1, result=3, loop=loop)
task = asyncio.ensure_future(coro, loop=loop)
result = loop.run_until_complete(task)
print("Result: {}".format(result))
print("CPU time: {:.4f}".format(task.cputime))

rawDescription: How to measure Python's asyncio code performance?

description: Measure Python's asyncio code performance


code:
def build(self):
    parent = Widget()
    self.painter = MyPaintWidget()
    clearbtn = Button(text='Clear')
    clearbtn.bind(on_release=self.clear_canvas)
    parent.add_widget(self.painter)
    parent.add_widget(clearbtn)

    quitbtn = Button(pos=(100,0),text='quit')
    quitbtn.bind(on_release=self.quit_app)
    parent.add_widget(quitbtn)
    return parent

rawDescription: How can I add one more button on kivy?

description: Add one more button on kivy


code: "field-checks"

rawDescription: 'CheckboxSelectMultiple' options -not aligned


rawDescription: Trying to create a list of users in AD

description: Trying to create a list of users in AD


code:
x = pd.read_csv("data.txt", delimiter='\n', dtype=str, squeeze=True)
x

rawDescription: Vectorized Splitting of String on Character Count using Numpy or Pandas


code:
#create node <mObject>
element = document.createElement("mObject")
#add text content to the node
element.appendChild(document.createTextNode("content"))
#add attribute id to the node
element.setAttribute("id"  , "foo")
#result: <mObject id="foo">content</mObject>

rawDescription: Minidom element insertion into xml

description: Minidom element insertion into xml


code: result = re.sub(r'(\d+)', r'[\1]', inputstring)

rawDescription: Add [] around numbers in strings

description: Add [] around numbers in strings


code:
year = time.strftime('%Y')
month = time.strftime('%m')
day = time.strftime('%d')
hour = time.strftime('%H')
minute = time.strftime('%M')

rawDescription: Setting timezone in Python

description: Setting timezone in Python


code:
# module global_vals
VAL1 = get_from_db("...")
VAL2 = get_from_db("...")

rawDescription: Django Cached Class

description: Django Cached Class


rawDescription: Constructing String Without Concatenation in Python 2.7


code:
def is_prime(n):
    if n<=1: return False
    if n<=3: return True
    if not n%2 or not n%3: return False
    i=5
    while i*i<=n:
        if n%i==0: return False
        i+=2
        if n%i==0: return False
        i+=4
    return True

rawDescription: Prime number finder - optimization

description: Prime number finder - optimization


code:
def split_file(name):
    with open(name) as f:
        for l in f:
            if l:
                fn = temp_file_name(l)
                with open(fn, 'a') as of:
                    of.write(l)

rawDescription: Efficent way to split a large text file in python


code:
a_csc = scipy.sparse.csc_matrix(a)
a_csc.indices
rows, where = np.unique(a_csc.indices, return_inverse=True)
where = np.bincount(where)
rows
where
np.sum(where**2)

rawDescription: numpy matrix multiplication to triangular/sparse storage?

description: Numpy matrix multiplication to triangular/sparse storage


code:
agent = colander.SchemaNode(
    colander.String(),
    validator=agent_validator,
    widget=widget.AutocompleteInputWidget(
        size=40,
        style="width: 300px",
        min_length=3,
        values=url,
        css_class="form-control"
        ),
    title="Agent*")

rawDescription: How to make a Horizontal form with deform 2?

description: Make a Horizontal form with deform 2


code:
# Setthe callback name to "n"
convert_url = "http://quotes.money.163.com/stocksearch/json.do?type=&count=10&word=000001&callback=n"

rawDescription: How to write a regular expression to search such string?

description: Write a regular expression to search such string


code:
user_sow = 3  # wednesday (monday is 1, sunday is 7)

tmp.apply(lambda x: x.isocalendar()[1] - (x.isoweekday() < user_sow))

rawDescription: Python: Define starting day in week definition in isocalendar or strftime or else


code:
div  = response.xpath('//div[@class="product-description"]')[0]
div.css('h2::text').extract()
div.css('span[class="product-price-integer"]::text').extract()

rawDescription: Scrapy (Python) - skipping section of site


code:
import re
re.findall("[a-zA-Z0-9]+", "hello there1 A2... bl3h")
#>>> ['hello', 'there1', 'A2', 'bl3h']

rawDescription: Python: finding sequences in string

description: Python: finding sequences in string


code:
import numpy as np

# I choose the example f(x,y) = x**2 + y**2, with x,y the 1st and 2nd element of x below:
def f(x):
    return x[0]**2+x[1]**2

def f_jac_hess(x):
    if all(x==f_jac_hess.lastx):
        print('fetch cached value')
        return f_jac_hess.lastf
    print('new elaboration')
    res = array([2*x[0],2*x[1]]),array([[2,0],[0,2]])

    f_jac_hess.lastx = x
    f_jac_hess.lastf = res

    return res

f_jac_hess.lastx = np.empty((2,)) * np.nan

f_jac = lambda x : f_jac_hess(x)[0]
f_hes = lambda x : f_jac_hess(x)[1]

rawDescription: scipy.optimize.minimize : compute hessian and gradient together

description: Scipy.optimize.minimize : compute hessian and gradient together


code:
output
[{'type': 'xxxx'}, {'type': 'cccc'}, {'type': 'oooo'}, {'type': 'xxxx'}, {'type': 'cccc'}]

rawDescription: Python: sort specific pairs of dictionaries in a list of dictionaries based on occurrence of value


code:
import os
i = 0
while True:
    i += 1
    newname = '{}{:d}.png'.format(filename, i)
    if os.path.exists(newname):
        continue
    plt.savefig(newname)
    break

rawDescription: Python: Keep savefig from overwriting old plots


code:
class MD5TransparentFilter:
    def __init__(self, source):
        self._sig = hashlib.md5()
        self._source = source

    def __iter__(self):
        for line in self._source:
            self._sig.update(line)
            yield line

    def hexdigest(self):
        return self._sig.hexdigest()

rawDescription: python on-the-fly md5 as one reads a stream

description: Python on-the-fly md5 as one reads a stream


code:
import Tkinter as tk

class Drag_Window:
    def __init__(self, name, sizex, sizey, posx, posy, title, titlesize):
        self.name = name
        name.overrideredirect(True)
        name.config(relief='solid', bd=1, bg='white')
        name.wm_geometry("%dx%d+%d+%d" % (sizex,  sizey,  posx,  posy))
        frame = tk.Frame(name, width=sizex, height=80, relief='solid', bd=1, bg='black')
        frame.place(x=0, y=0)
        frame.bind("<ButtonPress-1>", self.StartMove)
        frame.bind("<ButtonRelease-1>", self.StopMove)
        frame.bind("<B1-Motion>", self.OnMotion)
        label = tk.Label(frame, text=title, font=('calibri', titlesize), bg='black', fg='white')
        label.place(x=10, y=15)
        self.button = tk.Button(frame, text='EXIT', font=('calibri', 13), bg='red', relief='flat', bd=1, width=8, pady=3, command=name.destroy)
        self.button.place(x=1170, y=20)
        frame2 = tk.Frame(name, width=sizex, height=20, relief='solid', bd=1, bg='black')
        frame2.place(x=0, y=sizey-20)

    def StartMove(self, event):
        self.x = event.x
        self.y = event.y

    def StopMove(self, event):
        self.x = None
        self.y = None

    def OnMotion(self, event):
        x1 = self.x
        y1 = self.y
        x2 = event.x
        y2 = event.y
        deltax = x2 - x1
        deltay = y2 - y1
        a = self.name.winfo_x() + deltax
        b = self.name.winfo_y() + deltay
        self.name.geometry("+%s+%s" % (a, b))

rawDescription: Python tkinter accessing object properties


code:
#!/usr/bin/env python
from mymodule import MyApplication

application= MyApplication()

if __name__=='main':
    import wsgiref.handlers
    wsgiref.handlers.CGIHandler().run(application)

rawDescription: How would you set up a python web server with multiple vhosts?


code:
import os
import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
wintypes.LPBOOL = ctypes.POINTER(wintypes.BOOL)

ERROR_NO_MORE_FILES = 0x0012
ERROR_BAD_LENGTH    = 0x0018
ERROR_MOD_NOT_FOUND = 0x007E

INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
DONT_RESOLVE_DLL_REFERENCES = 0x00000001
MAX_PATH = 260
MAX_MODULE_NAME32 = 255
TH32CS_SNAPMODULE   = 0x00000008

class MODULEENTRY32W(ctypes.Structure):
    _fields_ = (('dwSize',        wintypes.DWORD),
                ('th32ModuleID',  wintypes.DWORD),
                ('th32ProcessID', wintypes.DWORD),
                ('GlblcntUsage',  wintypes.DWORD),
                ('ProccntUsage',  wintypes.DWORD),
                ('modBaseAddr',   wintypes.LPVOID),
                ('modBaseSize',   wintypes.DWORD),
                ('hModule',       wintypes.HMODULE),
                ('szModule',      wintypes.WCHAR * (MAX_MODULE_NAME32 + 1)),
                ('szExePath',     wintypes.WCHAR * MAX_PATH))
    def __init__(self, *args, **kwds):
        super(MODULEENTRY32W, self).__init__(*args, **kwds)
        self.dwSize = ctypes.sizeof(self)

LPMODULEENTRY32W = ctypes.POINTER(MODULEENTRY32W)

def errcheck_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

def errcheck_ihv(result, func, args):
    if result == INVALID_HANDLE_VALUE:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.LoadLibraryExW.errcheck = errcheck_bool
kernel32.LoadLibraryExW.restype = wintypes.HMODULE
kernel32.LoadLibraryExW.argtypes = (wintypes.LPCWSTR,
                                    wintypes.HANDLE,
                                    wintypes.DWORD)

kernel32.FreeLibrary.errcheck = errcheck_bool
kernel32.FreeLibrary.argtypes = (wintypes.HMODULE,)

kernel32.GetProcAddress.errcheck = errcheck_bool
kernel32.GetProcAddress.restype = wintypes.LPVOID
kernel32.GetProcAddress.argtypes = (wintypes.HMODULE,
                                    wintypes.LPCSTR)

kernel32.CloseHandle.errcheck = errcheck_bool
kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)

kernel32.CreateToolhelp32Snapshot.errcheck = errcheck_ihv
kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel32.CreateToolhelp32Snapshot.argtypes = (wintypes.DWORD,
                                              wintypes.DWORD)

kernel32.Module32FirstW.errcheck = errcheck_bool
kernel32.Module32FirstW.argtypes = (wintypes.HANDLE,
                                    LPMODULEENTRY32W)

kernel32.Module32NextW.errcheck = errcheck_bool
kernel32.Module32NextW.argtypes = (wintypes.HANDLE,
                                   LPMODULEENTRY32W)

def GetRemoteProcAddress(pid, filename, procname):
    procname = procname.encode('utf-8')
    hLocal = kernel32.LoadLibraryExW(filename, None,
                                     DONT_RESOLVE_DLL_REFERENCES)
    try:
        procaddr = kernel32.GetProcAddress(hLocal, procname)
    finally:
        kernel32.FreeLibrary(hLocal)
    modname = os.path.basename(filename)
    hRemote = GetRemoteModuleHandle(pid, modname)
    return hRemote - hLocal + procaddr

def GetRemoteModuleHandle(pid, modname):
    modname = modname.upper()
    if '.' not in modname:
        modname += '.DLL'
    while True:
        try:
            hProcessSnap = kernel32.CreateToolhelp32Snapshot(
                                TH32CS_SNAPMODULE, pid)
            break
        except OSError as e:
            if e.winerror != ERROR_BAD_LENGTH:
                raise
    try:
        modentry = MODULEENTRY32W()
        kernel32.Module32FirstW(hProcessSnap,
                                ctypes.byref(modentry))
        while True:
            if modentry.szModule.upper() == modname:
                return modentry.hModule
            try:
                kernel32.Module32NextW(hProcessSnap,
                                       ctypes.byref(modentry))
            except OSError as e:
                if e.winerror == ERROR_NO_MORE_FILES:
                    break
                raise
        raise ctypes.WinError(ERROR_MOD_NOT_FOUND)
    finally:
        kernel32.CloseHandle(hProcessSnap)

rawDescription: GetModuleHandleA fails to get modules not used by python.exe when attached to another process


code:
def quicksort(A):
    if len(A) > 1:
        pivot = A[0]
        L = []
        E = []
        R = []
        for i in A:
            if i < pivot:
                L.append(i)
            elif i == pivot:
                E.append(i)
            else:
                R.append(i)
        quicksort(L)
        quicksort(R)
        A[:] = L + E + R

rawDescription: Python QuickSort returning original input


code:
import string

allow_characters = "#.-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
all_characters = string.maketrans('', '')
delete_characters = all_characters.translate(None, allow_characters)

s = s.translate(None, delete_characters)

rawDescription: Python Regular Expression Escape or not

description: Python Regular Expression Escape or not


code:
def myfunc(lst):
     return [item for item in lst if len(item) > 1 and item[0] == item[-1]]

rawDescription: Function that takes a list of strings and returns another specific list


code:
def rpn(arr, seq):
    '''
    Reverse Polish Notation algorithm
    (this version works only for binary operators)
    arr: array of objects
    seq: rpn sequence containing indices of objects from arr and functions
    '''
    stack = []
    for x in seq:
        if isinstance(x, int):
        # it's an object: push it to stack
            stack.append(arr[x])
        else:
        # it's a function: pop two objects, apply the function, push the result to stack
            b = stack.pop()
            #a = stack.pop()
            #stack.append(x(a,b))
            ## shortcut:
            stack[-1] = x(stack[-1], b)
    return stack.pop()

rawDescription: ordered reduce for multiple functions in python

description: Ordered reduce for multiple functions in python


code:
numbers = [3, 5, 77, 8]
print(id(numbers))
max_number = max(numbers)
numbers[:] = [number for number in numbers if number != max_number]
print(id(numbers))

rawDescription: How do you find and delete the highest integer in a list of unknown integers

description: Find and delete the highest integer in a list of unknown integers


rawDescription: Python convert a bytearray to hex array

description: Python convert a bytearray to hex array


rawDescription: every other element in a list then reverse

description: Every other element in a list then reverse


code:
with open("reference") as reference_file:
    references = reference_file.read().splitlines()

rawDescription: Hadoop/Python: Loading a reference file to use in the mapper


code:
from bs4 import BeautifulSoup
import re
sample = '''\

Website:  http://www.aa.com

'''
soup = BeautifulSoup(sample)
soup.find(text=re.compile('Website:'))
soup.find(text=re.compile('Website:')).next_sibling

rawDescription: BeautifulSoup - How do I extract a substring of a string between tags?


code:
q = """SELECT ?x ?z ?y
        WHERE {
           course:%s course:termName ?x;
                  ?s ?t.
           ?s ?d ?z.
           ?t course:termName ?y.
           FILTER (regex(?z,'[^a-z0-9]','i') && isLiteral(?z) )
        }ORDER BY ASC(?s)
        """%var_value

rawDescription: SPARQL parameterized queries

description: SPARQL parameterized queries


code:
import csv
import requests
from time import sleep

DELAY = 2
GENUS_COL = 4
SPECIES_COL = 5

with open("fish.csv") as inf:
    next(inf)  # skip header row
    for row in csv.reader(inf):
        url  = make_url(row[GENUS_COL], row[SPECIES_COL])

        # should add error handling, in case
        #   that page doesn't exist
        html = requests.get(url).text

        length = get_length_in_cm(html)

        # now store the length value somewhere

        # be nice, don't pound their site
        sleep(DELAY)

rawDescription: Python Search and Scrape

description: Python Search and Scrape


code:
import numpy as np
import pandas as pd

factor = pd.cut(distance, 100)

# the crosstab dataframe with the value counts in each bucket
ct = pd.crosstab(factor, adjacency, margins=True,
                 rownames=['distance'], colnames=['adjacency'])

# from here computing the probability of nodes being adjacent is straightforward
ct['prob'] = np.true_divide(ct[1], ct['All'])

rawDescription: Using pandas for the probability of two nodes to be linked in a network


code:
def translation(seq):
    return [(x[0], sorted(seq, key=lambda t: t[1]).index(x)) for x in seq]

rawDescription: Python sequence translation

description: Python sequence translation


code:
with open('file_b', 'r') as f,open('file_a', 'r') as template:
    lines = template.readlines()
    lines2 =  list(csv.reader(f))
    prod = (product(lines,lines2))
    for x,y in prod:
        print (x,y)

rawDescription: python: combining lists and strings

description: Python: combining lists and strings


code:
class Vote(db.Model):
    value = db.IntegerProperty() # Or whatever the vote value is.

rawDescription: More Efficient Way to Prevent Duplicate Voting


code:
def read_valid_terms(filename):
    with open(filename) as f:
        for line in f:
            for term in line.split():
                if any(c.isalpha() for c in term):
                    yield term

terms = list(read_valid_terms("terms.txt"))

rawDescription: Pythonic String Testing

description: Pythonic String Testing


code:
def test_doublewrap():
    from util import doublewrap
    from functools import wraps

    @doublewrap
    def mult(f, factor=2):
        '''multiply a function's return value'''
        @wraps(f)
        def wrap(*args, **kwargs):
            return factor*f(*args,**kwargs)
        return wrap

    # try normal
    @mult
    def f(x, y):
        return x + y

    # try args
    @mult(3)
    def f2(x, y):
        return x*y

    # try kwargs
    @mult(factor=5)
    def f3(x, y):
        return x - y

    assert f(2,3) == 10
    assert f2(2,5) == 30
    assert f3(8,1) == 5*7

rawDescription: How to create a Python decorator that can be used either with or without parameters?

description: Create a Python decorator that can be used either with or without parameters


code: temp = file.read().splitlines()

rawDescription: Reading a file without newlines

description: Reading a file without newlines


code:
my_weird_sort = np.empty_like(idx)
my_weird_sort[idx] = np.arange(idx.size)
my_weird_sort

rawDescription: Indirect-ish sort with Numpy

description: Indirect-ish sort with Numpy


rawDescription: Django Admin Non Staff Access Data Filtering


code:
obj=None
obj=[obj,9000][obj is None]
obj

rawDescription: How can i omit the redundant words in python condition loop

description: Omit the redundant words in python condition loop


rawDescription: Retrieving flickr favorites

description: Retrieving flickr favorites


code:
def lowercased(word): return word.lower()
lowercased('Some')
sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)

rawDescription: What is key=lambda

description: What is key=lambda


code:
def closeEvent(self):
   self.backEnd.stop()

rawDescription: Does closing a GUI in PyQt4 destroy its children Qobjects by default


code:
changes.eq(original)[count_columns].sum(1)
changes['match'] = changes.eq(original)[count_columns].sum(1).values
changes

rawDescription: Counting similarities among two pandas dataframes


rawDescription: Calling Python functions from inline C with scipy.weave


code:
def argNames(*args):
    """
    Get the names of the argument for a function

    Returns:
    --------
    A set whose members are the argument names

    Parameters:
    -----------
    func1, func2, ... -- the functions to be analyzed. The arguments
        are discovered by inspecting func. In addition, if
        func.argNames is defined, it is called (without arguments) to
        get a list of addition names. Any number of functions may be
        listed. If func is a class, func.__init__ is used
        instead. 'self' is always removed from the argument list.
    """
    names = set({})
    for a in args:
        try:
            func = a
            spec = inspect.getargspec(func)
        except TypeError:
            func = a.__init__
            spec = inspect.getargspec(func)
        names |= set(spec.args)
        try:
            names |= set(func.argNames())
        except AttributeError:
            pass
    names.discard('self')
    return(names)

def filterArgs(func, **kwargs):
    """
    Select keyword arguments for a function
    """
    args = argNames(func)
    ks = set(kwargs.keys())
    ks.discard('self')
    kinc = ks & args
    kexc = ks - args
    inc = {k: kwargs[k] for k in kinc}
    exc = {k: kwargs[k] for k in kexc}
    return(inc, exc)

rawDescription: How to promulgate a list of arguments for a python function?

description: Promulgate a list of arguments for a python function


code: from modname import ClassName

rawDescription: logging being stopped by importing a trivial function?

description: Logging being stopped by importing a trivial function


code: dict.__repr__.__get__(None, dict) is dict.__repr__  # None means no instance

rawDescription: Very strange behavior of operator 'is' with methods


code:
from ctypes import *

class mystruct(Structure):
    _fields_ = [("str", c_char_p),
                ("str_length", c_long),
                ("count", c_long)]

s = b"ABC" * 10
c = 44

#convert python string to null terminated c char array
c_str = create_string_buffer(s)
#cast char array to char*
c_str_pointer = cast(c_str, c_char_p)
#create structure
a = mystruct(c_str_pointer, len(s), c)

# print byte representation of structure
print(bytes(a))

print(a.str)
print(a.str_length)
print(a.count)

rawDescription: generating a binary buffer with python to be read in C as a struct

description: Generating a binary buffer with python to be read in C as a struct


code:
newFiles={'key1': [], 'key2':[], 'key_file':[]}
for i,j in enumerate(Files['key_file']):
  if j not in newFiles['key_file']:
     for key in newFiles.keys():
        newFiles[key].append(Files[key][i])
newFiles

rawDescription: Python remove duplicate values of one key in dict


rawDescription: Truncating multi-indexed dataframe

description: Truncating multi-indexed dataframe


code:
from itertools import chain,count,cycle
with open("out.txt","wb") as f:
    for eachlist in alllists:
        merged = zip(cycle([eachlist[0],]),count(1),eachlist[1:])
        f.write( "\t".join( map(str,chain.from_iterable(merged)) ) )
        f.write("\n")

rawDescription: Python speed up the code for reconstructing lists


rawDescription: How to split a column based on several string indices using pandas

description: Split a column based on several string indices using pandas


code:
import datetime

def iso_year_start(iso_year):
    "The gregorian calendar date of the first day of the given ISO year"
    fourth_jan = datetime.date(iso_year, 1, 4)
    delta = datetime.timedelta(fourth_jan.isoweekday()-1)
    return fourth_jan - delta

def iso_to_gregorian(iso_year, iso_week, iso_day):
    "Gregorian calendar date for the given ISO year, week and day"
    year_start = iso_year_start(iso_year)
    return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)

rawDescription: What's the best way to find the inverse of datetime.isocalendar()?


rawDescription: Strings, ints and leading zeros

description: Strings, ints and leading zeros


code:
from App1.App1 import App1, app1_init
from App2.App2 import App2
config = {'global': {'server.socket_host':  '0.0.0.0'}}
class Root():
    global config
    def __init__(self):
        self.app1 = App1('app1')
        self.app2 = App2('app2')
        config.update(self.app1.config)
        config.update(self.app2.config)

if __name__ == '__main__':
    app1_init()
    cherrypy.quickstart(Root(), '/', config)

rawDescription: Prevent code from running at import time


code:
def function(olinks):
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537)'}
    session = requests.Session()
    response = session.get(olinks, headers=headers)
    soup = BeautifulSoup(response.content)
    oname = soup.find("title")
    if oname.text.find('Saison') >= 0:
        regexp = r'(.*?\s+-\s+S)aison\s+(\d+)\s+\xc9.*?(\d+)(.*)'
        subst = "{title} {season:02d} Ep {episode}"
    else:
        regexp = r'(.*?\s+-)(\s+)\xc9.*?(\d+)(.*)'
        subst = "{title} Ep {episode}"
    return re.sub(regexp,lambda m: subst.format(title=m.group(1), season=int(m.group(2)) if m.group(2).find(" ")==-1 else "", episode=m.group(3)),oname.text)

rawDescription: how to use external code python in python files

description: Use external code python in python files


code:
True
False

rawDescription: Is it possible to create a completely new instance of the members of a parent class?


code:
subject = "by the way I know 54 how to take praise for 65 excellent questions 34 thank you for asking appreciated. One Two Three Four 55 Extend 66 a b c d AA BB CC DD 71 HH DD, JJ FF"
for match in re.finditer(r"(?=((?:\b[a-z]+[ ,]+){4}(?:\d+ (?:[a-z]+ ){1,3}?)*?\d+.*?(?:[ ,]+[a-z]+){4}))", subject, re.IGNORECASE):
    print(match.group(1))

rawDescription: python regex find substrings centered with numbers

description: Python regex find substrings centered with numbers


rawDescription: Pandas reformatting multiple columns into one.


rawDescription: Converting a column value when filtering in pandas


code:
# my_functions.py
from math   import sqrt
from pandas import DataFrame as df
#Or import pandas as pd

def sqrt_product(a, b):
    return sqrt(a*b)

def create_df(lst):
    return df(lst)
    #return pd.DataFrame(lst)

rawDescription: Python: how to properly import a function from another file that depends on module


code:
# 2x2 windows of the original array
windows = sliding_window(a, (2,2))
# make a windowed boolean array for indexing
notNan = sliding_window(np.logical_not(np.isnan(a)), (2,2))

rawDescription: resize a 2D numpy array excluding NaN

description: Resize a 2D numpy array excluding NaN


code: column_names = [col.name for col in MyClass.__table__.columns if not col.nullable]

rawDescription: return NOT NULL columns from class with sqlalchemy

description: Return NOT NULL columns from class with sqlalchemy


code: dt = np.dtype([('foo', np.float64, nfoo), ('bar', np.float64, nbar)])

rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


code: cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1')

rawDescription: general connection to a mysql server

description: General connection to a mysql server


code: povijest= sorted([list(set(x)) for x in povijest ])

rawDescription: sorting list of lists Python 2.7

description: Sorting list of lists Python 2.7


code:
parse_string = "http://www.google.pl/search?q={0}&restofurl".format(
               '%2C'.join(tag.strip() for tag in tags_list))
parse_string

rawDescription: Parsing a list into a url string

description: Parsing a list into a url string


code:
xml = """
<metaGroups>
    <Groups>
        <GroupID>age</GroupID>
        <description>age</description>
        <groupname>
            <Name>0 - <10</Name>
            <min>0</min>
            <minInc>TRUE</minInc>
            <max>10</max>
            <maxInc>FALSE</maxInc>
        </groupname>
        <groupname>
            <Name>10 - <18</Name>
            <min>10</min>
            <minInc>TRUE</minInc>
            <max>18</max>
            <maxInc>FALSE</maxInc>
        </groupname>
        <groupname>
            <Name>18 - <35</Name>
            <min>18</min>
            <minInc>TRUE</minInc>
            <max>35</max>
            <maxInc>FALSE</maxInc>
        </groupname>
        <groupname>
            <Name>35 - <50</Name>
            <min>35</min>
            <minInc>TRUE</minInc>
            <max>50</max>
            <maxInc>FALSE</maxInc>
        </groupname>
        <groupname>
            <Name>50 - <65</Name>
            <min>50</min>
            <minInc>TRUE</minInc>
            <max>65</max>
            <maxInc>FALSE</maxInc>
        </groupname>
        <groupname>
            <Name>65 - <75</Name>
            <min>65</min>
            <minInc>TRUE</minInc>
            <max>75</max>
            <maxInc>FALSE</maxInc>
        </groupname>
        <groupname>
            <Name>&ge;75</Name>
            <min>75</min>
            <minInc>TRUE</minInc>
        </groupname>
    </Groups>
</metaGroups>
"""

rawDescription: Grouping values using pandas cut

description: Grouping values using pandas cut


rawDescription: User flow after registration

description: User flow after registration


code:
from nltk.corpus import brown
wordcounts = nltk.ConditionalFreqDist(brown.tagged_words())
wordcounts["set"].tabulate(10)

rawDescription: Python NLTK - Making a 'Dictionary' from a Corpus and Saving the Number Tags


code:
def get_line(filename, n):
    with open(filename, 'r') as f:
        for line_number, line in enumerate(f):
            if line_number == n:
                return line

rawDescription: Python: linecache not working as expected?


code:
from .my_class import MyClass

__all__ = ['MyClass',]

rawDescription: python pep8 class in init imported but not used

description: Python pep8 class in init imported but not used


code: asd

rawDescription: Why don't these two string equal each other?


code:
items = [1,2,3,4,5]
inGroup, outGroup = partition(items, is_even)
inGroup
outGroup

rawDescription: python equivalent of scala partition

description: Python equivalent of scala partition


code: output, stderr = subprocess.Popen("some-program").communicate()

rawDescription: Subprocess calls are they done in parallel?


rawDescription: Extracting Data From Python Classes

description: Extracting Data From Python Classes


code:
# ...
def add_tab():
    text = "Tab {}".format(len(notebook.tabs()))
    frame = Frame(notebook, width=100, height=100)
    notebook.add(frame, text=text)

menu=MyMenu()
menu.add_command(label="Add tab", command=add_tab)
tk.config(menu=menu)

rawDescription: interaction of different elements of window in Tkinter

description: Interaction of different elements of window in Tkinter


code:
import itertools
a = '4433555555666666'
[''.join(value) for key, value in itertools.groupby(a)]

rawDescription: Split if two consecutive characters are not same


code:
import collections
from itertools import islice
preresult = collections.OrderedDict(zip(range(200), range(200)))
list(islice(preresult, 100))[-10:]

rawDescription: Get the first 100 elements of OrderedDict


code: df['Interval']=df['Interval'].apply(lambda x: x + Timedelta(days=1) if x < 0 else x)

rawDescription: Add 24 hours to a negative time difference in python


code:
((0 < abs(C)) & (abs(C) < 2.0**-126)).sum()  # number of subnormal entries
C.size

rawDescription: Strange performance results for numpy matrix multiplication


code:
import re
import json

#...your code...

for x in nodes:
    matches = re.findall(r'quoteDataObj\s\=\s\[(\{.+\})\]', str(x.text))
    if len(matches) > 0:
        python_dict = json.loads(matches[0])

rawDescription: Extracting between specific <script> </script> tag


code:
for key, group in groups:
    groupList = list(group)
    if len(groupList) > 1:
        print(groupList)

[{'command': '1;2;3;4', 'name': 'fire'}, {'command': '2;2;3;4', 'name': 'brain'}]

rawDescription: how to goup items in a list of dictionaries by matching values in python

description: Goup items in a list of dictionaries by matching values in python


rawDescription: Linear Programming (Simplex LP) PuLP?

description: Linear Programming (Simplex LP) PuLP


code:
import csv
with open('<excel file>','w') as f:
    writer = csv.writer(f)
    #writer.writerow([<header row>]) #uncomment this and put header, if you want header row , if not leave it commented.
    for x in zip(*list_of_lists):
        writer.writerow(x)

rawDescription: How to export a list with different size from python to excel

description: Export a list with different size from python to excel


code:
# A variable to keep track of the least-nested level of your hierarchy
top_lvl = ''
k = ''
for i in range(len(a)):
    # Pre-compute this value so you don't have to do it twice or more
    c = a[i].count(' ')
    # This case is the topmost level
    if c == 0:
        top_lvl = a[i]
        d[top_lvl] = []
    # This case is the middle level
    elif c == 1:
        d[a[i]]=[]
        k=a[i]
        d[top_lvl].append(k)
    # This case is the most deeply nested level
    else: # c==2
        d[k].append(a[i])

rawDescription: when i try to append value in dict its showing key error

description: When i try to append value in dict its showing key error


code: xlrd_results == openpyxl_results

rawDescription: Reading Excel file is magnitudes slower using openpyxl compared to xlrd


code:
varsdict = {}
for v in prob.variables():
    varsdict[v.name] = v.varValue

rawDescription: How to get the optimal optimization variables in Pulp with Python?

description: Get the optimal optimization variables in Pulp with Python


code:
from datetime import datetime, timedelta

twenty_hours= datetime.now() + timedelta(hours=20)

rawDescription: Calculate time after X hours?

description: Calculate time after X hours


code:
# get all Posts with has a least one tag from the list ["aa", "bb"]
q = sess.query(Post).filter(Post.tags.any(Tag.name.in_(["aa", "bb"])))

# get all Post with all of the tags in the list ["aa", "bb"]
q = sess.query(Post).filter(
        and_(
            Post.tags.any(Tag.name.in_(["aa"])),
            Post.tags.any(Tag.name.in_(["bb"])),
            )
        )

rawDescription: Searching many to many relationship

description: Searching many to many relationship


code:
merged = pd.merge(longref, melted, how='left')
#      Item    Position  value
# 0  Item 1  Contractor    1.0
# 1  Item 1  Contractor    1.0
# 2  Item 1  Contractor    NaN
# 3  Item 1   President    1.0
# 4  Item 1   President    1.0
# 5  Item 1   President    NaN
# 6  Item 2   President    1.0
# 7  Item 2   President    0.0
# 8  Item 2   President    1.0

grouped = merged.groupby(['Position'])
result = (grouped['value'].sum() / grouped['value'].count())*100
result = result.rename('Overall%').reset_index()

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


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

def main():
    data = [ 10.49531611,  22.49511583,  10.90891806,  18.99525417,
            21.57165972,   6.687755  ,   6.52137028,  15.86534639,
            18.53823556,   6.32563583,  12.99365833,  11.06817056,
            17.29261306,  15.31288556,  19.16236667,  10.38483333,
            14.51442222,  17.01413611,   6.96102278,  15.98508611,
            16.5287    ,  15.26533889,  20.83520278,  17.21952056,
             7.3225775 ,  16.42534361,  14.38649722,  21.63573111,  16.19249444]
    data = np.array(data)*60*60
    axes = plot_clock(data)
    for ax in axes:
        realign_polar_xticks(ax)
    plt.show()

def realign_polar_xticks(ax):
    for x, label in zip(ax.get_xticks(), ax.get_xticklabels()):
        if np.sin(x) > 0.1:
            label.set_horizontalalignment('left')
        if np.sin(x) < -0.1:
            label.set_horizontalalignment('right')

def plot_clock(data):
    def hour_formatAM(x, p):
        hour = x * 6 / np.pi
        return '{:0.0f}:00'.format(hour) if x > 0 else '12:00'

    def hour_formatPM(x, p):
        hour = x * 6 / np.pi
        return '{:0.0f}:00'.format(hour + 12) if x > 0 else '24:00'

    def plot(ax, theta, counts, formatter):
        colors = plt.cm.jet(theta / 12.0)
        ax.bar(theta, counts, width=np.pi/6, color=colors, alpha=0.5)
        ax.xaxis.set_major_formatter(tkr.FuncFormatter(formatter))

    plt.rcParams['font.size'] = 8

    bins = np.r_[0, 0.5:12, 12, 12.5:24,  23.99999]
    data = np.array(data) / (60*60)
    counts = np.histogram(data,bins)[0]

    counts[13] += counts[0]
    counts[-1] += counts[13]

    fig, axes = plt.subplots(ncols=2, figsize=(5.5, 3), dpi=200,
                             subplot_kw=dict(projection='polar'))
    fig.subplots_adjust(wspace=0.5)

    for ax in axes:
        ax.set(theta_offset=np.pi/2, theta_direction=-1,
               xticks=np.arange(0, np.pi*2, np.pi/6),
               yticks=np.arange(1, counts.max()))

    plot(axes[0], bins[1:13] * np.pi / 6, counts[1:13], hour_formatAM)
    plot(axes[1], bins[14:26] * np.pi / 6, counts[14:26], hour_formatPM)
    return axes

main()

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

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


code:
if x and y and z:
    ...

rawDescription: Python: How to chain boolean tests to get False as soon as it gets the first False


code:
row = []
title = soup.note.title.string
created = soup.note.created.string
row.append(title)
row.append(created)

rawDescription: Removing a tag and its contents in xml using BeautifulSoup an lxml in Python


code:
intA=int(input("Integer A: "))
intB=int(input("Integer B: "))

rawDescription: How do I change a string to an integer?

description: Change a string to an integer


code:
make_names(["a"])
make_names(["a"], ["b"])
make_names(["a"], ["b"], ["c"], ["d"])
make_names(["Johnny", "Joseph", "Mary"], ["Mendez", "Nash", "Johanson"], ["John", "Allen", "Ann"])

rawDescription: combining and looping through lists python

description: Combining and looping through lists python


code:
for filepath in iglob(os.path.join(folderpath,'*.txt')):
    with open(filepath,'r') as filehandle:
        words = set(removegarbage(filehandle.read()).split())
        counter.update(words)

rawDescription: word frequency calculation in multiple files

description: Word frequency calculation in multiple files


code:
import itertools as it
a = ['a','b','c']
l = [map("x".join, list(it.combinations(a, l))) for l in range(1,len(a)+1)]
l

rawDescription: Python, recursively reduce a list (combinations/permutations)


code:
from emoji import UNICODE_EMOJI

def is_emoji(s):
    count = 0
    for emoji in UNICODE_EMOJI:
        count += s.count(emoji)
        if count > 1:
            return False
    return bool(count)

rawDescription: Find there is an emoji in a string in python3


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

my_variables = {'list_a' : list_a}

def examineVar():
    for i in my_variables[input('>>> ')]:
        print(i, end='')

    print('\n')

examineVar()

rawDescription: How can I allow users to reference variables and other data structures via input?

description: Allow users to reference variables and other data structures via input


code:
import pandas as pd
columns=    ['text','lemma','pos','markintext','doublelemme','multiwordexpr','nodetail']

rows = [['Per','per','epsf',0,0,0,0],
    ['dietro a','dietro a','eilksl',0,0,1,0],
    ['Per','per','epsf',0,0,0,0]]

orig_f = pd.DataFrame(rows,columns=columns)
df = pd.DataFrame(columns=columns)

for index, row in orig_f.iterrows():
    # check for multiwordexpr
    if row[5] == 1:
        s = row.copy()
        s[0]   = row[0].split(' ')[0]
        row[0] = row[0].split(' ')[1]
        df = df.append(s)
        df = df.append(row)

    else:
        df = df.append(row)

df = df.reset_index(drop=True)
#there are no more multi words
df.ix[df['multiwordexpr']==1, 'multiwordexpr'] = 0

rawDescription: Insert new rows in pandas dataframe

description: Insert new rows in pandas dataframe


code:
class FromJSON():
    def __init__(self, string):
        self.string = string
    def decode(self):
        return json.loads(self.string)

dict_parser.add_argument('--dict',type=FromJSON)
arg2 = dict_parser.parse_args(['--dict', '{"name":"man", "address": "kac", "tags":"don"}'])

rawDescription: Python: Parse multiple datatypes using argparse


code:
...
widget.setGeometry(200, 200, 100, 50)
widget.show()
app.exec_()

rawDescription: PyQt4: Window shows up at another position after hide() and show()


code:
@userreg.route('/mypics',methods=['GET','POST'])
def mypics():
   if request.method=='POST':
      mydata=MyPics()
      mydata.name=request.form['myname']
      file=request.files['file']
      filedata=file.read()
      if file:
         mydata.pic=db.Blob(filedata)
      mydata.put()
      return redirect(url_for('home'))
   return render_template('mypicform.html')

rawDescription: Storing images in google datastore using Flask (Python)


code:
buff = fichier.read()
matches = re.findall(".*?I Doc ):.*", buff)
for match in matches:
    tableau = ...

rawDescription: Read only lines that contain certain specific string and apply regex on them


code:
def buttons_for_grid(key):
    return [buttons[button] for button in grid[key]]

rawDescription: method to create variables

description: Method to create variables


rawDescription: Bit masking in Python

description: Bit masking in Python


rawDescription: Grouping and finding most frequent values


rawDescription: Python - delete blank lines of text at the end of the file


code:
#Import the necessary namespaces
from Spotfire.Dxp.Application.Visuals import VisualContent
from Spotfire.Dxp.Application.Visuals import AxisRange
from Spotfire.Dxp.Data import DataPropertyClass

#Define variables
min = Document.Properties["StartDate"]
max = Document.Properties["EndDate"]

#Cast visual as specific plot type
#Note use of VisualContent for any chart type
plot1= plot1.As[VisualContent]()
plot2= plot2.As[VisualContent]()
plot3= plot3.As[VisualContent]()

#Set visualization parameters
plot1.XAxis.ManualZoom = True
plot2.XAxis.ManualZoom = True
plot3.XAxis.ManualZoom = True
plot1.XAxis.ZoomRange = AxisRange(min,max);
plot2.XAxis.ZoomRange = AxisRange(min,max);
plot3.XAxis.ZoomRange = AxisRange(min,max);

rawDescription: Set Spotfire Graph Axis Range Programatically


code: [t for t in myList if t != ()]

rawDescription: Python 3: Removing an empty tuple from a list of tuples


rawDescription: Qt - Get the pixel length of a string in a QLabel


code:
urlpatterns = patterns('',
    url('^test/$', ClassView.as_view(), name="test"),
)

rawDescription: Django class based generic view redirect


code:
from scipy.interpolate import SmoothBivariateSpline

x=x.ravel()
x=(x[x!=np.isnan])
y=y.ravel()
y=(y[y!=np.isnan])
z=z.ravel()
z=(z[z!=np.isnan])

xnew = np.arange(9,11.5, 0.01)
ynew = np.arange(10.5,15, 0.01)

f = SmoothBivariateSpline(x,y,z,kx=1,ky=1)

znew=np.transpose(f(xnew, ynew))

rawDescription: 2-d interpolation ignoring nan values

description: 2-d interpolation ignoring nan values


rawDescription: how to change the title of an image upload to a name in a class in django

description: Change the title of an image upload to a name in a class in django


rawDescription: Comprehensive `for...in` different from standard loops


code:
vv = [v-1 for v in vv]
vv
vv[3]

rawDescription: How to minus one on multiple variable? python

description: Minus one on multiple variable? python


code:
for integral in range(integral, 0, -1):  # xrange if you're using Python 2.x
    fractional1, integral1 = modf(a / (integral**2))
    print(fractional1)

rawDescription: How to pass a Tkinter Entry through a function

description: Pass a Tkinter Entry through a function


code:
self.tc_ZONEVOL1 = wx.TextCtrl(panel, -1, "", (0,0), (30,21))
self.sliderZone1 = wx.Slider(self, -1, 50, 0, 100, size=(400,10),
                         style=wx.SL_HORIZONTAL)

self.Bind(wx.EVT_SLIDER,lambda event: self.sliderUpdate(
     event, self.sliderZone1, self.tc_ZONEVOL1,), self.sliderZone1)

rawDescription: How to pass a wxWidget to a generic function?

description: Pass a wxWidget to a generic function


code:
import scitools.filetable

fp = open("blabla.dat", "r")
fp.next()

a, b, c, d, e = scitools.filetable.read_columns(fp)

rawDescription: Read columns from file where first row is string


code: sorted(inputlist, key=lambda t: -1 if t != (0, 0) else 0)

rawDescription: For Python, how to sort and lump elements in a fixed-sized list


code:
import time
import datetime

class timer():
    def start(self):
        while 1:
            x = datetime.datetime.utcnow()
            print(x.strftime('%M.%S.%f'))
            time.sleep(0.1)

worker = timer()
worker.start()

rawDescription: How to fix a timer issue

description: Fix a timer issue


rawDescription: How do I generate 8 different random numbers in python?

description: Generate 8 different random numbers in python


code:
print(dom.find("Body"))
# <Element Body at 8506cd4>

rawDescription: lxml etree xmlparser namespace problem

description: Lxml etree xmlparser namespace problem


code:
def my_function():
    print("Hello")

rawDescription: why does importing a module executes all statements in python?

description: Why does importing a module executes all statements in python


code:
('TrnIq: Thread on', 37)
('TrnIq: Thread on', 44)
('IP-Thread on', 33)
('FANOUT Thread on', 37)
('Filter-Thread on', 51)
('TRN TMR Test 2 Supervisor Thread on', 34)
('HomographyWarp Traking Thread[0] on', 26)

rawDescription: Best Method to Find Multiple String Occurrences in Python


code:
import re

pattern = re.compile(u"<.*?>| |&|\u260e",re.DOTALL|re.M)
s = u"bla ble \u260e blo"
re.sub(pattern, "", s)

rawDescription: How to eliminate the ☎ unicode?

description: Eliminate the ☎ unicode


code:
import re

print(re.sub(r'''(?x)    # VERBOSE mode
                 [#]     # literal #
                 |       # or
                 \s*     # zero-or-more spaces
                 \w*     # zero-or-more alphanumeric characters
                 [#]     # literal #
                 \w*     # zero-or-more alphanumeric characters
                 $       # end of line
                 ''',
             '', # substitute matched text with an empty string
             'What a #great day #happy'))

rawDescription: regex to remove the last word if it contains a character

description: Regex to remove the last word if it contains a character


code:
k = numpy.zeros((1,4))
k

rawDescription: Why does python 2.6 not update my numpy array?


rawDescription: Python: finding files with matching extensions or extensions with matching names in a list


code:
def f(j, ls):
    output = [ls[:] for _ in xrange(len(ls) + 1)]
    for i, sublist in enumerate(output):
        output[i].insert(i, j)
    return output
f('k', range(4))
def f(j, ls):
    return [ls[:i] + [j] + ls[i:] for i in xrange(len(ls) + 1)]
f('k', range(4))

rawDescription: Insert an element into a list in python

description: Insert an element into a list in python


code:
from collections import Counter
aList = [{'country': 'japan', 'city': 'tokyo', 'year': '1995'}, {'country': 'japan', 'city': 'hiroshima', 'year': '2005'}, {'country': 'norway', 'city': 'oslo', 'year': '2005'}]
# Get all of the country names
[x['country'] for x in aList]
# Total the names
Counter(x['country'] for x in aList)
# Get the most common country
Counter(x['country'] for x in aList).most_common(1)
# Use iterable unpacking to extract the country name
[(country, _)] = Counter(x['country'] for x in aList).most_common(1)
print(country)

rawDescription: Count Occurrences of a Value in a List of Dictionaries


code:
from xadmin.plugin.related import RELATE_PREFIX  # or just set RELATE_PREFIX = '_rel_'

qs = qs.filter(**{key[len(RELATE_PREFIX):]: value
                  for key, value in request.GET.iteritems()
                  if key.startswith(RELATE_PREFIX)})

rawDescription: Overidde queryset filters while generating django admin URLs


code:
class Borg(object):
    _state = {}
    def __new__(cls, *p, **k):
        self = object.__new__(cls)
        self.__dict__ = cls._state
        return self

    def __init__(self, foo):
        print(foo)

rawDescription: Borg design with new-style classes

description: Borg design with new-style classes


code:
import urllib, cStringIO
from PIL import Image

# given an object called 'link'

SITE_URL = "http://www.targetsite.com"
URL = SITE_URL + link['src']
# Here's a sample url that works for demo purposes
# URL = "http://therealtomrose.therealrosefamily.com/wp-content/uploads/2012/08/headshot_tight.png"
file = cStringIO.StringIO(urllib.urlopen(URL).read())
im=Image.open(file)
width, height = im.size
if link.has_key('height'):
    height = link['height']  # set height if site modifies it
if link.has_key('width'):
    width = link['width']  # set width if site modifies it

rawDescription: Get Image Dimensions from Url in Python

description: Get Image Dimensions from Url in Python


code: deck = ['%i of %s' % (n, suit) for suit in ('spades', 'hearts', 'diamonds', 'clubs') for n in range(2, 10)]

rawDescription: How to write this Python code shorter?

description: Write this Python code shorter


code:
import threading
import time
def regen_life(player):
    while True:
        player.life += amount_of_life
        time.sleep(1)

threading.Thread(target=regen_life, args=(game.player,)).start()
while True:
    do_some_updates(game)
    render_frame(game)

rawDescription: In Python, how do I add 1 every second

description: In Python, how do I add 1 every second


code:
def doStuff():
    test = "hello world" # These 2 lines could be one
    return test          # return "hello world"

def main():
    test = doStuff()
    print(test)

rawDescription: Are variables instantiated to 'None' pass by value in Python?


code: filt = resonator.poles_exp(freq=freq * Hz, bandwidth=bw * Hz)

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
import sys
sys.modules['A'] = A
sys.modules['B'] = B
sys.modules['C'] = C

rawDescription: Importing a python module by path

description: Importing a python module by path


code:
def hello_world():
    print('hello world!')

hello_world()

rawDescription: py.test - How to inherit other tests

description: Py.test - How to inherit other tests


rawDescription: python argparse extra args

description: Python argparse extra args


code:
from flask.ext.admin.model import BaseModelView

admin.add_view(BaseModelView(MyModel, 'Menu Text'))

rawDescription: Flask-Admin : Customize table name for the admin interface


code:
def costs(vol):
    interval = vol/10 # vol must be positive int
    if interval in dic:
        price = dic[interval]
        return price[0] + price[1]*(vol-price[1] + 10)
    else:
        return dic[3][0] + dic[3][1]*(vol-dic[3][1] + 10)

rawDescription: What is an efficient way to calculate cost constrained by thresholds


code:
seedresult = None

def seed(addy):
    global seedresult
    ...

rawDescription: Function Return But No Value

description: Function Return But No Value


code:
@decorate_all_functions(print_on_call)
class Foo:
    def func1(self):
        print('1')
    def func2(self):
        print('2')

c = Foo()
c.func1()
c.func2()

rawDescription: Catch "before/after function call" events for all functions in class


code:
Lines = []

for line in File1:
    Lines.append(int(line))

rawDescription: write specific lines from a file python

description: Write specific lines from a file python


code:
def RebuildProxy(func, token, serializer, kwds):
    '''
    Function used for unpickling proxy objects.

    If possible the shared object is returned, or otherwise a proxy for it.
    '''
    server = getattr(process.current_process(), '_manager_server', None)

    if server and server.address == token.address:
        return server.id_to_obj[token.id][0] # This returns the referent
    else:
        incref = (
            kwds.pop('incref', True) and
            not getattr(process.current_process(), '_inheriting', False)
            )
        return func(token, serializer, incref=incref, **kwds) # This returns the Proxy

rawDescription: Python: How to pass an Autoproxy object

description: Python: How to pass an Autoproxy object


rawDescription: Python. Get pairs of keys (n0, _), (n1, _) with maximum values for each key pair (n0, a), (n0, b) in a dictionary. Not a trivial task


code:
iter(f) is f
iter(r) is r
iter(ri) is ri

rawDescription: how to check if an iterable allows more than one pass?

description: Check if an iterable allows more than one pass


code:
faces = {11: "Queen", 12: "Jack", 13: "King"} # it's usually J Q K, though
cardnum1 = faces.get(num1, num1)
suits = {1: "Spades", 2: "Hearts", 3: "Diamonds", 4: "Clubs"}
cardnum2 = suits[num2]

rawDescription: Python Random Playing Card Generator Game


rawDescription: Adding null values to a pandas dataframe


code:
from pylab import *
a=array(rand(10000,4))*[[20,20,200,1]] # data in a 20*20*200 space
a[:,:2] //= 1 # int coords for X,Y
bj=a.T[0]+1j*a.T[1] # trick for sorting on 2 cols.
b=np.unique(bj)
ib=bj.argsort() #  indices for sorting /X,Y
splits=bj[ib].searchsorted(b) # indices for splitting.
xy=np.split(a[ib],splits)  # list of subsets of data grouped by (x,y)
c=array([s[abs(s.T[2]-100).argmin()] for s in xy[1:]]) #locate the good point in each list
print(c[:10])

rawDescription: Find closest value in array column 4 where array column 1 and 2 match data of another array. Create a new array extracting the results


code:
def func(lst, start):
    result = []
    while True:
        found = False
        for item in lst:
            if start in item:
                item.remove(start)
                result.append(start)
                found = True
                if item:
                    start = item[0]
                    item.remove(start)
                    break
        if not found:
            result.append(start)
            break
    return result

rawDescription: Python - Can't code iteration or recursion


rawDescription: Why does sage treat local python variables as global?


rawDescription: Redirecting Django built-in login View to a URL taking user's pk as argument


code:
img = 'ABCDEFGHIJKL'
x, y = 4, 3
def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

[row for row in chunks(img, x)]
''.join(reversed([row for row in chunks(img, x)]))

rawDescription: Flip (reverse) image vertically given its string?


rawDescription: Python 2.5 for loop

description: Python 2.5 for loop


code:
import numpy as np

lats = np.linspace(50, 60, 11)
lons = np.linspace(110, 120, 11)

xx, yy = np.meshgrid(lats, lons)

rawDescription: Subdividing NumPy array into Regular Grid


code:
class Product(models.Model):
    ...
    category = models.ForeignKey(Category)

rawDescription: Make that my categories displays each respective content isolatedly


code:
import requests
import progressbar

ISO = "http://www.ubuntu.com/start-download?distro=desktop&bits=32&release=lts"
CHUNK_SIZE = 1024 * 1024 # 1MB

r = requests.get(ISO)
total_size = int(r.headers['content-length'])
pbar = progressbar.ProgressBar(maxval=total_size).start()

file_contents = ""
for chunk in r.iter_content(chunk_size=CHUNK_SIZE):
    file_contents += chunk
    pbar.update(len(file_contents))

rawDescription: python urllib2 download size

description: Python urllib2 download size


code:
import operator
checkNameSet = set(map(operator.itemgetter(0), checkNameArr))
found = []
notfound = []
for i in queryNameArr:
    if i[0] in checkNameSet:
        found.append(i)
    else:
        notfound.append(i)

rawDescription: Iterating and comparing list of lists in Python


code:
from templet import stringfunction

def get_val():
    return 100

@stringfunction
def testcode(get_val):
    """
    This is a sample string
    that references a function whose value is: ${ get_val() }
    Incrementing the value: ${ get_val() + 1 }
    """

print(testcode(get_val))

rawDescription: What is the Python equivalent of embedding an expression in a string? (ie. "#{expr}" in Ruby)


code:
def accumulate(iterator):
    total = 0
    for item in iterator:
        total += item
        yield total

rawDescription: Accumulate items in a list of tuples

description: Accumulate items in a list of tuples


code:
import random

def isolate_letters(original):
    characters = list(original.lower())
    return characters

def obsfucate(word):
    return [random.choice(["!", "%", "*", "#", "@"]) if random.random() > 0.1 else char for char in word]

def recompose_obfuscated_letters(letters):
    obfuscated = ''.join(letters)
    return obfuscated

original = input("Enter a 4-letter word:  ")

letters = isolate_letters(original)
obsfucate_letters = obsfucate(letters)
obfuscated = recompose_obfuscated_letters(obsfucate_letters)

print("Original:", original)
print("Obfuscated:", obfuscated)

rawDescription: Python, obfuscating letters in a list

description: Python, obfuscating letters in a list


code:
class Menu(drawingGeometric.rectangle):
    [...]
    def itemUp(self, argument):
        print(argument) # This will print "some_argument"
        self.turtle.left(90)
        position.position.forwardWithoutPen(self, 16)
        self.turtle.right(90)

rawDescription: How can I pass arguments inside that method?

description: Pass arguments inside that method


code:
def proj_levenberg(x,y,wsqrt,A):
    """
    Finds a homography between two sets of 2d points.

    Specifically, approximately minimize the weighted image plane
    error

       \(min_A  sum_{X,y,w}  w  ||(A_12 x_) /  (A_3 x_1)  -  y||^2\)

    where \(x_1\)=[x;1], \(A_{12}\) are the first two rows of A and \(A_3\) is the
    third row of A.
    """

rawDescription: Emacs preview-latex to format python comments and docstrings


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup('''<html>
    <body>
        <select>
            <option>Option 1
                <option>Option 2
                    <option>Option3
                        <option>Option 4
                        </option>
                    </option>
                </option>
            </option>
        </select>
    </body>
</html>''')

print(soup)

rawDescription: Changing HTML child tags to siblings in Python


code:
del connections[p]
for conn in connections.values():  # edit, bug fixed.
    if p in conn:
         del conn[p]

rawDescription: Big graph in memory

description: Big graph in memory


code:
mystr = "    That's four spaces"
n = next(i for i, c in enumerate(mystr) if c != ' ') # Count spaces at start
(' ' * n, mystr[n:])

rawDescription: Split leading whitespace from rest of string


rawDescription: MATLAB to Python Conversion Arrays

description: MATLAB to Python Conversion Arrays


rawDescription: How does the key argument in python's sorted function work?


code:
class ndb_Project(ndb.Model):
    name = ndb.StringProperty()
    description = ndb.StringProperty()
    version = ndb.StructuredProperty(ndb_Version)
    parentProj = ndb.KeyProperty()
    childProj = ndb.KeyProperty(repeated=True)

    @classmethod
    def getChildProjects(cls, key):
        proj = key.get()
        a = ndb.get_multi(proj.childProj) if proj.childProj else []
        o = proj.to_dict()
        o['urlSafe'] = proj.key
        o['childProj'] = a
        return o

rawDescription: GAE Recursive Query

description: GAE Recursive Query


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

rawDescription: How to integrate djangobb in an existing project?

description: Integrate djangobb in an existing project


code:
def run(command):
    proc = subprocess.Popen(command, stdout=subprocess.PIPE)
    for lineno, line in enumerate(proc.stdout):
        try:
            print(line.decode('utf-8').replace('\n', ''))
        except UnicodeDecodeError:
            print('error(%d): cannot decode %s' % (lineno, line))

rawDescription: Trouble printing text live with Python subprocess.call


code:
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

rawDescription: Python, pandas: how to sort dataframe by index


rawDescription: numpy.insert troubles

description: Numpy.insert troubles


code:
from itertools import groupby
test_list = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b', 'a', 'a']
max_count = {}
for val, grp in groupby(test_list):
    count = sum(1 for _ in grp)
    if count > max_count.get(val, 0):
        max_count[val] = count

max_count

rawDescription: Python, work with list, find max sequnce length


code:
first_line_update = "WRITE IN THE FIRST LINE \n"
with open(tableTempFile, 'r+') as f:
  lines = f.readlines()
  lines[0] = first_line_update
  f.writelines(lines)

rawDescription: How to efficiently append a new line to the starting of a large file?

description: Efficiently append a new line to the starting of a large file


rawDescription: Printing 'var' = var

description: Printing 'var' = var


code:
def get_form(self, *args, **kwargs):
        f = super(CommentAdmin, self).get_form(*args, **kwargs)
        f.base_fields['categories'].initial = 1

        return f

rawDescription: ModelChoiceField initial value in change form


rawDescription: What hardware is required to run this program?


code:
import numpy
numpy.random.seed(17)
m = numpy.random.rand(5,4)
m
c = numpy.cov(m,bias=1)
c
numpy.cov(m/c[0][0]**0.5, bias=1)

rawDescription: How to determine scaling factor so that covariance matrix has a first element of 1?

description: Determine scaling factor so that covariance matrix has a first element of 1


code:
def func1():
    func1.a = somevalue

rawDescription: Access a Python variable which is inside a function, in another function


code:
J, I = np.ogrid[:yt, :xt]
x[idx, J, I]

rawDescription: NumPy: Evaulate index array during vectorized assignment


code:
# urls.py
from django.conf.urls import url

from .views import graph, play_count_by_month

urlpatterns = [
    url(r'^$', graph),
    url(r'^api/play_count_by_month', play_count_by_month, name='play_count_by_month'),
]

rawDescription: Passing data from Django to D3

description: Passing data from Django to D3


code:
ordering_dict = {}
for i in range(len(ordering)):
    ordering_dict[ordering[i]] = i

rawDescription: Optimizing something in Python

description: Optimizing something in Python


code:
def get_feed(thing=None, feed_type=api.GetYouTubeUserFeed):

    if feed_type == 'user':
        feed = api.GetYouTubeUserFeed(username=thing)

    if feed_type == 'related':
        feed = api.GetYouTubeRelatedFeed(video_id=thing)

    if feed_type == 'comments':
        feed = api.GetYouTubeVideoCommentFeed(video_id=thing)

    feeds = []
    entries = []

    while feed:
        feeds.append(feed)
        feed = api.GetNext(feed)

    [entries.extend(f.entry) for f in feeds]

    return entries

rawDescription: How to gather personal information (age,gender..) of all the authors of the comments on a specific video, with Python YouTube API

description: Gather personal information (age,gender..) of all the authors of the comments on a specific video, with Python YouTube API


rawDescription: How to do a groupby of a list of lists

description: Do a groupby of a list of lists


rawDescription: Get Absolute URL in Django when using Class Based Views


code:
from itertools import tee
from collections import Counter
def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)    # itertools.izip() in python2
N = 5
c = Counter(tuple(sorted(a)) for a in pairwise(textNP.split()))
c.most_common(N)

rawDescription: Creating a dictionary with calculated values


code:
if x%3 == 0 and x%5 == 0:
    print ("FizzBuzz")

elif x%3 == 0 :
        print("Fizz")
elif x%5 == 0 :
        print("Buzz")

rawDescription: how to check the result is multiples (python)?

description: Check the result is multiples (python)


rawDescription: How can I format a float using matplotlib's LaTeX formatter?

description: Format a float using matplotlib's LaTeX formatter


code:
import sys
import pprint as PP
PP.pprint("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ZZZZZ",width=sys.maxsize,compact=True)

rawDescription: Can I make pprint in python3 not split strings, like in python2?

description: Make pprint in python3 not split strings, like in python2


code: fig, ax_list = plt.subplots(4, 2)

rawDescription: Update subplots in Matplotlib figure that is already open


code: df1.merge(df2, on=['member', 'time'], how='inner')

rawDescription: Python/Pandas filter out unique rows from DataFrames


code:
var1 = message[0]
var2 = message[1]

rawDescription: How do you calculate the amount of characters including spaces and numbers in a string

description: Calculate the amount of characters including spaces and numbers in a string


code: "  good\tbuono  \n".split()

rawDescription: converting a list of strings into a tuple

description: Converting a list of strings into a tuple


code:
class  A(object):
    cl_att = 'I am an A class attribute'

@inherit_and_append('cl_att')
class  B(A):
    cl_att = ' modified for B type'

@inherit_and_append('cl_att')
class  C(A):
    cl_att = ' modified for C type'

rawDescription: Python Class Attributes and Subclassing

description: Python Class Attributes and Subclassing


code:
df.head()
df.columns
df.index

rawDescription: Where did my dimensions go when I did a groupby in pandas?


code:
# faster than numpy.histogram, but only works in the range (0,1)
digitized = (nbins*vals).astype(int)
histogram = np.bincount(digitized)

offsets = np.cumsum(histogram[:-1])
grouped = np.partition(vals, offsets)

result = [func(group) for group in np.split(grouped, offsets)]

rawDescription: Efficiently get indices of histogram bins in Python


code:
class IsStaffNode(Node):
    def __init__(self, var):
        self.var = var

    def render(self, context):
        if context['user'].is_staff():
            return var.resolve(context)
        return ""

@register.tag
def is_staff(parser, token):
    var = parser.compile_filter(token.split_contents()[1])
    return IsStaffNode(var)

rawDescription: Define variables in template based on user being staff or not


rawDescription: python 3.3 dict: how to convert struct PyDictKeysObject to python class?

description: Python 3.3 dict: how to convert struct PyDictKeysObject to python class


code:
class Thing:
    keywords = 'foo', 'bar', 'snafu', 'fnord'
    def __init__(self, **kwargs):
        for kw in self.keywords:
            setattr(self, kw, kwargs[kw])

rawDescription: Python 3 object construction: which is the most Pythonic / the accepted way?


code:
df['Score'] = df.iloc[:, 1:].sum(axis=1)
df

rawDescription: Apply function row wise on pandas data frame on columns with numerical values


code:
class Species(models.Model):
    name = models.CharField(db_column='Name', max_length=100)

class Status(models.Model):
    species = models.ForeignKey(Species, db_column='Species ID', primary_key=True)
    protected = models.NullBooleanField(db_column='Protected')

class Images(models.Model):
    species = models.ForeignKey('Species', db_column='Species ID')
    url = models.CharField(db_column='URL', max_length=719)

rawDescription: Multiple joins in Django model

description: Multiple joins in Django model


code:
template = 'prefix%s_' % day
timeit.timeit("[template + s for s in signals]", 'from __main__ import template, signals')

rawDescription: Python, optimizing a list comprehension for string concatenation


code:
if form.is_valid():
    cd = form.cleaned_data
    obj = ContactModel()
    for key, value in cd.iteritems():
        setattr(obj, key, value)
    obj.save()

rawDescription: How to save form fields in the model in a view

description: Save form fields in the model in a view


code:
def str2cords(scords):
    return [float(c) for c in scords.split(',')] #or maybe just scords.split(',') since float might mess up the exact cords?

rawDescription: python - urls.py regex help with coordinates

description: Python - urls.py regex help with coordinates


rawDescription: How to remove a column from a structured numpy array *without copying it*?

description: Remove a column from a structured numpy array *without copying it*


code: item = table[1][3]  # get item 1 of the outer list, and from that inner list get item 3

rawDescription: why does order of loop nesting matter python?

description: Why does order of loop nesting matter python


code:
class Line(object):
    @property
    def length(self):
        """The length of the line"""
        return self.__length

    def __init__(self):
        """Create a line"""
        self.__length = None
        self.__run_equation()

    def _run_equation(self):
        self.__length = 50

rawDescription: Where to define a method that is used only inside __init__ and must not be called anywhere else?


code:
try:
    import tkinter as tk  # using Python 3
except ImportError:
    import Tkinter as tk  # using Python 2

def move(event=None):
    global x1, x2, y1, y2, oval
    if event.char == 'w':
        y1 -= 10
        y2 -= 10
        oval = (x1, y1, x2, y2)
        canvas.coords(oval_id, oval)

m = tk.Tk()

canvas = tk.Canvas(m)
canvas.pack(expand=1, fill='both')
x1, x2 = 50, 100
y1, y2 = 50, 100
oval = (x1, y1, x2, y2)
oval_id = canvas.create_oval(oval)
canvas.bind_all('<w>', move)

m.mainloop()

rawDescription: Binding a key press event on a Canvas widget


code:
def enum_mapper(enum, mapper):
    assert not enum.symmetric_difference(mapper)
    return mapper.__getitem__

rawDescription: How to ensure solid contracts without strong typing?

description: Ensure solid contracts without strong typing


code:
class Media( models.Model ):
    @property
    def clean_band_name( self ):
        if self.bandname_alt[:4] == 'The ':
            return self.bandname_alt[4:] + ', The'
        else:
            return self.bandname_alt

rawDescription: Django/python: loop through a dictionary and add an item to it


code:
from webapp2_extras import jinja2 as webapp_extras_jinja2
# ...

def get_message_html():
  jinja2 = webapp_extras_jinja2.get_jinja2()
  return jinja2.render_template('relative/path/to/template.html')

# ...
def send_email():
   # ...
   message.html = get_message_html()
   # ...

rawDescription: Send HTML email in Appengine [PYTHON] using HTML file


code: set_the_data_shortcut(a, newvalue)

rawDescription: Pythonic ways to avoid Pointers

description: Pythonic ways to avoid Pointers


code:
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
A = np.arange(0,100).reshape(10,10)
plt.matshow(A)                        # defaults
plt.matshow(A, vmin=0, vmax=99)       # same
plt.matshow(A, vmin=10, vmax=90)      # top/bottom rows get min/max colors, respectively

rawDescription: Controlling the Range of a Color Matrix Plot in Matplotlib


code: indices = indices[a1[indices] >= 0]

rawDescription: Get the three minimum values of an array in Python, ignoring a value


code:
with open("out.csv", "w", newline="") as outfile:
    writer = csv.DictWriter(outfile, sorted(fieldnames))
    writer.writeheader()
    for item in result:
        result[item]["ID"] = item
        writer.writerow(result[item])

rawDescription: Combining multiple CSV file into a single one


code:
text.rpartition('offset ')
text.rpartition('offset ')[-1]

rawDescription: Extract specific characters from the string


code:
import os
import hashlib

def sha1OfFile(filepath):
    sha = hashlib.sha1()
    with open(filepath, 'rb') as f:
        while True:
            block = f.read(2**10) # Magic number: one-megabyte blocks.
            if not block: break
            sha.update(block)
        return sha.hexdigest()

for (path, dirs, files) in os.walk('.'):
  for file in files:
    print('{}: {}'.format(os.path.join(path, file),  sha1OfFile(os.path.join(path, file))))

rawDescription: shell command in python for sha

description: Shell command in python for sha


code: pd.to_datetime(df.index, dayfirst=True)

rawDescription: pandas.to_datetime inconsistent time string format

description: Pandas.to_datetime inconsistent time string format


code:
import re
datepattern = re.compile("\w{3}, \d{2} \w{3} \d{4} \d{2}:\d{2}:\d{2} \w{3}")
matcher = datepattern.search(string_to_match_against)
print(matcher.group(0))

rawDescription: Extract timestamp from large string

description: Extract timestamp from large string


code:
html = '8.6685.7868'
soup = BeautifulSoup(html)
offers =  soup.find_all("span", "rcnt")
elements = [tag.text for tag in offers]
elements

rawDescription: Python Beautifulsoup4 remove <span> tags


code:
my_list = ['deviceA;portZ,portchanC', ... , 'deviceE;portX,portchan2']
a = []

for ele in my_list:
    arr = ele.split(';')
    device = arr[0]
    a.append(device)
a = set(a)

rawDescription: Python: Cutting column from list and storing as list


code:
import numpy as np
v = np.array(np.arange(24)).reshape(2,3,4)
v
v[:, 1, 3]

rawDescription: select first column in a 3d ndarray

description: Select first column in a 3d ndarray


code:
from flask import Flask
from gevent.wsgi import WSGIServer
import gevent
import signal

from gevent import monkey
monkey.patch_all()

rawDescription: Flask and Web.py both hang on atexit

description: Flask and Web.py both hang on atexit


code:
df = pd.concat([df]*1000).reset_index(drop=True)

print (df)
df_a = df.copy()

def a(df):
    df1 = (df['product'].str.split('|', expand=True))
    prods = df1.columns = ['prod_' + str(col) for col in df1.columns]

    df2 = (df['Prices'].str.split('|', expand=True))
    prices = df2.columns = ['part_' + str(col) for col in df2.columns]

    df3 = (pd.concat([df[['date','conv']], df1, df2], axis=1))

    return (pd.lreshape(df3, {'product' : prods, 'price' : prices}))

def b(df):
    s1 = (df['product'].str.split('|', expand=True)).stack()
    s1.index = s1.index.droplevel(-1)
    s1.name = 'product'

    s2 = (df['Prices'].str.split('|', expand=True)).stack()
    s2.index = s2.index.droplevel(-1)
    s2.name = 'price'

    df = df.drop(['product','Prices'], axis=1)

    df1 = (df.join(s1).reset_index(drop=True))
    df2 = (df.join(s2).reset_index(drop=True))

    return (pd.concat([df1, df2[['price']]], axis=1))

print (a(df))
print (b(df_a))

rawDescription: Transpose a Python Dataframe according many variables


code:
cur.execute(
    "SELECT version,name FROM data2.files WHERE name IN (" +
    ",".join(("%s",) * len(filenames)) +
    ")",
    tuple(filenames)
)

rawDescription: How to address a python list in MySQL query with "WHERE"?

description: Address a python list in MySQL query with "WHERE"


code:
with open('my_file_name') as in_file:
    print(next(in_file))

rawDescription: Python3 Print First File Line

description: Python3 Print First File Line


code:
l = [1, 2, 3, 4, 5]
sum_list(l)

l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)

rawDescription: Python: Total sum of a list of numbers with the for loop