code: C = [word for word in A if not blacklist.search(word)]

rawDescription: Delete item from list if it contains a substring from a "blacklist"


rawDescription: How to read line in python using defaultdict?

description: Read line in python using defaultdict


code:
import datetime
dt = datetime.datetime.now()
dayslater = 5
hourslater = 7
minuteslater = 30
delta = datetime.timedelta(days=dayslater, hours=hourslater, minutes=minuteslater)
delta
dt
dt + delta

rawDescription: What is the best way to handle datetime value overflow


code:
oldFile = 'C:\\folder\\subfolder\\inFile.txt'
newFile = 'C:\\foo\\bar\\somewhere\\other\\outFile.txt'

os.rename(oldFile, newFile)

rawDescription: Rename files using python

description: Rename files using python


code:
class BlogPostView(ListView):
    template_name = 'blog.html'

    def get(self, request, *args, **kwargs):
        slug = kwargs.get('slug')
        slug_id = ... # code here to determine id of slug's category
        self.queryset = Post.objects.filter(category=slug_id)[:5]
        return super(BlogPostView, self).get(request, *args, **kwargs)

rawDescription: Slug and generic views

description: Slug and generic views


code:
def mixins(*args):
    bases = args if object in args else args + (object,)
    return type('Foo', bases, {})

rawDescription: Factory function to create a class with an unknown number of mixins


rawDescription: Merging hierarchy of dictionaries in Python


code:
try:
    item = stats[field]
except KeyError:
    item = stats[field] = very_expensive_initializer(field)

rawDescription: How do I initialize values in a dictionary?

description: Initialize values in a dictionary


code:
data_0 = data[data['result'] == 0]
data_1 = data[data['result'] == 1]

rawDescription: python pandas : split a data frame based on a column value

description: Python pandas : split a data frame based on a column value


rawDescription: Dynamic order in django-mptt

description: Dynamic order in django-mptt


code:
include_files =["icon-16px.ico",
                "icon-32px.ico",
                "logo-t-160x56.png",
                "cacert.pem",
                ]

setup(
    scripts = [
        Executable_Esky(
            "myapp.py",
            gui_only = False,
            icon = "icon-16px.ico",
        ),
    ],
    data_files = include_files,
    options={"build_exe":
                 {"packages":packages,
                  "includes": includes,
                  "include_files": include_files,
                  "excludes": excludes,
                  "optimize": 2,
                  "icon":"icon-16px.ico",
                 },
             "bdist_esky":{
                 'freezer_module':"cxfreeze",
                 'includes': includes,
                 'excludes': excludes,
             },
    },
    executables = [Executable(script="myapp.py",base="Win32GUI")],
)

rawDescription: Error using Requests in a frozen app

description: Error using Requests in a frozen app


code: s, r = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world")

rawDescription: Python: Pass execution statement as function parameter


rawDescription: Merging (logical OR) together the contents of two 'bitmaps' in strings


code:
from time import process_time

t = process_time()
#do some stuff
elapsed_time = process_time() - t

rawDescription: accurately measure time python function takes

description: Accurately measure time python function takes


rawDescription: Method count per class in PyDev

description: Method count per class in PyDev


code:
import dis
x=[34534534, 23423523, 77645645, 345346]
dis.dis(lambda: [e for e in x])
dis.dis(lambda: list(e for e in x))

rawDescription: Python's [<generator expression>] at least 3x faster than list(<generator expression>)?


code:
replay = True
while replay == True:
    replay = False

rawDescription: Trying to re-loop a game only if a user says to


code:
def setUp(self):
    path = 'projectname.common.credential.CredentialCache.mymethodname'
    self.patcher1 = patch(path)

rawDescription: how to handle long path name for pep8 compliance?

description: Handle long path name for pep8 compliance


code: print(archive + url)

rawDescription: Send data and get the response

description: Send data and get the response


code:
A[np.ix_(idx,idx+1)]  # or with
A[idx[:,None],idx+1]

rawDescription: Conversion of Matlab sparse to Python scipy csr_matrix


code:
'
some test
'.strip('')

rawDescription: Stripping chars in python

description: Stripping chars in python


code:
ref_regex = re.compile('''
(?<!\w)                      # Not preceeded by any words
((?i)q(?:uote)?\s+)?            # Match 'q' or 'quote' followed by many spaces
(
    (?:(?:[1-3]|I{1,3})\s*)?    # Match an arabic or roman number between 1 and 3.
    [A-Za-z]+                   # Match many alphabetics
)\.?                            # Followed by an optional dot
(?:
    \s*(\d+)                    # Match the chapter number
    (?:
        [:.](\d+)               # Match the verse number
        (?:-(\d+))?             # Match the ending verse number
    )                    # <-- no '?' here
)
(?:
    \s+
    (?:
        (?i)(?:from\s+)|        # Match the keyword 'from' or 'in'
        (?:in\s+)|
        (?P<lbrace>\()      # or stuff between (...)
    )\s*(\w+)
    (?(lbrace)\))
)?
''', re.X | re.U)

rawDescription: Overlapping matches with finditer() in Python


code:
import ujson
import pandas as pd
from pandas.io.json import json_normalize

pd.set_option('display.expand_frame_repr', False)

with open('aaa') as f:
    data = ujson.load(f)

df = json_normalize(data)[['id', 'name', 'address.region', 'address.street-address']].rename(columns={'address.region': 'region', 'address.street-address': 'street-address'})
print(df)

rawDescription: pandas slicing nested values along with other columns

description: Pandas slicing nested values along with other columns


rawDescription: most pythonic way to interate a finite but arbitrary number of time through list values

description: Most pythonic way to interate a finite but arbitrary number of time through list values


code: lambda a:(lambda f, a: f(f, a))(lambda f, a:len(a) if not isinstance(a,(tuple,list)) else sum(f(f,e) for e in a), a)

rawDescription: Lambda recursion over list in Python

description: Lambda recursion over list in Python


code: df['YYYY-MM'] = df['Due Date'].apply(lambda x: x.strftime("%Y-%m"))

rawDescription: Pivot DataFrame

description: Pivot DataFrame


code:
longitudes, latitudes = [], []
for row_index, row in df.iterrows():
    x, y = db.getLocation(row_index)
    lat, lon = m(y, x)
    longitudes.append(lon)
    latitudes.append(lat)
    plt.annotate(
        str(row_index),
        xy = (x, y), xytext = (-20, 20),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

df['lon'] = longitudes
df['lat'] = latitudes
cmap = plt.get_cmap('gist_rainbow_r')
ax = plt.gca()
df.plot(kind='scatter', x='lon', y='lat', s=df['Total']*50, c=df['Total'],
        cmap=cmap, ax=ax)

rawDescription: Draw different sized circles on a map

description: Draw different sized circles on a map


code: OPENSSLDIR: "/etc/pki/tls"

rawDescription: what is my openssl and ssl Default CA Certs Path?

description: What is my openssl and ssl Default CA Certs Path


code:
import numpy as np

def GetBitmap( self, width=640, height=480, leftColour=(255,128,0), rightColour=(64,0,255) ):
        ## Create a horizontal gradient
        array = np.zeros( (height, width, 3),'uint8')
        # alpha is a one dimensional array with a linear gradient from 0.0 to 1.0
        alpha = np.linspace( 0., 1., width )
        # This uses alpha to linearly interpolate between leftColour and rightColour
        colourGradient = np.outer(alpha, leftColour) + np.outer((1.-alpha), rightColour)
        # NumPy's broadcasting rules will assign colourGradient to every row of the destination array
        array[:,:,:] = colourGradient
        image = wx.EmptyImage(width,height)
        image.SetData( array.tostring())
        return image.ConvertToBitmap()# wx.BitmapFromImage(image)

rawDescription: How to do a dregradê on wx.Panel Background?

description: Do a dregradê on wx.Panel Background


code: listOfDf = [DF.copy().join(df.loc[i]) for i in df.index.get_level_values(1).unique()]

rawDescription: Pandas. Selection by label. One-row output


code:
i== 0
i== 1
i== 2
i== 3
i== 4
i== 5
i== 6
j== 0
"8 Or thinly veil the heav'ns' mysterious face;\n"
j== 1
'9 When in some river, overhung with green,\n'
j== 2
'10 The waving moon and trembling leaves are seen;\n'
i== 0
i== 1
i== 2
i== 3
i== 4
i== 5
i== 6
j== 0
'18 Shew trivial beauties watch their hour to shine;\n'
j== 1
"19 Whilst Salisb'ry stands the test of every light,\n"
j== 2
'20 In perfect charms, and perfect virtue bright:\n'
i== 0
i== 1
i== 2
i== 3
i== 4

rawDescription: Using python to process a chunk of a file every x lines


code:
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM thetable")
while True:
   row = cursor.fetchone()
   if row is None: break
   # here: do something with the row

rawDescription: Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python


code:
def compare_triples(a, b):
    return cmp((a[0], b[2], a[1]), (b[0], a[2], b[1]))

rawDescription: Sort string-matrix [[a, b, c], ...] by a, -c, b, maintaining order?


code:
reportPat=re.compile(
   r'(Clinical details|indication)(.*)'
   r'(result|description|report)(.*?)'
   r'(?:(Interpretation|conclusion)(.*))?$',
   re.IGNORECASE|re.DOTALL)

rawDescription: Python regex string groups capture

description: Python regex string groups capture


rawDescription: Change specific value in CSV file via Python


code: my_figure.y_range.end = 10

rawDescription: Python bokeh modify axis scale

description: Python bokeh modify axis scale


code: [(u'1062', None, u'bar', u'1 MILLION DOLLARS!', None, None)]

rawDescription: Sqlite thinks I lack bindings

description: Sqlite thinks I lack bindings


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

def get_color():
    for item in ['r', 'g', 'b', 'c', 'm', 'y', 'k']:
        yield item

x = 0.3 * np.array(range(40))

color = get_color()

for group in range(5):
    # generates a collection of points
    y = np.exp2(x + 0.5 * group)
    # fit to a polynomial
    z = np.polyfit(x, y, 6)
    p = np.poly1d(z)

    acolor = next(color)

    plt.scatter(x, y, color=acolor, marker='o')
    plt.plot(x, p(x), acolor + '-', label=str(group))

plt.legend()
plt.xlim((0, 15))
plt.show()

rawDescription: Color and Line writing using MatPlotLib

description: Color and Line writing using MatPlotLib


code:
print(df.groupby(['Year','Month','Day']).agg(
    {'AirTemperature': 'mean',
     'AirHumidity': 'mean',
     'SoilTemperature': 'max'
    }).reset_index())

rawDescription: Create multiple mean columns in csv

description: Create multiple mean columns in csv


code:
from unittest import TestCase, main as unittest_main

class TestSimpleFoo(TestCase):
    foo = 'bar'

    def setUp(self):
        pass

    def test_a(self):
        self.assertEqual(self.__class__.foo, 'bar')
        self.__class__.foo = 'can'

    def test_f(self):
        self.assertEqual(self.__class__.foo, 'can')

if __name__ == '__main__':
    unittest_main()

rawDescription: Persist variable changes between tests in unittest?


code:
class A:
    a = 42
    b = list(a + i for i in range(10))

rawDescription: Python scoping issue with dictionary comprehension inside class level code


code:
with open('test.csv','r') as in_file, open('final.csv','w') as out_file:

    lines = Counter(file.readlines())

    for itm in lines:
        out_file.write(itm)

rawDescription: Python extract unique values from CSV

description: Python extract unique values from CSV


code: win32ui.MessageBox("The website has changed.", "Website Change", MB_SYSTEMMODAL)

rawDescription: Have Win32 MessageBox appear over other programs


code:
import pandas

urls = ['https://www.google.com/something','https://mail.google.com/anohtersomething','https://www.amazon.com/yetanotherthing'] # tested with list of 186 urls instead
df['protocol'],df['domain'],df['path'],df['query'],df['fragment'] = zip(*df['url'].map(urlparse.urlsplit))

rawDescription: pythonic way to parse/split URLs in a pandas dataframe

description: Pythonic way to parse/split URLs in a pandas dataframe


code:
def where(s, l):
    if not l:
        return s+1
    return np.where(np.logical_and(tobebuckets > s, tobebuckets <= l[0]),
                    l[0], where(l[0], l[1:]))

buckets = np.where(tobebuckets <= 0, 0, where(0, [10, 50, 100, 500, 1000]))

rawDescription: how to make long line as pep8 compatible in python?

description: Make long line as pep8 compatible in python


code:
def start_requests(self):
    with codecs.open(self.file_path, u"r", encoding=u"GB18030") as f:
        for index, line in enumerate(f):
            try:
                url = line.strip()
                yield Request(url, meta={'priority': index})
            except:
                continue

rawDescription: the order of Scrapy Crawling URLs with long start_urls list and urls yiels from spider

description: The order of Scrapy Crawling URLs with long start_urls list and urls yiels from spider


code:
from operator import index

class natural_num_range(object):
    def __init__(self, maxnum=None):
        if maxnum is not None:
            maxnum = index(maxnum)  # Ensure a true native int (or long)
        self.maxnum = maxnum

    def __contains__(self, x):
        try:
             x = index(x)
        except TypeError:
             return False
        return x >= 1 and (self.maxnum is None or x < self.maxnum)

rawDescription: Variable that represents all numbers in Python?


code: foo(x)

rawDescription: What does *map mean in python?

description: What does *map mean in python


code:
def binsearch(field, lower=True, a=0, b=None):
  if b is None:
    b = len(field)
  while a + 1 < b:
    c = (a + b) / 2
    if lower:
      if field[c] < c:
        a = c
      else:
        b = c
    else:  # search for upper bound
      if field[c] > c:
        b = c
      else:
        a = c
  return b if lower else a

def indexMatchCount(field):
  upper = binsearch(field, lower=False)
  lower = binsearch(field, b=upper+1)
  return upper - lower + 1

rawDescription: dificulty solving a code in O(logn)

description: Dificulty solving a code in O(logn)


code:
from subprocess import Popen, PIPE
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

#this is how I'd mangle the arguments together
output = Popen([
    self._ghostscriptPath,
   'gswin32c',
   '-q',
   '-dNOPAUSE',
   '-dBATCH',
   '-sDEVICE=tiffg4',
   '-r196X204',
   '-sPAPERSIZE=a4',
   '-sOutputFile="%s %s"' % (tifDest, pdfSource),
], stdout=PIPE).communicate()[0]

rawDescription: What is the best way on python 2.3 for windows to execute a program like ghostscript with multiple arguments and spaces in paths?


rawDescription: Find indices of specific rows in a 3d numpy array


code:
for mol in mols:
    for energy, density in data:
        fig = plt.figure()
        ax = fig.addsubplot(111)
        ax.plot(density, energy, 'ro')

        ax.set_xlabel(...)
        ax.set_ylabel(...)
        [a.label.set_color('black') for a in (ax.xaxis, ax.yaxis)]
        # more spines and axis tinkering

        fig.savefig(mol+".png")

rawDescription: Looping over data and creating individual figures


code:
from itertools import repeat
d = [[] for i in repeat(None, n)]

rawDescription: Python: fastest way to create a list of n lists


code:
{'Date:': 'November 23 1234 ',
 'Other:': 'Other information',
 'Title:': 'Example: of a title '}

rawDescription: Create a dictionary with a string with colons


rawDescription: Django-date incrementation in a list with ManyToManyField


code: data = urllib.parse.urlencode({'hashable': 'test'})

rawDescription: Simple POST using urllib with Python 3.3


code: sorted([2, 3, 1], key=lambda x: -x)

rawDescription: Sorting Counter collection in python with secondary term (tie breaker)


code:
#!/usr/bin/env python
from scapy.all import *
INFILE = 'sample.pcap'
OUTFILE = 'stripped.pcap'
paks = rdpcap(INFILE)
for pak in paks:
    pak[TCP].remove_payload()
wrpcap(OUTFILE, paks)

rawDescription: Stripping payload from a tcpdump?

description: Stripping payload from a tcpdump


code:
from zope.interface.registry import Components
from zope.interface import Interface
registry = Components()
class IA(Interface):
    pass

data = {}
registry.registerAdapter(lambda o: 'adapter from dict to IA', [dict], IA)
registry.queryAdapter(data, IA)

rawDescription: How to use zope.interface.directlyProvides with instances of build in types (dict, string, ...)

description: Use zope.interface.directlyProvides with instances of build in types (dict, string, ...)


code:
def create(self, validated_data):
    # This expects an input format of {"country": "iso"}

    # Instead of using the ID/PK of country, we look it up using iso field
    country_iso = validated_data.pop('country')
    country = Country.objects.get(iso=country_iso)

    # Create the new Office object, and attach the country object to it
    office = Office.objects.create(country=country, **validated_data)

    # Notice I've left **validated_data in the Office object builder,
    # just in case you want to send in more fields to the Office model

    # Finally a serializer.create() is expected to return the object instance
    return office

rawDescription: Django REST Framework: create and update an object with a nested object value (instead of Primary Key)


code:
i=0
while i<n:
    j=0
    while j<n:
        arr[i][j]=0
        j+=1
    i+=1

rawDescription: filling a n*n matrix with n elements

description: Filling a n*n matrix with n elements


rawDescription: Reorganise list in list python

description: Reorganise list in list python


code:
class InterfaceManager(BoxLayout):

    def __init__(self, **kwargs):
        super(InterfaceManager, self).__init__(**kwargs)
        self.forms = {}

    def add_form(self, key, form):
        self.forms[key] = form

    def uniCallback(self, button):
        self.clear_widgets()
        # You could introduce a more elegant key
        # handling system here.
        self.add_widget(self.forms[button.text])

rawDescription: Switching kivy widgets

description: Switching kivy widgets


code: esum_same = np.einsum('ij,jl->il', lowDimRepresentation, principalComponents)

rawDescription: Numpy rewriting operation using einsum

description: Numpy rewriting operation using einsum


code: word = ln.rstrip().lower()

rawDescription: count suffixes appearing in the word file

description: Count suffixes appearing in the word file


code:
def foo(m):

  for i in range(0, len(m), 2):

    for j in range(len(m[i])-1):
      current = tuple(m[i][j:(j+2)])
      mm = m[i+1]
      if(len(mm) % 2 != 0 or (len(mm) > 1 and not type(mm[1][0]) is types.ListType)):
        currentl = mm[j]
        for k in range(0, len(currentl)-1):
          yield current, tuple(currentl[k:(k+2)])

      else:
        for res in foo(mm[2*j:2*j+2]):
          # this is for pretty print only
          if type(res) is types.TupleType and len(res)>1 and not type(res[0]) is types.TupleType:
            yield current, res
          else:
            # pretty print again
            c = [current]
            c+= res
            yield tuple(c)

rawDescription: loop over tree like structure

description: Loop over tree like structure


code:
def date_diff(y1, m1, d1, y2, m2, d2):
    x = min(y1, y2)   # base date
    days1 = year_days_since(x, y1) + days_this_year(y1, m1, d1)
    days2 = year_days_since(x, y2) + days_this_year(y2, m2, d2)
    return days2 - days1

rawDescription: Python difference between two dates

description: Python difference between two dates


rawDescription: how to parse column data to arrays?

description: Parse column data to arrays


rawDescription: Matching everything after series of hyphens


rawDescription: Getting Raw Binary Representation of a file in Python


code: hash("foo")

rawDescription: How does the dictionary add keys in python?


code:
test = pd.Series(data = [NaN, 2, u'string'])
pd.isnull(test)

rawDescription: Count NaNs when unicode values present

description: Count NaNs when unicode values present


rawDescription: Adding list/string ord() values in Python


rawDescription: How can I plot this data?

description: Plot this data


code:
NewBase = ParentBase("NewBase", (object,), {})
class Parent(NewBase):
    pass

rawDescription: Class inheritance and __new___

description: Class inheritance and __new___


code:
convert = {"tab1_name": "tab1", "tab2_name": "tab2", "tab3_name": "tab3"}
a = mainframe.tab(mainframe.select(), "text")
b = convert[a]

code1 = "w = %s.winfo_reqwidth()" % b
code2 = "h = %s.winfo_reqheight()" % b
exec(code1) # for python 2 it is: exec code1
exec(code2) # python 3 changed the exec statement to a function
mainframe.configure(width=w, height=h)

rawDescription: Convert string into a Tkinter notebook frame


code: [[os.stat(f).st_size, os.path.realpath(f)] for f in glob.glob('*.sh')]

rawDescription: Python tuple instead of list

description: Python tuple instead of list


rawDescription: Grouping and aggregating by counts: how to keep column names?


code:
with open('dummy.csv', 'wb') as f:
    f.write(b'foo\x01302.0\x011407339259000\nbar\x01206.0\x011407339259230\n')

import pandas
foo = pandas.read_csv('dummy.csv', sep='\x01')
foo.keys()
foo.values

rawDescription: Saving a string with \x01 characters to disk


code:
# listener function
def listener():
    print('listening...')

class Button:
    def __init__(self, mouse_listener):
        mouse_listener() # you call the function inside __init__

button = Button(listener)

rawDescription: How to pass a function to another function in order to create an action listener

description: Pass a function to another function in order to create an action listener


code: pan = DataReader(['AAPL', 'GM'], data_source='yahoo')

rawDescription: Getting end of period change with different index


code:
@register.simple_tag(takes_context=True)
def subtractify(context, obj):
    newval = obj.loan_amount - obj.service_charge
    return newval

rawDescription: Subtracting two variables in django template


code:
import argparse
print(argparse.Namespace(a=1, b=2))

rawDescription: Standard Python base class as a container for arbitrary attributes


code: data['members']

rawDescription: Retrieving items from a dictionary data type created from a JSON request


code:
[
 {'delim_type': '', 'arcana_list': 'Life 3'},
 {'delim_type': ' and/or ', 'arcana_list': 'Mind 3, Prime 3'},
]

rawDescription: Reduce a list of 2-dicts, to a list unique by the one item, concatenating the other items in python3


code:
d = dict(a=1, b=2, c=3, d=4)
from operator import itemgetter
sum(itemgetter('a', 'b', 'c', 'd')(d))

rawDescription: R with function in python

description: R with function in python


code:
def df(node):
    if visited(node):
        pass # found a cycle here, do something with it
    visit(node)
    [df(node_id) for node_id in graph[node]]

rawDescription: how to represent graphs /trees in python and how to detect cycles?

description: Represent graphs /trees in python and how to detect cycles


code: type(rab)(rab.func_code, foo.__dict__)

rawDescription: Python 2 inject into module scope with global keyword and closures


code:
nb.select()
nb.index(nb.select())

rawDescription: Finding the currently selected tab of Ttk Notebook


code: self.add_line(u'   :annotation: = ' + objrepr, '<autodoc>')

rawDescription: Omit (or format) the value of a variable when documenting with Sphinx


code:
headrev = pysvn.Revision( pysvn.opt_revision_kind.head )
revlog = svnclient.log( url, revision_start=headrev, revision_end=headrev, discover_changed_paths=False)
headrev = revlog[0].revision.number

rawDescription: Get HEAD revision number of SVN Repository with PYSVN


code:
import numpy as np
from matplotlib import pyplot as plt
import cv2

file_name = 'myimage.jpg'
img = cv2.imread(file_name)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,150,100,apertureSize = 3)

#display image
plt.figure(1)
plt.imshow(edges)
plt.title('edges of image')
plt.show()

rawDescription: matplotlib figures are not displayed when one types imshow(img) in the command prompt in pdb mode

description: Matplotlib figures are not displayed when one types imshow(img) in the command prompt in pdb mode


code: [{'task_id':task.pk, 'name': Lesson.objects.get(pk=task.relatedresourceid).name if task.tasktype==1 else Exam.objects.get(pk=task.relatedresourceid).name} for task in Task.objects.all()]

rawDescription: Django ORM: Dynamically determine another table name according one field value


code: mc.set(key, val, time)

rawDescription: Which Python module to use for Memcached?


code: my_variable = self.myinstance[:]

rawDescription: Python: How to I unbind a variable from instance in a class?


code:
class randomInRange:
    def getRandom(self, start, end, quantity):
        resList = []
        for i in range(quantity):
            selList = range(start, end)
            resNum = random.choice(selList)
            resList.append(resNum)
        return (resList)

rawDescription: Python: Preventing elements being appended to the same list over and over


code: sleepEvent.wait(10) # wait for up to 10 seconds

rawDescription: Make a thread wait for either a Timer or a Signal?


code: merged_file = pd.merge(df2, df1, on='Billing Country', how = 'left')

rawDescription: fuzzywuzzy ratio of 2 columns if one column satisfies 100 percent match the best one

description: Fuzzywuzzy ratio of 2 columns if one column satisfies 100 percent match the best one


code:
data = {}
for entry in csv.DictReader(StringIO.StringIO(results), delimiter='\t'):
    data[entry['sku']] = [entry['delivered-price-gbp'], entry['delivered-price-euro']]

rawDescription: Building a dictionary from a tab delimited file in a pythonic way


code:
from __future__ import print_function
import sys

from openmdao.api import IndepVarComp, Component, Problem, Group, ScipyOptimizer

class Paraboloid(Component):

    def __init__(self):
        super(Paraboloid, self).__init__()

        self.add_param('x', val=0.0)
        self.add_param('y', val=0.0)

        self.add_output('f_xy', val=0.0)

    def solve_nonlinear(self, params, unknowns, resids):

        x = params['x']
        y = params['y']

        #unknowns['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0
        unknowns['f_xy'] = (1000.*x-3.)**2 + (1000.*x)*(0.01*y) + (0.01*y+4.)**2 - 3.

    def linearize(self, params, unknowns, resids):
        """ Jacobian for our paraboloid."""
        x = params['x']
        y = params['y']
        J = {}

        #J['f_xy', 'x'] = 2.0*x - 6.0 + y
        #J['f_xy', 'y'] = 2.0*y + 8.0 + x
        J['f_xy', 'x'] = 2000000.0*x - 6000.0 + 10.0*y
        J['f_xy', 'y'] = 0.0002*y + 0.08 + 10.0*x

        return J

if __name__ == "__main__":

    top = Problem()

    root = top.root = Group()
    root.fd_options['force_fd'] = True

    root.add('p1', IndepVarComp('x', 3.0))
    root.add('p2', IndepVarComp('y', -4.0))
    root.add('p', Paraboloid())

    root.connect('p1.x', 'p.x')
    root.connect('p2.y', 'p.y')

    top.driver = ScipyOptimizer()
    top.driver.options['optimizer'] = 'SLSQP'

    top.driver.add_desvar('p1.x', lower=-1000, upper=1000, scaler=1000.)
    top.driver.add_desvar('p2.y', lower=-1000, upper=1000,scaler=.001)
    top.driver.add_objective('p.f_xy')

    top.setup()
    top.run()

    print('\n')
    print('Minimum of %f found at (%f, %f)' % (top['p.f_xy'], top['p.x'], top['p.y']))

rawDescription: Paraboloid optimization requiring scaling


code:
button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
button.grid()

rawDescription: Program runs a button command on startup?


code:
from tkinter import *

class application(Frame):
    """ A Gui application with three buttons"""
    def __init__(self, master = None):
        """ Inititalization the fram"""
        Frame.__init__(self,master)
        self.master = master
        #self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.master.title("My GUI")
        self.pack(fill=BOTH, expand=1)
        buttons1 = Button(self,text = "this wroks", command= self.program_button)
        buttons1.place(x=250,y=250)
        #self.buttons1.place(x=5, y=10)

        menu = Menu(self.master)
        self.master.config(menu=menu)

        self.test = StringVar()
        eBox = Entry(self, textvariable=self.test)
        #eBox.pack()
        eBox.grid()

        file = Menu(menu)
        file.add_command(label='Save', command=self.text_capture)
        file.add_command(label='Exit', command=self.program_exit)
        menu.add_cascade(label='File', menu=file)

    def program_button(self):
        exit()

    def program_exit(self):
        exit()

    def text_capture(self):
        mtext = self.test.get()
        print(self.test)
        print(mtext)
        print(self.test.get())

root = Tk()

root.geometry("500x500")

app = application(root)

root.mainloop()

rawDescription: Store data from Entry widget tkinter

description: Store data from Entry widget tkinter


code:
output = []
for row in dictList:
  one_entity = {row[0]:row[1],row[2]:row[3]}
  output.append(one_entity)

rawDescription: How to write into, or create a dictionary, using indexes in a row from another file

description: Write into, or create a dictionary, using indexes in a row from another file


code: print (src + newdir), fname, (dest + newdir), newdir + "_data.txt"

rawDescription: Using os.walk in Python to create a txt file for a corresponding folder and subfolders


code:
while (True):
    try:
        loop.run_until_complete(asyncio.sleep(0.001))
        ch = input()
    except KeyboardInterrupt:
        break
    loop.run_until_complete(sendChar(transport, ch))

rawDescription: cannot receive datagram correctly in python3 asyncio

description: Cannot receive datagram correctly in python3 asyncio


code:
package_data = {
    '' : [f for f in copy_dir()]
},

rawDescription: Copy an entire folder in a setup.py file


code: pow is math.pow

rawDescription: Difference between the built-in pow() and math.pow() for floats, in Python?


code: dict2 = dict(map(func, dict1.iteritems()))

rawDescription: Mapping func over dictionary

description: Mapping func over dictionary


code:
def flatten(seq):
    l = []
    for elt in seq:
        t = type(elt)
        if t is tuple or t is list:
            for elt2 in flatten(elt):
                l.append(elt2)
        else:
            l.append(elt)
    return l

rawDescription: How to get every element in a list of list of lists?

description: Get every element in a list of list of lists


code: df.plot(kind='barh', colormap='RdBu')

rawDescription: different colors for rows in barh chart from pandas dataframe python

description: Different colors for rows in barh chart from pandas dataframe python


code: data = [ [255] * image.size[1] ] * image.size[0]

rawDescription: Python Image Library - Convert pixels to 2D list


code:
activity_logs = ActivityLog.objects.filter(object_raw='foo')
if activity_logs.exists():
    activity_logs.first()  # get one object
    activity_logs.count()  # get number of objects

rawDescription: Django - Aggregate equal values of fields in model


code:
class Bunch(object):
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

rawDescription: Does Python have anonymous classes?

description: Does Python have anonymous classes


rawDescription: Why is hardcoding this list slower than calculating it?


rawDescription: How do you pack three bytes into a python struct?

description: Pack three bytes into a python struct


code: myadd = lambda xs,ys: tuple(x + y for x, y in izip(xs, ys))

rawDescription: How to add with tuples

description: Add with tuples


code:
def Test(object):
    def __init__(self):
         from functools import partial
         self.partial = partial

rawDescription: Python, Django, using Import from inside of a class, can't seem to figure this out


rawDescription: Finding the difference between times in different columns through a CSV file


code: somelist = [x for x in somelist if determine(x)]

rawDescription: Remove items from a list while iterating in Python


code:
from codecs import getencoder
encoder = getencoder('rot-13')
rot13string = encoder(mystring)[0]

rawDescription: Stream/string/bytearray transformations in Python 3


rawDescription: Calling python function with an unknown number of arguments


code:
def discard_func(list_of_dicts):
    list_of_dicts[:] = [x for x in list_of_dicts if test(x)]
    return list_of_dicts

rawDescription: Recursively remove nested items in dictionary


code:
SplitSegments = cut_line_at_points(MyLine, IntPoints)
gpd.GeoSeries(SplitSegments)

rawDescription: Shapely Split LineStrings at Intersections with other LineStrings


rawDescription: Python csv writer truncates number format


code:
idx = df.groupby('word')['count'].idxmax()
print(idx)

rawDescription: python pandas, DF.groupby().agg(), column reference in agg()

description: Python pandas, DF.groupby().agg(), column reference in agg()


code:
List = ['android', 'ios', 'android', '', 'none', 'android']
OS_list = ['android', 'ios', 'windows']

[i for i in OS_list if i in List]

rawDescription: Python List: Pythonic way to get unique items in given List from a given Set


code:
np.random.seed(2015)
data = []
for i in range(5):
    data.append(dict(zip(np.random.choice(10, replace=False, size=5),
                         np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)

rawDescription: How to append rows in a pandas dataframe in a for loop?

description: Append rows in a pandas dataframe in a for loop


code:
# slower.
twosArr = array.array('i', [2] * 1000000)

# faster.
twosArr = array.array('i', [2]) * 1000000

rawDescription: What is the fastest way to initialize an integer array in python?


code:
class ActivityForm(ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(ActivityForm, self).__init__(*args, **kwargs)
        if 'initial' in kwargs:
            self.fields['participants'].queryset = Member.objects.filter(group__id=initial.group.id)

    class Meta:
        model = Activity

rawDescription: Django ModelForm Field Filtering with multiple model dependancies


code:
[item[0] for item in x]
#or
[item for (item,) in x]

rawDescription: Python list of tuples, need to unpack and clean up


rawDescription: Allow users to create an "appointment" using a django form


code:
import os
path = 'C:/'
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         '001_MN_DX' in i]

rawDescription: Choose a file starting with a given string


code: [df.loc[list(sum(tups, ()))] for tups in product(*[list(permutations(grp.index)) for (name, grp) in age])]

rawDescription: Quick way to find all permutations of a pandas DataFrame that preserves a sort?


code: ['long ', 'string ', 'that ', 'I want to split up']

rawDescription: Splitting a string by list of indices

description: Splitting a string by list of indices


rawDescription: Python specify popen working directory via argument


code:
class Genre(GenreBase):
    genres = ['comic', 'scifi', ... ]
    def __getattr__(self, attr):
        if attr in type(self).genres:
            self.__dict__[attr] = type(self)(attr)
        return self.__dict__[attr]

rawDescription: python enumeration class for ORM purposes

description: Python enumeration class for ORM purposes


code:
import json

with open('input') as f:
    dicts = [json.loads(line) for line in f]

rawDescription: How to read lines of dictionary and write to a CSV file

description: Read lines of dictionary and write to a CSV file


code:
for key in results:
    print("%s: %d" % (key, results[key]))

rawDescription: Python 3.X combining similar lines in .txt files together


code:
def vc_xml(df):
    for col in df:
        yield '<variable = "{}">'.format(col)
        for k,v in df[col].value_counts().items():
            yield "   <code>{}</code>".format(k)
            yield "   <count>{}</count>".format(v)
        yield '</variable>'

with open("out.xml", "w") as fp:
    for line in vc_xml(df):
        fp.write(line + "\n")

rawDescription: Pandas: count unique value in each column, by looping through them?


code: a, b = [i[:3] for i in the_array], [i[3:] for i in the_array]

rawDescription: Splitting arrays python

description: Splitting arrays python


rawDescription: What is the difference between the following two statements?


code:
[{'score': u'2 - 2', 'team1': u'CSKA Moscow', 'team2': u'Manchester City'},
 {'score': u'3 - 0', 'team1': u'Zenit St. Petersburg', 'team2': u'Standard Liege'},
 {'score': u'4 - 0', 'team1': u'APOEL Nicosia', 'team2': u'AaB'},
 {'score': u'3 - 0', 'team1': u'BATE Borisov', 'team2': u'Slovan Bratislava'},
 {'score': u'0 - 1', 'team1': u'Celtic', 'team2': u'Maribor'},
 {'score': u'2 - 0', 'team1': u'FC Porto', 'team2': u'Lille'},
 {'score': u'1 - 0', 'team1': u'Arsenal', 'team2': u'Besiktas'},
 {'score': u'3 - 1', 'team1': u'Athletic Bilbao', 'team2': u'SSC Napoli'},
 {'score': u'4 - 0', 'team1': u'Bayer Leverkusen', 'team2': u'FC Koebenhavn'},
 {'score': u'3 - 0', 'team1': u'Malmo FF', 'team2': u'Salzburg'},
 {'score': u'1 - 0', 'team1': u'PFC Ludogorets Razgrad *', 'team2': u'Steaua Bucuresti'}]

rawDescription: BeautifulSoup data scrapping and database


rawDescription: Python: cycle through elements in list reversing when the end is reached


code: {u'color': u'orange', u'data': u'none', u'size': u'big'}

rawDescription: SQLAlchemy - Dictionary of tags

description: SQLAlchemy - Dictionary of tags


code:
def returnJSONQuestion(id):

    if not minuteMod(2):
        return None or ''

    # rest of the code

rawDescription: Python: Check the url request per hour

description: Python: Check the url request per hour


rawDescription: Unable to get wxPython Sizers to work correctly


rawDescription: BFS algorithm in Python

description: BFS algorithm in Python


rawDescription: Sum Lists' value with corresponding index value in Python


code:
def locate_min(a):
    smallest = min(a)
    return smallest, [index for index, element in enumerate(a)
                      if smallest == element]

rawDescription: Python - getting all the min elements and its indices from a list


code:
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

from wallspider.items import Website

class storeSpider(CrawlSpider):
    name = "cppages"
    allowed_domains = ["www.store.com"]
    start_urls = ["http://www.store.com",]

    def cleanurl(link_text):
        return link_text.strip("\t\r\n '\"")

    rules = (
    Rule (SgmlLinkExtractor(allow=('/cp/', ),deny=('grid=false', 'sort=', 'stores=', r'\|\|', 'page=',), process_value=cleanurl)
    , callback="parse_items", follow= True, process_links=lambda links: [link for link in links if not link.nofollow],),
    Rule(SgmlLinkExtractor(allow=('/cp/', '/browse/', ),deny=('grid=false', 'sort=', 'stores=', r'\|\|', 'page='), process_value=cleanurl)),
    )

    def parse_items(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//html')
        items = []

        for site in sites:
            item = Website()
            item['url'] = response.url
            item['referer'] = response.request.headers.get('Referer')
            item['anchor'] = response.meta.get('link_text')
            item['canonical'] = site.xpath('//head/link[@rel="canonical"]/@href').extract()
            item['robots'] = site.select('//meta[@name="robots"]/@content').extract()
            items.append(item)

        return items

rawDescription: Links with space before and after are not parsed correctly


code:
for n, p in pos.iteritems():
    X.node[n]['pos'] = p

rawDescription: networkx add_node with specific position

description: Networkx add_node with specific position


code:
env.roledefs = {
    'node1':          ['node1.%s' % env.domain],
    'node2':          ['node2.%s' % env.domain]
}

rawDescription: fabric pass arguments to roledefs

description: Fabric pass arguments to roledefs


code: from coke import make, make2

rawDescription: Is it possible in python to define functions outside of a programs main namespace and add them for easy access like a .h file in c?


code:
import csv
from itertools import count

with open('MySpreadsheet.csv', 'rU') as f:
    reader = csv.DictReader(f, dialect=csv.excel)
    row_count = count(1)

    for row in reader:
        next(count)
        print(row)

for i in range(row_count):
    print('Stack Overflow')

rawDescription: Loop over rows of csv.DictReader more than once


code:
# "ignore" bind
def ibind(val, func):
    bind(val, lambda _ : func())

rawDescription: simplifying maybe Monad

description: Simplifying maybe Monad


code:
#!/usr/bin/env python
import Image

def makefilmstrip(images, mode='RGB', color='white'):
    """Return a combined (filmstripped, each on top of the other) image of the images.

    """
    width  = max(img.size[0] for img in images)
    height = sum(img.size[1] for img in images)

    image = Image.new(mode, (width, height), color)

    left, upper = 0, 0
    for img in images:
        image.paste(img, (left, upper))
        upper += img.size[1]

    return image

if __name__=='__main__':
    # Here's how it could be used:
    from glob import glob
    from optparse import OptionParser

    # process command-line args
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="file",
                      help="write combined image to OUTPUT")

    options, filepatterns = parser.parse_args()
    outfilename = options.file

    filenames = []
    for files in map(glob, filepatterns):
        if files:
            filenames += files

    # construct image
    images = map(Image.open, filenames)
    img = makefilmstrip(images)
    img.save(outfilename)

rawDescription: How to complete this python function to save in the same folder?

description: Complete this python function to save in the same folder


code:
out.shape
out[3,4]
arr[3].dot(arr[4])

rawDescription: Python, creating a large-dimensional matrix of 3-dimensional dot products


code:
a = [1, 2, 3]
b = [4, 5, 6]
result = []
for x in a:
    for y in b:
        result.append(x - y)

rawDescription: Pythonic way to write a loop

description: Pythonic way to write a loop


code:
urls.py
url(r'event/add/$', EventCreate.as_view(), name='event_create'),

rawDescription: Best practices on saving in a view, based on example code


code:
regex = re.compile("^s")
[x for d in dict1 for x in dict1[d] if regex.search(d)]

rawDescription: how to get dict value by regex in python

description: Get dict value by regex in python


code:
string1 = '10:00PM'
string2 = '11:00PM'

print(string2 > string1)

print(string1 > string2)

rawDescription: compare the int in the strings

description: Compare the int in the strings


rawDescription: Speed up a function in Python 2.7

description: Speed up a function in Python 2.7


rawDescription: HXS filtering with scrapy - python

description: HXS filtering with scrapy - python


code:
import pandas as pd
import numpy as np

dates = pd.date_range('19990101', periods=6000)
df = pd.DataFrame( np.random.randint(0,50,size=(6000,2)), index = dates)
df.columns = ['winners','losers']
new_df = pd.DataFrame()
new_df ['winners'] = df.groupby(df.index.year, as_index=True)['winners'].sum()
new_df ['losers'] = df.groupby(df.index.year, as_index=True)['losers'].sum()
new_df['winners_Percent'] = new_df['winners']/new_df['winners'].sum()
new_df['losers_Percent'] = new_df['losers']/new_df['losers'].sum()

rawDescription: groupby by years and generate new columns

description: Groupby by years and generate new columns


rawDescription: Can't *copy* an index from list to another with a twist in Python


code:
word[:2]    # The first two characters
word[2:]    # Everything except the first two characters

rawDescription: How to split a single word using split()

description: Split a single word using split()


code:
seta = set()
regexa = re.compile(r'\*(\d+)') #matches asterisk followed by digits, captures digits
for line in a:
    m = regexa.match(line)      #looks for match at start of line
    if m:
        seta.add(m.group(1))

rawDescription: regex python Fasta

description: Regex python Fasta


rawDescription: Handle multiple values in column

description: Handle multiple values in column


code: self.secondel = q[1:2]

rawDescription: Numpy array assignment inside class

description: Numpy array assignment inside class


rawDescription: regular expression Pattern object getting converted to string if fetched from config.cfg file

description: Regular expression Pattern object getting converted to string if fetched from config.cfg file


code: imgs = [img_1, ..., img_n]

rawDescription: Find median of list of images

description: Find median of list of images


rawDescription: Parsing HTML with requests and BeautifulSoup


code:
import os, fnmatch

def locate(pattern, root_path):
    for path, dirs, files in os.walk(os.path.abspath(root_path)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

rawDescription: search in wildcard folders recursively in python

description: Search in wildcard folders recursively in python


code:
options = webdriver.ChromeOptions()
options.add_argument('--user-data-dir=/path/to/my/profile')
driver = webdriver.Chrome(chrome_options=options)

rawDescription: how can I use selenium with my normal browser

description: Use selenium with my normal browser


code: s = set().union(t1, t2, t3)

rawDescription: How can I extend a set with a tuple?

description: Extend a set with a tuple


rawDescription: count number of ones in a given integer

description: Count number of ones in a given integer


code:
colors = [elm.get("data-label", "No color specified")
          for elm in soup.find_all("div", class_="sfa-pa-product-swatches-color")]

rawDescription: web scraping using python beautifulsoup getting values after equal sign

description: Web scraping using python beautifulsoup getting values after equal sign


code:
z = np.row_stack([x, y])
z

rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


code:
d = {(2,4): 1, (1,3): 2, (1,2): 3, (3,1): 4}
sorted(d)
sorted(d.items())
collections.OrderedDict(sorted(d.items()))

rawDescription: How to sort dictionary on first element of the key (tuple)

description: Sort dictionary on first element of the key (tuple)


code:
def paintGL(self):
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glEnable(GL_TEXTURE_2D)
    glBindTexture(GL_TEXTURE_2D, texture)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslate(0.0, 0.0, -50.0)
    glScale(20.0, 20.0, 20.0)
    glRotate(self.yRotDeg, 0.2, 1.0, 0.3)
    glTranslate(-0.5, -0.5, -0.5)

    glBegin(GL_TRIANGLES)
    for vert in self.poly_verts:
        glTexCoord2f (vert[6], vert[7]);
        glVertex3f(vert[0], vert[1], vert[2])

    glEnd()
    glDisable(GL_TEXTURE_2D)

rawDescription: uv mapping python OpenGL triangles

description: Uv mapping python OpenGL triangles


rawDescription: Complex query in Django ORM

description: Complex query in Django ORM


rawDescription: How to encode a long string of hex values in unicode easily in python

description: Encode a long string of hex values in unicode easily in python


rawDescription: Convert a RDD of Tuples of Varying Sizes to a DataFrame in Spark


code:
df = pd.DataFrame({'a':[1,2,3],'b':[3,2,1]})
plt.interactive(False) # This will prevent matplotlib from showing the plots immediately
# You would want to create placeholders for different figures to show:
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
# Then place your plots on the relevant placeholders:
df.a.plot(ax=ax1)
df.b.plot(ax=ax2)

rawDescription: Combining Jupyter rich display and matplotlib charts


code:
ind1=[i[-1] for i in ind]   # last of all groups
ind1
ind2=[i[0] for i in ind]   # first of all groups
ind2

rawDescription: Efficient way of appending / extracting list elements


rawDescription: Getting list based on text lxml

description: Getting list based on text lxml


code:
from win32com.shell import shell, shellcon
app_data_local = shell.SHGetFolderPath(0, shellcon.CSIDL_LOCAL_APPDATA, None, 0)

rawDescription: Python - cannot "find" files with "getenv("APPDATA")"?


code:
myObj = MyClass()
NewClass = type("NewClass", (myObj.__class__,), {})
newObj = NewClass()
myObj, newObj

rawDescription: class name as variable in python

description: Class name as variable in python


code: validSortOrders = {'ascending': ASCENDING, 'descending': DESCENDING}

rawDescription: Ascending and descending not working while passing as argument in mongodb with python


code: msg = q.get()

rawDescription: How to wakeup thread from thread pool in python?

description: Wakeup thread from thread pool in python


code: matching_results = [t for t in list_ if t[0] in c_codes]

rawDescription: How can I get a Tuple from a list in python (3.3)

description: Get a Tuple from a list in python (3.3)


code:
from datetime import datetime, timedelta
from pyspark.sql.types import BooleanType, TimestampType
from pyspark.sql.functions import udf, col

def in_last_5_minutes(now):
    def _in_last_5_minutes(then):
        then_parsed = datetime.strptime(then, '%d-%b-%y %I.%M.%S.%f %p')
        return then_parsed > now - timedelta(minutes=5)
    return udf(_in_last_5_minutes, BooleanType())

rawDescription: Column filtering in PySpark

description: Column filtering in PySpark


code: chars = "".join( [random.choice(string.letters[:26]) for i in xrange(15)] )

rawDescription: Generating random text strings of a given pattern


rawDescription: Python: Get multiple random lines for a given category


code: do_stuff(API_come_query, lambda i: i['from']['id'])

rawDescription: Slightly different loops in python / Minimize code


code:
def compute_correlation_coefficient(real_and_predicted):
    """
    compute and display the correlation coefficient from a list of real and predicted values
    """
    list1=[]
    list2=[]
    for tuple in real_and_predicted:
        list1.append(tuple[0])
        list2.append(tuple[1])
    print("correlation coefficient")
    print(numpy.corrcoef(list1, list2)[0, 1])

rawDescription: random forest with spark: get predicted values and R²

description: Random forest with spark: get predicted values and R²


code:
import importlib
import inputs #import the module here, so that it can be reloaded.
importlib.reload(inputs)
from inputs import A # or whatever name you want.

rawDescription: Python reload file

description: Python reload file


code:
arr -= 2
arr = np.where(arr==-1, 102, arr)

rawDescription: Discrete then linear colormap in matplotlib


code: {'age': 29, 'name': 'ehsan', 'family': 'shirzadi'}

rawDescription: How to access a class field values in its base class?

description: Access a class field values in its base class


rawDescription: python hex to decimal using for loop

description: Python hex to decimal using for loop


code:
def distance(lista, listb):
    return sum( (b - a) ** 2 for a,b in zip(lista, listb) ) ** .5

rawDescription: algorithm to compare lists of numbers for similarity?

description: Algorithm to compare lists of numbers for similarity


code:
import urllib.request
import csv

IMAGE_COLUMN = 14
ROOT_URL = 'http://www.fakesite.com/pimages/'
images = []

with open('test.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=",")
    for row in readCSV:
        images.append(row[IMAGE_COLUMN])

for image in images:
    url = ROOT_URL + image
    urllib.request.urlretrieve(url, image)

rawDescription: Download files from FTP or HTTP using filenames in CSV - Python 3


rawDescription: Converting NLTK phrase structure trees to BRAT .ann standoff


code: True + True

rawDescription: python: don't understand "while len(list1) and len(list2):"

description: Python: don't understand "while len(list1) and len(list2):"


rawDescription: Count number of values in python

description: Count number of values in python


code:
from pyspark.mllib.tree import DecisionTreeMode

numTrees = 3
trees = [DecisionTreeModel(model._java_model.trees()[i])
    for i in range(numTrees)]

predictions = [t.predict(testData) for t in trees]

rawDescription: How to access individual predictions in Spark RandomForest?

description: Access individual predictions in Spark RandomForest


rawDescription: In Python, how can I create lists that contain a certain index of other lists?


code:
result = re.sub(
    r"""(?x)       # Enable verbose mode (comments)
    (?<=\d)        # Assert that we're not at the start of the number.
    (?=            # Assert that it's possible to match:
     (\d{2}){0,2}  # 0, 2 or 4 digits,
     \d{3}         # followed by 3 digits,
     (\d{7})*      # followed by 0, 7, 14, 21 ... digits,
     (?!\d)        # and no more digits after that.
    )              # End of lookahead assertion.""",
    ",", subject)

rawDescription: Using regular expression to comma separate a large number in south asian numbering system


code: sizes = [len(rec) for rec in records]

rawDescription: Parsing fasta file with biopython to count number sequence reads belonging to each ID


rawDescription: Spark: Manipulation of Multiple RDDs

description: Spark: Manipulation of Multiple RDDs


code:
class Ordered(object):
  __metaclass__ = BaseWithOrderedFields

  x = MyOrderedField(0)
  z = MyOrderedField(0)
  b = MyOrderedField(0)
  a = MyOrderedField(0)

rawDescription: How can I get fields in an original order?

description: Get fields in an original order


code:
scaler = sklearn.preprocessing.StandardScaler(copy=False)
readings_array = scaler.fit_transform( readings_array )
# do stuff with scaled data
readings_for_plotting = scaler.inverse_transform( readings_array )

rawDescription: matplotlib: Rescale axis labels

description: Matplotlib: Rescale axis labels


code:
df = pd.DataFrame({'A': pd.Series(range(df.A.min(), df.A.max() + 1)),
                   'B': pd.Series(range(df.B.min(), df.B.max() + 1))})

rawDescription: Appending variable length columns in Pandas dataframe Python


code:
(
    "com.apple.speech.synthesis.voice.Agnes",
    "com.apple.speech.synthesis.voice.Albert",
    "com.apple.speech.synthesis.voice.Alex",
    "com.apple.speech.synthesis.voice.BadNews",
    "com.apple.speech.synthesis.voice.Bahh",
    "com.apple.speech.synthesis.voice.Bells",
    "com.apple.speech.synthesis.voice.Boing",
    "com.apple.speech.synthesis.voice.Bruce",
    "com.apple.speech.synthesis.voice.Bubbles",
    "com.apple.speech.synthesis.voice.Cellos",
    "com.apple.speech.synthesis.voice.Deranged",
    "com.apple.speech.synthesis.voice.Fred",
    "com.apple.speech.synthesis.voice.GoodNews",
    "com.apple.speech.synthesis.voice.Hysterical",
    "com.apple.speech.synthesis.voice.Junior",
    "com.apple.speech.synthesis.voice.Kathy",
    "com.apple.speech.synthesis.voice.Organ",
    "com.apple.speech.synthesis.voice.Princess",
    "com.apple.speech.synthesis.voice.Ralph",
    "com.apple.speech.synthesis.voice.Trinoids",
    "com.apple.speech.synthesis.voice.Vicki",
    "com.apple.speech.synthesis.voice.Victoria",
    "com.apple.speech.synthesis.voice.Whisper",
    "com.apple.speech.synthesis.voice.Zarvox"
)

rawDescription: calling Objective C functions from Python?

description: Calling Objective C functions from Python


code:
import numpy as np
a=np.array([1,2,3,np.nan,np.nan,np.nan,np.nan]) # an example
n=len(a)
p=n-np.isnan(a).sum() # count of valids assuming nan's at the end.
repeats=n//p
m=n-repeats*p # number of overfilled.
q=m*(repeats+1) #border
a[q:]=a[m:p].repeat(repeats) #the end
a[:q]=a[:m].repeat(repeats+1) #the beginning

rawDescription: Repeat elements of list between each other until we reach a certain length


code:
myTag = soup.new_tag("div", style="white-space:pre-wrap")
myTag.string = "My text \n with a new line"

rawDescription: Replace "\n" in element string with <br> tag in Beautifulsoup


code:
def chunked(size, source):
    for i in range(0, len(source), size):
        yield source[i:i+size]

rawDescription: Chunking bytes (not strings) in Python 2 and 3


rawDescription: How do I separate words using regex in python while considering words with apostrophes?

description: Separate words using regex in python while considering words with apostrophes


code:
import mymodule
...

mymodule.write_data_to_file()

rawDescription: Structuring of Python code

description: Structuring of Python code


code:
for row in cur:
    channel = row[0].encode('ascii')
    channelList.append(channel)

# set the channels text
for index in range(len(channelList)):
      self.setControlLabel(4010 + index, channelList[index])

rawDescription: how to put number of strings in each label

description: Put number of strings in each label


code:
a = "dialog-bmp"
b = "dialog-bmp"
a is b
id(a)
id(b)
a = "brand"
b = "brand"
a is b
id(a)
id(b)

rawDescription: Python returns false for if 'dialog-bmp' is 'dialog-bmp'


code:
def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

rawDescription: question about python names using a default parameter value

description: Question about python names using a default parameter value


code:
with open(filename, 'rb') as f:
    things = []
    while True:
        thing = parser(f)
        if not thing:
            break
        things.append(thing)

rawDescription: Copying dicts from csv to a new dict-python


rawDescription: Subsetting a 2D numpy array

description: Subsetting a 2D numpy array


code:
title, spaces = (str(item.title).ljust(25)+" ").split(" ", 1)
content += '%s%s  %s' % (item.slug, title,
                                            spaces, item.date.ljust(10))

rawDescription: Python Not Web Linking Entire variable in str.ljust


code:
x.py
import ctypes

class Example(ctypes.Structure):

    _fields_ = [
        ('data',ctypes.POINTER(ctypes.c_char)),
        ('len',ctypes.c_int),
        ('doubles',ctypes.POINTER(ctypes.c_double)),
        ('count',ctypes.c_int)]

    def __init__(self,length,count):
        self.data = ctypes.cast(ctypes.create_string_buffer(length),ctypes.POINTER(ctypes.c_char))
        self.len = length
        self.doubles = (ctypes.c_double * count)()
        self.count = count

    def __repr__(self):
        return 'Example({},[{}])'.format(
            ctypes.string_at(self.data),
            ','.join(str(self.doubles[i]) for i in range(self.count)))

class Dll:

    def __init__(self):
        self.dll = ctypes.CDLL('x')
        self.dll.func.argtypes = [ctypes.POINTER(Example)]
        self.dll.func.restype = None

    def func(self,ex):
        self.dll.func(ctypes.byref(ex))

d = Dll()
e = Example(20,5)
print('before:',e)
d.func(e)
print ('after:',e)

rawDescription: How to use malloc and free with python ctypes?

description: Use malloc and free with python ctypes


rawDescription: Python Diferences between lines of strings


code:
result = np.linalg.lstsq(A, y)
result[0]

rawDescription: Broadcasting issues with numpy.linalg.lstsq


code:
Foo.zap = lambda self,x: x + Foo.y
dill.dumps(f, byref=True)
dill.dumps(f, byref=False)

rawDescription: Why dill dumps external classes by reference, no matter what?


code:
import operator
reduce(operator.add, a)

rawDescription: Adding together timedeltas in Python

description: Adding together timedeltas in Python


rawDescription: Including logic in a numerical function

description: Including logic in a numerical function


code:
import numpy as np
x = np.arange(12)
x

rawDescription: What is the most efficient way to subdivide a large list?


code:
x = np.random.pareto(shape, size*5/4) + lower
x = x[x<upper][:size]

rawDescription: How to generate random numbers in specyfic range using pareto distribution in Python

description: Generate random numbers in specyfic range using pareto distribution in Python


code:
import os

os.system("drutil tray open")

rawDescription: How can I eject a CD from MacOS with Python?

description: Eject a CD from MacOS with Python


code: df.to_csv('test.csv', mode='a', header=True, index=False)

rawDescription: Keep header while appending to Pandas dataframe w/ Python


code:
class B(A):
    dictionary = dict(A.dictionary, key='value')

rawDescription: Alter superclass' variable from subclass on Python


rawDescription: Padding or truncating a Python list

description: Padding or truncating a Python list


rawDescription: keeping same formatting for floating point values

description: Keeping same formatting for floating point values


rawDescription: Python: beautify numerical and dict outputs


code:
"""bugaga URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""

from django.conf.urls import *
from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static

from djangobb_forum import settings as forum_settings
from djangobb_forum.sitemap import SitemapForum, SitemapTopic

sitemaps = {
    'forum': SitemapForum,
    'topic': SitemapTopic,
}

urlpatterns = patterns('',
    # Admin
    url(r'^admin/', include(admin.site.urls)),

    # Sitemap
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),

    #My_Apps
    url(r'^places/', include('app_places.urls')),
    url(r'^shows/', include('app_shows_and_times.urls')),

    # DjangoBB_Forum
    url(r'^forum/account/', include('allauth.urls')),
    url(r'^forum/', include('djangobb_forum.urls', namespace='djangobb')),
)

# PM Extension
if (forum_settings.PM_SUPPORT):
    urlpatterns += patterns('',
        url(r'^forum/pm/', include('django_messages.urls')),
   )

if (settings.DEBUG):
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rawDescription: How to integrate djangobb in an existing project?

description: Integrate djangobb in an existing project


code: questions[i]['question']

rawDescription: StringVar() from JSON list using pop() - Python / tkinter


code:
temp = tempfile.NamedTemporaryFile(delete=False)
with open('myfile.csv', 'rU') as myfile, closing(temp):
    for line in myfile:
        temp.write(line.replace('\r'))
os.rename(tempfile.name, 'myfile.csv')

rawDescription: Removing newline from a csv file

description: Removing newline from a csv file


code:
from scipy.signal import medfilt

alpha = 0.0025
Ybase = medfilt(Y, 51) # 51 should be large in comparison to your peak X-axis lengths and an odd number.
peaks = np.array(peaks)[Ybase[peaks] - Y[peaks] > alpha]

rawDescription: find peaks location in a spectrum numpy

description: Find peaks location in a spectrum numpy


code:
os.getcwd()
with cwd('/usr/share'):
    print(os.path.abspath('./test'))

os.getcwd()

rawDescription: Can you set cwd for abspath?

description: Set cwd for abspath


rawDescription: re.scanner only searching start of string

description: Re.scanner only searching start of string


code:
import fileinput
import os
import glob

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

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


code:
list1 = ['apple', 'orange', 'grape']
list2 = ['pineapple', 'banana', 'pear']
[ list1[x]+ " " +list2[x] for x in range(len(list1))]   # both should must have same length

rawDescription: How would one add two lists in this way in Python?


rawDescription: How to load txt and sum hours?

description: Load txt and sum hours


code:
import skimage.morphology.label
labeled=skimage.morphology.label(img,8,255) #255 for the white background

rawDescription: Python Image Library two color image to black and white


rawDescription: wxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times?

description: WxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times


code: subprocess.Popen(['myscript.sh "var=11; ignore all" /path/to/files'], shell=True, executable="/bin/bash")

rawDescription: python subprocess calling bash script - need to print the quotes out too

description: Python subprocess calling bash script - need to print the quotes out too


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fg = plt.figure(1); fg.clf()
axx = [fg.add_subplot(4,1,1+i, projection='3d') for i in range(4)]
for ax,azel in zip(axx, [(115,10), (115,-10), (-115,10), (-115,-10)]):
    ax.set_title(u"Azim, elev = {}°, {}°".format(*azel))
    ax.set_zlabel('label text')
    ax.azim, ax.elev = azel
fg.canvas.draw()  # the angles of the text are calculated here

# Read drawn z-label rotations and switch them if needed
for ax in axx:
   ax.zaxis.set_rotate_label(False)
   a = ax.zaxis.label.get_rotation()
   if a<180:
       a += 180
   ax.zaxis.label.set_rotation(a)
   a = ax.zaxis.label.get_rotation() # put the actual angle in the z-label
   ax.set_zlabel(u'z-rot = {:.1f}°'.format(a))
fg.canvas.draw()

plt.show()

rawDescription: Rotating axes label text in 3D matplotlib


code:
import numpy as np
df['incomebracket'] = np.where((df.income >= 100000) & (df.income < 150000), 1, 0)

rawDescription: Create dataframe column based on other column


code: glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

rawDescription: Selecting 3D surfaces with a selection box (in two different ways)


code:
def getI(self):
    M,N = self.shape
    if M == N:
        from numpy.dual import inv as func
    else:
        from numpy.dual import pinv as func
    return asmatrix(func(self))

rawDescription: Scipy inv(A) vs A.I

description: Scipy inv(A) vs A.I


code:
# replace with `soup.findAll` if you are using BeautifulSoup3
for div in soup.find_all("div", {'class':'sidebar'}):
    div.decompose()

rawDescription: Deleting a div with a particlular class using BeautifulSoup


code:
for item in [1,2,3,4]:
    print(item, " ", end="")

rawDescription: How can I suppress the newline after a print statement?

description: Suppress the newline after a print statement


code:
s = 'long string that I want to split up'
indices = [0,5,12,17]
indices.append(None)
parts = [s[indices[i]:indices[i+1]] for i in xrange(len(indices)-1)]

rawDescription: Splitting a string by list of indices

description: Splitting a string by list of indices


rawDescription: Comparing elements between elements in two lists of tuples


code: zip(*a)

rawDescription: Sum Lists' value with corresponding index value in Python


code:
import pandas as pd
tableA= pd.read_csv('tableA.csv')

rawDescription: How do I manipulate pandas DataFrame with a column that has rows with strings that needs spliting

description: Manipulate pandas DataFrame with a column that has rows with strings that needs spliting


code:
def round_nearest(x, a):
    return round(x / a) * a

rawDescription: Python rounding a floating point number to nearest 0.05


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

import math

def ToSI(d):
  incPrefixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
  decPrefixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']

  degree = int(math.floor(math.log10(math.fabs(d)) / 3))

  prefix = ''

  if degree!=0:
    ds = degree/math.fabs(degree)
    if ds == 1:
      if degree - 1 < len(incPrefixes):
        prefix = incPrefixes[degree - 1]
      else:
        prefix = incPrefixes[-1]
        degree = len(incPrefixes)

    elif ds == -1:
      if -degree - 1 < len(decPrefixes):
        prefix = decPrefixes[-degree - 1]
      else:
        prefix = decPrefixes[-1]
        degree = -len(decPrefixes)

    scaled = float(d * math.pow(1000, -degree))

    s = "{scaled} {prefix}".format(scaled=scaled, prefix=prefix)

  else:
    s = "{d}".format(d=d)

  return(s)

if __name__ == "__main__":
  d = 23392342.1
  print(ToSI(d))

rawDescription: Convert float number to string with engineering notation (with SI prefixe) in Python


code:
mydict = {'corrector':0}
mydict['corrector'] = 1

rawDescription: Python how to change the value of a variable on the fly


code:
X[np.ix_(a, b)]
# This is roughly equal to matlab's
X(a, b)

rawDescription: Logical indexing in Numpy with two indices as in MATLAB


code: Table(data, colWidths=[1.9*inch] * 5)

rawDescription: How to resize column to content in ReportLab?

description: Resize column to content in ReportLab


code:
stdin_handle.write(input)
stdout_handle.readline() #gets the processed input

rawDescription: Repeatedly write to STDIN and read STDOUT of a Subprocess without closing it


code:
from itertools import chain

Statistics.chiSqTest(DenseMatrix(
    numRows=crosstab.count(), numCols=len(crosstab.columns) - 1,
    values=list(chain(*zip(*crosstab.drop(crosstab.columns[0]).collect())))
))

rawDescription: Use the result from Cross tab (spark dataframe) for chi-square test in SparkMlib


code: ''.join([random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))])

rawDescription: which random am i looking for to achieve this:

description: Which random am i looking for to achieve this:


code:
class TeleportAbilityMixin(object):
    def teleport(self, destination):
        cost = 20
        if self.mp >= cost:
            # Unpack the x, y coordinates
            self.x, self.y = destination
            self.mp -= cost

class TeleportingMagician(Magician, TeleportAbilityMixin):
    pass

m = TeleportingMagician()
new_location = (10, 5)
m.teleport(new_location)

rawDescription: Sharing Class Variables

description: Sharing Class Variables


code:
from operator import sub
{k:map(sub, d1[k], d2[k]) for k in d1}

rawDescription: subtracting all values in dictionaries were values are list of floats

description: Subtracting all values in dictionaries were values are list of floats


rawDescription: Vectorized version of array calculation

description: Vectorized version of array calculation


rawDescription: How to draw stacked histogram in pandas

description: Draw stacked histogram in pandas


code: np.sum(adj1 == adj2)

rawDescription: Python: Count similar elements of two matrices


code:
elements = []
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
   # will prompt "Enter Element 1: " on the first iteration
   userInput = raw_input("Enter Element %s" % (i+1, ))
   elements.append(userInput)

rawDescription: Generating raw_inputs based on user input? [Python]


code: df

rawDescription: Indexing column values in pandas

description: Indexing column values in pandas


rawDescription: Python decorators compared to CLOS "around" method


code:
class Item(Base):
    id = Column(Integer, primary_key=True)
    title = Column(String)
    date = Column(Date)

rawDescription: mysql sqlalchmey keywords search

description: Mysql sqlalchmey keywords search


code:
def noneCat(*args):
    """
    Concatenate arguments. Treats None as the empty string, though it returns
    the None object if all the args are None. That might not seem sensible, but
    it works well for managing lxml text components.
    """
    for ritem in args:
        if ritem is not None:
            break
    else:
        # Executed only if loop terminates through normal exhaustion, not via break
        return None

    # Otherwise, grab their string representations (empty string for None)
    return ''.join((unicode(v) if v is not None else "") for v in args)

def unwrap(e):
    """
    Unwrap the element. The element is deleted and all of its children
    are pasted in its place.
    """
    parent = e.getparent()
    prev = e.getprevious()

    kids = list(e)
    siblings = list(parent)

    # parent inherits children, if any
    sibnum = siblings.index(e)
    if kids:
        parent[sibnum:sibnum+1] = kids
    else:
        parent.remove(e)

    # prev node or parent inherits text
    if prev is not None:
        prev.tail = noneCat(prev.tail, e.text)
    else:
        parent.text = noneCat(parent.text, e.text)

    # last child, prev node, or parent inherits tail
    if kids:
        last_child = kids[-1]
        last_child.tail = noneCat(last_child.tail, e.tail)
    elif prev is not None:
        prev.tail = noneCat(prev.tail, e.tail)
    else:
        parent.text = noneCat(parent.text, e.tail)
    return e

rawDescription: lxml strip_tags results in AttributeError

description: Lxml strip_tags results in AttributeError


code:
def char_to_pos(char):
    from string import ascii_lowercase
    try:
        return ascii_lowercase.index(char) + 1
    except ValueError as e:
        pass # no match - do what's sensible here

rawDescription: Python: Use variable as a lookup reference in CSV and return value


code:
my_dict = {frozenset(['key1', 'key2']): 'foo'}
k = frozenset(["key1","key2"])
k2 = frozenset(["key2","key1"])
my_dict[k]
my_dict[k2]

rawDescription: 2D Dictionary or other data structure where order of keys doesn't matter


code:
"""
x = 5
y = x**2
print(x,y)
"""
exec(_)
x, y # above code was executed in current scope, see?

rawDescription: How to test python code containing blank lines in the interpreter

description: Test python code containing blank lines in the interpreter


code: sum(1 for line in file)

rawDescription: Why no len(file) in Python?

description: Why no len(file) in Python


rawDescription: Map list to dictionary according to value from other list


code:
if exam_solution[i] == student_answers[i]:
    i += 1
else:
    questions_missed.append(i+1)

rawDescription: Using two lists to compare elements and creating a list of non-same elements within those two lists?


code:
def some_shared_function(caller, context):
    # ...
    return

class A(bpy.types.Operator):
    (...)
    def execute(self,context):
        some_shared_function(self, context)

class B(bpy.types.Operator):
    (...)
    def execute(self,context):
        # other code here
        some_shared_function(self, context)

rawDescription: Call a function in a class from different class


rawDescription: Is it possible to create a 2D array where the row index is in a reverse order?


code:
d = Dummy()
d.mylist.insert(0, 'tu')
d.save()

d.mylist.remove('tu')
d.save()

d.insert_to_mylist(0, "tu")
d.save()

d.remove_from_mylist('tu')
d.save()

rawDescription: Django ListField with add and remove

description: Django ListField with add and remove


rawDescription: How to handle multiple search condition of xpath in python Element Tree

description: Handle multiple search condition of xpath in python Element Tree


code:
class Boy():
    def __init__(self, age, height):
        self.age    = age
        self.height = height
    def __str__(self):
        return 'age=%d height=%d' % (self.age, self.height)

def create_boy(name):
    age = int(input('enter age for %s: ' % name))
    height = int(input('enter height for %s: ' % name))
    return Boy(age, height)

boynames = []

while(True):
   name = input('enter boy name: ')
   if name == '':
       break
   boynames.append(name)

boys = {}
for boyname in boynames:
    boys[boyname] = create_boy(boyname)

for name, boyinfo in boys.items():
    print('name=%s %s' % (name, boyinfo))

rawDescription: in python is it possible to use/execute a string within a list as an object name

description: In python is it possible to use/execute a string within a list as an object name


rawDescription: How can I iterate through the indices of the list?

description: Iterate through the indices of the list


code:
line_number = 0 # a counter for line number
for line in lines:
  line_number = line_number + 1 # increment counter

rawDescription: Using line.rfind to find a changing variable


code: ['apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana']

rawDescription: How to implement biased random function?

description: Implement biased random function


code:
# Import stuff. This section was simplified.
from psychopy import visual, event, gui  # gui is not used in this script
import random, os, glob
from PIL import Image

pos1 = [-.05,-.05]
pos2 = [.05, .05]

# import two images sequences and randomize in the same order
target = glob.glob("DDtest/targetimagelist1/*")
distractor = glob.glob("DDtest/distractorimagelist1/*")
indices = random.sample(range(len(target)), len(target))  # because you're using python 2
target = map(target.__getitem__, indices)
distractor = map(distractor.__getitem__, indices)

# Create window and stimuli ONCE. Think of them as containers in which you can update the content on the fly.
win = visual.Window(size=(1280, 800), fullscr=True, screen=0, monitor='testMonitor', color=[-1,-1,-1])  # removed a default value
targetstim = visual.ImageStim(win=win, pos=pos2, size=[0.5,0.5])
targetstim.autoDraw = True
distractorstim = visual.ImageStim(win=win, pos=pos1, size=[0.5,0.5])  # removed all default values and initiated without an image. Set autodraw here since you didn't seem to change it during runtime. But feel free to do it where you please.
distractorstim.autoDraw = True

# No need to pack in a function. Just loop immediately. Rather than just showing two stimuli, I've set it to loop over all stimuli.
for i in range(len(target)):
    # set images. OBS: this may take some time. Probably between 20 and 500 ms depending mainly on image dimensions. Smaller is faster. It's still much faster than generating a full Window/ImageStim each loop though.
    distractorstim.image = distractor[i]
    targetstim.image = target[i]

    # Display and wait for answer
    win.flip()
    event.waitKeys(keyList = ['space'])

rawDescription: Shuffle two lists in the same order in python


code:
t = ThreadedServer(TestService, port = 2942,
                protocol_config={"allow_all_attrs":True,
                                 "allow_setattr": True,
                                 "allow_delattr": True,})

rawDescription: using rpyc to update properties on a remote object

description: Using rpyc to update properties on a remote object


code: find_non_uk = lambda x: re.match(pattern, x)

rawDescription: How can I explain the function of filter and lambda in a line of code?

description: Explain the function of filter and lambda in a line of code


rawDescription: Python add a string to all set's elements


code:
import my_file
my_file.dump = my_local_dump_fn

rawDescription: How do I override a function of a python library?

description: Override a function of a python library


code:
from whatever import Home
h = Home(3,3000,2)
h.show_info()

rawDescription: Inheritance and classes

description: Inheritance and classes


code: 'There     is a way'.title()

rawDescription: Python Titlecase a String with exceptions


code:
merged = pd.merge(dfm, df2m, on=['labels', 'index'], how='outer')
merged

rawDescription: Pandas MultiIndex Operations on Sub-Index


rawDescription: argparse argument order

description: Argparse argument order


code:
listOfReview = []
review = {'Positive':0, 'Negative':0, 'Neutral':0}

for i in xrange(0,3979):
    f = open("ReviewsOutput%i.txt" %i, "r")
    myOutput = f.read()
    review['Positive'] = myOutput.count("Positive")
    review['Negative'] = myOutput.count("Negative")
    review['Neutral'] = myOutput.count("Neutral")
    largest = max(review, key=review.get)
    listOfReview.append(largest)
    f.close

rawDescription: Showing up the "variable" not the number Python


code:
class Group(models.Model):
    name = models.CharField(max_length=32, unique=True)
    keywords = models.ManyToManyField(MyKeywords)

    def __unicode__(self):
        return '%s' % (self.name)

class MyKeywords(models.Model):
    name = models.CharField(max_length=32, unique=True)

    def __unicode__(self):
            return self.name

rawDescription: django many to many association

description: Django many to many association


code:
a = np.array(range(24)).reshape((2, 3, 4))
a[make_index(3, 2)]
a[make_index(3, 1)]
a[make_index(3, 0)]

rawDescription: Python: Index an array using the colon operator in an arbitrary dimension


rawDescription: Regex for matching block of text having a similar first line


rawDescription: Extracting a specific PIECE of a line from a textfile(Python)


code:
b = np.zeros((2,2))
b.shape
b.ndim

rawDescription: missing dimension in numpy array shape

description: Missing dimension in numpy array shape


rawDescription: Comparing two files and printing similar lines


code:
import ctypes

libcap = ctypes.cdll.LoadLibrary("libcap.so")
cap_t = libcap.cap_get_file('/bin/ping')
libcap.cap_to_text.restype = ctypes.c_char_p
libcap.cap_to_text(cap_t, None)

rawDescription: How to read file capabilities using Python?

description: Read file capabilities using Python


code:
import webapp2
from google.appengine.ext import ndb
import mimetypes

class Images(ndb.Model):
    file_name = ndb.StringProperty()
    blob = ndb.BlobProperty()

class FileUpload(webapp2.RequestHandler):

    def post(self):

        file_upload = self.request.POST.get("file", None)
        file_name = file_upload.filename
        image = Images(id=file_name, file_name=file_name, blob=file_upload.file.read())
        image.put()

        self.response.headers[b'Content-Type'] = mimetypes.guess_type(image.file_name)[0]
        self.response.write(image.blob)

class ImgServe(webapp2.Requesthandler):

    def get(self, resource):

        image = ndb.Key('Images', resource).get()
        self.response.headers[b'Content-Type'] = mimetypes.guess_type(image.file_name)[0]
        self.response.write(image.blob)

rawDescription: Google App Engine: Storing images in database (Python)


rawDescription: Error while trying to interpolate across rows in pandas dataframe


code:
class Foo(object):
   class_var = {'one': 1}
Foo.class_var
a, b = Foo(), Foo()
a.class_var
b.class_var
a.class_var is b.class_var

rawDescription: Python: Static objects in a class

description: Python: Static objects in a class


code: [' '.join(col).strip() for col in df.columns.values]

rawDescription: Python Pandas - How to flatten a hierarchical index in columns


code:
vertexMatrix = matrix([vertex.x,vertex.y,vertex.z,1])
productMatrix = (vertexMatrix * camMatrix)
pVectSS = vector(prodMatrix[0][0],prodMatrix[0][1],prodMatrix[0][2])

pointX = ((pVectSS.x/(-pVectSS.z))/tan(radians(hFOV/2)))/2.0+.5
pointY = ((pVectSS.y/(-pVectSS.z))/tan(radians(vFOV/2)))/2.0+.5

rawDescription: Checking for bounding box intersections/collisions with a view frustum


code:
class Registered(object):
    _all = set()
    def __init__(self):
        self.__class__._all.add(self)

rawDescription: How to obtain all instances of a class within the current module

description: Obtain all instances of a class within the current module


code: slug = AutoSlugField(populate_from=("column1", "column2"))

rawDescription: django model save - override method not invoked during migrations

description: Django model save - override method not invoked during migrations


code:
def sort_few(lst):
    if len(lst)==2:
        if lst[0] > lst[1]:
            return (lst[1], lst[0])
        else:
            return lst
    else:
        if lst[0] > lst[1]:
            if lst[1] > lst[2]:
                return (lst[2], lst[1], lst[0])
            else:
                return (lst[1], lst[2], lst[0])
        elif lst[1] > lst[2]:
            if lst[2] > lst[0]:
                return (lst[0], lst[2], lst[1])
            else:
                return (lst[2], lst[0], lst[1])
        elif lst[2] > lst[0]:
            if lst[0] > lst[1]:
                return (lst[1], lst[0], lst[2])
            else:
                return lst

rawDescription: Fastest way to sort tiny lists in python


rawDescription: What does [:-1] mean/do in python?

description: What does [:-1] mean/do in python


code:
from setuptools import setup, find_packages

setup(
    name='my_flask_package',
    version='1.0',
    packages=find_packages(),
    install_requires=['flask', 'flask-sqlalchemy'],
)

rawDescription: Share sqlalchemy models between flask and other apps


rawDescription: arrange values in a python 2D array

description: Arrange values in a python 2D array


code:
import numpy as np
import contextlib

@contextlib.contextmanager
def printoptions(*args, **kwargs):
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    yield
    np.set_printoptions(**original)

rawDescription: Pretty-printing of numpy.array

description: Pretty-printing of numpy.array


code: getcontext().prec = 38

rawDescription: Long long data type python

description: Long long data type python


code:
import random

ALPHA = "ATGC"

def randDNA(n):
    return ''.join(random.choice(ALPHA) for i in range(n))

def mutate(strand,times):
    nucleotides = list(strand)
    n = len(strand)
    for i in range(times):
        j = random.randint(0,n-1)
        nucleotides[i] = random.choice(ALPHA)
    return ''.join(nucleotides)

def HammingOne(s,t):
    #assumes s and t are strings of the same length
    #returns True if s,t are Hamming distance 1
    #otherwise returns False

    clashes = 0
    for x,y in zip(s,t):
        if x != y:
            clashes += 1
            if clashes > 1: return False
    return True if clashes == 1 else False

def neighbors(s):
    n = set()
    for i,c in enumerate(s):
        n.update([s[:i] + d + s[(i+1):] for d in ALPHA if d != c])
    return n

def summary(sList, fpSize = 10):
    n = len(sList)
    refString = sList[0]
    ncount = 0 #count of Hamming-neighbors
    position = {}

    for i,c in enumerate(refString):
        position[i] = dict.fromkeys(ALPHA,0)
        position[i][c] += 1

    refPrint = refString[:fpSize]
    s = neighbors(refPrint)
    refTail = refString[fpSize:]

    for strand in sList[1:]:
        fp = strand[:fpSize]
        if (fp == refPrint) and \
           (strand[fpSize:] == refTail or HammingOne(strand[fpSize:],refTail)) or \
           (HammingOne(fp,refPrint) and strand[fpSize:] == refTail):
            ncount += 1
            for i,c in enumerate(strand):
                position[i][c] += 1

    #assemble summary strand

    mode = []
    for i in range(len(refString)):
        c = ALPHA[0]
        m = position[i][c]
        for x in ALPHA[1:]:
            if position[i][x] > m:
                c = x
                m = position[i][x]
        mode.append(c)

    return(ncount,''.join(mode))

#example problem

strand = randDNA(10000)
sList = [mutate(strand,5) for i in range(10000)]

n,s = summary(sList,100)
print(n, "close strands found")
print("First 30 positions in summary strand are ", s[:30])

rawDescription: Would using hash in python speed up string/char comparison?


code:
df_sorted = df.sort_index(ascending=False)
df[df_sorted[(pd.rolling_sum((df_sorted==0), window=2) == 2)].first_valid_index()+1:]

rawDescription: Pandas: complex filtering with apply

description: Pandas: complex filtering with apply


code:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 2)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.download.dir", download_folder)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")

rawDescription: Is there a way to pass an instance of a Selenium Webdriver profile into several functions with Python


code:
import requests
import tempfile

from django.core import files

def download_file_from_url(url):
    # Stream the image from the url
    try:
        request = requests.get(url, stream=True)
    except requests.exceptions.RequestException as e:
        # TODO: log error here
        return None

    if request.status_code != requests.codes.ok:
        # TODO: log error here
        return None

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

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

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

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

    return files.File(lf)

rawDescription: django-allauth: Check whether user signed up using a social account

description: Django-allauth: Check whether user signed up using a social account


code:
ml = max(len(s) for s in stringlist)
result = list(set(s for s in stringlist if len(s) == ml))

rawDescription: Longest strings from list

description: Longest strings from list


rawDescription: NumPy slice notation in a dictionary

description: NumPy slice notation in a dictionary


code:
experience_runner = tf.train.QueueRunner(
    experience, [perceive(game()) for num in range(available_threads)])

rawDescription: How to add dynamically created input images to a RandomShuffleQueue using a QueueRunner in tensor flow

description: Add dynamically created input images to a RandomShuffleQueue using a QueueRunner in tensor flow


rawDescription: How can I merge two nested dictionaries together?

description: Merge two nested dictionaries together


code:
counts = {}
for character in word.upper():
    # count the character.
    counts[character] = counts.get(character, 0) + 1

rawDescription: How to apply a for loop to a string in Python

description: Apply a for loop to a string in Python


code:
['age', 'name']
['age', 'surname', 'name']

rawDescription: Python ConfigParser: how to work out options set in a specific section (rather than defaults)


rawDescription: Python string split multiple brackets

description: Python string split multiple brackets


code:
inds = np.where(~np.isnan(df))
zip(*inds)

rawDescription: Retrive the (index,column) tuple of non nan values


code:
for layerObject in layer_list:
    print(layerObject)
    #Do whatever you want with it.

rawDescription: Saving instances when created by an iterator - Python


code:
filename = "class{}".format(form)       # use string formatting to get the right filename
with open (filename,'a',newline='') as keerthan:    # open the file using a variable name
    foo = csv.writer(keerthan,delimiter=',',)

    if keerthan.tell() == 0:
        bar = ['Name', 'Surname', 'Score']
        foo.writerow(bar)

    bar = [[user,surname, score]]
    foo.writerows(bar)

rawDescription: writing string to a new row

description: Writing string to a new row


code:
u2tourfans.com
tvadsview.com
gfanatic.com
blucigs.com
...
twply.com
sweethomeparis.com
vvchart.com

rawDescription: Python not getting text between html tags


code:
doc = webview.page().mainFrame().documentElement()
option = doc.findFirst('select[name="birthday_m"] > option[value="3"]')

rawDescription: How to choose value from an option list using PyQt4.QtWebKit

description: Choose value from an option list using PyQt4.QtWebKit


code:
s1 = b'abc'
s2 = b'efg'
''.join(chr(ord(i)^ord(j)) for i,j in zip(s1,s2))

rawDescription: Xor bits in python

description: Xor bits in python


code:
import random

def guess(start,limit):
    return random.choice(range(start, limit + 1))

rawDescription: List index out of range even though I'm asking for [0]?


code: months = lambda a, b: abs((a.year - b.year) * 12 + a.month - b.month) + int(abs(a.day - b.day) > 15)

rawDescription: Subtract dates in Django?

description: Subtract dates in Django


rawDescription: Json count elements depending on value of another using Python


code:
#!/usr/bin/env python
from subprocess import Popen, PIPE
from plistlib import readPlist
from pprint import pprint

AirportPath = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport'

proc = Popen([AirportPath, '-s', '-x'], stdout=PIPE)

ssid_data = readPlist(proc.stdout)
pprint(ssid_data)

rawDescription: python parsing wifi SSID data

description: Python parsing wifi SSID data


code: a = bar(5)

rawDescription: python decorator for field

description: Python decorator for field


code:
def __call__(self, cls):
    def init(cls_self, *args, **kw):
        for param, value in zip(self.params, args):
            if param in kw:
                raise TypeError("Multiple values for %s"%param)
            kw[param]=value
        if len(args) > len(self.params) or set(kw) != set(self.params):
            raise TypeError("Wrong number of arguments")
        vars(cls_self).update(kw)
    cls.__init__ = init
    return cls

rawDescription: Create a python function procedurally (specifically the arguments)


rawDescription: Numpy: change max in each row to 1, all other numbers to 0


rawDescription: decision trees from features of multiple datatypes

description: Decision trees from features of multiple datatypes


code:
def block_width(block):
    try:
        return block.index('\n')
    except ValueError:
        return len(block)

def stack_str_blocks(blocks):
    """Takes a list of multiline strings, and stacks them horizontally.

    For example, given 'aaa\naaa' and 'bbbb\nbbbb', it returns
    'aaa bbbb\naaa bbbb'.  As in:

    'aaa  +  'bbbb   =  'aaa bbbb
     aaa'     bbbb'      aaa bbbb'

    Each block must be rectangular (all lines are the same length), but blocks
    can be different sizes.
    """
    builder = []
    block_lens = [block_width(bl) for bl in blocks]
    split_blocks = [bl.split('\n') for bl in blocks]

    for line_list in itertools.izip_longest(*split_blocks, fillvalue=None):
        for i, line in enumerate(line_list):
            if line is None:
                builder.append(' ' * block_lens[i])
            else:
                builder.append(line)
            if i != len(line_list) - 1:
                builder.append(' ')  # Padding
        builder.append('\n')

    return ''.join(builder[:-1])

rawDescription: Displaying a tree in ASCII

description: Displaying a tree in ASCII


code:
from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.setitimer(signal.ITIMER_REAL,seconds) #used timer instead of alarm
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

rawDescription: How to timeout function in python, timeout less than a second

description: Timeout function in python, timeout less than a second


code: head, tail = seq[0], seq[1:]

rawDescription: python head and tail in one line

description: Python head and tail in one line


code: [x['name'] for x in temp[0]['trends'] if x['name'].startswith('#')]

rawDescription: extracting hashtags out of Twitter trending topics data with Python Tweepy

description: Extracting hashtags out of Twitter trending topics data with Python Tweepy


rawDescription: Creating Variables Based Off A String

description: Creating Variables Based Off A String


rawDescription: Adding ith element of two lists

description: Adding ith element of two lists


code: newSentence = ""

rawDescription: Python 3 Pig Latin Sentence

description: Python 3 Pig Latin Sentence


code: df['Time'] = df['Time'].apply(lambda x: x.replace(microsecond=0))

rawDescription: Python: reduce precision pandas timestamp dataframe


code:
message.mail.replace_header("From", from_addresses[0])
message.mail.replace_header("To", to_addresses[0])
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(settings.RECEIPTS_EMAIL_ACCOUNT, settings.RECEIPTS_EMAIL_PASSWORD)
server.sendmail(from_addresses[0], to_addresses, message.mail.as_string())
server.close()

rawDescription: Cannot forward an email with attachments using imap and smtplib


code:
self.exit = False
self.thread = threading.Thread(target=self.run, args=())
self.thread.setDaemon(True)
self.thread.start()

def run(self):
    while self.is_listening:
        cmd = ['application.exe']
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        while proc.poll() is None or not self.exit:
            pass
        data = ""
        while True:
            if self.exit:
                break
            txt = proc.stdout.readline()
            data = txt[5:].strip()
            txt += data

rawDescription: How to run another process in a loop on a different thread

description: Run another process in a loop on a different thread


code:
df
newdf = df.dropna()
result = newdf[(newdf['bookings'] - newdf['rolling_mean']) > (2 * newdf['rolling_std_dev'])]
result

rawDescription: How to return new data frame when using a apply function on old dataframe?

description: Return new data frame when using a apply function on old dataframe


code:
xl = pd.ExcelFile("dummydata.xlsx")
xl.sheet_names
df = xl.parse("Sheet1")
df.head()

rawDescription: Reading an Excel file in python using pandas


code:
for value in customRange(['A1', 'A5']):
    print(value)

A1
A2
A3
A4

rawDescription: Range with alphabets Python

description: Range with alphabets Python