code: [zip(*sublist) for sublist in List]

rawDescription: Python reorder lists inside lists

description: Python reorder lists inside lists


code:
variants = ("".join(item) for item in itertools.product("0123456789", repeat=inp)) #now its a generator expression

with open("outfile","wb") as variant:
    for number in variants:
        variant.write("%s\n"%number)

rawDescription: Python itertool variations, memory maximum reached


code:
import string

class Del:
  def __init__(self, keep=string.digits):
    self.comp = dict((ord(c),c) for c in keep)
  def __getitem__(self, k):
    return self.comp.get(k)

DD = Del()

x='aaa12333bb445bb54b5b52'
x.translate(DD)

rawDescription: Python: removing characters except digits from string


code:
def call_all(*funcs):
    """Create a new wrapper to call each function in turn."""
    def wrapper(*args, **kwargs):
        """Call the functions and return a list of their outputs."""
        return [func(*args, **kwargs) for func in funcs]
    return wrapper

rawDescription: Adding lines to a function

description: Adding lines to a function


code:
net.layers[1].blobs[0].data.shape  # >> (64, 3, 7, 7)
net.layers[1].blobs[1].data.shape  # >> (64,)

rawDescription: Finding gradient of a Caffe conv-filter with regards to input


code:
df
df.B.isnull()

rawDescription: How to compare two columns and create new dataframe

description: Compare two columns and create new dataframe


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2','/')

# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
                            requestHandler=RequestHandler)
server.register_introspection_functions()

# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)

# Register a function under a different name
def adder_function(x,y):
    return x + y
server.register_function(adder_function, 'add')

# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
    def div(self, x, y):
        return x // y

server.register_instance(MyFuncs())

# Run the server's main loop
server.serve_forever()

rawDescription: Create a SimpleHTTPServer to use the python code as API


rawDescription: boolean indexing that can produce a view to a large pandas dataframe?

description: Boolean indexing that can produce a view to a large pandas dataframe


code:
if distance <= self.radius:
    self.radius = self.radius // 2
...

rawDescription: Pygame circle and its associated rect for collision detection


code:
def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')

is_interesting({'target_type': 42})
is_interesting({'target_type': 670})
is_interesting({'target_type': 670, 'script': ''})
is_interesting({'target_type': 670, 'script': 'abc'})

rawDescription: Better approach to do this

description: Better approach to do this


code:
from collections import Counter
Counter(x for _, l in mylist for x in l)

rawDescription: Python: how can I count the occurrences in a list of tuples?


code: mydict['fieldname']

rawDescription: When and why should I use a namedtuple instead of a dictionary?


code:
def count_zeros_gen(matrix):
    return sum(row.count(0) for row in matrix)

rawDescription: Counting elements matching a pattern in a tuple of tuples


code:
import sys

data = []
with open('myInput03.txt', 'r') as myInput:
  for line in myInput:
    line = line.strip()
    if not line: continue
    try:
      (year, rainfall) = line.split()
      data.append((int(year), float(rainfall)))
    except ValueError:
      sys.stderr.write("Possible malformed line '%s'- skipping" % line)
      continue

dataSize = len(data)
if dataSize < 3:
  sys.stderr.write("Not enough data to compute 3 year average")
  sys.exit(1)

with open('myOutput03.txt', 'w') as myOutput:
  for i in xrange(2, dataSize):
    rainfallTotal = 0.0
    mySlice = data[i-2:i+1]
    for (year, rainfall) in mySlice: rainfallTotal += rainfall
    (firstYear, lastYear) = [data[j][0] for j in (i-2, i)]
    myOutput.write("%d-%d %f\n" % (firstYear, lastYear, rainfallTotal/len(mySlice)))

rawDescription: I am stuck on how to split up the file, then average it for each three years


code:
class Poly:
    def __init__(self, coefs):
        self.coefs = coefs

    def __str__(self):
        coefs_and_pows = reversed(list(enumerate(self.coefs)))
        return ' + '.join('{}*x**{}'.format(coef, i) for i, coef in coefs_and_pows)

    def __repr__(self):
        return '<function {} at 0x{:x}'.format(self, id(self))

    def __call__(self, x):
        return sum(coef * x**i for i, coef in enumerate(self.coefs))

rawDescription: Which information is returned when I type the name of a function in the Python interpreter?


code:
[li[n:n + length] for n in range(len(li) - length + 1)
    if li[n:n + length] == list(range(li[n], li[n] + length))]

rawDescription: Function that returns all sub-sequences in a list that are successive


code:
while True:
    fml=getFml()
    fml=parseFml(fml)
    count=count+1
    if count>1:
        oldfml=fml
    if oldfml == fml:
        ...

rawDescription: Comparing Strings in Python 3

description: Comparing Strings in Python 3


code: wordlist = [word for word in wordlist if all(f not in word for f in filters)]

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


code: [list(x) for x in zip(cities, airports)]

rawDescription: Using list comprehension in Python to do something similar to zip()?


code:
# Specify the y-position of the labels
y1 = df_MMCAlist['Total']
y2 = df_MMCAsale['Total']

xcoord = df_MMCAsale['Sale Date'] # Specify the x-position of the labels

annotationsList = [dict(
                x=xi,
                y=yi,
                text=str(yi),
                xanchor='right',
                yanchor='bottom',
                showarrow=False,
            ) for xi, yi in zip(xcoord, y1)]

annotationsSale = [dict(
                x=xi,
                y=yi,
                text=str(yi),
                xanchor='left',
                yanchor='bottom',
                showarrow=False,
            ) for xi, yi in zip(xcoord, y2)]

annotations = annotationsList + annotationsSale

rawDescription: Adding annotations to a bar graph in Plotly


code:
import os

path_var = os.pathsep.join(os.environ.get('PATH', os.defpath), some_dir)
env = dict(os.environ, PATH=path_var)
run("some_command", cwd=some_path, env=env)
run("another_command", cwd=another_path, env=env)

rawDescription: environment variables using subprocess.check_output pythoon

description: Environment variables using subprocess.check_output pythoon


rawDescription: Want to multiply, not repeat variable

description: Want to multiply, not repeat variable


code:
def letters(input):
    return ''.join(filter(str.isalpha, input))

rawDescription: How do you filter a string to only contain letters?

description: Filter a string to only contain letters


rawDescription: python function slowing down for no apparent reason

description: Python function slowing down for no apparent reason


code:
self.b1 = tk.Button(buttonframe,
    text="Page 1", command=lambda: self.open_page(0))
self.b2 = tk.Button(buttonframe,
    text="Page 2", command=lambda: self.open_page(1))

rawDescription: Still struggling with class scope

description: Still struggling with class scope


code:
import httplib
import socket

from selenium.webdriver.remote.command import Command

def get_status(driver):
    try:
        driver.execute(Command.STATUS)
        return "Alive"
    except (socket.error, httplib.CannotSendRequest):
        return "Dead"

rawDescription: Python Selenium: How to check whether the WebDriver did quit()?


code:
def lemmma(file):
    return [i for i in file]

rawDescription: get a list in a function in python

description: Get a list in a function in python


code:
class myClass(object):
    def __init__(self):
        self.x = 1

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        self._x = x
        self.y = 2 * self._x

rawDescription: Python classes: linked attributes

description: Python classes: linked attributes


rawDescription: Count odds in list of lists

description: Count odds in list of lists


code:
balance = int(input("Enter initial balance: $ "))
for i in range(11):
    n = int(input("Enter deposit #: %s " %(i)))
    total +=n

print("Original price: $ %d" %balance)
print("Final Amount: $ %d" %(total + balance) )

rawDescription: writing (for and while) loop program in python?

description: Writing (for and while) loop program in python


code: new_labels = labels.copy()

rawDescription: Set superpixel color

description: Set superpixel color


code:
def remove_letters(str1,str2):
    s = set(str1)
    return "".join([char for char in str2 if char not in s])

rawDescription: Removing letters from a string that occur in the previous string


code:
def numLen(inputstring, index):
    char = inputstring[index]
    return inputstring.count(char)

numLen("This is a Test", 3)

rawDescription: Return repeated count of given string position


code:
from xml.etree import ElementTree as et

def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

D = {36322:(17,2),22388:(5,8)}

job = et.Element('JOB')
for itemnumber,(salesman,quantity) in D.items():
    item = et.SubElement(job,'ITEMNUMBER').text = str(itemnumber)
    et.SubElement(job,'SALESMAN').text = str(salesman)
    et.SubElement(job,'QUANTITY').text = str(quantity)
indent(job)
et.dump(job)

rawDescription: How to copy certain information from a text file to XML using Python?

description: Copy certain information from a text file to XML using Python


code:
def return_common(first, second):
    return ",".join(sorted(set(first.split(","))&set(second.split(","))))

rawDescription: Better way to find common words in a tuple?


code:
from nltk.corpus import wordnet as wn

synonyms = wn.synsets('good','a')

for synset in synonyms:
    print(synset.name())
    print(synset.pos())

rawDescription: How to iterate through the synset list generated from wordnet using python 3.4.2

description: Iterate through the synset list generated from wordnet using python 3.4.2


code: from pandas import DataFrame

rawDescription: How to compute rolling rank correlation using Pandas

description: Compute rolling rank correlation using Pandas


code:
"""
Django settings for prova project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^%r&tw5_steltu_ih&n6lvht0gs(0p#0p5z0br@+#l1o(iz_t6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sessions',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
)

ROOT_URLCONF = 'prova.urls'

WSGI_APPLICATION = 'prova.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy'
    }
}
AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

rawDescription: Django - Auth with mongoengine DB

description: Django - Auth with mongoengine DB


code:
fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

rawDescription: How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

description: Plot a very simple bar chart (Python, Matplotlib) using input *.txt file


code:
from django.core import serializers
result = serializers.serialize('json',
                               City.objects.filter(code__exact=12345),
                               fields=('id', 'name', 'state__name', 'state__id'))

rawDescription: How to get objects inside another object from a Query?

description: Get objects inside another object from a Query


code:
my_args = ["foo", "bar", 42]
"Hello %s" % ', '.join([str(e) for e in my_args])

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

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


code:
input = 0x15

output = [int(x) for x in '{:08b}'.format(input)]

rawDescription: How do I convert an integer to a list of bits in Python

description: Convert an integer to a list of bits in Python


code: list(matches(list1, list2))

rawDescription: find all common sequences of two list in python

description: Find all common sequences of two list in python


code:
from collections import Counter
Counter(L1)  # dict_count
sum((Counter({k:v}) for k,v in zip(L1, L2)), Counter())  # dict_sum

rawDescription: Python: summarizing data from list using index from another list


code:
import sys
import cv2
import ctypes
import ctypes.util

if sys.platform == 'win32':
    LIBNAME = 'libtesseract302'
else:
    LIBNAME = 'tesseract'

class TesseractError(Exception):
    pass

class Tesseract(object):
    _lib = None
    _api = None

    class TessBaseAPI(ctypes._Pointer):
        _type_ = type('_TessBaseAPI', (ctypes.Structure,), {})

    @classmethod
    def setup_lib(cls, lib_path=None):
        if cls._lib is not None:
            return
        if lib_path is None:
            lib_path = ctypes.util.find_library(LIBNAME)
            if lib_path is None:
                 raise TesseractError('tesseract library not found')
        cls._lib = lib = ctypes.CDLL(lib_path)

        # source:
        # https://github.com/tesseract-ocr/tesseract/
        #         blob/3.02.02/api/capi.h

        lib.TessBaseAPICreate.restype = cls.TessBaseAPI

        lib.TessBaseAPIDelete.restype = None # void
        lib.TessBaseAPIDelete.argtypes = (
            cls.TessBaseAPI,) # handle

        lib.TessBaseAPIInit3.argtypes = (
            cls.TessBaseAPI, # handle
            ctypes.c_char_p, # datapath
            ctypes.c_char_p) # language

        lib.TessBaseAPISetImage.restype = None
        lib.TessBaseAPISetImage.argtypes = (
            cls.TessBaseAPI, # handle
            ctypes.c_void_p, # imagedata
            ctypes.c_int,    # width
            ctypes.c_int,    # height
            ctypes.c_int,    # bytes_per_pixel
            ctypes.c_int)    # bytes_per_line

        lib.TessBaseAPIGetUTF8Text.restype = ctypes.c_char_p
        lib.TessBaseAPIGetUTF8Text.argtypes = (
            cls.TessBaseAPI,) # handle

    def __init__(self, language='eng', datapath=None, lib_path=None):
        if self._lib is None:
            self.setup_lib(lib_path)
        self._api = self._lib.TessBaseAPICreate()
        if self._lib.TessBaseAPIInit3(self._api, datapath, language):
            raise TesseractError('initialization failed')

    def __del__(self):
        if not self._lib or not self._api:
            return
        if not getattr(self, 'closed', False):
            self._lib.TessBaseAPIDelete(self._api)
            self.closed = True

    def _check_setup(self):
        if not self._lib:
            raise TesseractError('lib not configured')
        if not self._api:
            raise TesseractError('api not created')

    def set_image(self, imagedata, width, height,
                  bytes_per_pixel, bytes_per_line=None):
        self._check_setup()
        if bytes_per_line is None:
            bytes_per_line = width * bytes_per_pixel
        self._lib.TessBaseAPISetImage(self._api,
                                      imagedata, width, height,
                                      bytes_per_pixel, bytes_per_line)

    def get_utf8_text(self):
        self._check_setup()
        return self._lib.TessBaseAPIGetUTF8Text(self._api)

    def get_text(self):
        self._check_setup()
        result = self._lib.TessBaseAPIGetUTF8Text(self._api)
        if result:
            return result.decode('utf-8')

rawDescription: Using C API of tesseract 3.02 with ctypes and cv2 in python


code:
interesting_data = []
for data in data_all:
    data_string_sample=((data['utcdate']['mday']),(data['utcdate']['mon']),(data['utcdate']['year']),(data['utcdate']['hour']),(data['utcdate']['min']),(data['tempm']),(data['hum']),(data['pressurem']))
    interesting_data.append(data_string_sample)

rawDescription: Python - Iterate through, and extract, elements of a dictionary type list


code:
x = []
y = []
for i in range(3):
   xi, yi = 3, 3    #initally set candidates to fail check
   while xi ** 2 + yi ** 2 > 9:
      xi = rand_range(-3, 3)
      yi = rand_range(-3, 3)
   x.append(xi)
   y.append(yi)

rawDescription: Using 'If' to run the loop again?

description: Using 'If' to run the loop again


code: df.pivot_table(index='dept', columns='position', values='name', aggfunc='count').fillna(0)

rawDescription: How to get the count of particular values in a column using pandas

description: Get the count of particular values in a column using pandas


code:
config = {'/static':
                {'tools.staticdir.on': True,
                 'tools.staticdir.dir': PATH_TO_STATIC_FILES,
                }
        }

cherrypy.tree.mount(MyApp(), '/', config=config)

rawDescription: How to send a directory to jinja2

description: Send a directory to jinja2


code: from bs4 import BeautifulSoup

rawDescription: Use Beautiful Soup findall to extract text between single quotations


code:
# do the work
i, j, values = d.T

ids = a[:, 0]
id_map = np.zeros_like(ids)
id_map[ids-1] = np.arange(len(ids))

res[id_map[i-1], j+3] = values

rawDescription: list comprehension with np.where to compare two arrays and combine them it first entry is equal

description: List comprehension with np.where to compare two arrays and combine them it first entry is equal


code: [list(x) for x in smaller_A]

rawDescription: Python and remove duplicates in list of lists regardless of order within lists


code:
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
pd.tseries.plotting.pylab.show()

rawDescription: Pandas plot doesn't show

description: Pandas plot doesn't show


code:
def convert(image):
    f = open(image,"rb")
    data = f.read()
    f.close()
    string = base64.b64encode(data)
    convert = base64.b64decode(string)
    t = open("Puppy2.jpg", "wb")
    t.write(convert)
    t.close()

rawDescription: Converting Images with Python

description: Converting Images with Python


code:
['firstname', 'bob', 'lastname', 'stewart', 'dob', '2010-0206',
 'hobbies', 'reading, singing', 'drawing', 'is_minor', True]

rawDescription: PyParsing a string representing a function


code:
import datetime
datetime.datetime.fromtimestamp(1267488000000 / 1000)

rawDescription: What the heck kind of timestamp is this: 1267488000000


code: sorted(cityPopulation.iteritems(),key=lambda k_v: k_v[1][2],reverse=True) #2010

rawDescription: Sorting a defaultdict by value in python


code:
import numpy as np
import numba as nb

unique, inverse, count = np.unique(ccl_np, return_counts = True, return_inverse = True)
xcm_array = np.zeros(len(count),dtype=np.float32)
ycm_array = np.zeros(len(count),dtype=np.float32)
inverse = inverse.reshape(64,64)

def mysolver(xcm_array, ycm_array, inverse, count):
    for i in range(64):
        for j in range(64):
            pos = inverse[i][j]
            local_count = count[pos]
            xcm_array[pos] += i/(local_count*1.)
            ycm_array[pos] += j/(local_count*1.)

@nb.jit(nopython=True)
def mysolver_nb(xcm_array, ycm_array, inverse, count):
    for i in range(64):
        for j in range(64):
            pos = inverse[i,j]
            local_count = count[pos]
            xcm_array[pos] += i/(local_count*1.)
            ycm_array[pos] += j/(local_count*1.)

rawDescription: Optimize python for Connected Component Labeling Area of Subsets


code:
template = """My {pet} ate my {object}.
This is a float: {number:0.2f}.
{integer:10d} is an integer on a newline."""

rawDescription: Reversing C-style format strings in Python (`%`)


code:
df['x']
df['x'].values

rawDescription: using python's stats.kendalltau function

description: Using python's stats.kendalltau function


code:
class DriverRideForm(forms.ModelForm):
    class Meta:
        model = Ride
        exclude = ('driver', 'passengers', )

rawDescription: django - Many To Many relationship issue

description: Django - Many To Many relationship issue


code:
import time
timeinseconds = 100000
while(1):
    time.sleep(timeinseconds)
    runProgram()

rawDescription: Autorun python script from python

description: Autorun python script from python


rawDescription: How to remove character from tuples in list?

description: Remove character from tuples in list


code:
from itertools import combinations, chain
arr = np.fromiter(chain.from_iterable(combinations(x, 2)), dtype=x.dtype)
arr.reshape(arr.size/2, 2)

rawDescription: efficiently compute ordering permutations in numpy array

description: Efficiently compute ordering permutations in numpy array


code:
sample = ({'name': 'bob', 'sex': 'male'}, {'name': 'sally', 'sex': 'female'})
{d['name']: d['sex'] for d in sample}
dict((d['name'], d['sex']) for d in sample)

rawDescription: turn tuple of dicts into single dict

description: Turn tuple of dicts into single dict


rawDescription: Getting the item with the maximun value in list of dicts after grouping the dict by key


code:
for ssid in overlaps:
    if ssid == subseq_id or ssid in merged:
      continue
    # ...

rawDescription: Can this Python loop be expressed more succinctly?


rawDescription: for-loops in Python modules

description: For-loops in Python modules


code: [np.r_[a, np.zeros((N - a.shape[0], m), dtype=a.dtype)] for a in your_arrays]

rawDescription: How to make a list of numpy arrays all have the same shape?

description: Make a list of numpy arrays all have the same shape


rawDescription: python range creation best practice

description: Python range creation best practice


rawDescription: Is it possible to np.concatenate memory-mapped files?


code:
from StringIO import StringIO

input_file = StringIO('''\
COMMAND     PID       USER   FD      TYPE             DEVICE  SIZE/OFF       NODE NAME
init          1       root  cwd       DIR                8,1      4096          2 /
kthreadd      2       root  txt   unknown                                         /proc/2/exe
kjournald    42       root  txt   unknown                                         /proc/42/exe
''')

rawDescription: Split a variable table in python

description: Split a variable table in python


code: {{ fetch_result }}

rawDescription: How to include a function call in a Django template?

description: Include a function call in a Django template


code:
print('Do you want to play again? (yes or no)')
playAgain = input()

rawDescription: How do I use 2 loops, and if it is false, repeat the program indefinetely

description: Use 2 loops, and if it is false, repeat the program indefinetely


code: A.m is A.m

rawDescription: Why is a method not identical to itself?

description: Why is a method not identical to itself


code:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

rawDescription: Change user agent for selenium driver

description: Change user agent for selenium driver


rawDescription: Converting the contents of a CSV file into a dictionary


rawDescription: How int() object using "==" operator without __eq__() method in python2?


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

    @property
    def spam(self):
        return self.__spam

rawDescription: Python class which instances' atributes can't be edited


code: name, email, lastlogon = row[0:3]

rawDescription: python copy to multiple variables

description: Python copy to multiple variables


rawDescription: How do I take a list of lists and rearrange them in python

description: Take a list of lists and rearrange them in python


code:
from PIL import Image
import StringIO

# define three new image sizes
card_dimensions = (108,108)
main_dimensions = (42,38)
thumb_dimensions = (18,14)
# covert uploaded image to Pillow object
raw_pil = Image.open(my_image.file)
# conversion to card size
raw_card_output = StringIO.StringIO()
raw_card = raw_pil.resize((card_dimensions))
raw_card.save(raw_card_output,format=raw_pil.format)
raw_card_output_contents = raw_card_output.getvalue()
# conversion to main size
raw_main_output = StringIO.StringIO()
raw_main = raw_pil.resize((main_dimensions))
raw_main.save(raw_main_output,format=raw_pil.format)
raw_main_output_contents = raw_main_output.getvalue()
#conversion to thumb size
raw_thumb_output = StringIO.StringIO()
raw_thumb = raw_pil.resize((thumb_dimensions))
raw_thumb.save(raw_thumb_output,format=raw_pil.format)
raw_thumb_output_contents = raw_thumb_output.getvalue()
# put card image into GridFS
fs.put(raw_card_output_contents)
# put main image into GridFS
fs.put(raw_main_output_contents)
# put thumb image into GridFS
fs.put(raw_thumb_output_contents)

rawDescription: How to put an image resized with Pillow into GridFS?

description: Put an image resized with Pillow into GridFS


code:
result=[0] #we put the initial value in the list
for _ in range(30): # the _ is to signal that we don use that value
    result.append( 10 + result[-1] ) # negative indices access the element in reverse order, -1 is the last, -2 is the previous to that etc
print(result)

rawDescription: Accessing a value from an np.array from a while loop


code:
#ifdef SO_RCVTIMEO
PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
#endif

rawDescription: Why SO_RCVTIMEO is inherited from listening socket to accepted socket?


code: s += ' '.join(str(a[i,j,k].imag))

rawDescription: Pythonic way to print a multidimensional complex numpy array to a string


code:
counter = 0

def addCount():
    global counter
    counter = counter + 1

rawDescription: What does action mean for scheduled events in python?


code:
import csv

with open('table2.txt', 'r') as f_table2:
    csv_table2 = csv.reader(f_table2, delimiter=' ', skipinitialspace=True)
    table2_header = next(csv_table2)
    table2_data = {cols[0] : cols[1:] for cols in csv_table2}

with open('table1.txt', 'r') as f_table1, open('output.csv', 'w', newline='\n') as f_output:
    csv_table1 = csv.reader(f_table1, delimiter=' ', skipinitialspace=True)
    table1_header = next(csv_table1)
    csv_output = csv.writer(f_output)
    csv_output.writerow(table2_header)

    csv_output.writerows(
        ['{}+{}'.format(cols[0], cols[1])] + [int(x) + int(y) for x, y in zip(table2_data[cols[0]], table2_data[cols[1]])] for cols in csv_table1)

rawDescription: Python - merging data in two tables

description: Python - merging data in two tables


code: space = np.meshgrid(*[np.linspace(low_bound, up_bound, m)]*dim, sparse=True)

rawDescription: Creating variables in loop for dynamicly creating griddata()


code:
import tokenize
import token
import io
import collections

class Token(collections.namedtuple('Token', 'num val start end line')):
    @property
    def name(self):
        return token.tok_name[self.num]

def get_non_string(text):
    result = []
    for tok in tokenize.generate_tokens(io.BytesIO(text).readline):
        tok = Token(*tok)
        # print(tok.name, tok.val)
        if tok.name != 'STRING':
            result.append(tok.val)
    return ''.join(result)

print(get_non_string("hello'''everyone'''!' :)'''"))

rawDescription: Does this code correctly identify python strings


code:
class status_file:
   myConfig = ConfigParser.RawConfigParser()
   myConfig.optionxform = str

   def __init__(self, str_statusfile):
       ...

rawDescription: python RawConfigParser

description: Python RawConfigParser


code: df4 = df3.drop_duplicates(subset='rownum', keep='last')

rawDescription: Remove rows with duplicate indices (Pandas DataFrame and TimeSeries)


code:
def cycle(echo):
    # Every second, sent a "ping" event.
    timestr = datetime.utcnow().isoformat()+"Z"
    echo("event: ping\n")
    echo('data: ' +  json.dumps(dict(time=timestr)))
    echo("\n\n")

    # Send a simple message at random intervals.
    if random.random() < 0.1:
        echo("data: This is a message at time {}\n\n".format(timestr))

class SSEResource(resource.Resource):
    def render_GET(self, request):
        request.setHeader("Content-Type", "text/event-stream")
        lc = task.LoopingCall(cycle, request.write)
        lc.start(1) # repeat every second
        request.notifyFinish().addBoth(lambda _: lc.stop())
        return server.NOT_DONE_YET

rawDescription: Server-sent events with Python,Twisted and Flask: is this a correct approach for sleeping?


code:
rows, col_names = walk_dict( input_dict_1 )
output_array_1 = [col_names]
for d in rows:
    output_array_1.append( [d[name] for name in col_names] )

rawDescription: Converting Arbitrarily Nested Dict to List of Lists


code:
def galPrice(commodity, values):
    comdata = filter(lambda i: i['name'] == commodity,
                     data['lastStarport']['commodities'])
    return [dict(zip(values, [com[value] for value in values]))
            for com in comdata]

rawDescription: Retrieve multiple values from JSON

description: Retrieve multiple values from JSON


code:
def get_urls(self):
    urls = super(classname, self).get_urls() # replace wit your class name
    my_urls = patterns(
        '',
        url(r'^export/$',
            ExportCampaignView.as_view(), name='export'),
    )
    return my_urls + urls

rawDescription: Triggering Custom Functionality in Django Admin


rawDescription: Learning Python - Permutation Error

description: Learning Python - Permutation Error


rawDescription: Efficient vector selection in numpy

description: Efficient vector selection in numpy


rawDescription: Python Regex - replace a string not located between two specific words


rawDescription: Python - When duplicate items are identified, which object does a set or frozenset take?


code:
value_map = {el: i for i, el in enumerate(set(child))}
child2 = [value_map[el] for el in child]

rawDescription: Efficient way of re-numbering elements in an array


code:
while total < 0:
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    ops = random.choice(opslist)

    total = (ops(num1,num2))

rawDescription: How do I use arithmetic symbols instead of built in functions

description: Use arithmetic symbols instead of built in functions


code: re.findall(r'<(.*)>', email_string2)

rawDescription: How to eliminate email formatting in received email?

description: Eliminate email formatting in received email


code:
from functools import partial
p = partial(print, 'aef','qwe')
p()
em = partial(exampleMethod, 5, 6)
em()

rawDescription: Abstract methods like in Java

description: Abstract methods like in Java


code:
d = {"key2" : "value2",
"key3" : "value3",
"key4" : "value4"}
any(isinstance(value, dict) for value in d.values())

rawDescription: Find whether dictionary is simple key-value pair or nested dicts


code:
et = lxml.etree.fromstring('''<item><img src="cat.jpg" /> Picture of a cat</item>''')
et.find('img').tail

rawDescription: Extracting text after tag in Python's ElementTree


rawDescription: Python look for a format that match specific format


code:
self.response.content_type = 'image/gif'
self.response.write(img_content)

rawDescription: How to return image with GAE?

description: Return image with GAE


rawDescription: Using a shared variable in a function

description: Using a shared variable in a function


rawDescription: Fermat Factorisation with Python

description: Fermat Factorisation with Python


code:
# -*- coding: utf-8 -*-
import wx
import sys

class PanelOne(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour("blue")
        font = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        button1 = wx.Button(self, -1, label='Button1')
        button2 = wx.Button(self, -1, label='Button2')
        button1.SetFont(font)
        button2.SetFont(font)

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(button1, 1, wx.EXPAND)
        vbox.Add(button2, 1, wx.EXPAND)
        self.SetSizer(vbox)

class PanelTwo(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.textctrl = wx.TextCtrl(self, -1, pos=(200,120), style=wx.TE_PROCESS_ENTER|wx.CENTER)

class PanelThree(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour("white")

        self.text = wx.TextCtrl(self, -1,
                            style = wx.TE_MULTILINE|wx.TE_READONLY|
                            wx.HSCROLL)
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.text, 1, wx.EXPAND)
        self.SetSizer(vbox)

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        topSplitter = wx.SplitterWindow(self, size=(800,600))
        vSplitter = wx.SplitterWindow(topSplitter)

        self.panelOne = PanelOne(vSplitter)
        self.panelTwo = PanelTwo(vSplitter)
        self.panelThree = PanelThree(topSplitter)

        self.panelTwo.textctrl.Bind(wx.EVT_KEY_DOWN, self.OnEnter)

        vSplitter.SplitVertically(self.panelOne, self.panelTwo)
        vSplitter.SetSashGravity(0.3)

        topSplitter.SplitHorizontally(vSplitter, self.panelThree)
        topSplitter.SetSashGravity(0.5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(topSplitter, 1, wx.EXPAND)

    def OnEnter(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER:
            """Here, I want to Print some message in PanelThree textctrl """
            self.panelThree.text.SetValue("ENTER PRESSED")
        else:
            self.panelThree.text.SetValue("")
        event.Skip()

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='my program',
                          size=(800,600))
        panel = MainPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: wxpython How to change the values of widgets in other panel

description: Wxpython How to change the values of widgets in other panel


code:
import threading
import time

class Foo():
    def __init__(self, interval, callbacks):
        self.thread = threading.Thread(target=self.loop)
        self.interval = interval
        self.thread_stop = threading.Event()
        self.callbacks = callbacks

    def loop():
        while not self.thread_stop.is_set():
            #do some stuff...
            for callback in self.callbacks():
                callback()
            self.thread_stop.wait(self.interval)

    def start(self):
        self.thread.start()

    def kill(self):
        self.thread_stop.set()

rawDescription: Interrupting a thread in Python with a KeyboardException in the main thread


code:
import pkg_resources
try:
    pkg_resources.require("BeautifulSoup>=X.X.X")
except pkg_resources.ResolutionError:
    from foobar import BeautifulSoup
else:
    import BeautifulSoup

rawDescription: Require BeautifulSoup in a Python Package - What's needed in setup.py?


code: {", ".join(key): val for key, val in new_data.items()}

rawDescription: Python: Compare Dictionary Keys

description: Python: Compare Dictionary Keys


code:
[new_value if i == replace_index else element
 for i, element in enumerate(my_list)]

rawDescription: Replacing a list item and returning a copy of the list (in one line) with Python


code: c.query("Select SourceName, Message from Win32_NTLogEvent where EventType =1, Logfile = \"Application\"")

rawDescription: WMI Query Date Filter

description: WMI Query Date Filter


code:
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlite3 import Connection as SQLite3Connection

@event.listens_for(Engine, "connect")
def _set_sqlite_pragma(dbapi_connection, connection_record):
    if isinstance(dbapi_connection, SQLite3Connection):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON;")
        cursor.close()

rawDescription: How can "on delete restrict" be used in a model?


code:
class Patchwork(object):

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

    @methdispatch
    def get(self, arg):
        return getattr(self, arg, None)

    @get.register(list)
    def _(self, arg):
        return [self.get(x) for x in arg]

rawDescription: How can I use functools.singledispatch with instance methods?

description: Use functools.singledispatch with instance methods


code:
for artist in data['results']['artistmatches']['artist']:
    image = max(artist['image'], key=lambda i: sizemap[i['size']])
    image_url = image['#text']
    print(image_url)

rawDescription: JSON dictionary lookup

description: JSON dictionary lookup


code:
def foo():
    A = 2

rawDescription: Scope of classes inside of functions and classes inside of a class in python


rawDescription: Extract a column from a list of rows with Python


code:
from datetime import datetime

fmt = 'Since then, {0} days, {1} hours, {2} minutes and {3} seconds have elapsed'
td = datetime.now() - datetime(year=1980, month=1, day=1, hour=18)
print(fmt.format(td.days, td.seconds // 3600, td.seconds % 3600 // 60, td.seconds % 60))

rawDescription: Python timedelta in full days, full hours and so on


code:
import myscript
myscript.myvar

rawDescription: examine the variables when running python script in python environment?

description: Examine the variables when running python script in python environment


code:
from operator import itemgetter
from collections import OrderedDict

class strings(tuple):
    __slots__ = ()
    _fields = tuple('a{}'.format(i) for i in range(400))
    def __new__(cls, *args, **kwargs):
        req = len(cls._fields)
        if len(args) + len(kwargs) > req:
            raise TypeError(
                '__new__() takes {} positional arguments but {} were given'.format(
                    req, len(args) + len(kwargs)))
        if kwargs.keys() > set(cls._fields):
            raise TypeError(
                '__new__() got an unexpected keyword argument {!r}'.format(
                    (kwargs.keys() - set(cls._fields)).pop()))
        missing = req - len(args)
        if kwargs.keys() & set(cls._fields[:-missing]):
            raise TypeError(
                '__new__() got multiple values for argument {!r}'.format(
                    (kwargs.keys() & set(cls._fields[:-missing])).pop()))
        try:
            for field in cls._fields[-missing:]:
                args += (kwargs[field],)
                missing -= 1
        except KeyError:
            pass
        if len(args) < req:
            raise TypeError('__new__() missing {} positional argument{}: {}'.format(
                missing, 's' if missing > 1 else '',
                ' and '.join(filter(None, [', '.join(map(repr, cls._fields[-missing:-1])), repr(cls._fields[-1])]))))
        return tuple.__new__(cls, args)

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new strings object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != len(self._fields):
            raise TypeError('Expected %d arguments, got %d' % (len(self._fields), len(result)))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        format = '{}({})'.format(self.__class__.__name__, ', '.join('{}=%r'.format(n) for n in self._fields))
        return format % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    __dict__ = property(_asdict)

    def _replace(self, **kwds):
        'Return a new strings object replacing specified fields with new values'
        result = self._make(map(kwds.pop, self._fields, self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % list(kwds))
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        return None

for i, name in enumerate(strings._fields):
    setattr(strings, name,
            property(itemgetter(i), doc='Alias for field number {}'.format(i)))

rawDescription: Any way to bypass namedtuple 255 arguments limitation?


code:
df = pd.DataFrame({'a':np.arange(5), 'b':np.arange(5)})
df.to_csv(r'c:\data\t.csv')

rawDescription: Pandas to_csv call is prepending a comma


code:
def __init__(self):
    self.dispatch_map = { 'a' : self.a, 'b' : self.b }

rawDescription: Dispatch a class method

description: Dispatch a class method


rawDescription: Setting all dictionary elements to 0 python


code: theano.dot(A[:, None, :] * B[None, :, :], C.T)

rawDescription: Matrix triple product with theano

description: Matrix triple product with theano


code:
def add_subtotal(g):
    category = g.index.get_level_values('Category')[0]
    g.loc[(category, 'subtotal'), :] = g.sum()
    return g

with_subtotals = andback.groupby(level='Category', axis=0).transform(add_subtotal)

with_subtotals.loc[('Grand', 'Total'), :] = with_subtotals\
    .loc[with_subtotals.index.get_level_values('Period')=='subtotal', :]\
    .sum()

rawDescription: Pivot a pandas dataframe and get the non-axis columns as a series


code:
from .client import clientclass as client
from .staff import staffclass as staff
from .order import orderclass as order

rawDescription: python MySQL module class file name

description: Python MySQL module class file name


code:
columns = {}
for row in rows:
    for column in rows[row]:
        columns.setdefault(column, []).append(row)

rawDescription: Storing large amount of boolean data in python


code:
from django.http import HttpResponse
import json

def get_statisics(request):
    j = MyModel.objects.values('field_a', 'field_b')
    return HttpResponse(json.dumps(j), content_type='application/json')

rawDescription: Override django admin landing page and pass variables to template


code: np.where(np.char.find(x, '.') > -1)

rawDescription: finding element of numpy array that satisfies condition

description: Finding element of numpy array that satisfies condition


code:
files =  sorted(get_files("."), key=os.path.getmtime,reverse=True)
filtered =  filter(lambda x: os.path.getmtime(files[0]) - os.path.getmtime(x) <= .09,files)

rawDescription: How to retrieve the most recently created files in a directory

description: Retrieve the most recently created files in a directory


code:
common_keys = set(d1).intersection(d2, d2, d3, d4)
'abc' in common_keys

rawDescription: check to see if key exist in 2 dictionary in same line

description: Check to see if key exist in 2 dictionary in same line


code: from tkinter import *

rawDescription: How to save text form a textbox (String and Int) in python 3.x tkinter

description: Save text form a textbox (String and Int) in python 3.x tkinter


code:
df2 = df.copy()
df2['value'] *= 2

rawDescription: Python Pandas. Creating DataFrame with Series does not preserve dtype


code:
import sys
import argparse

first_parser = argparse.ArgumentParser()
first_parser.add_argument('arg1')

second_parser = argparse.ArgumentParser()
second_parser.add_argument('arg2')

first_args = []
second_args = []
double_dashed = False
for arg in sys.argv[1:]:
    if arg == '--':
        double_dashed = True
    elif not double_dashed:
        first_args.append(arg)
    else:
        second_args.append(arg)
print(first_parser.parse_args(first_args))
print(second_parser.parse_args(second_args))

rawDescription: Two sets of arguments python

description: Two sets of arguments python


code:
import datetime
class NewDate(datetime.date):
    @classmethod
    def today(cls):
        return cls(2010, 1, 1)
datetime.date = NewDate

rawDescription: Python: Trying to mock datetime.date.today() but not working


code:
class SomethingView(FormView):
    def get_form_kwargs(self, *args, **kwargs):
        return dict(
            super(SomethingView, self).get_form_kwargs(*args, **kwargs),
            **{'user': self.request.user}
        )

rawDescription: Django default value for form

description: Django default value for form


code:
mystr = "StackOverflow"
from collections import deque
window = deque(maxlen=5)
for char in mystr:
    window.append(char)
    print ( ''.join(list(window)) )

rawDescription: Flexible sliding window (in Python)

description: Flexible sliding window (in Python)


code:
import wx

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Test")

        self.panel = wx.Panel(self)
        self.mainSizer = wx.BoxSizer(wx.VERTICAL)
        samples = [("Red", "Breathe Into Me", "End of Silence"),
                   ("eleventyseven", "Lonely", "Sugarfist"),
                   ("Lecrae", "Go Hard", "Rebel")]
        for sample in samples:
            artist, track, album = sample
            self.PlayLabel(artist, track, album)

        self.panel.SetSizer(self.mainSizer)
        panelSizer = wx.BoxSizer()
        panelSizer.Add(self.panel, 1, wx.EXPAND)
        self.SetSizer(panelSizer)
        self.Fit()

    def PlayLabel(self, artist, track, album):
        header_font = wx.Font(26, wx.SWISS, wx.NORMAL, wx.BOLD, False, "Helvetica")
        album_font = wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD, False, "Helvetica")

        block = self.panel

        # sizer
        sizer = self.mainSizer

        # artist
        label_artist = wx.StaticText(block, -1, artist)
        label_artist.SetForegroundColour('BLACK')
        label_artist.SetFont(header_font)

        # track
        label_track = wx.StaticText(block, -1, track)
        label_track.SetForegroundColour('BLACK')
        label_track.SetFont(header_font)

        # album
        label_album = wx.StaticText(block, -1, album)
        label_album.SetForegroundColour('BLACK')
        label_album.SetFont(album_font)

        sizer.AddMany([
                (label_artist, 1, wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT, 5),
                (label_track, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5),
                (label_album, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
        ])

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    frame.Show()
    app.MainLoop()

rawDescription: BoxSizer issue: Not expanding to fit contents of StaticText


code:
tms = []
for _ in xrange(5):
    begin_time = time.clock()
    func(cnt)
    tms.append(time.clock() - begin_time)

rawDescription: How to do profiling for this?

description: Do profiling for this


code: df['unixtime'] = pd.to_datetime(df['unixtime'].astype(int), unit='s')

rawDescription: timestamp string (Unix time) to datetime or pandas.Timestamp

description: Timestamp string (Unix time) to datetime or pandas.Timestamp


code:
def parse_number(stream):
    return int(next(stream).partition('#')[0].strip())

def parse_coords(stream, count):
    return [parse_number(stream) for i in range(count)]

def parse_test(stream):
    count = parse_number(stream)
    return list(zip(parse_coords(stream, count), parse_coords(stream, count)))

def parse_file(stream):
    for i in range(parse_number(stream)):
        yield parse_test(stream)

rawDescription: Python: Most optimal way to read file line by line


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

rawDescription: Numpy where function multiple conditions


code:
import subprocess
subprocess.call(["python", "local_script_name.py", "arg1", "arg2", "-etc"], cwd="script_dir")

rawDescription: How do I run Python script from a subdirectory?

description: Run Python script from a subdirectory


rawDescription: Python: Use Regular expression to remove something


code:
def __init__(self, node_id, c = None):
    if c is None:
        c = []

rawDescription: Python - unusual behaviour with custom tree


code: np.argwhere(df.values ==1)

rawDescription: Index of columns where rows match criterion Python Pandas


code:
class Foobar(object):
    def __init__(self, name, x=None, y=None, z=None):
        self.name = name
        self.x = x
        self.y = y
        self.z = z

rawDescription: How to return a dictionary in parallel processing in spark?

description: Return a dictionary in parallel processing in spark


code: fh = io.FileIO(filename, 'wb')

rawDescription: Google drive API download files - python - no files downloaded


code: re.sub(r"\d+\. |(?<!^)\n", "", modfile, flags=re.MULTILINE)

rawDescription: How to modify a text file using Python

description: Modify a text file using Python


code:
def show_table(table):
    string = ''
    for i in table:
        for j in range(len(i)):
            line = i[j]
            string += '| {} '.format(i[j])
        string += '|\n'

    return string

print(show_table([['A','BB'],['C','DD']]))

rawDescription: function def show_table create a and return a formatted string representing the 2D table

description: Function def show_table create a and return a formatted string representing the 2D table


rawDescription: Include and neglect the text between 2 special characters


code:
class C(object):
    def __init__(self, ID=0):
        self.ID=ID

rawDescription: How to assign value inside list comprehension

description: Assign value inside list comprehension


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

data = np.ones((25, 111))
specFig, specAx = plt.subplots()
specAx.set_xlim([0, data.shape[1]])

newax = specAx.twiny()
newax.set_xlim([0, data.shape[1]])

specAx.imshow(data, origin="lower")
specAx.set_aspect('equal', 'box-forced')
newax.set_aspect('equal', 'box-forced')
plt.show()

rawDescription: Matplotlib - Keep aspect ratio when using multiple axes


code: x = next((s for s in leest if re.search("th.*e", s)), "")

rawDescription: More line-efficient way to use re.search to match string in a list?


code:
class MyModel(models.Model):
    # model definition

    @transaction.atomic
    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)
        foo() # do_other_things

rawDescription: Django models: managing transactions when commit_manually is deprecated


rawDescription: Counting frequency of occurrence by month-year using python panda


code:
mask = 2 ** 32 - 1
format(mask, '032b')
x = 1
x ^ mask
format(x ^ mask, '032b')

rawDescription: Bit reversing in Python

description: Bit reversing in Python


code:
from PIL import Image, ImageOps

mask = Image.open('mask.png').convert('L')
im = Image.open('image.png')
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)
output.save('output.png')

rawDescription: How do I generate circular thumbnails with PIL?

description: Generate circular thumbnails with PIL


code:
flist = []
for i in range(30):
    def func(x, i=i):
        print(x * i)
    flist.append(func)

rawDescription: python - Is it possible to create a list of "def"?

description: Python - Is it possible to create a list of "def"


code:
def condense(l):
    outp = [l[0]]
    for x in l[1:]:
        if isinstance(x,list) and x[0]==l[0]:
            outp += x[1:]
        else:
            outp.append(x)
    return outp
def condense_r(l):
    outp = [l[0]]
    for x in l[1:]:
        if isinstance(x,list):
            z = condense_r(x)
            if z[0]==l[0]:
                outp += z[1:]
            else:
                outp.append(z)
        else:
            outp.append(x)
    return outp

rawDescription: Python : Iterate through list and sublists and match first elements and do some more manipulations


code:
def to_bytes(num, length, order):
    res = bytearray(length)
    for i in range(length):
        res[i] = num & 0xff
        num >>= 8
    if num:
        raise OverflowError("Number {} doesn't fit into {} bytes.".format(num, length))
    if order == 'little':
        res.reverse()
    return res

rawDescription: Add part of an integer to bytearray

description: Add part of an integer to bytearray


rawDescription: Creating dictionaries from a text file

description: Creating dictionaries from a text file


code:
from matplotlib import pyplot as plt

plt.imshow(img_array, cmap='gray')

rawDescription: Viewing .npy images

description: Viewing .npy images


code:
from pyspark.sql.window import Window
from pyspark.sql.functions import mean, col

# Hive timestamp is interpreted as UNIX timestamp in seconds*
days = lambda i: i * 86400

rawDescription: Spark Window Functions - rangeBetween dates


code: {'SR': 'Senior', 'FR': 'Freshman', 'SO': 'Sophomore', 'JR': 'Junior'}

rawDescription: Convert a Django Model Field Choices into a JSON


code:
cnames = {
'aliceblue':            '#F0F8FF',
'antiquewhite':         '#FAEBD7',
'aqua':                 '#00FFFF',
'aquamarine':           '#7FFFD4',
'azure':                '#F0FFFF',
'beige':                '#F5F5DC',
'bisque':               '#FFE4C4',
'black':                '#000000',
'blanchedalmond':       '#FFEBCD',
'blue':                 '#0000FF',
'blueviolet':           '#8A2BE2',
'brown':                '#A52A2A',
'burlywood':            '#DEB887',
'cadetblue':            '#5F9EA0',
'chartreuse':           '#7FFF00',
'chocolate':            '#D2691E',
'coral':                '#FF7F50',
'cornflowerblue':       '#6495ED',
'cornsilk':             '#FFF8DC',
'crimson':              '#DC143C',
'cyan':                 '#00FFFF',
'darkblue':             '#00008B',
'darkcyan':             '#008B8B',
'darkgoldenrod':        '#B8860B',
'darkgray':             '#A9A9A9',
'darkgreen':            '#006400',
'darkkhaki':            '#BDB76B',
'darkmagenta':          '#8B008B',
'darkolivegreen':       '#556B2F',
'darkorange':           '#FF8C00',
'darkorchid':           '#9932CC',
'darkred':              '#8B0000',
'darksalmon':           '#E9967A',
'darkseagreen':         '#8FBC8F',
'darkslateblue':        '#483D8B',
'darkslategray':        '#2F4F4F',
'darkturquoise':        '#00CED1',
'darkviolet':           '#9400D3',
'deeppink':             '#FF1493',
'deepskyblue':          '#00BFFF',
'dimgray':              '#696969',
'dodgerblue':           '#1E90FF',
'firebrick':            '#B22222',
'floralwhite':          '#FFFAF0',
'forestgreen':          '#228B22',
'fuchsia':              '#FF00FF',
'gainsboro':            '#DCDCDC',
'ghostwhite':           '#F8F8FF',
'gold':                 '#FFD700',
'goldenrod':            '#DAA520',
'gray':                 '#808080',
'green':                '#008000',
'greenyellow':          '#ADFF2F',
'honeydew':             '#F0FFF0',
'hotpink':              '#FF69B4',
'indianred':            '#CD5C5C',
'indigo':               '#4B0082',
'ivory':                '#FFFFF0',
'khaki':                '#F0E68C',
'lavender':             '#E6E6FA',
'lavenderblush':        '#FFF0F5',
'lawngreen':            '#7CFC00',
'lemonchiffon':         '#FFFACD',
'lightblue':            '#ADD8E6',
'lightcoral':           '#F08080',
'lightcyan':            '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgreen':           '#90EE90',
'lightgray':            '#D3D3D3',
'lightpink':            '#FFB6C1',
'lightsalmon':          '#FFA07A',
'lightseagreen':        '#20B2AA',
'lightskyblue':         '#87CEFA',
'lightslategray':       '#778899',
'lightsteelblue':       '#B0C4DE',
'lightyellow':          '#FFFFE0',
'lime':                 '#00FF00',
'limegreen':            '#32CD32',
'linen':                '#FAF0E6',
'magenta':              '#FF00FF',
'maroon':               '#800000',
'mediumaquamarine':     '#66CDAA',
'mediumblue':           '#0000CD',
'mediumorchid':         '#BA55D3',
'mediumpurple':         '#9370DB',
'mediumseagreen':       '#3CB371',
'mediumslateblue':      '#7B68EE',
'mediumspringgreen':    '#00FA9A',
'mediumturquoise':      '#48D1CC',
'mediumvioletred':      '#C71585',
'midnightblue':         '#191970',
'mintcream':            '#F5FFFA',
'mistyrose':            '#FFE4E1',
'moccasin':             '#FFE4B5',
'navajowhite':          '#FFDEAD',
'navy':                 '#000080',
'oldlace':              '#FDF5E6',
'olive':                '#808000',
'olivedrab':            '#6B8E23',
'orange':               '#FFA500',
'orangered':            '#FF4500',
'orchid':               '#DA70D6',
'palegoldenrod':        '#EEE8AA',
'palegreen':            '#98FB98',
'paleturquoise':        '#AFEEEE',
'palevioletred':        '#DB7093',
'papayawhip':           '#FFEFD5',
'peachpuff':            '#FFDAB9',
'peru':                 '#CD853F',
'pink':                 '#FFC0CB',
'plum':                 '#DDA0DD',
'powderblue':           '#B0E0E6',
'purple':               '#800080',
'red':                  '#FF0000',
'rosybrown':            '#BC8F8F',
'royalblue':            '#4169E1',
'saddlebrown':          '#8B4513',
'salmon':               '#FA8072',
'sandybrown':           '#FAA460',
'seagreen':             '#2E8B57',
'seashell':             '#FFF5EE',
'sienna':               '#A0522D',
'silver':               '#C0C0C0',
'skyblue':              '#87CEEB',
'slateblue':            '#6A5ACD',
'slategray':            '#708090',
'snow':                 '#FFFAFA',
'springgreen':          '#00FF7F',
'steelblue':            '#4682B4',
'tan':                  '#D2B48C',
'teal':                 '#008080',
'thistle':              '#D8BFD8',
'tomato':               '#FF6347',
'turquoise':            '#40E0D0',
'violet':               '#EE82EE',
'wheat':                '#F5DEB3',
'white':                '#FFFFFF',
'whitesmoke':           '#F5F5F5',
'yellow':               '#FFFF00',
'yellowgreen':          '#9ACD32'}

rawDescription: Named colors in matplotlib

description: Named colors in matplotlib


code:
from spyne.application import Application
from spyne.protocol.soap import Soap11
from spyne.util.wsgi_wrapper import WsgiMounter
from spyne.decorator import srpc
from spyne.service import ServiceBase
from spyne.model.primitive import Unicode
from spyne.util.appreg import get_application

class Service_Caller(ServiceBase):
  @srpc(_returns=Unicode)
  def call_service():
    # 'Application' is the default when you omit the `name` argument to the
    # `Application` initializer.
    app1 = get_application('example2', 'Application').null
    result = '\n'.join(app1.service.say_hello('world'))

    return result

class HelloWorldService(ServiceBase):
  @srpc(Unicode, _returns=Unicode)
  def say_hello(name):
      return [u'Hello, %s' % name]

if __name__ == '__main__':
  import logging
  logging.basicConfig(level=logging.DEBUG)
  app1 = Application([Service_Caller], 'example1',
        in_protocol=Soap11(), out_protocol=Soap11())
  app2 = Application([HelloWorldService], 'example2',
        in_protocol=Soap11(), out_protocol=Soap11())
  wsgi_app = WsgiMounter({"caller":app1, "hello":app2})

  from wsgiref.simple_server import make_server
  server = make_server('0.0.0.0', 8000, wsgi_app)
  server.serve_forever()

rawDescription: Timeout while trying to use one service to call another deployed in the same domain


code:
queue_state = channel.queue_declare(queue, durable=True, passive=True)
queue_empty = queue_state.method.message_count == 0

rawDescription: How to consume RabbitMQ messages via pika for some limited time?

description: Consume RabbitMQ messages via pika for some limited time


code:
@timeout(60)
def f():
    ...

rawDescription: Timeout a python function in windows

description: Timeout a python function in windows


code:
def get_node(a, b):
    if (a, b) not in existing_nodes:
        existing_nodes[a, b] = Node(a, b)
    return existing_nodes[a, b]

rawDescription: Dictionary of Objects to access by Reference


code:
def firstTwoWords(strings):
    return [s.split()[:2] for s in strings]

rawDescription: Eliminating redundant function calls in comprehensions from within the comprehension


code:
i,j,x=len(seq),0,[]

for k in range(m):

    a, j = j, j + (i+k)//m

    x.append(seq[a:j])

return x

rawDescription: How to split one list in a list of x list with python?

description: Split one list in a list of x list with python


code: df["TIME_DIFF"] = gs.diff().fillna(0) / pd.datetools.timedelta(hours=1)

rawDescription: How to calculate difference on previous within set of grouped rows in a dataframe

description: Calculate difference on previous within set of grouped rows in a dataframe


code: my_tuple = (1)    # my_tuple is still the integer 1, not a one-element tuple

rawDescription: Python string formatting

description: Python string formatting


code: or_(or_(or_(qs_list[0], qs_list[1]), qs_list[2]), qs_list[3])

rawDescription: Pythonic List Iteration

description: Pythonic List Iteration


code: reader = DictReader(file, delimiter='\t')

rawDescription: How to seperate rows based on the value of the first column from a csv file in Python

description: Seperate rows based on the value of the first column from a csv file in Python


code:
a=[];S="";p=""
s
for c in s:
    if c != p: a.append(S);S=""
    S=S+c
    p=c
a.append(S)
a
filter(None,a)

rawDescription: How to split this string with python?

description: Split this string with python


code:
def score(f1, f2, f3):
  if ( f1 == f2):
    return f3
  else:
    return None

rawDescription: field calculator based on attribute values

description: Field calculator based on attribute values


code: line.split(' ', 2)

rawDescription: Python/Regex splitting a specifically formatted return string


code: QtCore.QDate.currentDate = lambda: QtCore.QDate(2012, 1, 1)

rawDescription: Change local date in PyQt application

description: Change local date in PyQt application


code:
from pandas import DataFrame
df = DataFrame(np.random.randn(3,3), columns=['a','b','c'])
df
df.max()

rawDescription: Python Pandas drop columns based on max value of column


code:
nested_list = [['a', 'b'], ['c', 'd'], ['e', 'f']]
another_list = [['name0', 'aaa'], ['name1', 'aab'], ['name2', 'abd'], ['name3', 'abb']]

result = [tuple(sum(1 for c in s if c in lst)
                for lst in nested_list)
          for _, s in another_list]

rawDescription: Counting occurrences in nested lists

description: Counting occurrences in nested lists


code:
with open("products.txt", "r") as f:
    test=[i for line in f for i in line.split(',')]

rawDescription: Read txt file into list Python

description: Read txt file into list Python


code:
from collections import defaultdict
d=dict(zip(range(1,10),range(50,61)))
newdict = defauldict(int,d)

rawDescription: How to construct a defaultdict from a dictionary?

description: Construct a defaultdict from a dictionary


code:
df = pd.DataFrame(np.random.randn(24))
df
import itertools as it
series_id = it.cycle(list('abcdefghijkl'))  # first 12 letters.
idx = pd.MultiIndex.from_tuples(zip(series_id, df.index.repeat(12)[:len(df)]))

rawDescription: pandas: convert a CSV series into a data frame

description: Pandas: convert a CSV series into a data frame


code:
x = 'cat'
1 if x == 'dog' else 2 if x == 'cat' else 0 if x.isspace() else None

rawDescription: possible to set variable with multiple if statments?

description: Possible to set variable with multiple if statments


code:
random.sample([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
random.sample('even strings work', 4)

rawDescription: python random sequence from list

description: Python random sequence from list


code:
from scipy.sparse import coo_matrix
m = coo_matrix(np.array([[0,0,1],[1,0,0],[1,0,0]]))
a = np.ones(m.shape)

rawDescription: stacking sparse and dense matrices

description: Stacking sparse and dense matrices


code:
def get_file_str(filename):
    ID3_tag = ['Title','Artist','Album','Track']
    out = ['','','','']
    with open(filename) as f:
        for line in f:
            try:
                (tag, value) = line.split(':')
                tag = tag.strip('[ ]\n')
                value = value.strip('[ ]\n')
                i = ID3_tag.index(tag)
                out[i] = value
            except Exception as e:
                print('Invalid data:', e)
                return -1
    return out

print(get_file_str('thisboy.song'))

rawDescription: Reading ID3 tag and values from a text file


code:
import pandas as pd
import os

source_directory = r'H:\folder'

master_list = []

for file in os.listdir(source_directory):
    if file.endswith(".xlsx") or file.endswith(".xls"):
        dataframe = pd.read_excel(source_directory + '\\' + file)
        print(dataframe)
        master_list.append(dataframe)

masterDF = pd.concat(master_list, ignore_index=True)
print(masterDF)

rawDescription: Error with dataframe append

description: Error with dataframe append


code:
def lambdas_equivalencies(restfreq_hz):
    eq = [
    (lambdas, un.s, lambda x: x/restfreq_hz, lambda x: x*restfreq_hz),
    (lambdas, un.m, lambda x: x/restfreq_hz * co.c.to(un.m/un.s).value, lambda x: x/co.c.to(un.m/un.s).value * restfreq_hz),
    (un.m, un.s, lambda x: x/co.c.to(un.m/un.s).value, lambda x: x*co.c.to(un.m/un.s).value),
    ]
    return eq

rawDescription: Astropy Units equivalencies - interferometry baselines


code:
class Node:
    def __init__(self, value, node=None):
        self._value = value
        self._next = node
    def __str__(self):
        return "Node({}, {})".format(self._value, self._next)

rawDescription: Insertion Sort with a Linked List

description: Insertion Sort with a Linked List


code:
from collections import OrderedDict
od = OrderedDict(sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True))
od

rawDescription: Python: sorting dictionary of dictionaries


code: dateList = [(d, d.weekday()) for x in range(0,delta) for d in [base + timedelta(days=x)]]

rawDescription: List of (date, day_of_week) tuples

description: List of (date, day_of_week) tuples


code: open('statusfile.txt', 'w').write('%d\n' % r)

rawDescription: Python Scripts for mac, how to run a program and get value back


rawDescription: Python: Finding symmetries in list of lists


code:
engine = pyttsx.init()
voices = engine.getProperty('voices')
for voice in voices:
   engine.setProperty('voice', voice.id)  # changes the voice
   engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

rawDescription: Changing the voice with PYTTSX module in python


code:
pd.concat([a['x'], b['x']], axis=1).values.reshape(2,2,1)
np.allclose(pd.concat([a['x'], b['x']], axis=1).values.reshape(2,2,1), sol)

rawDescription: Colletting element from different DataFrames into arrays


code:
class Engine(object):
    def __init__(self, id):
        self.id = id

    def __hash__(self):
        return hash(self.id)

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.id == other.id
        return NotImplemented

rawDescription: are user defined classes mutable

description: Are user defined classes mutable


code:
import numpy as np
ca = np.array([100,33])
na = ca // 10
na
result_array = np.array([np.arange(1, x+1) for x in na])
result_array

rawDescription: Arrays generation from different arrays and arrays/numpy modules?


code: df["close"]

rawDescription: Most efficient way to loop through multiple csv files and calculate NYSE tick


code:
import random

sentence = 'Can I have some roti and aloo gobhi?'
new_sentence = sentence

replacements = {
'roti': ['pulka', 'butter kp', 'wheat parota', 'chapati', 'gobi parota', 'onion parota', 'paneer parota', 'kerala parota', 'aloo parota', 'plain naan', 'butter naan', 'garlic naan', 'plain kulcha', 'butter kulcha', 'lacha parota', 'tandoori roti', 'tandoori butter roti', 'roti'],
'aloo gobhi': ['paneer butter masala', 'palak paneer', 'kadai paneer', 'hydrabadi paneer', 'kadai gobi', 'aloo gobi', 'aloo mattar', 'mix veg curry', 'baby corn masala', 'dal fry', 'palak dal', 'dal tadka', 'mushroom masala', 'gobi masala', 'paneer tikka masala', 'mushroom tikka masala', 'aloo gobhi']
}

for key in replacements:
    new_sentence = new_sentence.replace(key, random.choice(replacements[key]))

rawDescription: Python multiple string replacement

description: Python multiple string replacement


code:
import urllib2
req = urllib2.Request(url='http://example.com/yourpath/yourscript.extension',
                  data='xml request body',
                  headers={'Content-Type': 'application/xml'})
response = urllib2.urlopen(req)
xml = response.read()

rawDescription: Using Python, POST A Block Of XML To A Web Server


code:
def h(x):
  return x + 5
h(123)

rawDescription: How to sort a Python dict by value

description: Sort a Python dict by value


code:
operator.setslice(a, b, c, v)
operator.__setslice__(a, b, c, v)

rawDescription: Check for [] operator

description: Check for [] operator


rawDescription: Strings not joining in Python

description: Strings not joining in Python


rawDescription: Parse mathematical expressions with pyparsing


code:
a = '\\xe9\\x82\\xa3'
a.encode().decode('unicode-escape').encode('latin1')

rawDescription: Turn a bytes-like string into actual bytes in Python


rawDescription: Compounded multiplier and divider in Python


code: data = randint(10,size=2000)

rawDescription: Quickest way to move numbers from one list to another


code: result = [[v + (i==j) for j, v in enumerate(test)] for i in range(len(test))]

rawDescription: Pythonic way to generate a list of possible arrays


code: x = arr7(i*0.1 for i in xrange(7))

rawDescription: How do I wrap this C function, with multiple arguments, with ctypes?

description: Wrap this C function, with multiple arguments, with ctypes


rawDescription: python what happens when a function is called?

description: Python what happens when a function is called


code:
plt.scatter(*zip(*testList2))
plt.title('Random Figure')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.show()

rawDescription: Python: plot list of tuples

description: Python: plot list of tuples


code: event.type == pygame.QUIT

rawDescription: When i make a pygame game and hover over it, the cursor turns into the loading thing


code:
for s in self.edits:
    s.deleteLater()

rawDescription: Dynamically deleting QLineEdit in PyQT4

description: Dynamically deleting QLineEdit in PyQT4


code:
kx = np.arange(10)
kx
kx.shape
wx = np.arange(10).reshape(1, 10)
wx
wx.shape

rawDescription: Python matrix represented as (40000,)

description: Python matrix represented as (40000,)


code: {u'url': u'https://vine.co/tags/funny', u'@context': u'http://schema.org', u'itemListElement': [{u'url': u'https://vine.co/v/iLKgAXeqwqu', u'position': 1, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLK6p2UHDTl', u'position': 2, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKrbIeXPTH', u'position': 3, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKrbZ5zir0', u'position': 4, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKvxUwLUxr', u'position': 5, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKvnVOd7VA', u'position': 6, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKv73UQmjB', u'position': 7, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKvBeO9Fmt', u'position': 8, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKnrqMDYeD', u'position': 9, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKnWrjMqwE', u'position': 10, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLK17Bg1wt0', u'position': 11, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLK5ExAZ7WB', u'position': 12, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLK5Eg7vHM7', u'position': 13, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKitbix3pb', u'position': 14, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKOleYJhUp', u'position': 15, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKOTFgXVFQ', u'position': 16, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKMI6t91xe', u'position': 17, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKMX6p0TD6', u'position': 18, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKM6Hh1nzr', u'position': 19, u'@type': u'ListItem'}, {u'url': u'https://vine.co/v/iLKhQWVIAj3', u'position': 20, u'@type': u'ListItem'}], u'@type': u'ItemList'}

rawDescription: Parsing html for specific script type

description: Parsing html for specific script type


code:
from collections import defaultdict

merged = defaultdict(int)

merged.update(list1)

for key, value in list2:
    merged[key] += value

rawDescription: What is the Pythonic way to merge 2 lists of tuples and add the nonunique values in the tuples?


rawDescription: Limiting queryset for foreign key for inline formset in Django


rawDescription: Two Lists Into One Dictionary Python

description: Two Lists Into One Dictionary Python


code: data.loc[0, 'transaction_amount']

rawDescription: Importing financial data into Python Pandas using read_csv


code:
def do_stuf():
    pass

do_stuf = fun1(do_stuf)

rawDescription: How can I pack several decorators into one?

description: Pack several decorators into one


code:
def func1():
        return None

def func2():
        pass

def func3():
        return

rawDescription: Differentiate between no returned value and return None


rawDescription: Use Beautiful Soup findall to extract text between single quotations


code:
import pandas as pd

df = pd.DataFrame(pd.np.random.rand(10,3), columns=list('abc'))
# get a list of Series from the column names
series_list = [df[col] for col in df]
print(series_list)

rawDescription: List of Series from a DataFrame in Pandas


code: parsed['result'][80]['High'] # 5e-08

rawDescription: Decoding JSON and printing some specific part?


code: results = pool.map(Parallel(args), self.list_objects)

rawDescription: Parallel processing loop using multiprocessing Pool


code: sorted(yourdict.items(), key=lambda item: int(item[0].split()[0]))

rawDescription: Sort Python Dictionary by first four characters in Key


code:
hb = HtmlBuilder()
while True:
    menu = input("\nPress 1 to enter the file name for the HTML-page"
                 "\nPress 2 to enter title for the HTML-page"
                 "\nPress 3 to start entering code in body"
                 "\nPress 4 to exit\n")
    if menu == "1":
        hb.createHtml()
    elif menu == "2":
        hb.createTitle()
    elif menu == "3":
        hb.createBody()
    else:
        print ("Good bye!")
        break

hb.Dispose()

rawDescription: global name 'doc' is not defined, trouble withvcall from one function to annother

description: Global name 'doc' is not defined, trouble withvcall from one function to annother


code:
def preprocess(data):
    from collections import defaultdict # Python 2.5+ only
    preprocessed = defaultdict(list)
    # group by id
    for (id, age), value in data.iteritems():
        preprocessed[id].append((float(age), value))
    # sort lists for binary search, see edit
    for key, value in preprocessed.iteritems():
        value.sort()
    return preprocessed

rawDescription: fetching values from dictionary. Range match on keys

description: Fetching values from dictionary. Range match on keys


rawDescription: how to create a list sequence in python containing all possible pairs an equal number of times?

description: Create a list sequence in python containing all possible pairs an equal number of times


code:
def vigenere(plaintext, keyword):
    keystream = cycle(keyword)
    return ''.join(add_chars(pln, key)
                    for pln, key in zip(plaintext, keystream))

rawDescription: vigenere cipher - not adding correct values

description: Vigenere cipher - not adding correct values


code: [{value: index} for value, index in enumerate(a)]

rawDescription: Finding Index in string with recurring chars


code: cuts('XCXX', 1)

rawDescription: Python set combinations of adjacent letters


code:
instring = 'ABCD'
instring.translate(str.maketrans('ACac','gtgt'))

rawDescription: Wanting to Change specific Characters from TextFile into Other Characters. Not trying to Write, only wanting to print out into the console


code:
for item in b:
    a.append(item) # Order does not matter, we will sort it later
# a is currently [1, 3, 5, 2, 4] since append() adds to the end of the list
a.sort()
# a is now [1, 2, 3, 4, 5] as sort() re-ordered it

rawDescription: Is it possible to insert specific sections of one list into a specific location in another list?


code:
import pandas as pd
import numpy as np
df= pd.DataFrame(['Apple Pear',np.nan,'Orange Banana'], columns = ['fruits'])
df['first_fruit'] = df.fruits[~df.fruits.isnull()].apply(lambda x: x.split()[0])
# or: df['first_fruit'] = df.fruits[df.fruits.notnull()].apply(lambda x: x.split()[0])

rawDescription: How to create a new derived column in a pandas dataframe new column using only notnull vaues

description: Create a new derived column in a pandas dataframe new column using only notnull vaues


code:
img = win32gui.LoadImage(None, "C:\\tmp.bmp", win32con.IMAGE_BITMAP, 0, 0, flags)
pyiconinfo = (True, 0, 0, img, img)
hicon = win32gui.CreateIconIndirect(pyiconinfo)

rawDescription: Shell_NotifyIcon from RGB data

description: Shell_NotifyIcon from RGB data


code:
#!/usr/bin/env python

import cv2

def draw_circles(img, circles):
    # img = cv2.imread(img,0)
    cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
    for i in circles[0,:]:
    # draw the outer circle
        cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
        # draw the center of the circle
        cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
        cv2.putText(cimg,str(i[0])+str(',')+str(i[1]), (i[0],i[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.4, 255)
    return cimg

def detect_circles(image_path):
    gray = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
    gray_blur = cv2.medianBlur(gray, 13)  # Remove noise before laplacian
    gray_lap = cv2.Laplacian(gray_blur, cv2.CV_8UC1, ksize=5)
    dilate_lap = cv2.dilate(gray_lap, (3, 3))  # Fill in gaps from blurring. This helps to detect circles with broken edges.
    # Furture remove noise introduced by laplacian. This removes false pos in space between the two groups of circles.
    lap_blur = cv2.bilateralFilter(dilate_lap, 5, 9, 9)
    # Fix the resolution to 16. This helps it find more circles. Also, set distance between circles to 55 by measuring dist in image.
    # Minimum radius and max radius are also set by examining the image.
    circles = cv2.HoughCircles(lap_blur, cv2.cv.CV_HOUGH_GRADIENT, 16, 55, param2=450, minRadius=20, maxRadius=40)
    cimg = draw_circles(gray, circles)
    print("{} circles detected.".format(circles[0].shape[0]))
    # There are some false positives left in the regions containing the numbers.
    # They can be filtered out based on their y-coordinates if your images are aligned to a canonical axis.
    # I'll leave that to you.
    return cimg

rawDescription: Find all circles in image

description: Find all circles in image


rawDescription: How to get a list of tags and create new tags with python and dulwich in git?

description: Get a list of tags and create new tags with python and dulwich in git


rawDescription: How can I vectorize the averaging of 2x2 sub-arrays of numpy array?

description: Vectorize the averaging of 2x2 sub-arrays of numpy array


rawDescription: passing arrays with ctypes

description: Passing arrays with ctypes


rawDescription: How merge prev/next lists in python?

description: How merge prev/next lists in python


code:
import sys
sys.executable
sys.version

rawDescription: which python is running?

description: Which python is running


code: CELERY_RESULT_BACKEND = 'amqp'

rawDescription: Django Celery Periodic Tasks Run But RabbitMQ Queues Aren't Consumed


rawDescription: python binding of variable to particular expression

description: Python binding of variable to particular expression


code:
for user in tree.xpath('//coureurs/coureur'):
    for child in user:
        print(child.text,end=" ")
    print()

rawDescription: Parse childs in XML python

description: Parse childs in XML python


code:
p = re.compile(r'\bYEAR=([^;]+)')
test_str = "1  0001    1   UG  science,ee;YEAR=onefour;standard->2;district->9"
robj = re.search(p, test_str)
if robj:
    print(robj.group(1))

rawDescription: Extract substring from a line in python, if another keyword is found


code: Counter((raw_input().split()[0]) for _ in range(int(raw_input())))

rawDescription: Python taking paired string and integer input


code:
def generateSecondary(outerObject):
    class Secondary(object):
        def __init__(self):
            outerObject.proceed()
    return Secondary

rawDescription: How can I acess a metod from an object inside a class in python 2.6?

description: Acess a metod from an object inside a class in python 2.6


code:
from sqlalchemy import create_engine
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
df.to_sql('table_name', engine)

rawDescription: How to write DataFrame to postgres table?

description: Write DataFrame to postgres table


code: '{{gettext("message")}}'

rawDescription: serving i18n js using babel, django, & jinja2

description: Serving i18n js using babel, django, & jinja2


code:
def f(df):
    #print (sorted(df['address'].unique()))
    dfs = []
    for x in [list(x) for x in itertools.combinations(sorted(df['address'].unique()), 2)]:
        c1 = df.loc[df['address'].isin([x[0]]), 'ID']
        ...
        ...

rawDescription: Sort strings in column and print graph

description: Sort strings in column and print graph


rawDescription: Summation of TFIDF sparse vector values for each document in Spark with Python


code:
interp = sp.interpolate.interp2d(x, y, image)
vinterp = np.vectorize(interp)

for r in (15, 30, 45):    # radii for circles around image's center
    xcenter = len(x)/2
    ycenter = len(y)/2
    arclen = 2*np.pi*r
    angle = np.linspace(0, 2*np.pi, arclen*2, endpoint=False)
    value = vinterp(xcenter + r*np.sin(angle),
                    ycenter + r*np.cos(angle))
    plt.plot(angle, value, label='r={}'.format(r))

plt.legend()
plt.show()

rawDescription: Take data from a circle in python

description: Take data from a circle in python


rawDescription: Create constants for offsets into a list


code:
from __future__ import print_function

import pprint

from itertools import groupby
from operator import itemgetter

def group_by_keys(iterable, keys):
    key_func = itemgetter(*keys)

    # For groupby() to do what we want, the iterable needs to be sorted
    # by the same key function that we're grouping by.
    sorted_iterable = sorted(iterable, key=key_func)

    return [list(group) for key, group in groupby(sorted_iterable, key_func)]

dicts = [
    {'name': 'b', 'type': 'new', 'color': 'blue', 'amount': 100},
    {'name': 'c', 'type': 'new', 'color': 'red', 'amount': 100},
    {'name': 'd', 'type': 'old', 'color': 'gold', 'amount': 100},
    {'name': 'e', 'type': 'old', 'color': 'red', 'amount': 100},
    {'name': 'f', 'type': 'old', 'color': 'red', 'amount': 100},
    {'name': 'g', 'type': 'normal', 'color': 'red', 'amount': 100}
    ]

rawDescription: How to group an array by multiple keys?

description: Group an array by multiple keys


code:
class MyToken(UserToken):
    user = ndb.StringProperty(required=True)

class MyUser(User):
    token_model = MyToken
    # etc.

rawDescription: GAE webapp2 delete all UserTokens (drop all sessios) for specific user


code:
log_names = {
    "/var/log/apache2/error.log" : 'C:\\remote\\NewFile.log',
    "/var/log/apache/a.log" : 'C:\\remote\\NewFile_a.log',
} # add here all the log files you want to retrieve
for log_file, local_name in log_names.iteritems():
    sftp.get(log_file, local_name)

rawDescription: I want to retrieve multiple logs from a server with minimum lines of code


code:
import re

for pattern, replacement in zip(array[1:], rep_array[1:]):
    pattern = r'{}\b'.format(re.escape(pattern))
    string = re.sub(pattern, replacement, string)

rawDescription: Python replace, using patterns in array

description: Python replace, using patterns in array


code:
pair_of_letters = re.compile(r'(.).*(.).*\1.*\2.*')
repeated_letter_with_one_between = re.compile(r'(.).\1')

rawDescription: Python Regexes differ in Pythex vs. console


code:
#myproject/core/myresources.py
from import_export import resources
from core.models import Book

class BookResource(resources.ModelResource):

    class Meta:
        model = Book

rawDescription: Django Import Export: Documentation cannot be understood


code:
x = """<records>
<record something="this" name="ABC"/>
<record something="this" name="DEF"/>
<record name="ABC"  something="this"/>
<record name="ABC"  something="this"/>
<record name="GHI"  something="this"/>
<record noname="ijk"  something="this"/>
<record noname="lmn"  something="this"/>
<record noname="xyz"  something="this"/>
</records>"""

from lxml.etree import  fromstring
tree = fromstring(x)

print(sorted({n.get("name") for n in tree.findall(".//record[@name]")}))

rawDescription: Python: Find Unique XML Attributes

description: Python: Find Unique XML Attributes


code:
# open the file so you can read from it
with open("myfile.txt") as inf:
    # for each line in the file,
    # split it on commas (results in a list of strings)
    # then convert each string to a float (results in a list of floats)
    items = (map(float, line.split(",")) for line in inf)
    # transpose (convert columns to rows),
    # then assign each row to a variable)
    xs, ys = zip(*items)

rawDescription: Print float (x,y) data in a graph with Python


rawDescription: Dynamic Programming: Mission Per Day, Scheduling for Maximum Profit


code:
Hindi
English

rawDescription: accessing values in subgroups in html code

description: Accessing values in subgroups in html code


code:
import base64
s = 'cw==ZA==YQ==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==dA==ZQ==cw==dA=='
''.join(base64.b64decode(s[i:i+4]) for i in range(0, len(s), 4))

rawDescription: Python: Decode base64 multiple strings in a file


rawDescription: Convert Levenshtein ratio to C++

description: Convert Levenshtein ratio to C++


rawDescription: counting the amount of True/False values in a pandas row

description: Counting the amount of True/False values in a pandas row


code: #define SET_TOP(v)        (stack_pointer[-1] = (v))

rawDescription: Is it possible to access enclosing context manager?


code:
import csv
from itertools import zip_longest

d = [[2,3,4,8],[5,6]]

with open("file.csv","w+") as f:
    writer = csv.writer(f)
    for values in zip_longest(*d):
        writer.writerow(values)

rawDescription: Write lists of different size to csv in columns in Python


code:
class runMeCommand(sublime_plugin.WindowCommand):
    def run(self, **kwargs):
        try:
            if "$file_name" in kwargs["cmd"]:
                cur_view = self.window.active_view()
                cmd_string=kwargs["cmd"].replace("$file_name",cur_view.file_name())
                os.system("start "+cmd_string)
            else:
                os.system("start "+cmd_string)
        except TypeError:
            sublime.message_dialog("Something went wrong with the command given... \n\n\n"+traceback.format_exc())

rawDescription: In Sublime Text 2 how can I pass the current file path to a command called by a key binding


code:
def trackable_type(name, obj, base):
    def func_logger(func):
        def wrapped(self, *args, **kwargs):
            before = base(self)
            result = func(self, *args, **kwargs)
            after = base(self)
            if before != after:
                obj.revisions[name].append(after)
            return result
        return wrapped

    methods = (type(list.append), type(list.__setitem__))
    skip = set(['__iter__', '__len__', '__getattribute__'])
    class TrackableMeta(type):
        def __new__(cls, name, bases, dct):
            for attr in dir(base):
                if attr not in skip:
                    func = getattr(base, attr)
                    if isinstance(func, methods):
                        dct[attr] = func_logger(func)
            return type.__new__(cls, name, bases, dct)

    class TrackableObject(base):
        __metaclass__ = TrackableMeta

    return TrackableObject()

rawDescription: Track changes to lists and dictionaries in python?


rawDescription: Python Thread that runs at the start of every minute


code:
from io import StringIO
import csv
demofile = StringIO('''\
lamp, 000000, False
tv, 000000, False
bedside, 000000, False
pc, 000000, False
bed tv, 000000, False
''')
irTable = {}
for label, freq, state in csv.reader(demofile, skipinitialspace=True):
    irTable[label] = int(freq), state

irTable

rawDescription: Python reading \n on the end of a line

description: Python reading \n on the end of a line


code:
def countLeaves(root):
    if root.get_left() is None and root.get_right() is None: return 1
    return (0 if root.get_left() is None else countLeaves(root.get_left())) + (0 if root.get_right() is None else countLeaves(root.get_right()))

rawDescription: Recursion counting leaves in binary trees


code:
su - postgres

createuser -P

createdb --owner [user_you_just_created] [db_name]

rawDescription: The default location of where Postgresql gets installed?


code: df.fillna('', downcast='infer').dtypes

rawDescription: Pandas Pivot table converts float to int


code:
from werkzeug import BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthorizationMixin

class Request(BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthorizationMixin):
    pass

rawDescription: What is a mixin, and why are they useful?


code:
import string
alphabet = set(string.ascii_lowercase)
input_string = 'We promptly judged antique ivory buckles for the next prize'
set(input_string.lower()) >= alphabet
set(input_string[:15].lower()) >= alphabet

rawDescription: How do I check if a string contains ALL letters of the alphabet in python?

description: Check if a string contains ALL letters of the alphabet in python


code:
Namespace(cmd='subcommand_a', opt1='foo', opt2=['1', '2', '3'], req1='FOO')
['subcommand_b', 'BAR', '--opt3', 'a', 'b', 'c']
Namespace(cmd='subcommand_b', opt1=None, opt2=None, opt3=['a', 'b', 'c'], req1='BAR')
[]

rawDescription: Python argparse, run one or more sub-commands


code:
o = object()
o.x = 1

rawDescription: How can I create a separate namespace within a Python script?

description: Create a separate namespace within a Python script


rawDescription: Adding legend to pandas.dataframe.plot when y option is used


rawDescription: Clearing a QWebView widget PyQt

description: Clearing a QWebView widget PyQt


code:
class SupplyTypeForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SupplyTypeForm, self).__init__(*args, **kwargs)
        self.fields['sevice_type'].initial = User.DUAL_SUPPLIER

rawDescription: django model form initial value on choicefield

description: Django model form initial value on choicefield


code: s.index = pd.DatetimeIndex(s.index)

rawDescription: Extend index on business day range

description: Extend index on business day range


code: write(a, indent=1)

rawDescription: Print tree with indentations

description: Print tree with indentations


rawDescription: Is there a JavaScript equivalent to Python's for loops?


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

class ButtonTest:
    def __init__(self):
        ax = plt.axes([0.81, 0.05, 0.1, 0.075])
        self.bnext = Button(ax, 'Next')
        self.bnext.on_clicked(self._next)

    def show(self):
        plt.show()

    def _next(self, event):
        print("next !")

ButtonTest().show()

rawDescription: matplotlib, plt.show() in a different method = no on_clicked

description: Matplotlib, plt.show() in a different method = no on_clicked


code:
from scrapy.dupefilters import RFPDupeFilter

class DBDupeFilter(RFPDupeFilter):

    def __init__(self, *args, **kwargs):
        # self.cursor = .....                       # instantiate your cursor
        super(DBDupeFilter, self).__init__(*args, **kwargs)

    def request_seen(self, request):
        if self.cursor.execute("myquery"):          # if exists
            return True
        else:
            return super(DBDupeFilter, self).request_seen(request)

    def close(self, reason):
        self.cursor.close()                         # close  your cursor
        super(DBDupeFilter, self).close(reason)

rawDescription: How to access pipeline database pool in scrapy spider

description: Access pipeline database pool in scrapy spider


code: flags = re.DOTALL | re.VERBOSE

rawDescription: Python Regex matching choice between "\*" (literal Asterisk char) OR "\s" (Space)


code: ls = filter(lambda item: all(tuple[1] != m for tuple in item),ls)

rawDescription: Delete item from list upon a condition

description: Delete item from list upon a condition


code:
r = map(exp.findall, abc)
filter(None, sum(sum(r, []), ()))

rawDescription: Is there a way for checking a certain pattern in a list?


code:
from itertools import chain
set(chain(*map(itemgetter("food"), orders.values())))

rawDescription: Obtaining list (or set) of unique values in nested dictionary


code:
list1 = []
while True:
    race_time = input("Enter a race time: ")
    if race_time == "no more races":
        break
    list1.append(float(race_time))
print(min(list1))

rawDescription: Python homework - take list of times and print the fastest time


code:
class MethodArgAjaxModelLoader(sqla.ajax.QueryAjaxModelLoader):
    def get_list(self, term, offset=0, limit=10):
        query = self.session.query(self.model).filter_by(mid=term)
        return query.offset(offset).limit(limit).all()

class RecipeArgAdmin(sqla.ModelView):
    column_list = ('recipe', 'methodarg', 'strvalue')
    form_ajax_refs = {
        'methodarg': MethodArgAjaxModelLoader('methodarg', db.session, MethodArg, fields=['methodarg'])
    }
    column_editable_list = column_list

rawDescription: flask-admin form: Constrain Value of Field 2 depending on Value of Field 1

description: Flask-admin form: Constrain Value of Field 2 depending on Value of Field 1


code:
import csv

def Cid2xy(csv_file, cid):
    reader = csv.reader(csv_file)
    while True:
        try:
            line = reader.next()
            if line[0] == cid:
                return line[4:6]
        except StopIteration:
            return None

rawDescription: Using CSV file in python to print column


code:
for chunk in chunks(f):
    process(chunk)

rawDescription: Process large data in python

description: Process large data in python


rawDescription: Using numpy.bincount with array weights

description: Using numpy.bincount with array weights


rawDescription: Pandas Groupby : group **by** a column containing tuples


code:
from itertools import count
c = count(0.0, 0.0001)
c.next()
c.next()
c.next()

rawDescription: Rounding values for normalised variables


code:
import random

class WordDict(dict):
    def __getitem__(self, key):
        vals = dict.__getitem__(self, key)
        return random.choice(vals)

words = WordDict(
    cold = ["cold", "frigid", "freezing"],
    hot = ["scathing", "burning", "hot"]
)

for x in xrange(10):
    print('the water is {word[cold]}'.format(word=words))

rawDescription: Python string format using dict of arrays


code:
numbers = input("Enter your numbers followed by commas: ")
sum(map(int,numbers.split(',')))

rawDescription: Sum function prob TypeError: unsupported operand type(s) for +: 'int' and 'str'


rawDescription: Django asymettrical self through relationship query


code: os.system("matlab.exe -nosplash -nodesktop -wait -r \"addpath('c:\\some\\folder'); someFunction(); quit();\"")

rawDescription: calling several matlab commands from python using os.system

description: Calling several matlab commands from python using os.system


code: find_value = driver.find_element_by_xpath('//span[@class = "minimal-list__title" and . = "ETF Home Page:"]/following-sibling::span/a').get_attribute("href")

rawDescription: XPath locate child following sibling

description: XPath locate child following sibling