code:
import numpy as np

def independent_roll_inplace(arr, ind, amount):
    arr[ind] = np.roll(arr[ind], amount)

def independent_roll_copy(arr, ind, amount):
    arr = arr.copy()
    arr[ind] = np.roll(arr[ind], amount)
    return arr

grid = np.array([['A', 'D', 'G'],
                 ['B', 'E', 'H'],
                 ['C', 'F', 'I']])

rawDescription: Numpy: how to roll 1 "row" in an array of arrays


rawDescription: python, convert a dictionary to a sorted list by value instead of key

description: Python, convert a dictionary to a sorted list by value instead of key


rawDescription: Please explain reasoning behind code snippet from argparse module


code: mask

rawDescription: Relocate zeros to the end of the last dimension in multidimensional numpy array


code:
def has_index_in_slice(indices, a, b):
   r = bisect.bisect_left(indices, a)

   return r < len(indices) and indices[r] < b

def check(byvalue, x, a, b):
    indices = byvalue.get(x, None)
    if not indices: return False

    return has_index_in_slice(indices, a, b)

rawDescription: Fast membership in slices of lists

description: Fast membership in slices of lists


code:
def setProgress(self, progress):
    self.progressBar.setValue(progress)

rawDescription: Python PySide and Progress Bar Threading


rawDescription: Python quickly hash mutable object

description: Python quickly hash mutable object


code: lines = (line for line in open('data', 'rb')  if line.split(None, 1)[0].lstrip('0') in '123456789')

rawDescription: NumPy genfromtxt - skipping rows that start with specific number


rawDescription: Regex for capturing URL path in groups separated by a forward slash


rawDescription: python :same character, different behavior

description: Python :same character, different behavior


code: address = ui.config('changegroup.mail_someone', 'to_address')

rawDescription: Can I configure mercurial hooks like some extensions are configured in the hgrc file?

description: Configure mercurial hooks like some extensions are configured in the hgrc file


code: c = numpy.rec.fromarrays([a, b], names='f, i')

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


rawDescription: How to assign scipy.sparse matrix to NumPy array via indexing?

description: Assign scipy.sparse matrix to NumPy array via indexing


code:
def ugly_validate(value_lst, rules, default):
    if value_lst[0].lower() not in rules:
        value_lst[0] = default
v = "something"
allowed = ["someoption", "someother"]
default = "default_value"
v_lst = [v]
ugly_validate(v_lst, allowed, default)
v_lst
v = "someoption"
v_lst = [v]
ugly_validate(v_lst, allowed, default)
v_lst

rawDescription: pass value by reference into python function

description: Pass value by reference into python function


code:
# lst represents what is returned by itertools.groupby
lst = [(1, 2), (3, 4), (5, 6)]
for i, (j, k) in enumerate(lst):
    i, j, k

rawDescription: How to get index of key/group in itertools.groupby?

description: Get index of key/group in itertools.groupby


code:
from collections import deque

five_prev = deque(an_iterator, maxlen=5)
for something in an_iterator:
    five_lines_back = five_prev.popleft()
    # ...
    five_prev.append(something)

rawDescription: Is there a counterpart of next()?

description: Is there a counterpart of next()


code: rand(movie())

rawDescription: Using name of strings in different functions


code:
import types
obj_a.Test = types.MethodType(ClassA.Test, obj_a)
obj_a.Test()

rawDescription: How to update the the class type and methods in an existing object

description: Update the the class type and methods in an existing object


rawDescription: Re-order a numpy array python

description: Re-order a numpy array python


code:
def print_table(table):
    col_width = [max(len(str(x)) for x in col) for col in zip(*table)]
    for line in table:
        print("| " + " | ".join("{:{}}".format(x, col_width[i])
                                for i, x in enumerate(line)) + " |")

table = [['/', 2,    3],
         ['a', '2a', '3a'],
         ['b', '2b', '3b']]

print_table(table)

rawDescription: How do i put things in a table in python

description: Put things in a table in python


code:
from pprint import pprint
titles = ['Foo de Bar', 'Bring us a Shrubbery!', 'The airspeed of a laden swallow']
ids = ['42', '81', '3.14']
pprint({'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]})

rawDescription: How do I make a JSON file out of a list in Python?

description: Make a JSON file out of a list in Python


code:
from myclass import MyClass
from foo.bar.yourclass import YourClass

rawDescription: Importing functions bad, classes okay?

description: Importing functions bad, classes okay


rawDescription: Pandas best practice to select multiple column data


rawDescription: How do I print methods of a class

description: Print methods of a class


code:
df['month'] = df.month_num.map(lambda n: calendar.month_abbr[int(n)].lower())+'_avg_prod_count'
df
pt = df.pivot_table(columns='month',index='prod_desc',values='prod_count', aggfunc=sum)
pt

rawDescription: How to create variables inside a for loop to assign dataframes?

description: Create variables inside a for loop to assign dataframes


code:
import inspect

def who_called():
    frame = inspect.stack()[2][0]
    if 'self' not in frame.f_locals:
        return None, None
    cls = frame.f_locals['self'].__class__
    method = frame.f_code.co_name
    return cls, method

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

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value

    # Assuming this existed it would also work
    def change_value(self, value):
        self.value = value

rawDescription: Discriminate between callers inside and outside class hierarchy


code:
def parent_obj_to_camera(b_obj, b_camera):
    origin = (0,0,0) #can be replaced with b_obj.location
    b_empty = bpy.data.objects.new("Empty", None)
    b_empty.location = origin
    b_camera.parent = b_empty #setup parenting

    scn = bpy.context.scene
    scn.objects.link(b_empty)
    scn.objects.active = b_empty
    b_empty.select = True

rawDescription: Blender camera rotation with python - not planar?


code:
def split_at(s, c, n):
    words = s.split(c)
    return c.join(words[:n]), c.join(words[n:])

rawDescription: Python split a string at an underscore

description: Python split a string at an underscore


code:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse

from .models import *
from .forms import *

class PostCreateView(CreateView):
   model = Post
   form_class = PostForm
   template_name = 'form.html'

   def form_valid(self, form):
      self.object = form.save(commit=False)
      # any manual settings go here
      self.object.save()
      return HttpResponseRedirect(self.object.get_absolute_url())

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
      return super(PostCreateView, self).dispatch(request, *args, **kwargs)

class PostUpdateView(UpdateView):
   model = Post
   form_class = PostForm
   template_name = 'form.html'

   def form_valid(self, form):
      self.object = form.save(commit=False)
      # Any manual settings go here
      self.object.save()
      return HttpResponseRedirect(self.object.get_absolute_url())

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
     return super(PostUpdateView, self).dispatch(request, *args, **kwargs)

class PostDeleteView(DeleteView):
   model = Post

   def get_success_url(self):
      return reverse('post-index')  # Or whatever you need

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
      return super(PostDeleteView, self).dispatch(request, *args, **kwargs)

rawDescription: Django editing and deleting, using Generic editing views or making functions in views.


code:
import fhp.api.five_hundred_px as f
import fhp.helpers.authentication as authentication
from pprint import pprint
key = authentication.get_consumer_key()
secret = authentication.get_consumer_secret()

client = f.FiveHundredPx(key, secret)
results = client.get_photos(feature='popular')

i = 0
PHOTOS_NEEDED = 2
for photo in results:
    pprint(photo)
    i += 1
    if i == PHOTOS_NEEDED:
        break

rawDescription: Get the code from inspect element using Python


code:
def foo (l):
    for in_str in l[0]:
        print(l[1](in_str))

# format of list
l = [["Hello world!", "helloworld"], str.isalpha]
print(foo(l))

rawDescription: Passing method to a function in Python

description: Passing method to a function in Python


code:
from twisted.internet.task import Clock
fake_reactor = Clock()
loop_http.clock = fake_reactor
fake_reactor.advance(120)  # move time forward two minutes...

rawDescription: Twisted / perform asynchronous http requests


code:
with sqlite3.connect("GuitarLessons.db") as db:
            cursor = db.cursor()
            sql = "delete from tblStudents where StudentID = ?"
            cursor.execute(sql,(StudentID))
            db.commit()

rawDescription: Is it possible to write a python program that will enable you to sort the content of a text file in python


code:
def rec_range(n):
    """Takes a natural number n and returns a tuple of numbers starting with 0 and ending before n.

    Natural Number -> tuple"""
    if n == 0:
        return
    elif n == 1:
        return (0,)
    else:
        return rec_range(n-1) + (n-1,)

rawDescription: Recursively return a tuple of numbers 0 to n in python


code: max(lambda x: -x, arg1, arg2, arg3)

rawDescription: Python inspect module: keyword only args


code: some_function(*args, **kwargs)

rawDescription: Python equivalent of ActionScript's apply()/call() methods?


code:
from os import path, listdir
import sys
from collections import defaultdict

snps = defaultdict(lambda: defaultdict(str))
pth = sys.argv[1]  # get full path
myfiles = listdir(pth)  # get list of all files in that path/directory

with open("Fer1_INDELs_clones_filtered.csv","w") as out: # file to write all filtered data to
    out.write("Fermentor\tTrajectory\tChromosome\tPosition\tMutation\tGene\tEffect\t1.20.1\t1.20.2\t1.20.3\t1.30.1\t1.30.2\t1.30.3\t1.40.1\t1.40.3\t1.50.1\t1.50.2\t1.50.3\t1.60.1\t1.60.2\t1.60.3\t1.90.1\t1.90.2\t1.90.3\t1.100.1\t1.100.2\t1.100.3\t1.130.1\t1.130.2\t1.130.3\t1.200.1\t1.200.2\t1.200.3\n")
    for f1 in myfiles:
        with open(path.join(pth, f1)) as f:  # join -> pth/f1
            tpp = f1.split("_", 1)[0].split(".")
            tp = ".".join(tpp[0:3])  # same as tp=tpp[0]+'.'+tpp[1]+'.'+tpp[2]
            for line in f:
                ls = line.split()
                if line.find("#") == -1 and len(ls) > 6:
                    print(line)
                    # use unpacking and slicing
                    chrom, pos, ref, alt, freq, typ, gene = ls[:7]
                    if len(alt) == 1:
                        # use str.fromat
                        snps["{}_{}-{}_{}_{}_{}".format(pos,ref,alt,chrom,gene,typ)][tp] = freq
                    elif len(alt) > 1:
                        # use enumerate
                        for ind,k in enumerate(alt.split(",")):
                            snps["{}_{}_{}_{}_{}_{}".format(pos,ref,k,chrom,gene,typ)][tp] = freq.split(",")[ind]
    traj = 1
    tp_list = ['1.20.1', '1.20.2', '1.20.3', '1.30.1', '1.30.2', '1.30.3', '1.40.1', '1.40.2', '1.40.3', '1.50.1', '1.50.2',
               '1.50.3', '1.60.1', '1.60.2', '1.60.3', '1.90.1', '1.90.2', '1.90.3', '1.100.1', '1.100.2', '1.100.3',
               '1.130.1', '1.130.2', '1.130.3', '1.200.1', '1.200.2', '1.200.3']
    for pos in sorted(snps):
        # split once and again use unpacking and slicing
        pos1, mut, chrom, gene, typ = pos.split("_")[:5]
        tp_string = ""
        for tp in tp_list:
            #print(tp)
            if snps[pos][tp]: # empty value will be False no need to check len
                tp_string += "\t{}".format(snps[pos][tp])
            else:
                tp_string += "\t0/0"

        out.write(("F1{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(traj,chrom,pos1,mut,gene,typ,tp_string)))
        traj += 1

rawDescription: Combining items from several files into one matrix using Python


code: from ..mypackage import server

rawDescription: Scripts in python package

description: Scripts in python package


code: bubble(unsortedList)

rawDescription: Bubble sort in Python not sorting properly


rawDescription: Inserting list into list containing multiple list


code:
import subprocess
cmdline = ["cmd", "/q", "/k", "echo off"]
cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
batch = b"""\
set TEST_VAR=Hello World
set TEST_VAR
echo %TEST_VAR%
exit
"""
cmd.stdin.write(batch)
cmd.stdin.flush() # Must include this to ensure data is passed to child process
result = cmd.stdout.read()
print(result.decode())

rawDescription: Running three commands in the same process with Python


rawDescription: Pandas: Achieving speed of 'built-in' methods (e.g. mean,std) for groups manipulations


code:
import numpy as np
m=np.arange(24).reshape(2,3,4)
print(m.shape)
# (2, 3, 4)

rawDescription: Iterate across arbitrary dimension in numpy


code: ['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']

rawDescription: Python Brute Force algorithm

description: Python Brute Force algorithm


code: ("hello", "blah", 7)

rawDescription: Get all objects of a given structure, and their global names


code:
from collections import defaultdict

data = defaultdict(list)

with open('filename') as f:
    for line in f:
        row = line.split()
        data[row[0]].append(row[1])

rawDescription: Extracting data from a text file

description: Extracting data from a text file


code:
def active_users():
    return select(u for u in User if not user.disabled)

rawDescription: Writing select functions for customized Pony


code: display_names = [f['channel']['display_name'] for f in data['follows']]

rawDescription: Parsing JSON data Python

description: Parsing JSON data Python


code:
with open('file.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=",", fieldnames=["id","movie"], restkey="actors")
    for row in reader:
        actors = row['actors']

rawDescription: Keep CSV commas inside fields with Python


code:
import glob
myFiles = glob.glob('C://my_folder//*.csv')

rawDescription: pandas read dataframes in a loop and get the mean

description: Pandas read dataframes in a loop and get the mean


rawDescription: Sorting from first lowest number

description: Sorting from first lowest number


code:
from pathlib import WindowsPath
import os.path

class PathTest(WindowsPath):

    def __new__(cls, *args, **kwargs):
        return super(PathTest, cls).__new__(cls, *args, **kwargs)

    @classmethod
    def expanduser(cls):
        """ Return a new path with expanded ~ and ~user constructs
        (as returned by os.path.expanduser)
        """
        return cls(os.path.expanduser('~'))

p = PathTest('C:/')
print(p) # 'C:/'

q = PathTest.expanduser()
print(q) # C:\Users\Username

rawDescription: Getting Home Directory with pathlib

description: Getting Home Directory with pathlib


code:
def a():
    # first, yield a function to access i
    yield lambda: i
    # now, set i to different values successively
    for i in range(100): yield

g = a() # create generator
f = next(g) # get the function
f() # -> error as i is not set yet
next(g)
f() # -> 0
next(g)
f() # -> 1
# and so on
f.func_closure # -> an object stemming from the local scope of a()
f.func_closure[0].cell_contents # -> the current value of this variable

rawDescription: Python: lambda function behavior with and without keyword arguments?


code:
# Query the relative positions, divide to get quantiles
left_rank_row = np.searchsorted(sorted_array[:length], add_array, side="left")
right_rank_row = np.searchsorted(sorted_array[:length], add_array, side="right")
quantile_row = (left_rank_row + right_rank_row).astype(np.float) / (length * 2)

rawDescription: Pandas - expanding inverse quantile function


code: import xml.etree.cElementTree as ET  # use cElementTree for faster processing

rawDescription: Python: In an xml, How to delete nodes within a parent node


code: data = int( conn.recv(32) );

rawDescription: Is int in C# and Python the same thing?

description: Is int in C# and Python the same thing


rawDescription: Issue sorting lots of files in python

description: Issue sorting lots of files in python


code:
aList = ["a", "b", "c"]
listAndFlags = [ (item,item in aList) for item in someQuerySet ]

rawDescription: Is 'if element in aList' possible with Django templates?


rawDescription: In python, test for 1 or 3 consecutive instances of a string, but not 2 (without regex)


code: X = numpy.delete(X, 3, axis=1)

rawDescription: change a list of dictionaries to feature vector and target in scikit

description: Change a list of dictionaries to feature vector and target in scikit


code:
from numpy import s_
s_[0, 3:5, 6::3]
Out[1]: (0, slice(3, 5, None), slice(6, None, 3))

rawDescription: Python: shorter syntax for slices with gaps?


rawDescription: averaging every five minutes data as one datapoint in pandas dataframe

description: Averaging every five minutes data as one datapoint in pandas dataframe


code: -2 & 0xffffffff

rawDescription: Why does python's zlib.crc32 need a bitwise AND to be considered "stable"?


code: draw_chromosome(0, 120, y, "#1C2F4D")

rawDescription: Why is my line clipping in matplotlib?

description: Why is my line clipping in matplotlib


code:
from yourmodule import generate_image

def overlay():
    background = generate_image(*args) # Or what ever arguments you want.

rawDescription: Passing values between modules in Python


code:
import sys

def findIndent (lst):
    # given a list of text strings, returns a list containing the
    # indentation levels for each string
    spcCount = [len(s)-len(s.lstrip(' ')) for s in lst]
    indent = sorted(set(spcCount))
    levelRef = {indent[i]:i for i in range(len(indent))}
    return [levelRef[i]+1 for i in spcCount]

lst = []
for li in sys.stdin:
    if li.lstrip(' ').find('::') == 0:
        lst.append(li.rstrip())
    else:
        lst[-1] = lst[-1].rstrip() + ' ' + li.lstrip(' ').rstrip()

for i,li in zip(findIndent(lst),lst):
    print (' '*i + li.lstrip())

rawDescription: How to parse blocks based on indentation

description: Parse blocks based on indentation


code:
import sys
import datetime

def show_mem(data, indent="    ", depth=0):
    "Recursively show the memory usage of a data structure"
    mysize = sys.getsizeof(data)
    if isinstance(data, (list,tuple,dict)):
        childsize = 0
        print("{}{} bytes: [".format(indent*depth, mysize))
        for d in data:
            childsize += show_mem(d, indent, depth+1)
        print("{}]  (total: {} bytes)".format(indent*depth, mysize+childsize))
        return mysize+childsize
    else:
        print("{}{} bytes: {}".format(indent*depth, mysize, repr(data)))
        return mysize

show_mem([1223456, 1245361536363, 'infooooooooo123', datetime.date(1975,7,21), "http://www.somesite.org/the/path/page.htm"])

rawDescription: More than 3 mb of data for list of list for 1500 records


code: transpose = zip(*list_o_tuples)

rawDescription: Change List of Tuples into Dictionary (pythonic way)


code:
def proj11_1_a():
    # Using eval in such place does not seem a good idea
    # unless you want to accept things like "2*4-2"
    # You might also consider putting try: here to check for correctness

    n = int(input("Enter the size of the square matrix: "))
    matrix = []

    for _ in range(n):
        row = []

        for _ in range(n):
            # same situation as with n
            value = float(input("Enter a value to go into the matrix: "))
            row.append(value)

        matrix.append(row)

    return matrix

rawDescription: Creating a matrix using lists Python

description: Creating a matrix using lists Python


code:
class Team:

    TEAMS = [("Arsenal", "ARS"), ("Manchester United", "MNU", "ManUtd"), ...]

    def __init__(self, name):
        if not any(name in names for names in self.TEAMS):
            raise ValueError("Not a valid team name.")
        self.name = name

    def __eq__(self, other):
        for names in self.TEAMS:
            if self.name in names and other.name in names:
                return True
        return False

rawDescription: Finding equality between different strings that should be equal


rawDescription: organizing numbers in numpy

description: Organizing numbers in numpy


code:
form = """

    <form action="/feedback" method="POST">

Aiutaci a migliorare

un piacere sapere cosa cambiereste di Metrico

                <textarea class="input-xxlarge" name="comment" rows="3"></textarea>

<input class="btn btn-inverse" type="submit"/>

    </form>

"""

class FormTest(webapp2.RequestHandler):

    def get(self):
        self.response.out.write(form)

    def post(self):
        data = self.request.POST
        comment = data.get('comment')
        body = """
Feedback:
%s
""" % comment
        self.response.out.write(body)

rawDescription: How to get text from modal and insert in email body?

description: Get text from modal and insert in email body


code:
from os import open as open_
# lets you use os.open without destroying the
# built in open() which returns file handles.

rawDescription: `from ... import` vs `import .`

description: `from ... import` vs `import .`


rawDescription: How to parse a collection of lists returned from cypher?

description: Parse a collection of lists returned from cypher


code:
df = pd.DataFrame(np.arange(24).reshape(6,4), columns=list('ABCD'))
df
df[list('CDAB')]

rawDescription: Pandas order datafarme column

description: Pandas order datafarme column


code:
part = pd.concat([pd.get_dummies(frame2[x]) for x in frame2], axis=1)
part

rawDescription: Dummy variables from levels of other data frame


code:
Group.objects.filter(
    Q(person__position="worker")
    & ~Q(person__position__gt="worker")
    & ~Q(person__position__lt="worker")
)

rawDescription: Complex Django query

description: Complex Django query


code:
# How much text shrinks when going to the next-smallest level.  GROW_FACTOR
# must be the inverse of SHRINK_FACTOR.
SHRINK_FACTOR   = 0.7
GROW_FACTOR     = 1.0 / SHRINK_FACTOR
# The number of different sizes of chars to use, beyond which they will not
# get any smaller
NUM_SIZE_LEVELS = 6
# Percentage of x-height of additional horiz. space after sub/superscripts
SCRIPT_SPACE    = 0.2
# Percentage of x-height that sub/superscripts drop below the baseline
SUBDROP         = 0.3
# Percentage of x-height that superscripts drop below the baseline
SUP1            = 0.5
# Percentage of x-height that subscripts drop below the baseline
SUB1            = 0.0
# Percentage of x-height that superscripts are offset relative to the subscript
DELTA           = 0.18

rawDescription: Matplotlib: set superscript font size

description: Matplotlib: set superscript font size


code:
from itertools import product

def adjacent_grid(centre):
    steps = product([-1, 0, 1], repeat=len(centre))
    return (tuple(c+d for c,d in zip(centre, delta)) for delta in steps)

rawDescription: get adjacent matrix of point in python

description: Get adjacent matrix of point in python


code:
non_duplicated = sc.broadcast(set(
    counts.filter(lambda x: x[1] == 1).keys().collect()
))

a.filter(lambda x: x[0] in non_duplicated.value)

rawDescription: Spark RDD remove records with multiple keys


code:
strs1 = "your future doesn't look good."
strs2 = "Your FUTURE looks good."
'FUTURE' or 'future' in strs1
'Foobar' or 'future' in strs1
'Foobar' or 'cat' in strs1
'' or 'cat' in strs1    #  empty string is a falsey value,

rawDescription: For loop python multiple checks

description: For loop python multiple checks


code:
os.chdir(my_dir)
glb = glob.iglob('*.txt')

with open("monthly.csv", "w") as f:
    p= pd.read_csv(next(glb), names=['Name', 'Date', 'Open', 'High',
                                  'Low', 'Close', 'Volume', 'Null'])
    del p["Null"]
    p.to_csv(f)
    for files in glb:
        p = pd.read_csv(files, names=['Name', 'Date', 'Open', 'High',
                                      'Low', 'Close', 'Volume', 'Null'])
        del p["Null"]
        p.to_csv(f, sep=',', header=False)

rawDescription: Pandas prints to screen corrently but saves only some data to csv


code: L = getattr(L, 'string', None)

rawDescription: Is there a `?.` operator in Python?

description: Is there a `?.` operator in Python


rawDescription: Django counter in loop to index list

description: Django counter in loop to index list


code: x == repr(eval(x))

rawDescription: Learn Python the hard way, exercise 10.4


code:
cursor.execute('UPDATE nonesuch SET baz=3 WHERE bar=2')
cursor.execute('UPDATE foo SET nonesuchcolumn=3 WHERE bar=2')

rawDescription: How to tell whether an update statement is successful in pysqlite 2.6.3

description: Tell whether an update statement is successful in pysqlite 2.6.3


code:
def block_process(a, blocksize, filt, args):
    b = numpy.empty(a.shape)
    for row in xrange(0, a.shape[0], blocksize):
        for col in xrange(0, a.shape[1], blocksize):
            b[col:col + blocksize, row:row + blocksize] = (
                filt(a[col:col + blocksize, row:row + blocksize], *args))
    return b

rawDescription: Calling filter functions from within a block-by-block processing function


code: pd.read_csv("oniwa.dat", sep="\t") # no good

rawDescription: pandas shifts column names and fills last column with NAN

description: Pandas shifts column names and fills last column with NAN


code: df1 = df1.reindex_like(df2)

rawDescription: Match rows and columns of two DataFrames


code:
with open('output.txt', 'w') as f:
    f.write(some_string)

rawDescription: Python: Text saving issue

description: Python: Text saving issue


code:
vtype = "vidis.fit"
vtype.rstrip("dis.fit")
vtype.rstrip("ditfs.")

rawDescription: Weird string stripping

description: Weird string stripping


code:
import sys
sys.stdout.write('this is a very long line')
sys.stdout.write('\rshort line')
sys.stdout.write('\n')

rawDescription: Bash or Python, When print characters to terminal, how to CHANGE a character at a FIXED position?


code: b = datetime.now()

rawDescription: Calculating the time difference between two datetime values in Python


code:
def tupelize_keys(kv):
    k, v = kv
    return tuple(k), v

rdd1H = sc.parallelize([
    ([1, 2], 0), ([2, 4], 1), ([9, 9], 3)
]).map(tupelize_keys)

rdd2H = sc.parallelize([
    ([2, 4], 0), ([1, 2], 1), ([1, 2], 3)
]).map(tupelize_keys)

rawDescription: Pyspark: Get indexes of an RDD elements from another RDD


code:
import numpy as np
from numpy.lib.stride_tricks import as_strided
import pandas as pd
import matplotlib.pyplot as plt

def windowed_view(x, window_size):
    """Creat a 2d windowed view of a 1d array.

    `x` must be a 1d numpy array.

    `numpy.lib.stride_tricks.as_strided` is used to create the view.
    The data is not copied.

    Example:

    >>> x = np.array([1, 2, 3, 4, 5, 6])
    >>> windowed_view(x, 3)
    array([[1, 2, 3],
           [2, 3, 4],
           [3, 4, 5],
           [4, 5, 6]])
    """
    y = as_strided(x, shape=(x.size - window_size + 1, window_size),
                   strides=(x.strides[0], x.strides[0]))
    return y

def rolling_max_dd(x, window_size, min_periods=1):
    """Compute the rolling maximum drawdown of `x`.

    `x` must be a 1d numpy array.
    `min_periods` should satisfy `1 <= min_periods <= window_size`.

    Returns an 1d array with length `len(x) - min_periods + 1`.
    """
    if min_periods < window_size:
        pad = np.empty(window_size - min_periods)
        pad.fill(x[0])
        x = np.concatenate((pad, x))
    y = windowed_view(x, window_size)
    running_max_y = np.maximum.accumulate(y, axis=1)
    dd = y - running_max_y
    return dd.min(axis=1)

def max_dd(ser):
    max2here = pd.expanding_max(ser)
    dd2here = ser - max2here
    return dd2here.min()

if __name__ == "__main__":
    np.random.seed(0)
    n = 100
    s = pd.Series(np.random.randn(n).cumsum())

    window_length = 10

    rolling_dd = pd.rolling_apply(s, window_length, max_dd, min_periods=0)
    df = pd.concat([s, rolling_dd], axis=1)
    df.columns = ['s', 'rol_dd_%d' % window_length]
    df.plot(linewidth=3, alpha=0.4)

    my_rmdd = rolling_max_dd(s.values, window_length, min_periods=1)
    plt.plot(my_rmdd, 'g.')

    plt.show()

rawDescription: Compute *rolling* maximum drawdown of pandas Series


rawDescription: How to calculate cohen's d in Python?

description: Calculate cohen's d in Python


code:
@asyncio.coroutine
def fetch(url):
    response = yield from aiohttp.request('GET', url)
    response = yield from response.read_and_close()
    return response.decode('utf-8')

@asyncio.coroutine
def print_page(url):
    page = yield from fetch(url)
    print(page)

@syncio.coroutine
def print_pages_sequential(url, num_pages):
    for food in range(num_pages):
        menu_url = url + '/' + str(food)
        yield from print_page(menu_url)

l = [print_pages_sequential('http://a-restaurant.com/menu', 10)]

conc_url = 'http://another-restaurant.com/menu'
for food in range(10):
    menu_url = conc_url + '/' + str(food)
    l.append(print_page(menu_url))

loop.run_until_complete(asyncio.wait(l))

rawDescription: Fetching data with Python's asyncio in a sequential order


code:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    # This field is required.
    user = models.OneToOneField(User)
    # Other fields here
    uid = models.CharField(max_length=254)
    cn = models.CharField(max_length=254)
    sn = models.CharField(max_length=254)
    givenName = models.CharField(max_length=254)
    userPassword = models.CharField(max_length=254)
    shadowLastChange = models.IntegerField(null=True)
    shadowMax = models.IntegerField(null=True)
    shadowWarning = models.IntegerField(null=True)
    loginShell = models.CharField(max_length=254)
    uidNumber = models.IntegerField(null=True)
    gidNumber = models.IntegerField(null=True)
    homeDirectory = models.CharField(max_length=254)
    gecos = models.CharField(max_length=254)
    mail = models.EmailField(max_length=254)
    l = models.CharField(max_length=254)
    telephoneNumber = models.CharField(max_length=254)

def create_user_profile(sender, instance, created, **kwargs):
    #if created:
    #    UserProfile.objects.create(user=instance)
    UserProfile.objects.get_or_create(user=instance)

post_save.connect(create_user_profile, sender=User)

rawDescription: django-auth-ldap - Display user information from LDAP in custom view

description: Django-auth-ldap - Display user information from LDAP in custom view


code:
def test(phrase):
    anas = [anagrammes2(word) for word in phrase.split(' ')]
    return [' '.join(x) for x in product(*anas)]

test('Mange ton orange')

rawDescription: Concatenate list items

description: Concatenate list items


code:
import pymel.core.uitypes as pmui

# assuming you know which modelPanel you want to affect
pmui.ModelEditor("modelPanel4").setRendererName("ogsRenderer")

rawDescription: How to query current viewport renderer in maya

description: Query current viewport renderer in maya


code:
from fabric.api import (cd, env, run)
from time import time

env.host_string = "127.0.0.1:2222"
env.user = "jfroco"
env.password = "*********"

remote_path = "/home/jfroco/development/fabric1"
remote_file = "test.txt"

variable = "My time is %s" % time()

with cd(remote_path):
    run("echo '%s' >> %s" % (variable, remote_file))

rawDescription: Python appending file remotely

description: Python appending file remotely


code:
# literal adaption from:
# http://stackoverflow.com/questions/4643285/how-to-generate-random-numbers-that-follow-skew-normal-distribution-in-matlab
# original at:
# http://www.ozgrid.com/forum/showthread.php?t=108175
def rand_skew_norm(fAlpha, fLocation, fScale):
    sigma = fAlpha / np.sqrt(1.0 + fAlpha**2)

    afRN = np.random.randn(2)
    u0 = afRN[0]
    v = afRN[1]
    u1 = sigma*u0 + np.sqrt(1.0 -sigma**2) * v

    if u0 >= 0:
        return u1*fScale + fLocation
    return (-u1)*fScale + fLocation

def randn_skew(N, skew=0.0):
    return [rand_skew_norm(skew, 0, 1) for x in range(N)]

# lets check they at least visually match the PDF:
plt.subplots(figsize=(12,4))
for alpha_skew in SKEW_PARAMS:
    p = randn_skew(NUM_SAMPLES, alpha_skew)
    sns.distplot(p)

rawDescription: generate N random numbers from a skew normal distribution using numpy

description: Generate N random numbers from a skew normal distribution using numpy


rawDescription: python natural comparison between strings?

description: Python natural comparison between strings


code:
dumped = cPickle.dumps(MyObject(100), 0)
timeit.timeit('cPickle.loads(dumped)', 'from __main__ import cPickle, dumped')
dumped = cPickle.dumps(MyObject(100), 1)
timeit.timeit('cPickle.loads(dumped)', 'from __main__ import cPickle, dumped')
dumped = cPickle.dumps(MyObject(100), 2)
timeit.timeit('cPickle.loads(dumped)', 'from __main__ import cPickle, dumped')

rawDescription: Why does it take longer to dump and load with pickle.HIGHEST_PROTOCOL?


code:
from timeit import timeit

some_array = [(i, 'a', True) for i in range(0,100000)]

def use_comprehension():
    return [(b, a, i) for i, a, b in some_array]

def use_enumerate():
    lst = []
    for j, k in enumerate(some_array):
        i, a, b = k
        lst.append((b, a, i))
    return lst

def use_for_in_with_append():
    lst = []
    for i in some_array:
        i, a, b = i
        lst.append((b, a, i))
    return lst

def use_for_in_with_indexes():
    lst = [None] * len(some_array)
    for j in range(len(some_array)):
        i, a, b = some_array[j]
        lst[j] = (b, a, i)
    return lst

print('comprehension:', timeit(use_comprehension, number=200))
print('enumerate:', timeit(use_enumerate, number=200))
print('for in append:', timeit(use_for_in_with_append, number=200))
print('for in indexes:', timeit(use_for_in_with_indexes, number=200))

rawDescription: Python List Indexing or Appending?

description: Python List Indexing or Appending


code:
from sympy.core.function import AppliedUndef
(f(x) + sin(x)).atoms(AppliedUndef)

rawDescription: Sympy: Get functions from expression

description: Sympy: Get functions from expression


code:
lst = []
for f in listdir(mypath):
    if isfile(join(mypath, f)):
        lst.append(f)

rawDescription: Elaborate on the following line

description: Elaborate on the following line


code:
from datetime import datetime

D = {'28.10.11/D/text1/' : {'key':'value1'},
     '27.01.11/D/text2/' : {'key':'value2'},
     '07.11.12/D/text3/' : {'key':'value3'}}

for k in sorted(D,key=lambda k: datetime.strptime(k[:8],"%d.%m.%y")):
    print(k,D[k])

rawDescription: Python: sorting multilevel dictionary by part of key


rawDescription: Is there a way to update a dictionary without changing any contained mutable types?


rawDescription: Python Efficiency / Optimization Project Euler #5 example


rawDescription: (Usage of Class Variables) Pythonic - or nasty habit learnt from java?


code:
import pandas as pd

df1 = pd.DataFrame({'A': range(5)}, index=list('abcde'))
df2 = pd.DataFrame({'A': range(5)}, index=list('AbCdE'))
print(df1)
#    A
# a  0
# b  1
# c  2
# d  3
# e  4

print(df2)
#    A
# A  0
# b  1
# C  2
# d  3
# E  4

print(df1.reindex(df1.index.intersection(df2.index)))

rawDescription: Pandas: How to get a new dataframe filled with unions of 2 or 3 or X other dataframes?


rawDescription: Reading chunks of csv file in Python using pandas


code:
a = "DRC(Carbamidomethyl)KPVNTFVHESLADVQAVC(Carbamidomethyl)SQKNVACK"
while True:
    begin, end  = a.find('('), a.find(')')
    if begin != -1 and end != -1:
        a = a[:begin] + a[end+1:] + " " + a[begin+1:end]
    else:
        break
a

rawDescription: Extracting part of string in parenthesis using python


rawDescription: extracting value from xml node

description: Extracting value from xml node


rawDescription: how to copy only upper triangular values into array from numpy.triu()?

description: Copy only upper triangular values into array from numpy.triu()


code:
result = self.opener.open(url)
with open(filename, 'wb') as f:
    f.write(result.read())

rawDescription: Make local urllib settings local?

description: Make local urllib settings local


code:
pi = np.pi; nan = np.nan
df = pd.DataFrame({"value": [3,4,9,10,11,np.nan,12]})
df.query("(value < 10) and (value > @pi)")

rawDescription: Querying for NaN and other names in Pandas


code:
from random import randint, choice

for _ in range(5):
    r = choice([(1,5),(9,15),(21,27)])
    print(randint(*r))

rawDescription: Python- How to generate random integers with multiple ranges?


code:
import itertools
itertools.product(a, b)

rawDescription: Comparing each variable in a list to each variable in another list


rawDescription: Get NumPy Array Indices in Array B for Unique Values in Array A, for Values Present in Both Arrays, Aligned with Array A


code:
def apply_rules(rules, input, start=0):
    # First yield the outcome of no applied rules.
    yield input[start:]

    for match, replace in rules:
        # Find the first match for this rule.
        index = input.find(match, start)
        if index < 0:
            # No match -- skip to next one
            continue
        # Prepare the result of the replacement.
        prefix = input[start:index] + replace
        # Apply further rules to the rest of the string
        # by a recursive call.
        for suffix in apply_rules(rules, input, index + len(match)):
            yield prefix + suffix

rawDescription: String Variations

description: String Variations


code:
with open('tblBuilding.csv', newline='') as building_file:
    building = csv.DictReader(building_file, delimiter=',', quotechar='"')
    buildings = {b['BuildingName']: b['BuildingID'] for b in building}

rawDescription: Nested DictReaders not resetting

description: Nested DictReaders not resetting


code:
pickle.dump(list(itertools.chain.from_iterable(
              myListGenerator(i) for i in range(10))), pickleFile)

rawDescription: Combining generators

description: Combining generators


code:
data = [(datetime.datetime.strptime(k, '%d.%m.%Y').date(), v)
        for k, v in yourdict.items()]
data.sort()

rawDescription: Python3: Date strings to chronological order


code:
a = "This is my sample text.\r\n\r\n\r\n\r\n\r\n Here start another sample text"
import re
re.sub(r'(\r\n){2,}','\r\n', a)

rawDescription: Python string clean up: How can I remove the excess of newlines of a string in python?


code:
import requests

resp = requests.get('http://localhost:1234')

rawDescription: What could I grep for in strace output from a gevent app to test whether it's using blocking network IO?


code: re.split('\s', "this is 'my string' that --has=arguments -or=something")

rawDescription: What is the difference between shlex.split() and re.split()?


code:
import wx

class MyFrame1 ( wx.Frame ):

    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 561,401 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )

        gbSizer1 = wx.GridBagSizer( 0, 0 )
        gbSizer1.SetFlexibleDirection( wx.BOTH )
        gbSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )

        gbSizer1.SetMinSize( wx.Size( 0,0 ) )
        self.m_panel25 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 40,10 ), wx.TAB_TRAVERSAL )
        self.m_panel25.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWTEXT ) )

        gbSizer1.Add( self.m_panel25, wx.GBPosition( 0, 0 ), wx.GBSpan( 1, 3 ), wx.EXPAND |wx.ALL, 5 )

        self.m_panel41 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
        gbSizer1.Add( self.m_panel41, wx.GBPosition( 5, 0 ), wx.GBSpan( 1, 1 ), wx.EXPAND |wx.ALL, 5 )

        self.m_panel26 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 10,10 ), wx.TAB_TRAVERSAL )
        self.m_panel26.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_INFOBK ) )

        gbSizer1.Add( self.m_panel26, wx.GBPosition( 0, 3 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )

        self.m_panel28 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 10,10 ), wx.TAB_TRAVERSAL )
        self.m_panel28.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_INFOBK ) )

        gbSizer1.Add( self.m_panel28, wx.GBPosition( 0, 4 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )

        self.m_panel27 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 10,10 ), wx.TAB_TRAVERSAL )
        self.m_panel27.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_INFOBK ) )

        gbSizer1.Add( self.m_panel27, wx.GBPosition( 0, 5 ), wx.GBSpan( 1, 1 ), wx.ALL, 5 )

        self.m_panel29 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 40,10 ), wx.TAB_TRAVERSAL )
        self.m_panel29.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_INFOBK ) )

        gbSizer1.Add( self.m_panel29, wx.GBPosition( 0, 6 ), wx.GBSpan( 1, 3 ), wx.EXPAND |wx.ALL, 5 )

        self.m_panel40 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 40,10 ), wx.TAB_TRAVERSAL )
        self.m_panel40.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_INFOTEXT ) )

        gbSizer1.Add( self.m_panel40, wx.GBPosition( 1, 3 ), wx.GBSpan( 5, 6 ), wx.EXPAND |wx.ALL, 5 )

        self.m_panel31 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 40,10 ), wx.TAB_TRAVERSAL )
        self.m_panel31.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT ) )

        gbSizer1.Add( self.m_panel31, wx.GBPosition( 1, 0 ), wx.GBSpan( 1, 3 ), wx.ALL, 5 )

        self.m_panel32 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 40,10 ), wx.TAB_TRAVERSAL )
        self.m_panel32.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT ) )

        gbSizer1.Add( self.m_panel32, wx.GBPosition( 2, 0 ), wx.GBSpan( 1, 3 ), wx.ALL, 5 )

        self.m_panel39 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 40,10 ), wx.TAB_TRAVERSAL )
        self.m_panel39.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT ) )

        gbSizer1.Add( self.m_panel39, wx.GBPosition( 3, 0 ), wx.GBSpan( 1, 3 ), wx.ALL, 5 )

        self.m_panel40 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 40,10 ), wx.TAB_TRAVERSAL )
        self.m_panel40.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT ) )

        gbSizer1.Add( self.m_panel40, wx.GBPosition( 4, 0 ), wx.GBSpan( 1, 3 ), wx.ALL, 5 )

        self.SetSizer( gbSizer1 )
        self.Layout()

        self.Centre( wx.BOTH )

def main():
    app = wx.App(False)
    MainFrame = MyFrame1(None)
    MainFrame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: How to understand wxGridBagSizer?

description: Understand wxGridBagSizer


code:
a
np.where(a>0)

rawDescription: Finding first non-zero value along axis of a sorted two dimensional numpy array


code:
set.seed(1) # for reproducability

n <- 100000 # number of random variables

# first beta distribution
a1 <- 0.5
b1 <- 0.9
X <- rbeta(n, a1, b1)

# second beta distribution
a2 <- 0.9
b2 <- 0.5
Y <- rbeta(n, a2, b2)

# calculate product
Z <- X * Y

# Have a look at the distributions
plot(density(Z), col = "red", main = "Distributions")
lines(density(X), lty = 2)
lines(density(Y), lty = 2)

rawDescription: Product of two beta distributions

description: Product of two beta distributions


code:
if request.method == 'POST':
    new_user = User(username = request.POST["username"],
                    email=request.POST["email"],
                    first_name=request.POST["first_name"],
                    last_name=request.POST["last_name"],
                    )
    new_user.set_password(request.POST["password"])
    new_user.save()
    Person.objects.create(user=new_user,
                      age=str(request.POST.get("age")),
                      city=str(request.POST.get("city")),
                      state=str(request.POST.get("state")))
    new_user.is_active = True
    new_user.save()
    return redirect('../')
else:
    return render(request, 'polls/create_account.html')

rawDescription: Django: Add additional properties to User


code:
class MyAuthTokenView(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        # log
        return response

my_token_view = MyAuthTokenView.as_view()

rawDescription: Adding loggin code to obtain_auth_token

description: Adding loggin code to obtain_auth_token


code: np.fromfunction(f, shape=(d1, d2))

rawDescription: Fastest way to initialize numpy array with values given by function


code:
import time
time.gmtime(0)

rawDescription: What is the oldest time that can be represented in python?


code: re.sub(re.compile('^\n', re.MULTILINE), '', s)

rawDescription: Sublime Text 3 API plugin for regex replacing text


code:
hidden_strings = ['python','java','ruby']
with open('path/to/textfile/as/in/example.txt') as infile:
    for line in infile:
        for hidden_string in hidden_strings:
            if hidden_string in line:
                print(hidden_string)

rawDescription: Python to print string from substring from list


code:
import scipy
X = scipy.randn(3,3)
X
X>0
scipy.where(X>0)
X[X>0] = 99
X
Y = scipy.randn(3,2)
scipy.dot(X, Y)

rawDescription: Is python capable of doing MATLAB equivalent matrix operations?


code:
import google

gae_dir = google.__path__.append('/path/to/appengine_sdk//google_appengine/google')
sys.path.insert(0, gae_dir) # might not be necessary

import google.appengine # now it's on your import path`

rawDescription: Google App Engine: ImportError: No module named appengine.ext


code:
from Tkinter import *
from random import randint

class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master, height=400, width=400)
        self.master = master
        self.master.bind('<Shift_L>', self.createArrow)

    def createArrow(self, event):
        #this is the only arrow method in this class. It waits for the Shift event,
        #then makes a new instance of Arrow and calls Arrow's method to get it moving
        self.arrow = Arrow(self)
        self.arrow.moveArrow(self.arrow, randint(0,400), randint(0,400))

class Arrow(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)    #This makes the frame,
        Label(self, text='===>').pack() #and puts a Label (the graphic) inside it

    def moveArrow(self, arrow, xCoord, yCoord):
        #the move arrow method - arguments are the arrow instance and the x,y coords
        arrow.place_forget()            #un-place the instance
        arrow.place(x=xCoord, y=yCoord) #replace with new x,y
        self.after(500, lambda: self.moveArrow(arrow, xCoord+1, yCoord)) #repeat, changing x

root = Tk()
app = App(root).pack()
root.mainloop()

rawDescription: Properly instantiate classes with Tkinter


code:
from shapely import geometry
import numpy as np

# lets create an example polygon
p = geometry.Point(0,0)
poly = p.buffer(100)

# you need to get the coordinates of the exterior (shell)
# pass these into a numpy array
shell_coords = np.array(poly.exterior)
print(shell_coords)

# you can do the same for interior (holes) as well

# then slice and dice to your heart's content
print(shell_coords[:,:1])
print(shell_coords[:,1:2])

rawDescription: How can I slice x and y coordinates from a Shapely polygon? [TypeError: 'Polygon' object is not iterable]

description: Slice x and y coordinates from a Shapely polygon? [TypeError: 'Polygon' object is not iterable]


code:
df['Teaching_grade'] = df['Teacher_ID'].map(TDict)
df['Student_grade'] = df['Student_ID'].map(SDict)

rawDescription: Using dicts to look up values for DataFrame variables


code:
with open('A Class, A.T.I..txt', "r") as file_out:
    a = a + 1
    Name2 = file_out.readline()
    print(Name2)
    Sur_name2 = file_out.readline()
    print(Sur_name2)
    Date2 = file_out.readline()
    print(Date2)
    Class2 = file_out.readline()
    print(Class2)
    Range_Limit2 = file_out.readline()
    print(Range_Limit2)
    N2 = file_out.readline()
    print(N2)
    Score_Percent2 = file_out.readline()
    print(Score_Percent2)

rawDescription: Unknown skip error file read in python

description: Unknown skip error file read in python


code:
import subprocess
direct_output = subprocess.check_output('ls', shell=True) #could be anything here.

rawDescription: How to store os.system() output in a variable or a list in python

description: Store os.system() output in a variable or a list in python


code: [callable(elem) for elem in inputiterator]

rawDescription: Why map returns an iterator

description: Why map returns an iterator


code:
from test.test_support import EnvironmentVarGuard
from django.test import TestCase

class MyTestCase(TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()
        self.env.set('VAR', 'value')

    def test_something(self):
        with self.env:
            # ... perform tests here ... #
            pass

rawDescription: django setting environment variables in unittest tests

description: Django setting environment variables in unittest tests


code:
a.T.ravel()
a.ravel('F')
a
a.T.ravel()  # or a.ravel('F')

rawDescription: Python row major to column major order vector


rawDescription: Filter list with regex

description: Filter list with regex


code:
gender = ['male','male','female','male','female']

import matplotlib.pyplot as plt
from collections import Counter

c = Counter(gender)

men = c['male']
women = c['female']

bar_heights = (men, women)
y = (1, 2)

fig, ax = plt.subplots()
width = 0.4

ax.barh(y, bar_heights, width)

ax.set_ylim((0, 3))
ax.set_xlim((0, max(men, women)*1.1))

ax.set_yticks([i+width/2 for i in y])
ax.set_yticklabels(['male', 'female'])

plt.show()

rawDescription: Matplotlib: how to plot categorical data on the y-axis?


rawDescription: Trouble with multiple regex options with Python re library


code:
import urllib.parse
urllib.parse.urlencode([('a', 'b'), ('c', 'd')])
urllib.parse.urlencode([('c', 'd'), ('a', 'b')])

rawDescription: Deterministically encode a dictionary as a url parameter list in Python


code:
django.db.transaction.enter_transaction_management(using='primary')
django.db.transaction.managed(True, using='primary')

i = 0
for record in records:
    i += 1
    r = PrimaryDBModel(**record)
    r.save() # This will no be committed until the end.
    if not i % 100:
        SecondaryDBModel.update()
        status = SecondaryDBModel(id=123)
        status.current_row = i
        status.save() # This will committed immediately.

django.db.transaction.commit(using='primary')
django.db.transaction.leave_transaction_management(using='primary')

rawDescription: Selective Transaction Management with Django ORM


code:
def quicksort(seq):
    if len(seq) <= 1:
        return seq
    lo, pi, hi = partition(seq)
    return quicksort(lo) + [pi] + quicksort(hi)

def partition(seq):
    pi, seq = seq[0], seq[1:]
    lo = [x for x in seq if x <= pi]
    hi = [x for x in seq if x > pi]
    return lo, pi, hi

rawDescription: Bucket sort faster than Quicksort

description: Bucket sort faster than Quicksort


code:
import argparse

args = ('foo','bar','baz','qux')
parser = argparse.ArgumentParser()

for x in args:
    parser.add_argument('--{0}'.format(x),help=x if x != 'baz' else argparse.SUPPRESS)

parser.parse_args(['-h'])

rawDescription: Python, argparse: turn off help description for selected parameters


code:
data = (
    (archive_file, archive_header, archive_body),
    (forum_file, forum_header, forum_body),
    (search_file, search_header, search_body),
    (rss_file, rss_header, rss_body)
)

for file, header, body in data:
    header = string.replace(header, "titlefixed", titlefixed)
    file.write(header + body + string.replace(footer_p, "<!-- recent posts -->", postgroup))
    file.close()

rawDescription: Can't solve a issue with for loop

description: Can't solve a issue with for loop


code: tempfile.mkstemp(suffix="", prefix=template, dir=None, text=False)

rawDescription: Using Python tempfiles permanently

description: Using Python tempfiles permanently


code:
import pandas as pd
merged_df = pd.merge(sortedregsubjdf, sortedcentralitiesdf, on='Name')

rawDescription: Combining dataframes of different lengths


rawDescription: How can I move WebDriver to new opened Chrome tab without knowing index?

description: Move WebDriver to new opened Chrome tab without knowing index


code: from . import db

rawDescription: Python: How to import from an __init__.py file?


code:
def db_update(new_cost, account):
    """ update the cost of an account
    """
    cursor.execute('''
    UPDATE transactions SET cost = cost + ? WHERE account = ?
    ''', (new_cost, account))
    connection.commit()

rawDescription: SQL : How to update existing value with variable


rawDescription: Remove negative sign in string format in python


code:
import math
def radians_from_triple(deg, min=0, sec=0):
    return math.radians(deg + min * 60 ** -1 + sec * 60 ** -2)

rawDescription: Entering precise degrees into python

description: Entering precise degrees into python


code:
unicode_html = myfile.read().decode('utf-8', 'ignore')
soup = BeautifulSoup (unicode_html)

rawDescription: What if the utf-8 encoding html file contains a non-utf-8 character?


code:
import matplotlib.pyplot as plt
plt.figure(figsize=(16, 10), dpi=100)
# ... your code
plt.savefig(filename)

rawDescription: How to do a plot in 1000 pixels?

description: Do a plot in 1000 pixels


code:
root = Tk()

menubar = Menu(root)

filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open")
filemenu.add_command(label="Save")
menubar.add_cascade(label="File", menu=filemenu)

#entryconfig method to change the item with index '0' to white
filemenu.entryconfig(0, foreground='white')

root.config(menu=menubar)
root.mainloop()

rawDescription: tkinter: change foreground color of specific menu items

description: Tkinter: change foreground color of specific menu items


rawDescription: Creating this block matrix in numpy

description: Creating this block matrix in numpy


code:
import bottle
from bottle import request, response

def foo(callback):
    def wrapper(*args, **kwargs):
        # before view function execution
        print(request.environ)  # do whatever you want

        body = callback(*args, **kwargs)  # this line basically means "call the view normally"

        # after view function execution
        response.headers['X-Foo'] = 'Bar'  # you don't need this, just an example

        return body  # another 'mandatory' line: return what the view returned (you can change it too)
    return wrapper

bottle.install(foo)

rawDescription: BottlePy pre-request processing

description: BottlePy pre-request processing


code:
import networkx as nx
net = nx.Graph()
net.add_edge("user_42", "user_9", trust=9)
net.adj

rawDescription: How do we represent a network as a dictionary in Python when using networkx?


code:
# gather all the relevant data first...
NEW_EMAIL = '--- new email ---'
END_EMAIL = '--- end email ---'
JACKPOT = '**JACKPOT WORD**'

email = []
jackpots = []
starting = True
with open('input.txt') as stream:
    for line in stream:
        if starting:
            if line.startswith(NEW_EMAIL):
                # start gathering new email lines
                email = []
                starting = False
        elif line.startswith(END_EMAIL):
            # start looking for a new email
            starting = True
        else:
            email.append(line)
            if JACKPOT in line:
                # only keep jackpot emails
                jackpots.append(email)

# now write out the final file...
with open('output.txt', 'w') as stream:
    for email in jackpots:
        stream.write('%s\n%s%s\n\n' % (
            NEW_EMAIL, ''.join(email), END_EMAIL))

rawDescription: How to isolate blocks of text containing specific words and remove the others?

description: Isolate blocks of text containing specific words and remove the others


code:
def foo(name, val):
    globals()[name] = val

rawDescription: How can a Python function create a global object with a name defined in an argument of that function?


code:
my_list = [-10,-10,-10,-20,-10,-10]
from collections import Counter
counter = Counter(my_list)
min(counter, key=counter.get)

rawDescription: How to efficiently find the odds one out in a list?

description: Efficiently find the odds one out in a list


code:
if (
    ("this phrase" in textfile or "that phrase" in textfile) and not (
    "not this phrase" in textfile or "not that phrase" in textfile)
):
    return True

rawDescription: Checking text files for certain strings in python


code:
from datetime import datetime
from collections import namedtuple
Range = namedtuple('Range', ['start', 'end'])
r1 = Range(start=datetime(2012, 1, 15), end=datetime(2012, 5, 10))
r2 = Range(start=datetime(2012, 3, 20), end=datetime(2012, 9, 15))
latest_start = max(r1.start, r2.start)
earliest_end = min(r1.end, r2.end)
overlap = (earliest_end - latest_start).days + 1
overlap

rawDescription: Efficient date range overlap calculation in python?


code:
import os

f = open(os.path.join(OUTPUT_DIR, 'file.txt'), 'w')
f.write('This is the new file.')
f.close()

rawDescription: Creating a file inside a directory in my working directory


code:
# Transverse
data = pd.read_csv("data.txt").T

# Insert your code to remove irrelevant rows, like a, b, c in your example
#

# Group by the trial number (the first six characters) and plot
data.groupby(lambda x: x[:6], axis=0).plot()

rawDescription: Efficiently plotting multiple columns in pandas


code:
from subprocess import check_output
from os import getlogin

c = check_output("users")
users = set(c.split())

print(all(user in {getlogin(),'(unknown)' } for user in users))

rawDescription: Optimization : Check if someone else is connected


code:
from google.appengine.ext import endpoints
from protorpc import messages
from protorpc import remote

class MyMessageClass(messages.Message):
  id = messages.StringField(1)  # Or any other field type

@endpoints.api(...)
class MyApi(remote.Service):
  @endpoints.method(MyMessageClass, SomeResponseClass,
                    ..., path='foos/{id}')
  def my_method(self, request):
    ...

rawDescription: Equivalent of @Named API parameter in Python


code:
def get(self, request, *args, **kwargs):
    if 'get_data' in kwargs:
        data_id = kwargs['get_data']
        step = kwargs['step']
        response = self.get_data(data_id, step)
    else:
        self.storage.reset()

        # reset the current step to the first step.
        self.storage.current_step = self.steps.first
        response = self.render(self.get_form())
    return response

rawDescription: Django SessionWizardView current step missing from form_list after Ajax request


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

driver = webdriver.Firefox()
driver.get("http://pastebin.com/search?q=ssh")

# wait for the search results to be loaded
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".gsc-result-info")))

# get all search results links
for link in driver.find_elements_by_css_selector(".gsc-results .gsc-result a.gs-title"):
    print(link.get_attribute("href"))

rawDescription: Python Crawling Pastebin (JavaScript rendered webpages)


rawDescription: Sqlalchemy get integer from text query

description: Sqlalchemy get integer from text query


code:
@classmethod
def get_objects(cls, service, references, as_dict=False):
    """
    More efficient way to get multiple objects at once. Requires the service
    instance and a list or tuple of references.
    """
    vo_list = database.get_objects_from_references(references)
    items = list()
    for vo in vo_list:
        items.append(cls(service, vo.getRef(), vo))

    return items

rawDescription: Python Reference Subclass in a Static Method


rawDescription: Numpy/pandas element-wise in operator

description: Numpy/pandas element-wise in operator


code: media = reduce(lambda x, y: x + y, [form.media for form in forms])

rawDescription: Django: correct way to group a bunch of media's


code:
import boto3

s3 = boto3.resource('s3')
# obj = s3.Object(bucket_name, key_name).get()
bucket = s3.Bucket(bucket_name)
obj = bucket.Object(key_name).get()
body = obj.get('Body')

rawDescription: How do you perform a credentialed download from s3 using boto3 without saving a file?

description: Perform a credentialed download from s3 using boto3 without saving a file


code:
from pyramid.config import Configurator

def main(global_config, **settings):
    config = Configurator(settings=settings, default_permission='authenticated')
    config.include('pyramid_chameleon')
    config.scan()
    return config.make_wsgi_app()

rawDescription: Obligatory authentication in Pyramid

description: Obligatory authentication in Pyramid


code:
def tearDown(self):
    def _cleanup():
        for tlw in wx.GetTopLevelWindows():
            if tlw:
                tlw.Destroy()
        wx.WakeUpIdle()
        #self.app.ExitMainLoop()
    wx.CallLater(50, _cleanup)
    self.app.MainLoop()
    del self.app

rawDescription: How to destroy a wxPython frame in unittest

description: Destroy a wxPython frame in unittest


code:
counter = dict(
    (a[0], (a[1], a[2]))
    for a in listX
)

for key, v1, v2 in listY:
    if key not in counter:
        counter[key] = (0, 0)
    counter[key][0] += v1
    counter[key][1] += v2

result = [(key, value[0], value[1]) for key, value in counter.items()]

rawDescription: Combine two lists: aggregate values that have similar keys


code:
from sklearn.cross_validation import train_test_split
X, y = dataset.iloc[:,:-1], dataset.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)

rawDescription: Preparing CSV file data for Scikit-Learn Using Pandas?


code:
p1 = re.compile('\d{12}')
p2 = re.compile('(\d{2})/(\d{2})/(\d{4})')
p3 = re.compile('(\d{4})')

# Functions to perform the processing steps required for each
# match- might be able to save some lines of code by making
# these lambdas
def result1(s, m):
    return s

def result2(s, m):
    return '%s%s0000%s' % (m.group(1), m.group(2), m.group(3))

def result3(s, m):
    return '01010000%s' % (m.group(1))

for pattern, result_getter in [(p1, result1), (p2, result2), (p3, result3)]:
    m = pattern.match(str)
    if m:
        result = result_getter(str, m)
        break

print('Result: ' + result)

rawDescription: Python equivallent of Perl match and capture within if block


code:
class B(object):
    def __getattr__(self, attr):
        if hasattr(self.a, attr):
            return getattr(self.a, attr)
        else:
            return object.__getattribute__(self, attr)

rawDescription: inherit all active variables of an input class

description: Inherit all active variables of an input class


code:
for x in ('p1', 'p2', 'p3', 'q1', 'q2', 'q3', 'q4', 'q5', 'x1', 'x2'):
    try:
        f = form[x]
        if not f.filename: raise
        outfile = '%s/%s.wav' % (savepath, x)
        oggfile = '%s/%s.ogg' % (oggdir, x)
        open(outfile, 'wb').write(f.file.read())
        command = 'oggenc %s -o %s' % (outfile, oggfile)
        output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
    except:
        pass

rawDescription: loops with multiple variables

description: Loops with multiple variables


code:
class rewindable_iterator(object):
    not_started = object()

    def __init__(self, iterator):
        self._iter = iter(iterator)
        self._use_save = False
        self._save = self.not_started

    def __iter__(self):
        return self

    def next(self):
        if self._use_save:
            self._use_save = False
        else:
            self._save = self._iter.next()
        return self._save

    def backup(self):
        if self._use_save:
            raise RuntimeError("Tried to backup more than one step.")
        elif self._save is self.not_started:
            raise RuntimeError("Can't backup past the beginning.")
        self._use_save = True

fiter = rewindable_iterator(file('file.txt', 'r'))
for line in fiter:
    result = process_line(line)
    if result is DoOver:
        fiter.backup()

rawDescription: Python: rewinding one line in file when iterating with f.next()


code:
def __getitem__(self, key):
    try:
        return [self.somelist[i] * 5 for i in key.indices(self.length)]
    except AttributeError:
        # not a slice object (no `indices` attribute)
        return self.somelist[key] * 5

rawDescription: Implementing __getitem__

description: Implementing __getitem__


rawDescription: Write python environmental variables to a javascript file


rawDescription: Python Multidimensional Array - Adding additional values to beginning and end of each row


code:
import urllib2
request = urllib2.Request('http://www.example.com', data)
response = urllib2.urlopen(request, timeout=4)
content = response.read()

rawDescription: setting the timeout on a urllib2.request() call

description: Setting the timeout on a urllib2.request() call


code:
from hypothesis.strategies import floats
get_float = floats().example
get_float
get_float()
get_float()
get_float()

rawDescription: Generate a random floating point, with no range constraint, but including +inf, -inf, NaN, in python


code:
import webbrowser
url = "https://www.google.com.tr/search?q={}".format(search_term)
webbrowser.open(url)

rawDescription: Script for opening up a Google search in a browser


code:
from bs4 import BeautifulSoup
import urllib2
html = urllib2.urlopen("http://www.auc.nl/news-events/events-and-lectures/events-and-lectures.html","r")
soup = BeautifulSoup(html)

all = soup.find('div',class_="agendaright")
time = all.find('span',class_="event-time").text
# u'18:00 - 20:00'
title = all.h3.text
# u'Images Without Borders Violence, Visuality, and Landscape in Postwar Ambon, Indonesia'
feature = all.find('span',class_="feature").text
# u' | Lecture'
description = all.find('p',class_="event-description").text
# u'This lecture explores the thematization of the visual and expansion of\nits terrain exemplified by the gigantic hijacked billboards with Jesus\nfaces and the painted murals with Christian themes which arose during\nthe ...'

l = [time,title,feature,description]

rawDescription: python parsing with beautiful soup

description: Python parsing with beautiful soup


code:
import numpy.uint32
valueA=uint32(5)
valueB=uint32(-5)
assert valueA < valueB

rawDescription: Python Custom Numeric Types: Wrap around number


rawDescription: How to separate a integral values

description: Separate a integral values


code:
for i in xrange(countMat.toarray().__len__()):
    row = countMat.toarray()[i]
    row / np.sqrt(np.sum(row**2))

rawDescription: How is TF calculated in Sklearn

description: How is TF calculated in Sklearn


code:
for item in list:
        item[1] += ' newdata'

rawDescription: Inserting data into a nested list in Python


code:
def offsetVTK(infilename, outfilename, offset):
    outfil = open(outfilename,'w')
    with open(infilename,'r') as infil:
        lin = 1
        while lin:
            lin = infil.readline()
            if lin.lower().startswith('points'):
                numpt = int(lin.split()[1])
                outfil.write(lin)
                for i in xrange(numpt):
                    outfil.write('{0[0]} {0[1]} {0[2]}\n'.format(
                       np.array(infil.readline().split(),dtype=float) + offset))
            else:
                outfil.write(lin)
    outfil.close()

offsetVTK('ray.vtk','ray_off.vtk', np.array([100,0,0]))

rawDescription: VTK UnstructuredGrid Offset coordinates

description: VTK UnstructuredGrid Offset coordinates


code:
import os
import os.path
import sys
import lxml.etree

if len(sys.argv) == 2:
    in_filename = str(sys.argv[1])
    if os.path.isfile (in_filename):
        for ent in lxml.etree.parse (in_filename).iter ('entry'):
            get = ent.xpath
            if ent.get ("kind") == "file":
                log_filename = get ('string(name)')
                log_revision = get('string(commit/@revision)') # Fixed ;)
                log_date = get ('string(commit/date)')
                print('{0},{1},{2}'.format(log_revision,log_date[:10],log_filename))

rawDescription: Parsing output of svn list command - Cannot get attribute


code:
class UploaderForm(forms.Form):
    file1 = forms.FileField(upload_to='user_files')

from django.forms.formsets import formset_factory
UploaderFormset = formset_factory(UploaderForm)

# long as you specify 'form-TOTAL_FORMS' and 2 other fields listed in the docs,
# the formset will auto generate form instances & populate with fields based on
# their 0 index.
formset = UploaderFormset(request.POST)

for form in formset.forms:
    form.save()

rawDescription: Arbitrary Number of File Uploads in Django


code:
import cv2
import numpy

white = cv2.imread('C:\white.jpg') #loading white image
reference = cv2.imread('C:\white.jpg') #loading white image
white = cv2.resize(white,(640,480)) #adjusting it to the size of the original image
reference = cv2.resize(white,(640,480)) #adjusting it to the size of the original image

y = 0 #for testing purposes the white image gets blackened manually
x = 0
j = 0

reference[10,10] = 0

while j < 50:

    if [255,255,255] in reference[y,x]:
        reference[y,x] = 0 #"0" creates a black pixel at the specified coordinate on the reference image
        white[y,x] = 0 #"0" creates a black pixel at the specified coordinate on the white image
        print("Coordinate not in system")
    else:
        print("coordinate already in system")
    x += 5
    y += 5
    j += 1

i = 0

while i < 100:

    cv2.imshow('image copy', white) #displays the image
    if cv2. waitKey(1) == ord('q'):
        break

rawDescription: Python create image with continous input


code:
def getPoints(connectionList):
    firstConnection = connectionList[0]
    points = [firstConnection[1][1]]
    lastLine = firstConnection[1][0]

    connectionList.remove(firstConnection)

    while len(connectionList):
        for connection in list(connectionList):
            (line1, p1), (line2, p2) = connection
            if lastLine == line1 or lastLine == line2:
                points.append(p1)
                lastLine = line1 if lastLine == line2 else line2
                connectionList.remove(connection)
                break
    return points

rawDescription: Searching and matching objects through tuples, list of lists


code:
from matplotlib import pyplot as plt
import numpy as np
x = np.array(range(1,129))
y = np.random.rand(14,128)
plt.plot(x, y)
plt.plot(x.T, y.T)

rawDescription: ValueError while plotting in python

description: ValueError while plotting in python


code:
def getFieldnames(csvFile):
    """
    Read the first row and store values in a tuple
    """
    with open(csvFile) as csvfile:
        firstRow = csvfile.readlines(1)
        fieldnames = tuple(firstRow[0].strip('\n').split("\t"))
    return fieldnames

def writeCursor(csvFile, fieldnames):
    """
    Convert csv rows into an array of dictionaries
    All data types are automatically checked and converted
    """
    cursor = []  # Placeholder for the dictionaries/documents
    with open(csvFile) as csvFile:
        for row in islice(csvFile, 1, None):
            values = list(row.strip('\n').split("\t"))
            for i, value in enumerate(values):
                nValue = ast.literal_eval(value)
                values[i] = nValue
            cursor.append(dict(zip(fieldnames, values)))
    return cursor

rawDescription: Read data from csv-file and transform to correct data-type


code: already_inserted = all(bitfield[i] for i in indexes)

rawDescription: Inline for in expression evaluation

description: Inline for in expression evaluation


code:
def require_post_decorator(function=None, redirect_url='/'):
    def _decorator(view_function):
        def _view(request, *args, **kwargs):
            if request.method == 'POST':
                #do some before the view is reached stuffs here.
                return view_function(request, *args, **kwargs)
            else:
                return HttpResponseRedirect(redirect_url)

        _view.__name__ = view_function.__name__
        _view.__dict__ = view_function.__dict__
        _view.__doc__ = view_function.__doc__

        return _view

    if function:
        return _decorator(function)
    return _decorator

rawDescription: response redirect to a different page when 405 raise

description: Response redirect to a different page when 405 raise


code:
cluster_to_tag = defaultdict(list)
#May want to assert that length of tags and T is same
for tag,cluster in zip(tags, T):
    cluster_to_tag[cluster].append(tag)

#cluster_to_tag now maps cluster ti list of tags

rawDescription: Extracting and integrating data from separate lists in Python


rawDescription: Match all characters except the last if it's a semicolon


code: lower, upper = dictionary1[key]

rawDescription: how do i access lists values stored in a dictionary key?

description: Access lists values stored in a dictionary key


code:
import csv
import re

with open("in.csv") as f, open("out.csv", "w") as out:
    out.write(next(f))
    r = csv.reader(f, delimiter=",")
    for row in r:
        out.write("{},{}\n".format(re.sub("_\d+|[_\d+]", ";",row[0]), ",".join(row[1:])))

rawDescription: Replace a part of a Python list element

description: Replace a part of a Python list element


code:
import bisect
a[bisect.bisect_left(a, 6):]

rawDescription: Python: Optimized method of cutting/slicing sorted lists


rawDescription: how to extract elements from a list in python?

description: Extract elements from a list in python


code:
# Available since Python 2.6
from __future__ import print_function

# Now you can use Python 3's print
print(1, 'hello', 2, 'fart', sep='\t')

rawDescription: Printing with tab separation instead of spaces


code:
query = "SELECT FRwoord, NLwoord FROM unite8app1 WHERE id=%s"
cursor.execute(query, (willekeurig,))

rawDescription: Read things out of database WHERE 'id'=

description: Read things out of database WHERE 'id'=


code:
def repl(match):
    return "{0} {1}{2}".format(match.group(1), match.group(2).upper(), match.group(3))

text = re.sub("~^(<.*?>)([0-9a-zа-яё]){1}(.*?)~eu", repl, text)

rawDescription: Eval code in re.sub as in php

description: Eval code in re.sub as in php


code:
a = {'foo': {'n': 'one', 'text': 'bla'},
     'bar': {'n': 'two', 'text': 'blah'},
     'baz': {'n': 'three', 'text': 'blabla'}}
mapping_dict = {'one':1,'two':2,'three':3}
sorted(a.keys(),key = lambda x: mapping_dict[a[x]['n']])

rawDescription: sorting dictionary values with a transformation function

description: Sorting dictionary values with a transformation function


code:
#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium

url = "http://example.com"

# use firefox to get page with javascript generated content
with closing(Firefox()) as browser:
    n = 1
    while n < 10:
        browser.get(url) # load page
        link = browser.find_element_by_link_text(str(n))
        while link:
           browser.get(link.get_attribute("href")) # get individual 1,2,3,4 pages
           #### save(browser.page_source)
           browser.back() # return to page that has 1,2,3,next -like links
           n += 1
           link = browser.find_element_by_link_text(str(n))

        link = browser.find_element_by_link_text("next")
        if not link: break
        url = link.get_attribute("href")

rawDescription: Using python with selenium to scrape dynamic web pages


code:
import csv
from openpyxl import Workbook
from openpyxl.cell import get_column_letter

f = open(r'C:\Users\Asus\Desktop\herp.csv')

csv.register_dialect('colons', delimiter=':')

reader = csv.reader(f, dialect='colons')

wb = Workbook()
dest_filename = r"C:\Users\Asus\Desktop\herp.xlsx"

ws = wb.worksheets[0]
ws.title = "A Snazzy Title"

for row_index, row in enumerate(reader):
    for column_index, cell in enumerate(row):
        column_letter = get_column_letter((column_index + 1))
        ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell

wb.save(filename = dest_filename)

rawDescription: openpyxl convert CSV to EXCEL

description: Openpyxl convert CSV to EXCEL


code:
gfgf=[[1],[2]]
for x in gfgf:
    if 1 in x:
        print(x)

rawDescription: Python list and range

description: Python list and range


code:
def splitstring(string):
    """
    >>> string = 'apple orange "banana tree" green'
    >>> splitstring(string)
    ['apple', 'orange', 'green', '"banana tree"']
    """
    import re
    p = re.compile(r'"[\w ]+"')
    quoted_item = p.search(string).group()
    newstring = p.sub('', string)
    return newstring.split() + [quoted_item]

rawDescription: Splitting arguments -- preserving quoted substrings -- in python


rawDescription: How can I create variables by iterating through a combination of integers and strings?

description: Create variables by iterating through a combination of integers and strings


code:
from Scientific.Geometry import Vector
v1 = Vector(1, 2, 3)
v2 = Vector(0, 8, 2)
v1.cross(v2)
v1.normal()
v2.cross(v1)
v1*v2 # dot product

rawDescription: Is there a Vector3 type in Python?

description: Is there a Vector3 type in Python


code:
class _RegisterScreen(tkinter.Frame):

    def __init__(self):
        self.gender = "NA" #Variable to be changed upon user selection

        self.root = tkinter.Tk()
        tkinter.Label(self.root, text="Sex").grid(row=1, padx=(0,10), sticky="w")

        self.sex_option = tkinter.StringVar()

        #This Radiobutton runs the setMale function when pressed
        tkinter.Radiobutton(self.root, text="Male", variable=self.sex_option,
            value="Male", command=self.setMale).grid(row=1, column=1)

        #This Radiobutton runs the setFemale function when pressed
        tkinter.Radiobutton(self.root, text="Female", variable=self.sex_option,
            value="Female", command=self.setFemale).grid(row=1, column=2)

        tkinter.Button(self.root, text="Submit",
            command=self._login_btn_clickked).grid(row=3, columnspan=4, pady=20)
        self.root.mainloop()

    def _login_btn_clickked(self):
        sex = self.gender #gets the value stored in gender and assigns it to sex
        print(sex)

    def setMale(self):
        self.gender="Male" #sets gender to Male

    def setFemale(self):
        self.gender="Female" #sets gender to Female

rawDescription: python tkinter.Radiobutton can't get value

description: Python tkinter.Radiobutton can't get value


code: DataFrame2 = DataFrame.query('Age < 40 & Age > 10')

rawDescription: How can I call data in a pandas DataFrame according to lower and upper bound?

description: Call data in a pandas DataFrame according to lower and upper bound


code:
answer = raw_input()
answer
answer == 'arst'
answer is 'arst'

rawDescription: Raw_input using python 2.7

description: Raw_input using python 2.7


code: my_str = "".join(reversed(my_str))

rawDescription: Python string/list reversal without using any library module or Dummy variable


code:
from subprocess import Popen, PIPE
from textwrap import dedent

isql = Popen(['./isql', '-I', '/app/sybase/...',
              '-S', mdbserver,
              '-U', muserid, ...,
              '-w', '99999'], stdin=PIPE, stdout=PIPE, cwd=sybase_path)
output = isql.communicate(dedent("""\
    SET NOCOUNT ON
    {}
    go
""".format(User_Query)))[0]

rawDescription: using subprocess module in python to run isql command

description: Using subprocess module in python to run isql command


code:
def create_form(model, field_names):
    # the inner class is the only useful bit of your ModelForm
    class Meta:
        pass
    setattr(Meta, 'model', model)
    setattr(Meta, 'include', field_names)
    attrs = {'Meta': Meta}

    name = 'DynamicForm'
    baseclasses = (forms.ModelForm,)
    form = type('DynamicForm', baseclasses, attrs)
    return form

def my_awesome_view(request):
    fields = ['start_time', 'end_time']
    form = create_form(Session, fields)
    # work with your form!

rawDescription: Django - ModelForm Dynamic field update

description: Django - ModelForm Dynamic field update


code:
# Initial connection and search
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://firmaopslag.dk")
element = driver.find_element_by_id("firmanavn")
element.send_keys("10403782")
element.send_keys(Keys.RETURN)

# wait for search results to appear
wait = WebDriverWait(driver, 10)
searchResults = wait.until(EC.presence_of_element_located((By.ID, "searchresult")))

for blue_house_result in searchResults.find_elements_by_xpath(".//button[.//span[contains(@class, 'glyphicon-home') and contains(@style, 'color: #002954;')]]"):
    label = blue_house_result.find_element_by_tag_name("h4")
    print(label.text)

rawDescription: Selenium - scrapping dynamically generated data Python


code:
DayDefn = ['Type1' if (x == 'H' and y>=7 and y<=23) else 'Type2'
           for x in HolidayWorkingDay for y in HE]

rawDescription: Python using multiple conditions inside a loop


rawDescription: Re.sub regex delete nested brackets python


code:
data = [
  ('A', 'blabla'),
  ('B', 'test1'),
  ('C', 'test2'),
]
stmt = "UPDATE product SET stock=%s WHERE ean=%s"
cur.executemany(stmt, data)

rawDescription: How to update MySQL faster by XML data?

description: Update MySQL faster by XML data


rawDescription: How to get ROS xml param from launch file using Python

description: Get ROS xml param from launch file using Python


code:
class SliderItemInline(TabularInline):
    model = SliderItem
    ordering = ['position']
    fields = ('position', 'story', 'active', 'story_status')
    readonly_fields = ('story_status',)

    def story_status(self, obj):
        return obj.story.status

rawDescription: Displaying a foreign key's field in an admin tabular inline


code:
self.tableView = QtGui.TableView(self)
self.table_model = QtGui.QStandardItemModel(0, 0)
self.proxyModel = CustomSortingModel(self)

self.proxyModel.setSourceModel(self.table_model)
self.tableView.setModel(self.proxyModel)

class CustomSortingModel(QtGui.QSortFilterProxyModel):
    def lessThan(self,left,right):

        col = left.column()

        dataleft = left.data()
        dataright = right.data()

        if col == 2:
            dataleft = float(dataleft)
            dataright = float(dataright)
        elif col == 3:
            dataleft = QtCore.QDate.fromString(dataleft, "d/M/yy").addYears(100)
            dataright = QtCore.QDate.fromString(dataright, "d/M/yy").addYears(100)

        return dataleft < dataright

rawDescription: QTableView Sorting dates and values

description: QTableView Sorting dates and values


code:
def my_view(request):
    if request.user.is_superuser:
        #your logic here
        return redirect("/admin/")# or your url name
    if request.user.is_staff:
        #your logic here
        return redirect("/dashboard/")# or your url name

rawDescription: How to redirect login urls depending upon user is admin or staff in django

description: Redirect login urls depending upon user is admin or staff in django


code:
import string
tweet = 'measles \xd2@theblackpenseur: gonorrhea rt @kylegotjokes: aids rt \xd2@cache___: my head itching so bad ?\xd3'
filter(lambda x: x in string.printable, tweet)

rawDescription: Removing Emojis from string

description: Removing Emojis from string


code:
import time
from functools import wraps

last_called = dict()  # When last called, and with what result

def ratelimit(seconds=10, timer=time.time):
    def decorator(func):
        last_called[func] = None

        @wraps(func)
        def wrapper(*args, **kwargs):
            now = timer()
            call_data = last_called.get(func, None)
            if call_data is None or now - call_data[0] >= seconds:
                result = func(*args, **kwargs)
                last_called[func] = (now, result)
            else:
                result = call_data[1]  # Replay rate-limited result
            return result
        return wrapper
    return decorator

rawDescription: How can I rate limit a function in Python 2.7 with a decorator?

description: Rate limit a function in Python 2.7 with a decorator


code:
def handle_result(rpc):
    result = rpc.get_result()
    # ... Do something with result...

# Use a helper function to define the scope of the callback.
def create_callback(rpc):
    return lambda: handle_result(rpc)

rpcs = []
for url in urls:
    rpc = urlfetch.create_rpc()
    rpc.callback = create_callback(rpc)
    urlfetch.make_fetch_call(rpc, url)
    rpcs.append(rpc)

# ...

# Finish all RPCs, and let callbacks process the results.
for rpc in rpcs:
    rpc.wait()

rawDescription: Google App Engine: how to parallelize downloads using TaskQueue or Async Urlfetch?


code:
def addone(x):
    x += 1
a = 2
addone(a)
a
def addone(x):
    x.append(1)

l=[2]
addone(l)
l
def addone(x):
    x = x + [1]

li=[2]
addone(li)
li

rawDescription: Python Change Variable In Place

description: Python Change Variable In Place


code:
d = {}
l1 = [1, 2, 3]
l2 = [4, 5, 6]
d['l1'] = l1  # Define your own key for 'l1'
d['l2'] = l2  # Define your own key for 'l2'

rawDescription: is it possible to get a dict of Lists in python?

description: Is it possible to get a dict of Lists in python


code:
finaldict = {}
dictlist = [{'a': ['e','f','g'], 'b': ['h','i','k'], 'c': ['u','v','w']},
            {'a': ['t','u']}]
for d in dictlist:
    for k in d.keys():
        try:
            finaldict[k] += d[k]
        except KeyError:
            finaldict[k] = d[k]

rawDescription: Merging dictionaries from a list of dictionaries in python


code: document[0] += ' GOOD'

rawDescription: Modifying corpus in python

description: Modifying corpus in python


code:
@receiver(
    post_delete,
    sender=ClientPhone,
    dispatch_uid="keep_one_client_phone_as_deafult"
)
def keep_one_default_phone_after_delete(sender, instance, **kwargs):
    phones = sender.objects.filter(client_id=instance.client_id)
    if len(phones) == 0:
        return
    elif len(phones) == 1:
        if not phones[0].default:
            phones[0].default = True
            phones[0].save()
            return
    else:
        if instance.default:
            sender.objects.get(client_id=instance.client_id).update(default=True)

@receiver(
    post_save,
    sender=ClientEmail,
    dispatch_uid="keep_one_client_email_as_deafult"
)
def keep_one_default_email(sender, instance, **kwargs):
    emails = sender.objects.filter(client_id=instance.client_id)
    if len(emails) == 0:
        return
    elif len(emails) == 1:
        if not emails[0].default:
            emails[0].default = True
            emails[0].save()
            return
    else:
        if instance.default:
            sender.objects.filter(
                ~Q(id=instance.id),
                client_id=instance.client_id
                ).update(default=False)
        else:
            emails[0].default = True
            emails[0].save()

rawDescription: Django model - One of foreigners set as main


code: SingleSelection, MultiSelection, ExtendedSelection, ContiguousSelection

rawDescription: QTableWidget select multiple cells permanently identical to Ctrl + MouseClick


code:
df0 = ddf.from_castra("data.castra")
df = odo.odo(df0, pd.DataFrame)
names = df.columns.tolist()
types = ['float32', 'float32', 'S20']  # adjust 'S20' to your max string length needs
cols = [bcolz.carray(df[c].values, dtype=dt) for c, dt in zip(names, types)]

ct = bcolz.zeros(0, dtype=np.dtype(zip(names, types)),
                    mode='w', chunklen=1000000,
                    rootdir="data.bcolz")
ct.append(cols)

rawDescription: data size blows out when storing in bcolz

description: Data size blows out when storing in bcolz


rawDescription: python Selenium close popup HTTP authentication

description: Python Selenium close popup HTTP authentication


code:
import os

tripo = [
('1.txt', []),
('2.txt', []),
('5.txt', []),
('4.txt', ['3.txt','6.txt']),
('7.txt', ['8.txt'])
]

def getname(f):
    return os.path.splitext(f)[0]

def getresult(t):
    result = []
    for k, v in tripo:
        values = [getname(n) for n in v]
        if len(values)>0:
            result.append(getname(k))
        for x in values:
            result.append(x)
    return result

def writedown(n,r):
    with open("test.csv","a") as f:
        for x in r:
            f.write("%s\t%s\n" % (n,x))
            print("%s\t%s\n" % (n,x))

print(getresult(tripo))

writedown(1, getresult(tripo))

rawDescription: How to save two-column array in a file in Python

description: Save two-column array in a file in Python


code:
for x in range(10):
        print("("+chr(ord('a')+x)+")"+str(LIST[x]))

rawDescription: Automated way of printing (a) (b) (c) before my string?


code:
class ImgProperty(ndb.BlobProperty):
  def __init__(self, height=32, width=32, **kwds):
    self.height = height
    self.width = width
    super(ImgProperty, self).__init__(**kwds)

rawDescription: Writing NDB Property Subclass

description: Writing NDB Property Subclass


code:
sql='SELECT x FROM myTable WHERE x LIKE %s'
args=[beginningOfString+'%']
cursor.execute(sql,args)

rawDescription: how to safely generate a SQL LIKE statement using python db-api

description: Safely generate a SQL LIKE statement using python db-api


code:
import csv

# File names: to read in from and read out to
input_file = "tester_2014-10-30_til_2014-08-01.txt"
output_file = input_file + "-SA_input.txt"

## ==================== ##
##  Using module 'csv'  ##
## ==================== ##
with open(input_file) as to_read:
    with open(output_file, "wb") as tmp_file:
        reader = csv.reader(to_read, delimiter = "\t")
        writer = csv.writer(tmp_file)

        desired_column = [6]        # text column

        for row in reader:     # read one row at a time
            myColumn = list(row[i] for i in desired_column)   # build the output row (process)
            writer.writerow(myColumn) # write it

rawDescription: Read and export a single column from a tab-separated file in Python


code:
#!/usr/bin/python3
from subprocess import Popen, PIPE

last_output = ""
while(1):
    proc = Popen(["mpc"], stdout=PIPE)
    output, retval = proc.communicate()
    if not output == last_output:
        print(output.decode('ascii'))
    last_output = output

rawDescription: Linux: MPC current song output

description: Linux: MPC current song output


code:
from collections import defaultdict

list1 = [6, 1, 8, 1, 2]
list2 = ["Mail Opened", "Mail Not Opened", "Mail Opened", "Mail Not Opened", "Mail Not Opened"]

added = defaultdict(int)

for i, k in enumerate(list2):
    added[k] += list1[i]

rawDescription: Python: Merging Two Lists

description: Python: Merging Two Lists


code:
ignore = {'the','a','if','in','it','of','or'}
result = collections.Counter(x for x in f if x not in ignore).most_common(1)

rawDescription: How to ignore some words when counting the frequency of a word accuracy in a text?

description: Ignore some words when counting the frequency of a word accuracy in a text


code:
def weakSidon(sequence_length):
    """Finds a weak Sidon sequence (a sequence (a_i) of integers where
       a_i + a_j for i < j are all unique) of the necessary length."""
    sequence = [1]
    sums = set()                                   # start with an empty set
    while len(sequence) < sequence_length:
        test_integer = sequence[-1] + 1
        test_sums = list(map(lambda x: test_integer + x, sequence))
        while any(x in sums for x in test_sums):   # testing set membership is O(1)
            test_integer = test_integer + 1
            test_sums = list(map(lambda x: test_integer + x, sequence))
        sequence.append(test_integer)
        sums.update(test_sums)                     # update set items
    return sequence

rawDescription: Test for Set Intersection Using Map Iterator


code:
class MultiWindows(QtGui.QMainWindow):

    def __init__(self, param):
        self.__windows = []

    def addwindow(self, window):
        self.__windows.append(window)

    def show():
        for current_child_window in self.__windows:
             current_child_window.exec_() # probably show will do the same trick

class PlanetApp(QtGui.QDialog):
    def __init__(self, parent, planet):
       QtGui.QDialog.__init__(self, parent)
       # do cool stuff here

class AnimalApp(QtGui.QDialog):
    def __init__(self, parent, animal):
       QtGui.QDialog.__init__(self, parent)
       # do cool stuff here

if __name__=="__main__":
    import sys # really need this here??

    app = QtGui.QApplication(sys.argv)

    jupiter = PlanetApp(None, "jupiter")
    venus = PlanetApp(None, "venus")
    windows = MultiWindows()
    windows.addWindow(jupiter)
    windows.addWindow(venus)

    windows.show()
    app.exec_()

rawDescription: Multiple Windows in PyQt4

description: Multiple Windows in PyQt4


code:
from kivy.clock import Clock
...
class MainApp(App):

    def build(self):

        main = MainWindow(cols=7)
        self.root = main  # don't use global!
        # make background
        with main.canvas:
            Rectangle(pos=main.pos, size=Window.size)

        # populate gridlayout with Buttons
        main.add_widget(Debug(text='debug', background_color=(1, 0, 0, 1)))
        main.popbtns()
        # print position of buttons...
        Clock.schedule_once(self.delayed_function, 0.1)

    def delayed_function(self, dt):
        self.print_buttons_pos()

    def print_buttons_pos(self):
        for child in self.root.children:
            print(str(child) + ' pos is ' + str(child.pos))

rawDescription: Kivy Instance of Button widget added to GridLayout missing pos value on creation?


code:
import xlsxwriter
workbook = xlsxwriter.Workbook('sample.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 2)
worksheet.write('B1', '=A1*4')
workbook.close()

rawDescription: How can I create a formula using xlsx writer

description: Create a formula using xlsx writer


code:
import pymysql
import os
import HTML
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

conn = pymysql.connect(host='localhost', port=1000, user='users', passwd='pw', db='database')

cur = conn.cursor()

#mysql query

query = ("""select * from table""")

cur.execute(query)

htmlcode = HTML.table(rows)

# me == my email address
# you == recipient's email address
me = "me@me.com"
you = "you@you.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = htmlcode

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()

rawDescription: Sending a MySQL query as HTML in Python

description: Sending a MySQL query as HTML in Python


code:
match = re.search('U:\s*(\S+)')
if match: username = match.group(1)

match = re.search('U:\s*(\S+ - \S+)')
if match: username_and_hash = match.group(1)

match = re.search('U:\s*(\S+) - (\S+)')
if match:
    username = match.group(1)
    userhash = match.group(2)

rawDescription: Regex/Python noob needs assistence

description: Regex/Python noob needs assistence


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from matplotlib.cbook import get_sample_data

def main():
    x = np.linspace(0, 10, 20)
    y = np.cos(x)
    image_path = get_sample_data('pic.png')
    fig, ax = plt.subplots()
    imscatter(x, y, image_path, zoom=0.1, ax=ax)
    ax.plot(x, y)
    plt.show()

def imscatter(x, y, image, ax=None, zoom=1):
    if ax is None:
        ax = plt.gca()
    try:
        image = plt.imread(image)
    except TypeError:
        pass
    im = OffsetImage(image, zoom=zoom)
    x, y = np.atleast_1d(x, y)
    artists = []
    for x0, y0 in zip(x, y):
        ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=False)
        artists.append(ax.add_artist(ab))
    ax.update_datalim(np.column_stack([x, y]))
    ax.autoscale()
    return artists

main()

rawDescription: Ploting img with matplotlib

description: Ploting img with matplotlib


code:
sum( 1 for line in fh)
fh.seek(0)  # Move file position/pointer to the beginning (0).
sum( 1 for line in fh)

rawDescription: file object (f = open(filename)) expires after using once?

description: File object (f = open(filename)) expires after using once


code:
def sendmail(toaddy, msg):
    debuglevel = 0
    smtp = SMTP()
    smtp.set_debuglevel(debuglevel)
    smtp.connect('YOUR.MAIL.SERVER', 26)
    smtp.login('USERNAME@DOMAIN', 'PASSWORD')
    fromaddy = 'USERNAME@DOMAIN'
    smtp.sendmail(fromaddy, toaddy, msg)
    smtp.quit()

rawDescription: Python mass email sending

description: Python mass email sending