code:
from bs4 import BeautifulSoup
from bs4.element import NavigableString, Tag

def extractNavigableStrings(context):
    strings = []
    for e in context.children:
        if isinstance(e, NavigableString):
            strings.append(e)
        if isinstance(e, Tag):
            strings.extend(extractNavigableStrings(e))
    return strings

soup = BeautifulSoup('''TEXT1 TEXT2 TEXT3 ''')

print(extractNavigableStrings(soup))

rawDescription: How to scrape between span tags using beautifulsoup

description: Scrape between span tags using beautifulsoup


code:
duplicate = []
# Sort the list so we can compare adjacent values
fail.sort()
#if you didn't want to modify the list in place you can use:
#sortedFail = sorted(fail)
#      and then use sortedFail in the rest of the code instead of fail
for i, x in enumerate(fail):
    if i+1 == len(fail):
        #end of the list
        break
    if x[:2] == fail[i+1][:2]:
        if x not in duplicate:
            duplicate.add(x)
        if fail[i+1] not in duplicate:
            duplicate.add(fail[i+1])
# diff is just anything not in duplicate as far as I can tell from the explanation
diff = [d for d in fail if d not in duplicate]

rawDescription: Python List Question

description: Python List Question


code:
def makeSomeNicelyDecoratedSubclass(someclass):
  mcl = type(someclass)
  return mcl('MyNiceName', (someclass,), {'new_attribute':'something'})

rawDescription: Python decorate a class to change parent object type


rawDescription: Evaluation inside string

description: Evaluation inside string


code:
class Program(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self,
                                 application_id="org.example.Foo",
                                 flags=Gio.ApplicationFlags.FLAGS_NONE)
    def do_activate(self):
        print("Activated!")

rawDescription: Python GTK3 inheritance

description: Python GTK3 inheritance


rawDescription: AttributeError when web-scraping data using Python


code:
with open('spectral_data.csv', 'ab') as f:
    writer = csv.DictWriter(f, ('name', 'data'))
    writer.writerow(data[-1])

rawDescription: Python 2.7 exporting data in a .csv

description: Python 2.7 exporting data in a .csv


code:
import clr
clr.AddReference("wx.NET.dll")
from wx import *

class MyFrame1(Frame):
    def __init__(self):
        XmlResource.Get().LoadFrame(self, None, "MyFrame1")
        self.EVT_BUTTON( XmlResource.XRCID("m_button1"), EventListener(self.OnMyButtonClicked) )
    def OnMyButtonClicked(self, sender, e):
        MessageDialog.ShowModal( self, "HELLO WORLD!", "", WindowStyles.DIALOG_OK | WindowStyles.ICON_INFORMATION )
class HelloWorldDemo(App):
    def OnInit(self):
        XmlResource.Get().InitAllHandlers()
        XmlResource.Get().Load( "hello_frame.xrc" )
        f = MyFrame1()
        f.Show()
        return True
def main():
    app = HelloWorldDemo()
    app.Run()
if __name__ == '__main__':
    main()

rawDescription: Developing cross-platform GUIs with IronPython: wx.NET for true native look and feel?


code: from myapi.common import A

rawDescription: What is the most pythonic way to import 'sibling' modules into one another?


rawDescription: Reading words from a file and putting into list


rawDescription: How to set a base template for jinja2 in python?

description: Set a base template for jinja2 in python


code: df.index = pd.to_datetime(df.index, format='%H:%M:%S:%f')

rawDescription: Generating regular time series from irregular time series in pandas


code:
nowFormat = "2014-04-07"
cmd = 'tail -n10000 /opt/rubedo/log/riskserver.'+nowFormat+'*'
os.system(cmd) #this will execute it through your linux shell you should see the output, allthough this call will not give you access to the output in python

rawDescription: Wildcard or * for matching a datetime python 2.7


rawDescription: Round to the nearest 500, Python

description: Round to the nearest 500, Python


rawDescription: Select rows from a DataFrame based on values in a column in pandas


code:
with open('input') as fin, open('output','w') as fout:
    fout.writelines(getlines(fin,'xxxxx\n','yyyyy\n'))
    fout.write('my_line\n')
    fout.writelines(fin)

rawDescription: How to write to a specific line in file in Python?

description: Write to a specific line in file in Python


code:
data = file1.read()
data = data.lower() #make it all lowercase
data = re.sub("[,-]","",data) #replace unwanted punctuation
list1= data.splitlines()

rawDescription: Return matching strings from different txt files containing lists. Each item on new line


code:
with open('ssm_resnik.txt', 'rbU') as uniprot_vs_uniprot:
    reader = csv.reader(uniprot_vs_uniprot, delimiter='\t')
    allVSall = { tuple(r[:2]): float(r[2]) for r in reader }

rawDescription: Computation time insanely long in python


code:
idnum = 11
# The loop and 'if' are good
# You just had the 'break' in the wrong place
for id, idnumber in A.iteritems():
    if idnum in idnumber.keys(): # you can skip '.keys()', it's the default
       calculate = some_function_of(idnumber[idnum])
       break # if we find it we're done looking - leave the loop
    # otherwise we continue to the next dictionary
else:
    # this is the for loop's 'else' clause
    # if we don't find it at all, we end up here
    # because we never broke out of the loop
    calculate = your_default_value
    # or whatever you want to do if you don't find it

rawDescription: Search for a key in a nested Python dictionary


code:
st ={1,2,3}
v = [1,4,5]
st.isdisjoint(v)
v = [7,4,5]
st.isdisjoint(v)

rawDescription: Filtering a dictionary by multiple values


code:
for k,v in d.items():
    print(k,v)
('Bob', 11.5)
('John', 22.0)

rawDescription: CSV in hashtable then calculate sum

description: CSV in hashtable then calculate sum


code:
counts = {}
for animal, food in zip(animals, foods):
    counts.setdefault((animal, food), 0)
    counts[(animal, food)] += 1

rawDescription: storing .csv data in Python

description: Storing .csv data in Python


code: df.pivot_table(index=['Name'], columns=['Car'], aggfunc=len, fill_value=0)

rawDescription: count distinct occurrences in pandas

description: Count distinct occurrences in pandas


code:
s = '12abcd405'
result = ''.join([i for i in s if not i.isdigit()])
result

rawDescription: Removing numbers from string

description: Removing numbers from string


code: sys.modules['path.to.foo'] = ...

rawDescription: Python runtime determine which module to load


rawDescription: Return minimum X (that can contain Y items) for arbitrary number of items


code: index_list = [ item_0, item_1, item_2, ...]

rawDescription: Making a index array from an array in numpy


code:
open('unicode.txt').read()    # has utf-8 BOM
codecs.open('unicode.txt').read()    #without encoding is the same as open
codecs.open('unicode.txt', encoding='utf-8').read()

rawDescription: Word-counter won't print foreign characters


code: objects = Entry.visible_objects.all()

rawDescription: Determine if entry is visible by startdate and enddate


code:
var=['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
sorted(var, key=lambda v: v.upper())

rawDescription: python sort upper case and lower case

description: Python sort upper case and lower case


code:
from pprint import pprint

conversion_factors = {
    'g' : 9.81,
    'cm' : 0.01,
    'bar' : 10**5,
    'mPas' : 10**-3
}

input_processed = {
    'units' : {
        'g' : 'g',
        'dx' : 'cm',
        'po' : 'bar',
        'muo' : 'mPas'
    },
    'g' : 1.0,
    'dx' : [10.0, 20.0, 10.0],
    'muo' : {
        'po' : [0.0, 1.0],
        'muo' : [32.7, 32.7]
    },
    'phi' : 0.05
}

def convert_dict(indata):
    units = indata['units']

    def convert(key, item):
        factor = conversion_factors.get(units.get(key))
        if factor is not None:
            if isinstance(item, list):
                item = [u * factor for u in item]
            else:
                item *= factor
        return item

    outdata = {'units': units.copy()}
    for k, v in indata.items():
        if k == 'units':
            continue
        if isinstance(v, dict):
            outdata[k] = newd = {}
            for k1, v1 in v.items():
                newd[k1] = convert(k1, v1)
        else:
            outdata[k] = convert(k, v)

    return outdata

input_converted = convert_dict(input_processed)
pprint(input_converted)

rawDescription: Modify values in a nested dictionary based on their keys


rawDescription: Substituting only unmasked values in a masked numpy array


code:
import urllib

f = open('local_file_name','wb')
f.write(urllib.urlopen(src).read())
f.close()

rawDescription: web scraping - how to download image into a folder python

description: Web scraping - how to download image into a folder python


code: url = res.history[0].url if res.history else res.url

rawDescription: How to get original url from requests

description: Get original url from requests


code:
with open('131014-data-xy-conv-1.txt', 'r') as f:

    firstline = f.readline()           # read off the first line
    firstvalues = firstline.split(',') # split it on the comma
    xvalues = firstvalues[1:]          # and keep the all but the first elements
    x = np.array(xvalues, int)         # make it an array of integers (or float if you prefer)

rawDescription: How to manipulate the data after numpy.loadtxt?

description: Manipulate the data after numpy.loadtxt


code:
[{'colourCode': 'RE', 'sizeCode': 'XS', 'sku': 'EP01-RE0'},
 {'colourCode': 'RE', 'sizeCode': 'S', 'sku': 'EP01-RE1'},
 {'colourCode': 'RE', 'sizeCode': 'M', 'sku': 'EP01-RE2'},
 {'colourCode': 'RE', 'sizeCode': 'L', 'sku': 'EP01-RE3'},
 {'colourCode': 'RE', 'sizeCode': 'XL', 'sku': 'EP01-RE4'},
 {'colourCode': 'RE', 'sizeCode': '2XL', 'sku': 'EP01-RE5'},
 {'colourCode': 'RE', 'sizeCode': '3XL', 'sku': 'EP01-RE6'}]

rawDescription: python insert or update order of list items

description: Python insert or update order of list items


rawDescription: How to add two Sparse Vectors in Spark using Python

description: Add two Sparse Vectors in Spark using Python


rawDescription: Find files by creation/modification date then moving to another dir in Python


code: multiplications[i, j] = i * j

rawDescription: Is my thought process right?

description: Is my thought process right


code:
maximi = dict.fromkeys(list1, (None, float('-inf')))

for key, nested in dictionary.items():
    for k in nested.keys() & maximi:  # intersection of keys
        if maximi[k][0] is None or dictionary[maximi[k][0]][k] < nested[k]:
            maximi[k] = (key, nested[k])

for value in list1:
    print(value, maximi[value][0])

rawDescription: Find Maximum Value in Nested Dictionary and return Key


rawDescription: How can I turn a csv file into a list of list in python

description: Turn a csv file into a list of list in python


code:
def foo(a, b):
    if not (a and b):  # equivalent of "not a or not b"
        return a or b

foo(False, True)  # produces True
foo(True, True)  # produces None

rawDescription: If else condition with or, return variable that evalutes to FALSE


code: arr[np.arange(len(arr))[:,None], idxs]

rawDescription: How do I sort the rows of a 2d numpy array based on indices given by another 2d numpy array

description: Sort the rows of a 2d numpy array based on indices given by another 2d numpy array


code:
df = DataFrame(randn(10,3),columns=list('ABC'))
df
df[['A','B']].apply(sum)
df[['A','B']].apply(lambda x: x.sum())

rawDescription: Using .apply() with more than 1 df column


code:
my_big_dict = {}
for i in range(0, 10):
    # create your dict
    my_dict= {'A':{'1':'a','2':'b'}}
    my_big_dict.update(my_dict)

rawDescription: Edit Dictionary in python

description: Edit Dictionary in python


code:
params = []
for param in functionNode:
   params.append({'name': xxx})

rawDescription: Dynamically building an "array of strcuts" in Python


rawDescription: how to extract a subset of a colormap as a new colormap in matplotlib?

description: Extract a subset of a colormap as a new colormap in matplotlib


code: newdata = maxwell.rvs(*params, size=100)

rawDescription: Fitting Maxwell-Boltzman distribution in Python


code:
if upload_form.validate_on_submit():
    if upload_form.filename.data.filename is not "":
        filename = secure_filename(upload_form.filename.data.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        # file_path = "imdb/static/pic/" + filename
        upload_form.filename.data.save(file_path)

    movie = Movie(
        title=upload_form.title.data,
        info=upload_form.info.data,
        year=upload_form.year.data,
        filename=file_path if upload_form.filename.data else None,
        rating=5
    )
    db.session.add(movie)
    db.session.commit()
    return 'Registration of movie successful.
Home'

rawDescription: Flask & Wtforms: 400 Bad Request - Submitting upload form


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
    "django.contrib.messages.context_processors.messages",
    "your_app.context_processors.root_url"
)

rawDescription: Current way to get Home URL (Domain) in Django Template?


code: pdf_path = "../pdf/file1.pdf"

rawDescription: Path information for a python application installed in a different folder per users


code: list_ = ["ah", 12, object(), lambda honey: str(honey) ]

rawDescription: Compare attributes of objects inside a list?


code:
import cv
import numpy as np
mat = cv.CreateMat( 3 , 5 , cv.CV_32FC1 )
cv.Set( mat , 7 )
a = np.asarray( mat[:,:] )
a

rawDescription: how to transform a OpenCV cvMat back to ndarray in numpy ？

description: Transform a OpenCV cvMat back to ndarray in numpy ？


rawDescription: Python: Data Structure for Maintaing Tabular Data in Memory?


code:
check_memory(mode_peak = False, mark = '#1 ')
page_size = 10000
a = numpy.zeros(page_size, dtype = 'i4')
i = 0
for element in generate_element():
    if (i != 0) and (i % page_size == 0):
        a.resize(i + page_size)
    a[i] = element
    i += 1
a.resize(i)
check_memory(mode_peak = False, mark = '#2 ')
check_memory(mode_peak = True, mark = '#2 ')

rawDescription: Split of numpy array into unequal chunks


code:
import random

def phn():
    p=list('0000000000')
    p[0] = str(random.randint(1,9))
    for i in [1,2,6,7,8]:
        p[i] = str(random.randint(0,9))
    for i in [3,4]:
        p[i] = str(random.randint(0,8))
    if p[3]==p[4]==0:
        p[5]=str(random.randint(1,8))
    else:
        p[5]=str(random.randint(0,8))
    n = range(10)
    if p[6]==p[7]==p[8]:
        n = (i for i in n if i!=p[6])
    p[9] = str(random.choice(n))
    p = ''.join(p)
    return p[:3] + '-' + p[3:6] + '-' + p[6:]

rawDescription: Making random phone number xxx-xxx-xxxx

description: Making random phone number xxx-xxx-xxxx


code:
with open(self.save_name, 'wb') as output:
    output.write(self.the_data) # insert processing here

rawDescription: Open file and save it in another function with tkinter


rawDescription: Python - How to unmock/reset mock during testing?


code:
import test2
test2.parent = sys.modules[__name__]

rawDescription: Python 3 pyQt4 updating GUI with variables from multiple modules/classes


code:
import lxml.html as lh
import urllib2

def text_tail(node):
    yield node.text
    yield node.tail

url='http://bit.ly/bf1T12'
doc=lh.parse(urllib2.urlopen(url))
for elt in doc.iter('td'):
    text=elt.text_content()
    if text.startswith('Additional  Info'):
        blurb=[text for node in elt.itersiblings('td')
               for subnode in node.iter()
               for text in text_tail(subnode) if text and text!=u'\xa0']
        break
print('\n'.join(blurb))

rawDescription: Parsing HTML with Lxml

description: Parsing HTML with Lxml


rawDescription: python pandas extract unique dates from time series

description: Python pandas extract unique dates from time series


code:
@property
def stb(self):
    """Service request status register."""

    return vpp43.read_stb(self.vi)

rawDescription: Python VISA serial polling function

description: Python VISA serial polling function


rawDescription: Sorting lines by the second word on each line of text file, then displaying it


code:
def intfloatsplit(x):
    i = int(x)
    f = x - i
    return i, f

def prettydegrees(d):
    degrees, rest = intfloatsplit(d)
    minutes, rest = intfloatsplit(60*rest)
    seconds = round(60*rest)
    return "{degrees}° {minutes}' {seconds}''".format(**locals())

rawDescription: Pretty-printing physical quantities with automatic scaling of SI prefixes


code:
import matplotlib.dates as mdates
xfmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)

rawDescription: Python Use data/time as x-axis?

description: Python Use data/time as x-axis


code:
classes.all_classes
classes.input_file
specific_class = classes.all_classes["specific_class_identifier"]
specific_class["specific_quiz_identifier"].avgGrade()

rawDescription: I'm creating a quiz which is for primary school students


rawDescription: re.split on multiple characters (and maintaining the characters) produces a list containing also empty strings

description: Re.split on multiple characters (and maintaining the characters) produces a list containing also empty strings


code:
slots = []
for i in range(NUMCOLS):
  column = []
  for j in range(NUMROWS):
    row = Slot(self.world, i, j)
    column.append(row)
  slots.append(column)

rawDescription: What does this nested for-loops compacted into a single line mean? - python


code: max([max(y) for y in x for x in a])

rawDescription: What does numpy.max function do?

description: What does numpy.max function do


code: df.pivot_table(index=['car_id', 'car_order'], columns=['car_name'], values=['car_rank'],dropna=True, fill_value='')

rawDescription: Pandas Pivot table converts float to int


code:
foo = 123
bar = 123
foo is bar
True
id(foo)
1993000432 # == id(bar)

rawDescription: Why does string equality not working in this Python code as expected?


code:
def add_renderer_globals(event):
    event['c'] = request.tmpl_context
    event['tmpl_context'] = request.tmpl_context

config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender')

rawDescription: Equivalent of template context in Pyramid (pylons user)


rawDescription: python: sort a nested dictionary

description: Python: sort a nested dictionary


code:
class MainController(object):

    def __init__(self):
        self.TVControllers = []
        self.TVControllers.append(TVController("VardagsrumsTV", self))
        self.TVControllers.append(TVController("Köks TV", self))
        print("Welcome to the TV-simulator")

rawDescription: Making classes within classes communicate


code:
import _winreg

def getProxy():
    proxy = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings")
    server, type = _winreg.QueryValueEx(proxy, "ProxyServer")
    enabled, type = _winreg.QueryValueEx(proxy, "ProxyEnable")
    if enabled:
        return server
    return None

rawDescription: Which Python module to use to access the Proxy setting of Windows 7?


code:
class User(Base, UserMixin):
    __table__ = user_table

    ...

    def get_auth_session_token(self):
        return self.auth_session_token

rawDescription: Ensuring single-user per account with flask-login


rawDescription: Selecting only some values from dictionaries in list


code: ind

rawDescription: Interleaving Pandas Dataframes by Timestamp


code:
from textwrap import dedent

s = dedent("""\
           Hello {0}
           Hello1 {0}""")
file_handle.write(s.format("world"))

rawDescription: Python equivalent syntax for verbatim string literal in C#


code:
with open('defs.txt') as f:
    Label = {}
    for line in f:
        line = line.strip()
        if line.startswith('$def'):
            labelKeys = line .split()[1]
            labelValues = labelVal(line)
            Label[labelKeys] = labelValues

rawDescription: Search and replace between two files with search phrase in first file: Python


rawDescription: Python Read Character by Character without printing


code: df.loc[date_sequence, 'column_name'] = value

rawDescription: Python Time Series

description: Python Time Series


code:
def add():
    global n
    n += 1

rawDescription: n+=1 returns 0 python function cannot change variable

description: N+=1 returns 0 python function cannot change variable


code:
from oauth2client.appengine import CredentialsModel
from oauth2client.appengine import StorageByKeyName
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

KEY_NAME = 'your_choice_here'
CREDENTIALS_PROPERTY_NAME = 'credentials'
SCOPE = 'https://www.googleapis.com/auth/drive'

storage = StorageByKeyName(CredentialsModel, KEY_NAME, CREDENTIALS_PROPERTY_NAME)
flow = OAuth2WebServerFlow(
    client_id=YOUR_CLIENT_ID,
    client_secret=YOUR_CLIENT_SECRET,
    scope=SCOPE)

run(flow, storage)

rawDescription: How can I log in to an arbitrary user in appengine for use with the Drive SDK?

description: Log in to an arbitrary user in appengine for use with the Drive SDK


code:
import subprocess

def runflac(idx, data):
    """Use the flac(1) program to convert a music file to FLAC format.

    Arguments:
        idx: track index (starts from 0)
        data: album data dictionary

    Returns:
        A tuple containing the track index and return value of flac.
    """
    num = idx + 1
    ifn = 'track{:02d}.cdda.wav'.format(num)
    args = ['flac', '--best', '--totally-silent',
            '-TARTIST=' + data['artist'], '-TALBUM=' + data['title'],
            '-TTITLE=' + data['tracks'][idx],
            '-TDATE={}'.format(data['year']),
            '-TGENRE={}'.format(data['genre']),
            '-TTRACKNUM={:02d}'.format(num), '-o',
            'track{:02d}.flac'.format(num), ifn]
    rv = subprocess.call(args, stdout=subprocess.DEVNULL,
                        stderr=subprocess.DEVNULL)
    return (idx, rv)

rawDescription: How to process sub-batches of asynchronous jobs?

description: Process sub-batches of asynchronous jobs


code:
func = {
        'large': lambda item: item > 100,
        'small': lambda item: item < 100,
        }[mode]
return [item for item in data if func(item)]

rawDescription: How does Python perform during a list comprehension?


code:
r = br.open('http://www.example.com/html-page-with-dynamic-image-embedded.html')

# Check if HTML content returned ok
if br.response().info()['Content-Type'] == 'text/html; charset=iso-8859-1':
    # Now that the main page is loaded you can open the dynamic image
    r = br.open('http://www.example.com/images/image.php')

    # From here you just treat the image as you wish
    png = r.read()
    f = open('image-new-name.png', 'wb')
    f.write(png)
    f.close()

rawDescription: Python: Save page's dynamic image

description: Python: Save page's dynamic image


code:
# ----------------------- #
# == process_catalogue == #
# ----------------------- #

speaker_stats = 'stats'
def make_catalogue(names_with_dialogue):
    speakers = {}
    for name, dialogue, paragraph in names_with_dialogue:
        speaker = speakers.setdefault(name, {})
        stats = speaker.setdefault(speaker_stats, {})
        stats.setdefault(paragraph, []).extend(dialogue)
    return speakers

word_count = 'word_count'
def sum_words_per_paragraph_items(speakers):
    for speaker in speakers:
        word_stats = speakers[speaker][speaker_stats]
        speakers[speaker][word_count] = Counter()
        for paragraph in word_stats:
            speakers[speaker][word_count][paragraph] += len(word_stats[paragraph])
    return speakers

total = 'total'
def total_word_count(speakers):
    for speaker in speakers:
        wc = speakers[speaker][word_count]
        speakers[speaker][total] = 0
        for c in wc:
            speakers[speaker][total] += wc[c]
    return speakers

rawDescription: Python: How to sum up the word count for each person in a dialogue?


code:
def thumbnail(request, pk):
    thumb_pk = pk
    instance = Model.objects.get(pk=thumb_pk)
    return render_to_response('thumbnail.html',{'instance': instance},context_instance = RequestContext(request))

rawDescription: Django- Imagekit Not Creating Thumbnails


code:
class dd(dict):
   def __init__(self, *a, **k):
     dict.__init__(self, *a, **k)
   def __missing__(self, k):
     addit(self, k)
     return self[k]

def with_dd():
  dc = dd(d)
  for k in range(100):
    lc = dc[k]

rawDescription: Python performance: Try-except or not in?


rawDescription: Convert Datetime object of type: %B %D %Y


code:
class MyModel(models.Model):
    ...
    def save(self, silent=False, *args, **kwargs):
        # Send notification if this is a new instance that has not been saved
        # before:
        if not silent and not self.pk:
            notification.send([self.to_user], 'wedding_invite', {'invitation': self})

        return super(MyModel, self).save(*args, **kwargs)

rawDescription: How to override default create method in django-rest-framework

description: Override default create method in django-rest-framework


code:
from django.views.generic import DetailView
from .models import City

class CityDetailView(DetailView):

    def get_object(self):
        city = City.objects.get(
            slug=self.kwargs.get('city'),
            state__slug=self.kwargs.get('state')
        )
        return city

rawDescription: Clean, name-based urls with class-based views


code:
from pyspark.sql.types import *

sqlContext.createDataFrame(rdd, ["foo", "bar"])

# With full schema
schema = StructType([
    StructField("foo", IntegerType(), False),
    StructField("bar", IntegerType(), False)])
sqlContext.createDataFrame(rdd, schema)

rawDescription: How do I order fields of my Row objects in Spark (Python)

description: Order fields of my Row objects in Spark (Python)


rawDescription: python django partial match regular expression

description: Python django partial match regular expression


code:
def _gen_parts(bits):
    for start in range(0,len(bits),8):
        b = int(bits[start:start+8], base=2)
        if USING_VS_3:
            yield b #bytes takes an iterator of ints
        else:
            yield chr(b)

def bits_to_bytes(bits): # -> (bytes, "leftover")
    split_i = -(len(bits)%8)
    byte_gen = _gen_parts(bits[:split_i])
    if USING_VS_3:
        whole = bytes(byte_gen)
    else:
        whole = "".join(byte_gen)
    return whole, bits[split_i:]

rawDescription: Writing bits as bits to a file

description: Writing bits as bits to a file


code:
fp = open("test.dat", "r")
txt = fp.read()
fp.close()
# Now determine starting and end positions (startpos, endpos)
# ..
# pass text that portion of the text to the fromstring function.
data = np.fromstring(txt[startpos:endpos], dtype=int, sep=" ")

rawDescription: Reading large formatted text file with NumPy


code:
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(s)-1:])]

rawDescription: Encrypt & Decrypt using PyCrypto AES 256


rawDescription: How to extract start and end sites based on capital letter in a sequence?

description: Extract start and end sites based on capital letter in a sequence


code:
class Parent(object):
    __metaclass__ = requireMeta

    def function(self):
        print("Doing Something")

rawDescription: How to enforce (with a warning) that parent functions are called by the children that override them?

description: Enforce (with a warning) that parent functions are called by the children that override them


rawDescription: Deleting consonants from a string in Python


code: field3d_mask[:,:,:] = field2d[np.newaxis,:,:] > 0.3

rawDescription: Mask a 3d array with a 2d mask in numpy

description: Mask a 3d array with a 2d mask in numpy


code:
single_item = lambda i: [y for y in list1[i] if y not in list2[i]]
newlist = [single_item(i) for i in enumerate(list1)]

rawDescription: Python: more readable list comprehension


code:
globaldict = globals() # don't do this - it's just to reflect the question
globaldict.update({'a':1,'b':2,'c':3}) # loop eliminated

rawDescription: Python setattr not working

description: Python setattr not working


code:
args = ["jim", "hello"]
kwargs = {"sender": "s0lder"}
print("tell {0} {sender} says: {1}".format(*args, **kwargs))

rawDescription: Python: Efficient Way to Substitute an Item of a List into a String


code:
def DeactivateAll(self):
    if self._active == 'PAN':
        self.pan('off')
        self.ToggleTool(self.wx_ids['Pan'], False)
    elif self._active == 'ZOOM':
        self.ToggleTool(self.wx_ids['Zoom'], False)
        self.zoom()

rawDescription: Toggling button state on matplotlib NavigationToolbar programmatically


code: df['id'] = df['y'].apply(lambda d: "id_%d" % d)

rawDescription: pandas: apply a function to each unique element in a dataframe column and merge back the output

description: Pandas: apply a function to each unique element in a dataframe column and merge back the output


code: f = open('example.txt', 'r')

rawDescription: How do I print the content of a .txt file in Python?

description: Print the content of a .txt file in Python


code: myDict

rawDescription: Entries in Nested Dictionaries

description: Entries in Nested Dictionaries


code:
def get_clean_string(string, substring):
    while substring in string:
        string = string.replace(substring, '')
    return string

rawDescription: Python, using Selenium how to clean page_source from char like /a0:


code:
#filter  json_object['results']  first, as some of the items are missing the key 'year'

In [33]: results=[x for x in json_object['results'] if 'year' in x]

In [34]: sorted(results,key=lambda x:x['year'])

rawDescription: Sorting JSON data by keys value

description: Sorting JSON data by keys value


code: [x for x in res.split() if "b3640" in x]

rawDescription: How to access a KEGG entry without specifying the organism using bioservices?

description: Access a KEGG entry without specifying the organism using bioservices


code:
def f3(a, s):
    r = []
    if s in a["contents"]:
        if "phrase" not in a:
            a["phrase"] = [s]
        else:
            a["phrase"].append(s)
        r.append(a)
    for b in a["descendent"]:
        r += f(b, s)
    return r

rawDescription: How to look through a phrase in a dictionary?

description: Look through a phrase in a dictionary


code:
r = Recipe.objects.get(id=1)
ingredients = r.ingredient_quantities.all()

rawDescription: Django ManyToMany with through model implementation


rawDescription: Can someone explain mdict in python (scipy.io), for example in scipy.io.savemat()?


code:
rboxPick = ["Default", "Strength", "Dexterity", "Constitution", "Intelligence", "Wisdom", "Charisma"]
labels = ["One", "Two", "Three", "Four"]
self.rollRbs = dict()

#create  the radioBoxes..
for row, label in enumerate(labels):
    lbl = wx.StaticText(panelControl)
    rbox = wx.RadioBox(panelControl, label="Roll %s"%(label),
                       choices=rboxPick)
    sizerControl.Add(rbox ,pos = (row, 1),span=(1,5),
                     flag=wx.EXPAND|wx.LEFT|wx.RIGHT,border = 2)

    self.rollRbs[rbox.GetLabel()] = rbox

#changing the label...
self.rollRbs["Roll One"].SetLabel("blah")

rawDescription: wxpython - Creating Unique GUI Elements With a Loop

description: Wxpython - Creating Unique GUI Elements With a Loop


code: English (en)

rawDescription: How do I display the language name instead of language code in Django?

description: Display the language name instead of language code in Django


code: name = name.rstrip('1')

rawDescription: python - remove text of string

description: Python - remove text of string


code:
class Test:

    def __init__(self, table=[]):
        """(Test, int) -> NoneType
        """
        self.table = [(0, []), (1, []), (2, [])]

    def add_to_table(self, amount):
        """(Test, int) -> NoneType

        Adds to the first table Coin(amount) to Coin(1)

        ex.

        [(0, [Coin(3), Coin(2), Coin(1)]), (1, []), (2, [])]

        """
        self.table[0][1].extend([Coin(n) for n in range(amount, 0, -1)])

class Coin:

    def __init__(self, length):
        """(Coin, int) -> NoneType
        """
        self.length = length

    def __repr__(self):
        return 'Coin(%s)' % (self.length,)

rawDescription: Appending objects to a list

description: Appending objects to a list


code: cur.execute("CREATE INDEX MyLittleIndex ON C(Id)");

rawDescription: Make sqlite3 column update faster

description: Make sqlite3 column update faster


rawDescription: GtkAboutDialog Close Button Bug

description: GtkAboutDialog Close Button Bug


code:
import inspect
def action(one, two, three=3): pass

argspec = inspect.getargspec(action)
dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))

rawDescription: Can I find which parameters are "pre-assigned" in python?

description: Find which parameters are "pre-assigned" in python


code:
contact = Contact.objects.get(pk = 25624)
journalist = Journalist(contact_ptr = contact)
journalist.save()

rawDescription: Django model inheritance problem. How to solve?


code:
#!/usr/bin/env python
from geopy import geocoders # $ pip  install geopy

g = geocoders.GoogleV3()
place, (lat, lng) = g.geocode('Tokyo')
timezone = g.timezone((lat, lng)) # return pytz timezone object
print(timezone.zone)

rawDescription: Getting the current day of another country python


rawDescription: What's wrong with my def function? how to fix it?


code:
if name in class_1:
    class_1[name].append(score)

rawDescription: How to add a value to a key in dictionary in Python

description: Add a value to a key in dictionary in Python


code:
a = [1, 2, 1, 3, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 1, 2]
b = [1, 1, 2, 1, 3, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 3, 1, 2]

from difflib import SequenceMatcher

s = SequenceMatcher(None, a, b, autojunk=False)

matched_element_indices = []
for m in s.get_matching_blocks():
    matched_element_indices += [(m.a+i,m.b+i) for i in range(m.size)]

rawDescription: What is the best approach to matching/joining elements in two non-identical unsorted python lists of different lengths?


code: [(i,j) for (i,j) in zip(a,x)]

rawDescription: Find the indices of elements greater than x


code: number, name = player.span.get_text().strip(), player.span.next_sibling.strip()

rawDescription: Parser returns "\n" instead of desired output.


code:
from string import ascii_letters
from random import choice
''.join(choice(ascii_letters) for _ in xrange(100000))

rawDescription: How to produce an arbitary string with a specific length in python?

description: Produce an arbitary string with a specific length in python


code: f = open('text.txt','wb')

rawDescription: How to print non-ascii characters to file in Python 2.7

description: Print non-ascii characters to file in Python 2.7


code:
import sys, os, pywinauto

app = pywinauto.Application().Start(r'npp.6.8.3.Installer.exe')

Wizard = app['Installer Language']

Wizard.Minimize()
Wizard.NextButton.Click()

Wizard = app['Notepad++ v6.8.3 Setup']

Wizard.Wait('visible')
Wizard.Minimize()

Wizard['Welcome to the Notepad++ v6.8.3 Setup'].Wait('ready')
Wizard.NextButton.Click()

Wizard.Minimize()
Wizard['License Agreement'].Wait('ready')
Wizard['I &Agree'].Click()

Wizard.Minimize()
Wizard['Choose Install Location'].Wait('ready')
Wizard.Button2.Click()

Wizard.Minimize()
Wizard['Choose Components'].Wait('ready')
Wizard.Button2.Click()

Wizard.Minimize()
checkbox = Wizard['Create Shortcut on Desktop'].Wait('enabled')
if checkbox.GetCheckState() != pywinauto.win32defines.BST_CHECKED:
    checkbox.Click()
Wizard.Install.Click()

Wizard['Completing the Notepad++ v6.8.3 Setup'].Wait('ready', timeout=30)
Wizard.Minimize()
Wizard['CheckBox'].Wait('enabled').Click()
Wizard.Finish.Click()
Wizard.WaitNot('visible')

rawDescription: Python - Control window with pywinauto while the window is minimized or hidden


code: item = test['store'] if 'store' in test else run()

rawDescription: Callable as the default argument to dict.get without it being called if the key exists


code: print (file_contents)

rawDescription: How do I print the content of a .txt file in Python?


rawDescription: Multiplying 2d array by 1d array

description: Multiplying 2d array by 1d array


code:
from string import punctuation

def countInFile(filename):
    with open(filename) as f:
        linewords = (line.translate(None, punctuation).lower().split() for line in f)
        return Counter(chain.from_iterable(linewords))

rawDescription: Efficiently count word frequencies in python


code: [(handler.regex.pattern, handler.handler_class) for handler in self.application.handlers[0][1]]

rawDescription: Is there a way to print the configured route handlers on a tornado web server internally?


code:
import sys
from PySide.QtGui import QLineEdit, QApplication, QVBoxLayout, QWidget
class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)

    def mousePressEvent(self, e):
        self.selectAll()

app = QApplication(sys.argv)
top = QWidget()
layout = QVBoxLayout()
layout.addWidget(MyLineEdit())
layout.addWidget(MyLineEdit())
top.setLayout(layout)
top.show()
app.exec_()

rawDescription: Pyside - Select all text when QLineEdit gets focus


rawDescription: Restrict kivy's TextInput to only ascii characters


code: print (dictionary[newkey])

rawDescription: How to store a list as a dictionary - python

description: Store a list as a dictionary - python


code:
end_time = f.lead(f.col("datetime")).over(w)

duration = (
    f.col("end_time").cast("integer") - f.col("datetime").cast("integer")) / 60

rawDescription: PySpark - Combining Session Data without Explicit Session Key / Iterating over All Rows


code:
def distance(a, b):
    """Distance between two bases a and b."""
    if a == b:
        return 0
    elif a == "_" or b == "_":
        return 1
    else:
        return 2

rawDescription: consensus score and WSP score in python

description: Consensus score and WSP score in python


code:
if 'test' in sys.argv:
    DATABASES['default'] = {'ENGINE': 'sqlite3'}

rawDescription: How to run Django's test database only in memory?

description: Run Django's test database only in memory


code:
from Tkinter import *

toggle_text = {'Yes': 'OK',
               'No': 'Cancel',
               'OK': 'Yes',
               'Cancel': 'No'}

def toggle():
    button1['text'] = toggle_text[button1['text']]
    button2['text'] = toggle_text[button2['text']]

root = Tk()
frame = Frame(root)
label = Label(frame , text='Example')
textbox = Text(frame)
textbox.insert
button1 = Button(frame , text='Yes', command=toggle)
button2 = Button(frame , text='No', command=toggle)

frame.pack()
label.pack( padx=20 , pady=5 )
button1.pack( padx=10 )
button2.pack( padx=10 )
root.mainloop()

rawDescription: How to change contents of a window depending on user input?

description: Change contents of a window depending on user input


rawDescription: Regular expression cant be extended to find similar pattern in Python


code: CHOICES = [(i,i) for i in range(11)]

rawDescription: Django IntegerField with Choice Options (how to create 0-10 integer options)


code:
import time
from scrapy.item import Item, Field

from selenium import webdriver

from scrapy.spider import BaseSpider

class ElyseAvenueItem(Item):
    name = Field()

class ElyseAvenueSpider(BaseSpider):
    name = "elyse"
    allowed_domains = ["ehealthinsurance.com"]
    start_urls = [
    'http://www.ehealthinsurance.com/individual-family-health-insurance?action=changeCensus&census.zipCode=48341&census.primary.gender=MALE&census.requestEffectiveDate=06/01/2013&census.primary.month=12&census.primary.day=01&census.primary.year=1971']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)
        el = self.driver.find_element_by_xpath("//input[contains(@class,'btn go-btn')]")
        if el:
            el.click()

        time.sleep(10)

        plans = self.driver.find_elements_by_class_name("plan-info")
        for plan in plans:
            item = ElyseAvenueItem()
            item['name'] = plan.find_element_by_class_name('primary').text
            yield item

        self.driver.close()

rawDescription: Python data scraping with Scrapy

description: Python data scraping with Scrapy


code:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
checkout = subparsers.add_parser('checkout', aliases=['co'])
checkout.add_argument('foo')
parser.parse_args(['checkout', 'bar'])

rawDescription: gem/git-style command line arguments in Python

description: Gem/git-style command line arguments in Python


code:
while responses and math.isnan(responses[-1]):
    responses.pop()

rawDescription: Python: remove repeated values only if at end of list


code: res = lambda x: all(map(test, x))

rawDescription: How to make my code more Pythonic?

description: Make my code more Pythonic


code: read, write = os.pipe()

rawDescription: Twisted pipe two processes with spawnProcess


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import itertools as IT
np.random.seed(2015)

N = 6
x, y = np.random.randint(100, size=(2,N))
colors = np.linspace(0, 1, N)
gs = gridspec.GridSpec(4, 2)
ax = plt.subplot(gs[0, :])
ax.scatter(x, y, s=200, c=colors)

for k, coord in enumerate(IT.product(range(1,4), range(2))):
    i, j = coord
    ax = plt.subplot(gs[i, j], sharex=ax, sharey=ax)
    ax.scatter(x[k], y[k], s=200, c=colors[k], vmin=0, vmax=1)
plt.tight_layout()
plt.show()

rawDescription: With MatPlotLib, how do I apply autoscaled axes from one graph to a separate graph?


code:
{'caption': '',
 'cinematography': '',
 'director': 'Sameer Butt',
 'distributor': '',
 'editing': '',
 'image': '',
 'music': 'Robin Ghosh',
 'name': 'Badmash Gujjar',
 'producer': '',
 'released': 'Film date2001',
 'starring': 'Saima
Shaan (actor)Shaan
',
 'writer': 'Nasir Adeeb'}

rawDescription: Remove repeated elements from list and HTML Tag


code:
try:
    session.add(value)
    session.commit()
except IntegrityError:
    session.rollback()

rawDescription: How to avoid adding rows to SQLAlchemy if value didn't change since last entry?

description: Avoid adding rows to SQLAlchemy if value didn't change since last entry


code:
from operator import eq
print(sum(map(eq, line1, line2))) # 3

rawDescription: Position based matching of 2 strings

description: Position based matching of 2 strings


code:
import pygame
x,y = pygame.mouse.get_pos()
pygame.mouse.set_pos([x+1,y+1])
pygame.mouse.set_pos([x,y])

rawDescription: PyGame Moniter dimming during game

description: PyGame Moniter dimming during game


code: reduce(lambda x, y: {y: x}, reversed(keys), value)

rawDescription: Create Nested Python Dictionary From Tuple of Keys


code:
from django.shortcuts import render

def create_a_my_model(request):
    ...
    return render(request, 'template.html', c)

rawDescription: Django Forms vs Templates

description: Django Forms vs Templates


code: new_data = {k: v for k, v in data.iteritems() if v[0] <= 30}

rawDescription: deleting entries in a dictionary based on a condition

description: Deleting entries in a dictionary based on a condition


code: x = 'foo,bar'.split(',')

rawDescription: How to return more than one value over multiple lines

description: Return more than one value over multiple lines


code:
dict = {}
for p in products:
    dict[p.get_type_display()] = 1 + dict.get(p.get_type_display(), 0)

ret = [[key,value] for key,value in dict.iteritems()]

rawDescription: Sort list elements belonging to enumerable object


code:
deleg = getattr(self,'elem_' + str(root.tag))
deleg(tree)

description: Lxml[.objectify] documentElement tagName


code:
shv="abcdef"
[shv[i:i+2] for i in range(0, len(shv)-1, 2)]
[shv[i:i+3] for i in range(0, len(shv)-2, 3)]

rawDescription: Return a list of string letters grouped by two


rawDescription: How to select multiple non-contigous columns from a list into another dataframe in python

description: Select multiple non-contigous columns from a list into another dataframe in python


code:
@register.inclusion_tag("yourapp/preview_list.html")
def ticket_preview_list():
    return {'object_list': Request.objects.all()}

rawDescription: Django - Have a class based view and Crispy form parrallell to each other on same page


code: myNumber = dictionary.get('myNumber') or 3

rawDescription: What is the python equivalent of 'var myNumber = dictionary['myNumber'] || 3


code:
import csv
from datetime import datetime

FORMAT = '%d/%m/%Y'

def load_list(filename):
    my_list = []
    with open(filename, "rU") as f:
        reader = csv.reader(f)
        for line in reader:
            my_list.append([line[0], datetime.strptime(line[1], FORMAT)])
    return my_list

def save_list(filename, my_list):
    with open(filename, "w") as f:
        writer = csv.writer(f)
        for item in my_list:
            writer.writerow([item[0], item[1].strftime(FORMAT)])

my_list = load_list('input.txt')
save_list('output.txt', my_list)

rawDescription: Saving list from python to text file in format


code:
var1 = 1
var2 = 2
call(['bash', 'run.sh', str(var1), str(var2)])

rawDescription: Pass a variable from python to shell script


code:
resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
sessionToken = resp['Credentials']['SessionToken']

rawDescription: How do I secure an AWS API Gateway with Cognito?

description: Secure an AWS API Gateway with Cognito


code:
nums = [substring.split(',') for substring in s.split()]
for row in nums:
    row[1] = '0'

rawDescription: Is there an elegant and concise syntax to do this in Python?


rawDescription: Python: search in file with multiple criteria


code:
from datetime import datetime
date_format = "%m/%d/%y %H:%M:%S"
datetime.strptime('12/28/13 16:49:19', date_format)

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


code: msg = MIMEMultipart('alternative')

rawDescription: Python-sent MIME email attachments not showing up in mail.live


rawDescription: Matplotlib changing axis ticks

description: Matplotlib changing axis ticks


code: raw_input("Press Enter to continue...")

rawDescription: Tell python to wait/pause a for loop

description: Tell python to wait/pause a for loop


code:
urls = ['http://123.45.67.89/asodibfo3ribawoifbadsoifasdf3/v.html',
        'http://123.45.67.89/alwefaoewifiasdof224a/v.html',
        'http://123.45.67.89/baoisdbfai235oubodsfb45/v.html',
        'http://123.45.67.89/i/0123/12345/aoief243oinsdf.jpg']

[i for i in urls if i.endswith('html')]

rawDescription: Using Regular Expressions to extract specific urls in python


code:
# ab_setup.py
import boto.swf.layer2 as swf

DOMAIN = 'stackoverflow'
ACTIVITY1 = 'ServerAActivity'
ACTIVITY2 = 'ServerBActivity'
VERSION = '1.0'

swf.Domain(name=DOMAIN).register()
swf.ActivityType(domain=DOMAIN, name=ACTIVITY1, version=VERSION, task_list='a_tasks').register()
swf.ActivityType(domain=DOMAIN, name=ACTIVITY2, version=VERSION, task_list='b_tasks').register()
swf.WorkflowType(domain=DOMAIN, name='MyWorkflow', version=VERSION, task_list='default_tasks').register()

rawDescription: Using Amazon SWF To communicate between servers


code: print(''.join(hex(letter) for letter in x))

rawDescription: Show hex value for all bytes, even when ASCII characters are present


code: [df[k]==v for k,v in di.iteritems()]

rawDescription: pandas: select all rows matching multiple conditions

description: Pandas: select all rows matching multiple conditions


code:
from __future__ import print_function
import re

REGEXP = re.compile(r'(\w+)/(\(.*?\))')

def main():
    words = {}

    with open('E:\\mach.txt', 'r') as fp:
        for line in fp:
            for item, category in REGEXP.findall(line):
                words.setdefault(category, {}).setdefault(item, 0)
                words[category][item] += 1

    with open('result.txt', 'w') as fp:
        for category, words in sorted(words.items()):
            print(category, file=fp)
            for word, count in words.items():
                print(word, count, sep=' ', file=fp)
            print(file=fp)
    return 0

if __name__ == '__main__':
    raise SystemExit(main())

rawDescription: word count problem

description: Word count problem


code:
import pandas as pd
df = pd.read_excel("abc.xls", skiprows=4)
df

rawDescription: Parse Excel Report

description: Parse Excel Report


code:
hello111
hello450
hellonice
goodbye111
goodbye450
goodbyenice
foo111
foo450
foonice
hellocan
hellobe
helloof
hellodifferent
hellosizes
goodbyecan
goodbyebe
goodbyeof
goodbyedifferent
goodbyesizes
foocan
foobe
fooof
foodifferent
foosizes
hello111can
hello111be
hello111of
hello111different
hello111sizes
hello450can
hello450be
hello450of
hello450different
hello450sizes
hellonicecan
hellonicebe
helloniceof
hellonicedifferent
hellonicesizes
goodbye111can
goodbye111be
goodbye111of
goodbye111different
goodbye111sizes
goodbye450can
goodbye450be
goodbye450of
goodbye450different
goodbye450sizes
goodbyenicecan
goodbyenicebe
goodbyeniceof
goodbyenicedifferent
goodbyenicesizes
foo111can
foo111be
foo111of
foo111different
foo111sizes
foo450can
foo450be
foo450of
foo450different
foo450sizes
foonicecan
foonicebe
fooniceof
foonicedifferent
foonicesizes

rawDescription: want to combine every element of a list with every element of n lists

description: Want to combine every element of a list with every element of n lists


code:
s_code = "func(cmd, param1, param2, param3, param4)"
pat_recognize_args = re.compile(r'func\(cmd([^)]*)\)')
pat_parse_args = re.compile(r'[, ]+([^, ]+)')

m = pat_recognize_args.search(s_code)
if m:
    s = m.group(1)
    lst = re.findall(pat_parse_args, s)

rawDescription: RegEx in Python matching multiple substrings using one group


code: fourier_transform(f*Heaviside(x), x, k)

rawDescription: Sympy Fourier Transform of exponential decay


rawDescription: make only left subplots and bottom subplots (in MxN panels) contain x and y axis labels

description: Make only left subplots and bottom subplots (in MxN panels) contain x and y axis labels


code:
i = "original"

def print_i1():
    print(i) # prints "changed" when called below

def print_i2(s=i): #default set at function creation, not call
    print(s) # prints "original" when called below

i = "changed"
print_i1()
print_i2()

rawDescription: lambda function acessing outside variable

description: Lambda function acessing outside variable


rawDescription: Reduce dimensionality in pandas.Panel

description: Reduce dimensionality in pandas.Panel


code:
rooms = {
    1 : {   "name"  :   "Hall"  },
    2 : {   "name"  :   "Bedroom" },
    3 : {   "name"  :   "Kitchen" },
    4 : {   "name"  :   "Bathroom" }
}

rawDescription: Invalid Syntax in Python for RPG game

description: Invalid Syntax in Python for RPG game


code:
def foo(bar, baz, spam='eggs', **kw): pass

import inspect
inspect.getargspec(foo)
inspect.getargspec(foo).args

rawDescription: How to check which arguments a function/method takes?

description: Check which arguments a function/method takes


code:
import pattern.en as en
base_form = en.lemma('ate') # base_form == "eat"

rawDescription: How to un-stem a word in Python?

description: Un-stem a word in Python


rawDescription: numpy selecting every other n entries

description: Numpy selecting every other n entries


code: list(cdict for cdict in my_list if cdict["task"] == key)

rawDescription: Python: Find dict in array based on value of key


code:
import sys
# calculcate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

rawDescription: Best way to return a value from a python script

description: Return a value from a python script


code: mockfun = mock.Mock(spec=specfun, func_code=specfun.func_code)

rawDescription: Mocking function argument names to work with inspect.getargspec


code: np.argwhere((Ax == Bx.min()) & (Ay == By.min()))

rawDescription: Where do two 2-D arrays begin to overlap each other?


code:
def __makeThumbnail(dbtable,ImageID,image_size=(600,600), thumbnail_size=(260,260)):
    try:
        thisImage=db(dbtable.id==ImageID).select()[0]
        from PIL import Image
    except: return

    full_path = path.join(request.folder,'static','images', thisImage.file)
    im = Image.open(full_path)
    im.thumbnail(image_size,Image.ANTIALIAS)
    im.save(full_path)
    thumbName='thumb.%s' % (thisImage.file)
    full_path = path.join(request.folder,'static','images', 'thumbs',thumbName)
    try:
        im.thumbnail(thumbnail_size,Image.ANTIALIAS)
    except:
        pass
    im.save(full_path)
    thisImage.update_record(thumb=thumbName)
    return

rawDescription: How to change the format of an Image upload field in Web2py?

description: Change the format of an Image upload field in Web2py


code:
for n in range(4):
    newImage.setPixel(4*r, 4*c+n, pixel)

rawDescription: Rescale an Image using Python3.2

description: Rescale an Image using Python3.2


rawDescription: How can I print 4 bytes as an integer

description: Print 4 bytes as an integer


code:
out = [[]]
for element in lst:
    out[-1].append(element)
    if predicate(element):
        out.append([])

rawDescription: Pythonic way to split a list after elements for which a given predicate is true


rawDescription: Importing dictionary from a different path in my project


code: c.create_text(xcor1, ycor1,fill='grey')

rawDescription: Tkinter in python- why can I not create text?


rawDescription: Python regex for detecting additions

description: Python regex for detecting additions


code:
result = {}
seen = set()
for (key, value) in the_list:
    if key not in result:
        result[key] = value
    elif key not in seen:
        result[key] = [result[key], value]
        seen.add(key)
    else:
        result[key].append(value)

rawDescription: converting a list of lists ina dictionary where inner lists are key-value pairs

description: Converting a list of lists ina dictionary where inner lists are key-value pairs


code: yfit = func(xdata, *popt)

rawDescription: Curve fitting in Python using scipy

description: Curve fitting in Python using scipy


code:
df = pd.DataFrame({'Postcode':['EC4', 'EC12', 'WC1']})
codemap = {'WC1': 'Center', 'EC4': 'Center', 'EC12': 'Eastern'}
df['Postcode'].map(codemap)

rawDescription: How to find strings in pandas

description: Find strings in pandas


code:
t = timeit.Timer("from __main__ import t_df, dateutil; map(dateutil.parser.parse, t_df.index.values)")
np.mean(t.repeat(10, number=1))
t = timeit.Timer("from __main__ import t_df, dateutil; t_df.index.map(dateutil.parser.parse)")
np.mean(t.repeat(10, number=1))
t = timeit.Timer("from __main__ import t_df, datetime; t_df.index.map(lambda x: datetime.strptime(x, \"%Y-%m-%d %H:%M:%S\"))")
t = timeit.Timer("from __main__ import t_df, np; map(np.datetime_, t_df.index.values)")
np.mean(t.repeat(10, number=1))
t = timeit.Timer("from __main__ import t_df, np; map(np.datetime64, t_df.index.values)")
np.mean(t.repeat(10, number=1))

rawDescription: Python Pandas: What is the fastest way to create a datetime index?


code:
from collections import defaultdict

def get_phrases(fle):
    phrase_dict = defaultdict(list)
    with open(fle) as ph:
        for line in map(str.rstrip, ph):
            k, _, phr = line.partition(" ")
            phrase_dict[k].append(line)
        return phrase_dict

from itertools import chain

def replace(fle, dct):
    with open(fle) as f:
        for line in f:
            phrases = sorted(chain.from_iterable(dct[word] for word in line.split()
                             if word in dct) ,reverse=1, key=len)
            for phr in phrases:
                  line = line.replace(phr, phr.replace(" ", "_"))
            yield line

rawDescription: Fastest way to replace space for underscore for a list of words in text


code: self.wavelength = wavelength_val

rawDescription: Using Eval in Python to create class variables


code:
print_dict(v, indent + "  ", depth=depth + 1, max_depth=max_depth)
print_dict(dict(i), indent + "  ", depth=depth + 1, max_depth=max_depth)

rawDescription: python ordereddict: access certain depth within dict

description: Python ordereddict: access certain depth within dict


code:
# Proxy and user/password
br.set_proxies({"http": "joe:password@myproxy.example.com:3128"})

# Proxy
br.set_proxies({"http": "myproxy.example.com:3128"})
# Proxy password
br.add_proxy_password("joe", "password")

rawDescription: Programmatic Web Browsing via a Proxy

description: Programmatic Web Browsing via a Proxy


code:
from sqlalchemy.sql import text
s = text(
    "SELECT users.fullname || ', ' || addresses.email_address AS title "
        "FROM users, addresses "
        "WHERE users.id = addresses.user_id "
        "AND users.name BETWEEN :x AND :y "
        "AND (addresses.email_address LIKE :e1 "
            "OR addresses.email_address LIKE :e2)")

rawDescription: Python, SQLAlchemy pass parameters in connection.execute


code:
a0, a1 = df0.align(df1)
different = (a0 != a1).any(axis=1)
comp = a0[different].join(a1[different], lsuffix='_old', rsuffix='_new')
comp
comp.to_excel("comparison.xls")

rawDescription: Compare records of 1 column from 2 different Excel files, report what is missing or added


rawDescription: Python - Can't create instances from a list or random instances


code:
def func():
    # This is equivalent to:  return (1, 2)
    return 1, 2
func()
type(func())
a,b = func()
a
b
a = func()[0]
a
b = func()[1]
b

rawDescription: How do I satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function?

description: Satisfy the Unused Variable rule from PEP8 if I don't need a variable returned by a function


code:
first_integer = input("Please enter the first integer: ")
second_integer = input("Please enter the second integer: ")
third_integer = input("Please enter the third integer: ")
fourth_integer = input("Please enter the fourth integer: ")

integer1 = int(first_integer)
integer2 = int(second_integer)
integer3 = int(third_integer)
integer4 = int(fourth_integer)

min_number = min(integer1, integer2, integer3, integer4)
max_number = max(integer1, integer2, integer3, integer4)
mid_number_min = min(max(integer1, integer2), max(integer2, integer3),
                     max(integer3, integer4), max(integer1, integer3),
                     max(integer1, integer4), max(integer2, integer4))
mid_number_max = max(min(integer1, integer2), min(integer2, integer3),
                     min(integer3, integer4), min(integer1, integer3),
                     min(integer1, integer4), min(integer2, integer4))

print (min_number, mid_number_min, mid_number_max, max_number)

rawDescription: I have to sort numbers using only the min() and the max() functions


code:
s = "AbCd"
result = []
for i, a in enumerate(s):
    if a.islower():
        result.append(i)

rawDescription: Detect index of lower case letters

description: Detect index of lower case letters


code:
np.any(nearest_neighbors_kd_tree(x, y, 12) == -1)
np.any(nearest_neighbors_kd_tree(x, y, 13) == -1)

rawDescription: finding nearest items across two lists/arrays in Python

description: Finding nearest items across two lists/arrays in Python


code:
temp = np.eye(len(shape))
[np.arange(j,k) for j,k in zip(temp[i,:],shape)]

rawDescription: python: making array index generation more efficient/elegant

description: Python: making array index generation more efficient/elegant


code:
class APITestCase(unittest.TestCase):

    def _patchObject(self, module_name, **kwargs):
        patcher = patch(module_name, **kwargs)
        mock = patcher.start()

        self.patches.append(patcher)
        return mock

    def setUp(self):
        logging.disable(logging.CRITICAL)
        self.patches = []
        self.session = self._patchObject('components.ApplicationAPI')
        self.database = self._patchObject('txpostgres.txpostgres.Connection')

    def tearDown(self):
        for patcher in self.patches:
            patcher.stop()

rawDescription: How to do unit test on Autobahn applications using Twisted Trial?

description: Do unit test on Autobahn applications using Twisted Trial


code:
data = numpy.genfromtxt('metab_averaged_zscored.csv.csv', delimiter=',', skip_header=1, names=True)
data

rawDescription: reading file into array only turns out the first 3 columns

description: Reading file into array only turns out the first 3 columns


rawDescription: Changing the colour of the tk.optionmenu widget


code:
#!/usr/bin/env python
import json
import sys

numbers = 1.2345, 1e-20
json.dump(numbers, sys.stdout)

rawDescription: Python subprocess.Popen : sys.stdout vs .txt file vs Cpickle.dump


code:
flat_labels = labels[np.concatenate(duplicates)]
# array([2, 3, 3, 2, 0, 0, 0])

rawDescription: Access 1D array with array of lists or arrays


rawDescription: Xenserver API - Create VM's with local storage?


code:
from sklearn import svm
from sklearn import datasets
clf = svm.SVC()
iris = datasets.load_iris()
X, y = iris.data, iris.target
clf.fit(X, y)
import pickle
s = pickle.dumps(clf)
clf2 = pickle.loads(s)
clf2.predict(X[0])
y[0]

rawDescription: scikit learn SVM, how to save/load support vectors?

description: Scikit learn SVM, how to save/load support vectors


code: arr2[ arr1 != 0 ] = numpy.NaN

rawDescription: Compare two numpy arrays and insert nans


code:
from tkinter import messagebox, Label, Button, FALSE, Tk, Entry

username = ("Tom")
password = ("")

def try_login():
    print("Trying to login...")
    if username_guess.get() == username:
        messagebox.showinfo("-- COMPLETE --", "You Have Now Logged In.", icon="info")
    else:
        messagebox.showinfo("-- ERROR --", "Please enter valid infomation!", icon="warning")

#Gui Things
window = Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("Log-In")
window.geometry("200x150")

#Creating the username & password entry boxes
username_text = Label(window, text="Username:")
username_guess = Entry(window)
password_text = Label(window, text="Password:")
password_guess = Entry(window, show="*")

#attempt to login button
attempt_login = Button(text="Login", command=try_login)

username_text.pack()
username_guess.pack()
password_text.pack()
password_guess.pack()
attempt_login.pack()
#Main Starter
window.mainloop()

rawDescription: Tkinter Password System

description: Tkinter Password System


code:
fig, ax = plt.subplots(1, 1, subplot_kw={'projection':'3d'})
xe, ye = np.ix_(xeval, yeval)
ax.plot_surface(xe, ye, H, cmap='Blues', alpha=0.5)
ax.scatter3D(x, y, z, 'ob')

rawDescription: How to generate data for matplotlib filled contour plots given the real coordinates?

description: Generate data for matplotlib filled contour plots given the real coordinates


code:
form = FilterForm(request.args)  # use get for filtering
schools = form.query()
if form.validate():
    schools = form.filter(schools)
return render_template('schools.html', form=form, schools=schools)

rawDescription: SQLAlchemy Flask, match some or all

description: SQLAlchemy Flask, match some or all


code: print (os.getcwd())

rawDescription: How to obtain absolute path via relative path for 'other' project files?

description: Obtain absolute path via relative path for 'other' project files


code:
import timeit

short_strings = ["foo", "bar", "baz"]
long_strings = [s*1000 for s in short_strings]

def concat(a, b, c):
    return a + b + c

def concat_from_list(lst):
    return lst[0] + lst[1] + lst[2]

def join(a, b, c):
    return "".join([a, b, c])

def join_tuple(a, b, c):
    return "".join((a, b, c))

def join_from_list(lst):
    return "".join(lst)

def test():
    print("Short strings")
    print("{:20}{}".format("concat:",
                           timeit.timeit(lambda: concat(*short_strings))))
    print("{:20}{}".format("concat_from_list:",
                           timeit.timeit(lambda: concat_from_list(short_strings))))
    print("{:20}{}".format("join:",
                           timeit.timeit(lambda: join(*short_strings))))
    print("{:20}{}".format("join_tuple:",
                           timeit.timeit(lambda: join_tuple(*short_strings))))
    print("{:20}{}\n".format("join_from_list:",
                             timeit.timeit(lambda: join_from_list(short_strings))))
    print("Long Strings")
    print("{:20}{}".format("concat:",
                           timeit.timeit(lambda: concat(*long_strings))))
    print("{:20}{}".format("concat_from_list:",
                           timeit.timeit(lambda: concat_from_list(long_strings))))
    print("{:20}{}".format("join:",
                           timeit.timeit(lambda: join(*long_strings))))
    print("{:20}{}".format("join_tuple:",
                           timeit.timeit(lambda: join_tuple(*long_strings))))
    print("{:20}{}".format("join_from_list:",
                           timeit.timeit(lambda: join_from_list(long_strings))))

rawDescription: Why is concatenating strings running faster than joining them?


rawDescription: join function of a numpy array composed of string

description: Join function of a numpy array composed of string


rawDescription: wxPython - Align buttons in an expanding sizer

description: WxPython - Align buttons in an expanding sizer


code:
_columns = {
    'name': fields.char('Name'),
    'partner_rel_ids': fields.one2many('partner_course_rel', 'course_id'),
}

rawDescription: How to add and show some attributes to a many2many relationship (OpenERP7)?

description: Add and show some attributes to a many2many relationship (OpenERP7)


code:
def tosequence(it):
    """Turn iterable into a sequence, avoiding a copy if possible."""
    if not isinstance(it, collections.Sequence):
        it = list(it)
    return it

rawDescription: Correct way to iterate twice over a list?


rawDescription: Getting selected text (python-gtk)

description: Getting selected text (python-gtk)


code:
s = Mtx.sum(0)
newMtx = Mtx[:,(s.A > 0)[0]]

rawDescription: slicing a matrix in python vs matlab

description: Slicing a matrix in python vs matlab


code:
import lxml.html as lh
import requests

url = 'http://www.wordreference.com/es/translation.asp?tranword=crane'

response = requests.get("http://www.wordreference.com/es/translation.asp?tranword=crane")
doc = lh.fromstring(response.content)

trans = doc.xpath('//td[@class="ToWrd"]/text()')
for i in trans:
    print(i)

rawDescription: Problems crawling wordreference

description: Problems crawling wordreference


rawDescription: Assignment to discontinuous slices in python


code:
def cross(a, b):
    return P3d(a.y*b.z - a.z*b.y,
               a.z*b.x - a.x*b.z,
               a.x*b.y - a.y*b.x)

rawDescription: Getting local 2D coordinates of vertices of a planar polygon in 3D space


code: __update_twitter('I am tweeting')

rawDescription: Django Tweepy File

description: Django Tweepy File


code: 'length %d, slope %d' % (length, slope)

rawDescription: python3.4.2 how to assign a string with texts and variables

description: Python3.4.2 how to assign a string with texts and variables


code: pd.to_datetime(test1['Received']).apply(lambda x: dt.datetime.strftime(x, '%y/%m/%d %H:%M:%S'))

rawDescription: How to rearrange a date in python

description: Rearrange a date in python


code: getattr(MSWord.Documents, "Close")

rawDescription: Problem with exiting a Word doc using Python


code:
def disp_plot(texts, terms):
    concat_text = ''.join(texts.values())
    tokens = nltk.word_tokenize(concat_text)
    text = nltk.Text(tokens)
    pylab_orig_show = pylab.show
    pylab.show = my_show
    text.dispersion_plot(terms)
    pylab.show = pylab_orig_show

rawDescription: How do I send NLTK plots to files?

description: Send NLTK plots to files


code:
class RedirectWWW(webapp2.RequestHandler):
    def get(self, *args, **kwargs):
        url = self.request.url.replace(self.request.host, 'domain.com')
        return self.redirect(url, permanent=True)

    def post(self, *args, **kwargs):
        return self.get()

rawDescription: How to do SEO Url changes and Redirects for google AppEngine Webapp2 Urls?

description: Do SEO Url changes and Redirects for google AppEngine Webapp2 Urls


code:
(14, 1, 'http://www.spiegelfechter.com/wordpress/8726/auswege-aus-der-sackgasse#comments')
(26, 1, 'http://www.spiegelfechter.com/wordpress/8722/die-asozialen-hinter-die-asozialen#comments')
(77, 4, 'http://www.spiegelfechter.com/wordpress/8717/in-gesetz-gegossene-verfassungswidrigkeit#comments')
(91, 1, 'http://www.spiegelfechter.com/wordpress/8714/the-same-procedure-as-every-year-europa-lugt-sich-selbst-in-die-tasche#comments')
(279, 2, 'http://www.spiegelfechter.com/wordpress/8709/konstruktionsfehler-des-grundeinkommens#comments')

rawDescription: Python: Get flattr count

description: Python: Get flattr count


code:
nx.draw(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')

rawDescription: NetworkX: Drawing Graph

description: NetworkX: Drawing Graph


code:
import thread

d = dict()
m = thread.allocate_lock()

def foo():
    m.acquire_lock()
    print(d['key'])

def bar():
    d['key'] = 'value'
    m.release_lock()

if __name__ == '__main__':

    m.acquire_lock()
    t1 = thread.start_new_thread(foo,())
    t2 = thread.start_new_thread(bar,())

rawDescription: Share a dictionary betweeen multiple live threads


code:
import datetime as DT
d1 = DT.datetime(2013, 7, 31, 9, 13, 8, 829)
epoch = DT.datetime(1970, 1, 1)

print(d1.timestamp()) #  python3
# 1375276388.000829
print((d1 - epoch).total_seconds())  # python2
# 1375261988.000829

rawDescription: Microsecond accurate timestamp in python?


code:
def test_form_saves_values_to_instance_user_on_save(self):
    """
    test form saves name, surname, email values to corresponding User object
    when commiting form
    """
    person = Person.objects.get(user__username='admin')
    personform = PersonForm(instance=person, data={'name': 'has_changed'})

    if personform.is_valid():
        person = personform.save()
        self.assertEquals(person.user.first_name, "has_changed")
    else:
        self.fail("personform not valid")

rawDescription: How to test ModelForm save() method saves changes in model?

description: Test ModelForm save() method saves changes in model


rawDescription: Find duplicate items within a list of list of tuples Python


rawDescription: Python WebDriver - can not use send_keys to uploading file to site. API will active file selection window


code: entry_list = [entry.title.text for entry in feed.entry]

rawDescription: Pythonic way to append list of strings to an array


code: b = map(list, zip(*(col for col in zip(*a) if col[0] == 2)))

rawDescription: Create new list based on values taken from sublist


code:
from django.db.models.signals import pre_save
from myapp.models import MyModel
import logging

def my_callback(sender, **kwargs):
    logging.debug("======================================")
pre_save.connect(my_callback, sender=MyModel)

rawDescription: Django pre_save signal does not work

description: Django pre_save signal does not work


code: "from setup import name_1, name_2, name_3"

rawDescription: Run setup code exactly once for different test statements using timeit


code:
a=0; plt.plot(xx, np.arange(1.,nobs+1)/(nobs+a))
plt.show()

rawDescription: ECDF in python without step function?

description: ECDF in python without step function


code:
from lxml import etree

tree = etree.iterparse('aFile.xlf')
for action, elem in tree:
    print("%s: %s %s %s" % (action, elem.tag, elem.text, elem.tail))

rawDescription: parsing xliff file using lxml library

description: Parsing xliff file using lxml library


code: [(u'rider', u'falls', u'backward'), (u'sewed', u'fig', u'leaves'), (u'yield', u'royal', u'dainties'), (u'during', u'mating', u'season'), (u'Salt', u'Sea', u').'), (u'Sea', u').', u'Twelve'), (u'Their', u'hearts', u'failed'), (u'Valley', u').', u'Melchizedek'), (u'doing', u'forced', u'labor'), (u'El', u'Beth', u'El')]

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code: pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)

rawDescription: Matplotlib color according to class labels


code: map(lambda d: {"name": d["name"]}, mine)

rawDescription: Python list of dictionaries projection, filter, or subset?


code:
for thisMatch in re.findall(r"(.+?)	.+?(.+?)	.+?(.+?)	", match3, re.DOTALL):
    print(thisMatch[0], thisMatch[1], thisMatch[2])

rawDescription: how do i loop a re.search for the next data

description: Loop a re.search for the next data


code:
app.conf.update(
  CELERY_TASK_RESULT_EXPIRES=3600,
  CELERY_ROUTES = {'tasks.task1': {'queue': 'queue_name'}},
  CELERY_ACCEPT_CONTENT = ['application/json']
)

rawDescription: How to execute celery task when new message arrives to queue?

description: Execute celery task when new message arrives to queue


code:
globalTotal = 0

class saved_money():

    def set_amount(self, amt):
        global globalTotal
        globalTotal += amt
        self.amount = amt
        return "$"+(format(self.amount, '.2f'))+""

rawDescription: How do you add integer variables from objects?

description: Add integer variables from objects


code:
def page(self):
    yield (
        '
-
'
        ''
    )
    for i in range(10):
        yield ''%i
        time.sleep(1)

rawDescription: Display the result on the webpage as soon as the data is available at server


code:
import csv
from datetime import datetime
from pprint import pprint

def sort_by_datetime(line):
    return datetime.strptime('{0}-{1}-{2}'.format(*line[2:5]), '%Y-%m-%d')

with open('input.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    pprint(sorted(reader, key=sort_by_datetime))

rawDescription: Sort a text file by multiple columns

description: Sort a text file by multiple columns


rawDescription: Python: Get data BeautifulSoup

description: Python: Get data BeautifulSoup


code: next((x[0] for x in lis if x[1]=='bar'), None)

rawDescription: Cleanest way to return a tuple containing a particular element?


rawDescription: Multiple data histogram in python

description: Multiple data histogram in python


rawDescription: Force pyplot to show actual axis values

description: Force pyplot to show actual axis values


rawDescription: How to do groupby in pandas with part of date string?

description: Do groupby in pandas with part of date string


code:
import datetime

my_model = MyModel()
my_model.duration = datetime.timedelta(days=20, hours=10)

rawDescription: How should I use DurationField in my model?


code:
def get_t1():
   return 0

def get_t2():
   return 1

switch={(get_t1(),get_t2()):run}
switch

rawDescription: Is this a "pythonic" method of executing functions as a python switch statement for tuple values?


code: total_seconds = lambda td: (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

rawDescription: Datetime to decimal to pull into matplotlib with Python


code:
def someview(request):
    #Get your number
    #Add to total using total+=number
    return redirect('/your/desired/url')

rawDescription: How do I total values from several instances of one page

description: Total values from several instances of one page


code:
import os

with zipfile.ZipFile(tDir + mainapk[0]) as z:
    with open(os.path.join(tDir, os.path.basename(icon[1])), 'wb') as f:
        f.write(z.read(icon[1]))

rawDescription: Extract a specific file from a zip archive without maintaining directory structure in python


code: soup.find_all('div', id=True)

rawDescription: BeautifulSoup: get elements that have a certain attribute, independent of its value


code:
import matplotlib.pyplot as plt
import cartopy
ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.add_feature(cartopy.feature.COASTLINE)
gridlines = ax.gridlines(draw_labels=True)
ax.text(-0.07, 0.55, 'latitude', va='bottom', ha='center',
        rotation='vertical', rotation_mode='anchor',
        transform=ax.transAxes)
ax.text(0.5, -0.2, 'longitude', va='bottom', ha='center',
        rotation='horizontal', rotation_mode='anchor',
        transform=ax.transAxes)
plt.show()

rawDescription: cartopy set_xlabel set_ylabel (not ticklabels)

description: Cartopy set_xlabel set_ylabel (not ticklabels)


code: os.environ['VARNAME'] = 'value'

rawDescription: switch database by ip or something else

description: Switch database by ip or something else


code:
class Foo:
    def __init__(self):
        self.x = 42;

    def bar(self):
        pass

rawDescription: boost python, using a namespace other than main global

description: Boost python, using a namespace other than main global


code:
first_saturday = next(day for day in
   datecount(datetime(year, 1, 4), timedelta(days=1))
   if day.weekday() == 6)

rawDescription: Finding week of year with week ending on Saturday and first week containing atleast 4 days, in python


rawDescription: In-place type conversion of a NumPy array


code:
orig = pd.read_csv("days1.txt", delim_whitespace=True)
new = pd.read_csv("days2up.txt", delim_whitespace=True)
orig
new

rawDescription: Updating a 2D database (CSV) with other databases in Python?


code:
{'number': 1,
 'question': ...,
 'answer': ...}

rawDescription: Is there a way to attach a 3rd value in Python dictionaries?


code: stdout = an_open_writeable_file_object

rawDescription: What's the difference between subprocess Popen and call (how can I use them)?


code:
def indexes(word, letter):
    return [i for i, c in enumerate(word) if c == letter]

rawDescription: I need help fixing this hangman function


rawDescription: Null a dictionary inside a function in python


code:
from itertools import groupby

for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
    if k:
        indices = list(g)
        new_v = (this_array[indices[0]-1] + this_array[indices[-1]+1]) / 2
        this_array[indices[0]:indices[-1]+1].fill(new_v)

rawDescription: Python: Replacing values in an array

description: Python: Replacing values in an array


code:
def function(bob, sally, **kwargs):
    print(kwargs['p1'])

rawDescription: In python, can you pass variadic arguments after named parameters?


code:
def encode_field(self, field, value):
    """Encode a python field value to a JSON value.

    Args:
      field: A ProtoRPC field instance.
      value: A python value supported by field.

    Returns:
      A JSON serializable value appropriate for field.
    """

    if (isinstance(field, messages.IntegerField) and
        field.variant in (messages.Variant.INT64,
                          messages.Variant.UINT64,
                          messages.Variant.SINT64)):
      if value not in (None, [], ()):

        if isinstance(value, list):
          value = [str(subvalue) for subvalue in value]
        else:
          value = str(value)
        return value

rawDescription: IntegerField() is converted to string in JSON for any number


code: body1 = delimitedList(OneOrMore(~kw + Word(alphas + nums)))('Body')

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

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


code:
def my_func(volume):
    if volume == 777:
        return "buy signal"
    elif volume == 12345:
        return "wait and see"
    else:
        return "nothing"

df['type'] = df.volume.apply(my_func)

rawDescription: Write a loop in Python to print out the words when the condition is valid


code:
for some in settings:
    pprint.pprint(some)

rawDescription: print list of dictonaries to template

description: Print list of dictonaries to template


code: (x.reshape((2, -1), order='f') * y).ravel('f')

rawDescription: How do I multiply corresponding elements in numpy arrays efficiently?

description: Multiply corresponding elements in numpy arrays efficiently


code:
text = 'a,b,c'
text = eval('[' + text + ']')

rawDescription: convert a string to an array

description: Convert a string to an array


code: pandas.read_csv('/tmp/data.csv', converters={'y': lambda x: float(x.replace('.','').replace(',','.'))})

rawDescription: How to efficiently handle european decimal separators using the pandas read_csv function?

description: Efficiently handle european decimal separators using the pandas read_csv function


code: self.values[index] = (self.generators[index].next(), index)

rawDescription: Sort generated numbers using another python generator


code:
hist, xedges, yedges = numpy.histogram2d(x, y, bins=20, range=[[-4, 4], [-4, 4]])

fig = plt.figure()
s = fig.add_subplot(1, 1, 1)
s.set_xlim(-4, 4)
s.set_ylim(-4, 4)
s.imshow(
    hist, interpolation='nearest',
    extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]],
    cmap=matplotlib.cm.viridis)
fig.savefig('t2.png')

rawDescription: How to calculate python 2D scatter points occupied area

description: Calculate python 2D scatter points occupied area


code:
from nltk import sent_tokenize

sentences = [sentence for string in soup.stripped_strings for sentence in sent_tokenize(string)]
sentences2 = [sentence for string in soup2.stripped_strings for sentence in sent_tokenize(string)]

diff = d.compare(sentences, sentences2)
changes = [change for change in diff if change.startswith('-') or  change.startswith('+')]
for change in changes:
    print(change)

rawDescription: Getting more granular diffs from difflib (or a way to post-process a diff to achieve the same thing)


code:
for inp in iter(input, 'quit'):
    print(inp)

rawDescription: Loop with sub assignment in parenthesis

description: Loop with sub assignment in parenthesis


code:
json.dumps(json_data)
json.dumps(json_data, separators=(',', ':'))

rawDescription: Python requests module url encode

description: Python requests module url encode


code:
acids = []
for codon in mutated_codon:
    acids.append(codon_lookup[codon])

rawDescription: How can I do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries?

description: Do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries


code:
pieces = ['a', 'b', 'c']
text = ''.join(pieces)
assert text == 'abc'

rawDescription: How to get mutable string?

description: Get mutable string


code:
from bs4 import BeautifulSoup

data = """

RecurringText

Text1

Text2

Text3

VariableText

"""

soup = BeautifulSoup(data, "html.parser")
for p in soup.find_all(lambda elm: elm and elm.name == "p" and elm.text == "RecurringText" and \
                       "consistent" in elm.get("class") and elm.strong):
    for item in p.find_next_siblings("p"):
        if item.strong:
            break
        print(item.text)

rawDescription: Extract based on instances of nodes

description: Extract based on instances of nodes


code: v.dot(np.rollaxis(a, 2, 1))

rawDescription: Numpy Array Broadcasting with different dimensions


code:
urlpatterns = patterns('',
    (r'^manager$', 'myapp.views.manager_view'),
    (r'^items/(?P<page>[0-9]+)$', 'django.views.generic.list_detail.object_list',
        items_list),
)

rawDescription: How to set-up generic views in an application's urls.py?

description: Set-up generic views in an application's urls.py


rawDescription: Efficiently page query results

description: Efficiently page query results


code:
def ips_in_log(log_name):
   with open(log_name, 'r') as f:
      log = f.read()
   ipcount = sum(1 for _ in re.finditer(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',log))
   print(ipcount)

rawDescription: Python searching for number of IPs in Apache log file


code:
a = 2
l = 5
r = 0.2
wp = (numpy.arange(2**l)[:,None] >> numpy.arange(l)[::-1]) & 1
wp = numpy.hstack([wp.sum(1,keepdims=True), wp])
ws = wp[:, 3:l+3]
re = numpy.zeros((a**l, a**l, a**l))

rawDescription: Performance issue in python with nested loop


rawDescription: Is there a function in python that returns true if all members of an iterable are true?


code: [v.get('path') for v in T.itervalues()]

rawDescription: Get all values from child elements of a dict as a list


code: [[seq[index-3:index+5] for index in [i.start() for i in re.finditer(s, seq)]] for s in l]

rawDescription: Finding a string pattern and printing the following characters for multiple occurrences in Python 3


code:
from subprocess import call
call(["screencapture", "screenshot.jpg"])

rawDescription: How to take Screenshot in Mac OS X from inside of Python: aka Command-Control-Shift-4

description: Take Screenshot in Mac OS X from inside of Python: aka Command-Control-Shift-4


rawDescription: Pandas boolean indexing vs comparision of two lists: Same (?) methods, different results


code:
from django.db.models import Max
Speed.objects.values_list('user').annotate(Max('speed'))

rawDescription: Selecting and sorting on unique foreign key with Django


code:
obj = grid_object()
obj.text
obj.x
obj.y
obj.been_here_before_bool

rawDescription: Global variable. I'm doing something wrong I just don't know what


code:
itemloaded = l.load_item()

# fill url contents
url = sel.select(item_url_xpath).extract()[0]
request = Request(url, callback = lambda r: self.parse_url_contents(r))
request.meta['item'] = itemloaded

yield request

rawDescription: Scrapy - parse a page to extract items - then follow and store item url contents


code:
def splitpoint(a):
    a = np.asarray(a)
    c1 = a.cumsum()
    c2 = a[::-1].cumsum()[::-1]
    return np.argmin(np.abs(c1-c2))

rawDescription: Find the equilibrium point in a numpy array


code:
world
hello

rawDescription: Reading netCDF and creating "virtual / pseudo" csv files


code:
class ClusterAssignment(object):

    def __str__(self):
        return "[string]"

    def __repr__(self):
        # Uses "private" dunder-method.
        return self.__str__()

class ClusterAssignment(object):

    def __str__(self):
        return "[string]"

    def __repr__(self):
        # Uses public interface.
        return str(self)

rawDescription: Specifics of converting a custom __repr__, __str__ on a custom python class


code:
if request.method == 'GET':
    form = MyForm()
else:
    form = MyForm(request.method.POST)
    form.is_valid()

do_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date'))

rawDescription: How to use form values from an unbound form

description: Use form values from an unbound form


code: dis.dis(compile('l = foo()\nfor num in list:pass', '', 'exec'))

rawDescription: Python: function foo() in the "for num in foo()" loop multiple times called?


code:
groupby("sentence", lambda c: c in 'nt')
[(k, list(g)) for k,g in groupby("sentence", lambda c: c in 'nt')]

rawDescription: Efficiently split a string using multiple separators and retaining each separator?


rawDescription: Python: Searching for an int in a list

description: Python: Searching for an int in a list


rawDescription: How to filter by sub-level index in Pandas

description: Filter by sub-level index in Pandas


code:
df2 = df[df.name.isin(name_filter)].pivot(index='ID', columns='name', values='Value').reset_index()
print(df2.to_string(index=False))

rawDescription: How to conditionally transpose in pandas (similar to SQL case when withn group by)

description: Conditionally transpose in pandas (similar to SQL case when withn group by)


rawDescription: Create a stacked 2D histogram using different weights


rawDescription: Plotting interpolated values using LinearNDInterpolator (Python)


rawDescription: python html pop open

description: Python html pop open


code:
import items
...
inp = raw_input("Type the name of the item you want to buy: ")
...
item_class = getattr(items, inp)

user.inventory.append(item_class.__name__)
if hasattr(item_class, strength):
    user.strength += item_class.strength

rawDescription: How to pull information from classes through raw input

description: Pull information from classes through raw input


code:
y = {}
for element in list_of_elements:
  y.update(_myfunction(element))

rawDescription: Python List to Dictionary conversion via Comprehension


code:
def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

rawDescription: Get multiple individual values from generator in Python


rawDescription: Scipy's Optimize Curve Fit Limits

description: Scipy's Optimize Curve Fit Limits


code: lambda x, y, i=int: i(x) * i(y), line1, line2

rawDescription: why is converting strings to ints in my lambda function slower than converting with list comprehension

description: Why is converting strings to ints in my lambda function slower than converting with list comprehension


code:
np.ma.cov(masked_a, masked_b)
np.cov([1,4])  # result of the autocovariance when 2 of the 4 values are masked

rawDescription: Covariance Matrix Python - Omit -9999 Value


rawDescription: Detect process abort

description: Detect process abort


code:
from itertools import imap
import numpy as np

funcs = np.array([lambda x: 2*x, lambda x: 2.5*x])
args = np.array([3.0,4.0])
answer = np.fromiter(imap(lambda func, arg: func(arg), funcs, args),float)
print(answer)

rawDescription: Calling array of functions

description: Calling array of functions


code:
from collections import Counter

results = [
    {"id":1234,"title":"apple"},
    {"id":1235,"title":"orange"},
    {"id":1236,"title":"apple"},
    {"id":1237,"title":"kiwi"},
]

title_counter = Counter()

for result in results:
    title = result["title"]
    title_counter[title] += 1
    if title_counter[title] > 1:
        result["title"] += " " + str(title_counter[title])

for result in results:
    print(result)

rawDescription: Finding dict objects with duplicated key values in array


code:
def openimage():
    picfile = tkFileDialog.askopenfilename()
    canvas.img = ImageTk.PhotoImage(file=picfile)
    canvas.create_image(0,0, anchor=NW, image=canvas.img)

rawDescription: Simple Image viewer

description: Simple Image viewer


rawDescription: alternative regex to match all text in between first two dashes

description: Alternative regex to match all text in between first two dashes


code: sum(masslog/(i+1) for i in range(10000))

rawDescription: Python3, map-function

description: Python3, map-function


code:
import pprint

dictionary = {
    4388464: ['getting'],
    43881: ['got'],
    827862 : ['Taruma', 'Varuna'],
}

d2 = {}

def add_it(d, k, words):
    knum = int(k[0])
    if len(k) == 1:
        d[knum] = {'words': words}
    else:
        dsub = d.setdefault(knum, {})
        add_it(dsub, k[1:], words)

for k, words in dictionary.items():
    add_it(d2, list(str(k)), words)

pprint.pprint(d2)

rawDescription: Split a key that is a string of numbers into single digit keys in Python


code: myiter = (100 if i in (0, 1, 3) else e for i, e in enumerate(mylist))

rawDescription: Replacing selected elements in a list in Python


code: bind('<Button-1>', foo.knight)

rawDescription: Long elif chains vs dictionary with exec()


code:
import os.path
fullpath = '/absolute/path/to/file'
os.path.dirname(fullpath)

rawDescription: Get the directory path of absolute file path in Python


code:
from collections import defaultdict
import csv
import functools
import itertools
import numpy as np

# name_to_id associates a name with an integer 0, 1, ...
name_to_id = defaultdict(functools.partial(next, itertools.count()))

with open('file.csv') as f:
    reader = csv.reader(f)

    # do one pass over the file to get all the IDs so we know how
    # large to make the matrix, then another to fill in the data.
    # this takes more time but uses less memory than loading everything
    # in in one pass, because we don't know how large the matrix is; you
    # can skip this if you do know the number of elements from elsewhere.
    for name_a, name_b, dist in reader:
        idx_a = name_to_id[name_a]
        idx_b = name_to_id[name_b]

    # make the (square) distances matrix
    # this should really be triangular, but the formula for
    # indexing into that is escaping me at the moment
    n_elem = len(name_to_id)
    dists = np.zeros((n_elem, n_elem))

    # go back to the start of the file and read in the actual data
    f.seek(0)
    for name_a, name_b, dist in reader:
        idx_a = name_to_id[name_a]
        idx_b = name_to_id[name_b]
        dists[(idx_a, idx_b) if idx_a < idx_b else (idx_b, idx_a)] = dist

condensed = dists[np.triu_indices(n_elem, 1)]

rawDescription: CSV of Distances to Triangular Distance Matrix in Python


rawDescription: removing duplicates in a string using set and get it back without order

description: Removing duplicates in a string using set and get it back without order


code:
stuff_lock = asyncio.Lock()

def get_stuff(url):
    with (yield from stuff_lock):
        if url in cache:
            return cache[url]
        stuff = yield from aiohttp.request('GET', url)
        cache[url] = stuff
        return stuff

rawDescription: what's Python asyncio.Lock() for?

description: What's Python asyncio.Lock() for


rawDescription: Resizing part of a list in python

description: Resizing part of a list in python


code:
mask = df[['PhaseA','PhaseB','PhaseC']].isin([415,423,427,432]).all(axis=1)
df.ix[mask]

rawDescription: Finding index values in a pandas data frame where columns are the same


rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


code: albums_json = json.dumps(albums_dict)

rawDescription: How to create a JSON file from a NDB database using Python

description: Create a JSON file from a NDB database using Python


code:
with open('arp_table_output.txt','r+') as myArps:
    for line in myArps:
        # select *ONLY* the lines that contain the IP and MAC information in the input file
        if "Dynamic" in line:
            # here we extract the IP and the MAC from the line (python3 syntax)
            ip, _, mac, *_ = [ x for x in line.split(" ") if x ]
            # if you prefer python2: use `x, _, y, _, _, _ = …`

            # Test to printout what works and what does not. If none pass, the "in" test below will fail.
            for target in mac_addr:
                print("'{}' vs '{}' -> {}".format(mac, target, mac == target))

            if mac in mac_addr:
                ipaddr.append(ip)

rawDescription: How do you search each line in a file for all contents of a list?

description: Search each line in a file for all contents of a list


code:
file1.py
def run(self):
    ...
    child_process = subprocess.Popen(args, ...)
    ...
    # time to quit - tell file2 to terminate
    child_process.terminate()

rawDescription: Read data from specific memory address / reference to object


code:
filename
filename_1
filename_2

rawDescription: creating a output file when the output file exists in the path

description: Creating a output file when the output file exists in the path


code:
for category, name in listOfModels:
    perms.setdefault(category, {})[name] = True

rawDescription: Python syntax. Beautiful, right, short code


rawDescription: Can somebody explain why is this datetime comparsion showing output the way it is in python?


code: "aa.bb.cccc.dd.ee".split('.', 3)[2]

rawDescription: Extracting part of a string based on its naming convention


code:
import eg2
while True:
    eg2.my_func()

rawDescription: Importing in Python between three or more files not working


rawDescription: Python Custom List Class - Slicing Self

description: Python Custom List Class - Slicing Self


code:
class PowerDict(dict):
    # http://stackoverflow.com/a/3405143/190597 (gnibbler)
    def __init__(self, parent = None, key = None):
        self.parent = parent
        self.key = key
    def __missing__(self, key):
        self[key] = PowerDict(self, key)
        return self[key]
    def append(self, item):
        self.parent[self.key] = [item]
    def __setitem__(self, key, val):
        dict.__setitem__(self, key, val)
        try:
            val.parent = self
            val.key = key
        except AttributeError:
            pass

a = PowerDict()
a['1']['2'] = 3
print(a)

b = PowerDict()
b['1']['2'].append(3)
b['1']['2'].append(4)
print(b)

a['1']['2'] = b
a['1']['2'].append(5)
print(a['1']['2'])

rawDescription: Python - Append to list nested in dict subclass


code:
def trade_spider():
    os.chdir(r"C:\Users\Independent Auditors Report")
    with stdout2file("auditfeesexpenses.txt"):
        for file in glob.iglob('**/*.html', recursive=True):
            xml = skip_to(file, "<?xml")
            tree = xml.getroot()
            nsmap = {"ix": tree.nsmap["ix"]}
            fractions = xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap)
            for fraction in fractions:
                print(file.split(os.path.sep)[-1], end="| ")
                print(fraction.get("name"), end="| ")
                print(fraction.text, end="|")

rawDescription: Code transformation from BS4 to lxml parser


code:
len_first = len(myList[0]) if myList else None
all(len(i) == len_first for i in myList)

rawDescription: Checking to see if a list of lists has equal sized lists


code:
add_dict = coll.defaultdict(list)
for atom_1, atom_2 in itertools.product(atoms_1, atoms_2):
    if atom_1 == atom_2: continue
    if atom_1 < atom_2:
        add_dict[atom_1].append(atom_2)
    else:
        add_dict[atom_2].append(atom_1)

rawDescription: Python: Optimising a list comprehension which compares two integers


code:
import csv
with open('somepath/file.txt', 'wb+') as outfile:
  w = csv.writer(outfile)
  w.writerow(['header1', 'header2'])
  for k, v in your_dictionary.items(): # eg list or dictionary i'm assuming a list structure
    w.writerow([
      k,
      v,
    ])

rawDescription: Output from function to text/CSV file?

description: Output from function to text/CSV file


code:
Code
from sklearn import mixture
import matplotlib.pyplot
import matplotlib.mlab
import numpy as np
from pylab import *
from scipy.optimize import leastsq

data = np.genfromtxt('gaussian_fit.dat', skiprows = 1)
x = data[:, 0]
y = data[:, 1]

def double_gaussian( x, params ):
    (c1, mu1, sigma1, c2, mu2, sigma2) = params
    res =   c1 * np.exp( - (x - mu1)**2.0 / (2.0 * sigma1**2.0) ) \
          + c2 * np.exp( - (x - mu2)**2.0 / (2.0 * sigma2**2.0) )
    return res

def double_gaussian_fit( params ):
    fit = double_gaussian( x, params )
    return (fit - y_proc)

# Remove background.
y_proc = np.copy(y)
y_proc[y_proc < 5] = 0.0

# Least squares fit. Starting values found by inspection.
fit = leastsq( double_gaussian_fit, [13.0,-13.0,1.0,60.0,3.0,1.0] )
plot( x, y, c='b' )
plot( x, double_gaussian( x, fit[0] ), c='r' )

rawDescription: How to fit a double Gaussian distribution in Python?

description: Fit a double Gaussian distribution in Python


code:
import py
py.test.cmdline.main(args)

rawDescription: How to use py.test from Python?

description: Use py.test from Python