code:
class Map(list):
    def __init__(self, height, width):
        for y in range(height):
            self.append([Square(y, x, tilemap[y][x]) for x in range(width)])
    def get_tile(self, x, y):
        return self[y][x]

rawDescription: Assigning unique names to each square in a game map


code:
plt.pie(x_list, labels=label_list, explode=explode, autopct="%1.1f%%", startangle=90)
plt.title('\n'.join(wrap(title, width=50)), size=12, style='italic')
plt.suptitle('some title', y=0.85, x=0.45) #y and x needed as you have adjusted the subplot size already.

rawDescription: title in italic font in matplotlib isn't working

description: Title in italic font in matplotlib isn't working


code:
(l[0]["address"])
(l[0]["address"]) == u"GENERAL YAGÜE 32"

rawDescription: Python. Same string appearing with different encodings?


code:
for i in xrange(height-1, (height/2)-1, -1):
    mid_pixel_bottom_half = img[i][width/2]
    R, G, B = mid_pixel_bottom_half[2], mid_pixel_bottom_half[1], mid_pixel_bottom_half[0]
    if (R<border_threshold_R) and (G<border_threshold_G) and (B<border_threshold_B):
        bottom_border_height+=1
    else:
        break

rawDescription: Detect if image has border using PIL

description: Detect if image has border using PIL


code:
from ctypes import cdll

libA = cdll.LoadLibrary(some_path)

class A:
    def __init__(self):
        self.obj = libA.A_new()

    def __del__(self):
        libA.delete_A(self.obj)

    def some_func(self):
        libA.A_someFunc(self.obj)

rawDescription: Python ctypes, C++ object destruction

description: Python ctypes, C++ object destruction


code:
from django.utils.crypto import get_random_string
unique_id = get_random_string(length=32)
unique_id

rawDescription: Django package to generate random alphanumeric string


rawDescription: Best Pythonic way to conditionally append lists


code:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)

rawDescription: Python: Find in list

description: Python: Find in list


code:
{'family': 'Lucida Grande',
 'weight': 'normal',
 'slant': 'roman',
 'overstrike': False,
 'underline': False,
 'size': 13}

rawDescription: How to change a widget's font style without knowing the widget's font family/size?

description: Change a widget's font style without knowing the widget's font family/size


code:
import json
import urllib.request
conditionsSetURL = 'http://httpbin.org/post'
newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"}
params = json.dumps(newConditions).encode('utf8')
req = urllib.request.Request(conditionsSetURL, data=params,
                             headers={'content-type': 'application/json'})
response = urllib.request.urlopen(req)
print(response.read().decode('utf8'))

rawDescription: Python3: JSON POST Request WITHOUT requests library


rawDescription: wxPython textctrl temporarily gets black rectangle

description: WxPython textctrl temporarily gets black rectangle


rawDescription: Match a sequence of numbers preceded by certain text


code:
#!/usr/bin/python

from distutils.core import setup
import py2exe, sys, wx, os

# Se eseguito senza argomenti, crea l'exe in quiet mode.
# If executed without args, it makes the exe in quiet mode
if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")

class FileBrowser(wx.FileDialog):
    def __init__(self):
        wildcard = "Python files (*.py)|*.py|" \
            "Tutti i files (*.*)|*.*"
        dialog = wx.FileDialog(None, "Choose the file", os.getcwd(),
            "", wildcard, wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            print(dialog.GetPath())
        self.file = dialog.GetPath()
        self.fin = open(self.file, 'r')
        dialog.Destroy()

class Target:
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # info di versione
        self.version = "1.0.0"
        self.company_name = "Bancaldo TM"
        self.copyright = "no copyright"
        self.name = "py2exe sample files"

manifest_template = '''
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level='asInvoker' uiAccess='false' />
      </requestedPrivileges>
    </security>
  </trustInfo>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
     type='win32'
     name='Microsoft.VC90.CRT'
     version='9.0.21022.8'
     processorArchitecture='*'
     publicKeyToken='1fc8b3b9a1e18e3b' />
    </dependentAssembly>
  </dependency>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
         type="win32"
         name="Microsoft.Windows.Common-Controls"
         version="6.0.0.0"
         processorArchitecture="*"
         publicKeyToken="6595b64144ccf1df"
         language="*" />
    </dependentAssembly>
  </dependency>
</assembly>
'''
# File Browser
app = wx.PySimpleApp()
fb = FileBrowser()
# Assegno il nome all'eseguibile di uscita
# Give the name at the exe file being created
textentry = wx.TextEntryDialog(None, "name file EXE?",'','')
if textentry.ShowModal() == wx.ID_OK:
    destname = textentry.GetValue()

RT_MANIFEST = 24

test_wx = Target(
    description = "A GUI app",
    script = fb.file,     # programma sorgente dal quale creiamo l'exe
                          # source from wich we create the exe
    other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="tried"))],
    icon_resources = [(1, "py.ico")],
#    dest_base = "prova_banco") # Nome file di destinazione
                                #Name Destination file
    dest_base = destname) # Nome file di destinazione

setup(
    data_files=["py.ico"],
    options = {"py2exe": {"compressed": 1,
                          "optimize": 2,
                          "ascii": 1,
                          "bundle_files": 1}},
    zipfile = None,
    windows = [test_wx],
    )

rawDescription: I need a stand alone python interpreter/compiler!


code: '::'.join(str(i) for i in L)

rawDescription: is there a sage equivalent to php 'implode' for a list?

description: Is there a sage equivalent to php 'implode' for a list


code:
chunks = 100
for i in xrange(0, len(deleteList), chunks):
   spss.Submit("DELETE VARIABLES %s." % " ".join(deleteList[i:i+chunks]))

rawDescription: Deleting all but a few Variables from a Dataset in SPSS


rawDescription: Is this a mistake of the core python programming,2nd editon?


code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))

rawDescription: How can I change the font size using seaborn FacetGrid?

description: Change the font size using seaborn FacetGrid


code:
import ruamel.yaml as yaml

yaml_str = """\
depth: !!omap
  - rows: 480
  - cols: 640
  - dt: f
  - data: x
"""

data1 = yaml.load(yaml_str)
data1['depth']['data2'] = 'y'
print(yaml.dump(data1, Dumper=yaml.RoundTripDumper))

rawDescription: sort a YAML block mapping sequence in python

description: Sort a YAML block mapping sequence in python


code:
class OrderedSetQueue(Queue.Queue):
    def _init(self, maxsize):
        self.queue = OrderedSet()
    def _put(self, item):
        self.queue.add(item)
    def _get(self):
        return self.queue.pop()

rawDescription: Check if element is already in a Queue

description: Check if element is already in a Queue


rawDescription: Why Python need rich comparison?

description: Why Python need rich comparison


code:
for i, var in enumerate(paraStringList):  # Enumerate creates a tuple
    with open("{0}.txt".format(i), 'w') as writer:
        writer.write(var)

rawDescription: Python Blog RSS Feed Scraping BeautifulSoup Output to .txt Files


rawDescription: Python Pandas- how to unstack a pivot table with two values with each value becoming a new column?


code:
lookup = {s: i for i, s in enumerate(code_order)}
print(sorted(l, key=lambda o: lookup[o['code']]))

rawDescription: Sort a list of dictionaries by a key, based on the order of keys in a separate list in Python


code:
z['name']=x['name'][y['point_index']]
z

rawDescription: python numpy left join recarray with duplicated key value

description: Python numpy left join recarray with duplicated key value


code:
data = {
    'O211YB': '1111 2222',
    'B896PM': '3333 4444',
    # Etcetera
}
if nomer in data.keys():
    print( data[nomer] )

rawDescription: Search element in list and print property element


code:
def decorator(func):

    def wrapped(*args):
        print("TEST")
        return func(*args)

    return wrapped

def decorate_object(p_object, decorator):
    for method_name in dir(p_object):
        if method_name.startswith("dec_"):
            attr = getattr(p_object, method_name)
            wrapped = decorator(attr)
            setattr(p_object, method_name, wrapped)

decorate_object(Xobject, decorator)

x = Xobject()

x.dec_me_1()
x.dec_me_2()

rawDescription: How to decorate all methods in a class? Can I just decorate the class?

description: Decorate all methods in a class? Can I just decorate the class


code:
class QuestionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Question
        fields = ('question',)

class SurveySerializer(serializers.ModelSerializer):
    questions = QuestionSerializer(source="question_set", many=True)

    class Meta:
        model = Survey
        fields = ('name', 'questions')
        depth = 1

rawDescription: Django Rest Framework how to customize ListAPIView


code:
import os, time, tkinter, urllib
from tkinter import *
from urllib.request import *
from urllib.error import *

class App:
    def __init__(self, master):
        start_time = time.time()
        frame = Frame(master)
        frame.pack()
        if self.internet_on() == 1:
            self.label = Label(frame, text="Internet is online")
            self.label.pack()
            start_time = time.time()
        else:
            self.label = Label(frame, text="Internet is offline!  Downtime: " + str(time.time() - start_time))
            self.label.pack()

    def internet_on(self):
        try:
            response=urllib.request.urlopen('http://www.google.com.br',timeout=1)
            return True
        except urllib.error.URLError as err: pass
        return False
top = tkinter.Tk()
app = App(top)

top.mainloop()

rawDescription: Tkinter set new value for labels

description: Tkinter set new value for labels


rawDescription: A function that takes in both a list (myList) and a value (n) and checks whether or not the value is in that list


code: [': error:', 'cc1plus:']

rawDescription: Python: defining a union of regular expressions


code:
for footnote in soup.find_all("div", "footnote"):
    new_tag = soup.new_tag("div")
    new_tag['class'] = 'footnote-out'
    wrap(footnote, new_tag)

rawDescription: Add parent tags with beautiful soup

description: Add parent tags with beautiful soup


code:
def addword(theIndex, word, pagenumber):
    theIndex.setdefault(word, [ ]).append(pagenumber)

rawDescription: python backports for some methods

description: Python backports for some methods


code:
def readSpecificLines(filepath, lines):
    # lines is a list of line numbers that you are interested in. Feel free to start with line number 1
    lines.sort()
    i=0
    answer = []
    with open(filepath) as infile:
        fileReader = enumerate(infile, 1)
        while i<len(lines):
            nextLine = lines[i]
            lineNum, line = next(fileReader)
            if lineNum == nextLine:
                answer.append(line)
                i += 1
    return answer

rawDescription: How can I return specific lines in python 2.7 by using f.readline()

description: Return specific lines in python 2.7 by using f.readline()


rawDescription: Split string into array with many char pro items


rawDescription: How would you evenly distribute a list of sublists that each have a numerical value across three lists?


code:
class A():
    def __init__(self, protocol='SERIAL'):
        std_f = ('connect', 'send', 'read', 'log')
        protocols = ('RTT', 'SERIAL')
        if protocol not in protocols:
            print("Protocol not supported!")
            raise Exception # your exception here

        prot_f = [getattr(self, name+'_'+protocol.lower()) for name in std_f]
        for f, new_f in zip(std_f, prot_f):
            setattr(self, f, new_f)

    def connect_serial(self, hostname):
        print('I am serial connect', hostname)
    def send_serial(self, hostname):
        print('I am serial send', hostname)
    def read_serial(self, hostname):
        print('I am serial read', hostname)
    def log_serial(self, hostname):
        print('I am serial log', hostname)

    def connect_rtt(self, hostname):
        print('I am RTT connect', hostname)
    def send_rtt(self, hostname):
        print('I am RTT send', hostname)
    def read_rtt(self, hostname):
        print('I am RTT read', hostname)
    def log_rtt(self, hostname):
        print('I am RTT log', hostname)

rawDescription: Deciding which class method to be called according to class initiatiation parameters


code:
def toeach_category(subf):
    print(subf)

rawDescription: Customizing rolling_apply function in Python pandas


code:
import os
from django import forms
from .models import MyModel

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['image']

    image = forms.FileField()

    def clean_image(self):
        uploaded_file = self.cleaned_data['image']
        try:
            # create an ImageField instance
            im = forms.ImageField()
            # now check if the file is a valid image
            im.to_python(uploaded_file)
        except forms.ValidationError:
            # file is not a valid image;
            # so check if it's a pdf
            name, ext = os.path.splitext(uploaded_file.name)
            if ext not in ['.pdf', '.PDF']:
                raise forms.ValidationError("Only images and PDF files allowed")
        return uploaded_file

rawDescription: Extend image field to allow pdf ( django )


code:
class SomeClass(object):
    dct = {}
    nbr = 0
    def method(self, nbr):
        self.dct[nbr]=nbr
        self.nbr+=nbr

    def __getstate__(self):
        res = self.__dict__
        print("pickled", res)
        return res

rawDescription: Modify object via Python multiprocessing.Pool: strange behavior


code:
list = [bin(x) for x in range(16)]
print(list)

rawDescription: Python List - basic binary

description: Python List - basic binary


code:
order = ['item 4.1', 'item 2.1', 'item 3.1', 'item 1.1']
my_list.sort(key=lambda x: order.index(x[0]))

rawDescription: Python sort list of lists over multiple levels and with a custom order


code:
all_scores = Score.objects.filter(score__lte=1000).order_by('player', '-score')
current_player = None
scores = []
for score in all_scores:
    if current_player != score.player:
        current_player = score.player
        scores.append(score)

rawDescription: How to reduce multiple queries to only one query?

description: Reduce multiple queries to only one query


rawDescription: Mathematical function in Python

description: Mathematical function in Python


code: pv = event.groupby( 'BatchNo' )['Event A Flag', 'Event B Flag'].aggregate( sum )

rawDescription: Collating timestamped events into date ranges with pandas


code:
# Python code
import maya.OpenMaya as om

def getInstances():
    instances = []
    iterDag = om.MItDag(om.MItDag.kBreadthFirst)
    while not iterDag.isDone():
        instanced = om.MItDag.isInstanced(iterDag)
        if instanced:
            instances.append(iterDag.fullPathName())
        iterDag.next()
    return instances

rawDescription: Maya find if an object is instanced?

description: Maya find if an object is instanced


code:
t = Test()
t.foo = 'bar'
t.foo
t.config

rawDescription: Using Python to create a dictionary with setters and getters


code:
'(%s, %s)' % a
'%s, %s' % a  # without parentheses

rawDescription: How to Modify a String in wx.StaticText?

description: Modify a String in wx.StaticText


code: any(char in stringB for char in stringA)

rawDescription: Doing "if string a contains any letter in string b" with Python


rawDescription: Python: Iterate over string with while loop


code:
import argparse
parser = argparse.ArgumentParser(prog='ipush',description='Utility to push the last commit and email the color diff')
p = parser.parse_args()
argument = vars(p)

rawDescription: accessing ArgumentParser variable with environment variable

description: Accessing ArgumentParser variable with environment variable


code:
# std
import ast
import dis
import sys
from pprint import pprint

# vendor
import byteplay
import greenlet

# bytecode snippet to increment our global opcode counter
INCREMENT = [
    (byteplay.LOAD_GLOBAL, '__op_counter'),
    (byteplay.LOAD_CONST, 1),
    (byteplay.INPLACE_ADD, None),
    (byteplay.STORE_GLOBAL, '__op_counter')
    ]

# bytecode snippet to perform a yield to our watchdog tasklet.
YIELD = [
    (byteplay.LOAD_GLOBAL, '__yield'),
    (byteplay.LOAD_GLOBAL, '__op_counter'),
    (byteplay.CALL_FUNCTION, 1),
    (byteplay.POP_TOP, None)
    ]

def instrument(orig):
    """
    Instrument bytecode.  We place a call to our yield function before
    jumps and returns.  You could choose alternate places depending on
    your use case.
    """
    line_count = 0
    res = []
    for op, arg in orig.code:
        line_count += 1

        # NOTE: you could put an advanced bytecode filter here.

        # whenever a code block is loaded we must instrument it
        if op == byteplay.LOAD_CONST and isinstance(arg, byteplay.Code):
            code = instrument(arg)
            res.append((op, code))
            continue

        # 'setlineno' opcode is a safe place to increment our global
        # opcode counter.
        if op == byteplay.SetLineno:
            res += INCREMENT
            line_count += 1

        # append the opcode and its argument
        res.append((op, arg))

        # if we're at a jump or return, or we've processed 10 lines of
        # source code, insert a call to our yield function.  you could
        # choose other places to yield more appropriate for your app.
        if op in (byteplay.JUMP_ABSOLUTE, byteplay.RETURN_VALUE) \
                or line_count > 10:
            res += YIELD
            line_count = 0

    # finally, build and return new code object
    return byteplay.Code(res, orig.freevars, orig.args, orig.varargs,
        orig.varkwargs, orig.newlocals, orig.name, orig.filename,
        orig.firstlineno, orig.docstring)

def transform(path):
    """
    Transform the Python source into a form safe to execute and return
    the bytecode.
    """
    # NOTE: you could call ast.parse(data, path) here to get an
    # abstract syntax tree, then filter that tree down before compiling
    # it into bytecode.  i've skipped that step as it is pretty verbose.
    data = open(path, 'rb').read()
    suite = compile(data, path, 'exec')
    orig = byteplay.Code.from_code(suite)
    return instrument(orig)

def execute(path, limit = 40):
    """
    This transforms the user's source code into bytecode, instrumenting
    it, then kicks off the watchdog and user script tasklets.
    """
    code = transform(path)
    target = greenlet.greenlet(run_task)

    def watcher_task(op_count):
        """
        Task which is yielded to by the user script, making sure it doesn't
        use too many resources.
        """
        while 1:
            if op_count > limit:
                raise RuntimeError("script used too many resources")
            op_count = target.switch()

    watcher = greenlet.greenlet(watcher_task)
    target.switch(code, watcher.switch)

def run_task(code, yield_func):
    "This is the greenlet task which runs our user's script."
    globals_ = {'__yield': yield_func, '__op_counter': 0}
    eval(code.to_code(), globals_, globals_)

execute(sys.argv[1])

rawDescription: Embedding a Low Performance Scripting Language in Python


code:
excludehosts = restAPI.objects.values_list('rest_host', flat=True)
missinghosts = soapAPI.objects.exclude(soap_host__in=excludehosts)
missinghosts.filter(soap_state='Live')

rawDescription: Compare two alike fields from two separate models


rawDescription: Using my own corpus instead of movie_reviews corpus for Classification in NLTK


code:
#!/usr/bin/env python
import sys
__import__('uu')
print(sys.modules['uu'])
print(dir(uu))

rawDescription: Cant get __import__() to dynamically import a module in python - I know this cause it doesn't show up in sys.modules


code:
import copy
a = ['foo', 'bar', 'baz']
b = ['spam', 'ham', 'eggs']
outer = [a, b]
copy_of_outer = copy.copy(outer)
outer is copy_of_outer
outer == copy_of_outer
outer[0] is a
copy_of_outer[0] is a
outer[0] is copy_of_outer[0]

rawDescription: Shallow/Deep copy in python

description: Shallow/Deep copy in python


code:
class WindowsHttpAuthenticated(HttpAuthenticated):
    """
    Provides Windows (NTLM) http authentication.
    @ivar pm: The password manager.
    @ivar handler: The authentication handler.
    """

    def u2handlers(self):
        # try to import ntlm support
        try:
            from ntlm import HTTPNtlmAuthHandler
        except ImportError:
            raise Exception("Cannot import python-ntlm module")
        handlers = HttpTransport.u2handlers(self)
        handlers.append(HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(self.pm))
        return handlers

rawDescription: Has anyone combined soap.py or suds with python-ntlm?


code:
for service in c.IIsWebService():
    result, = service.StopService()

rawDescription: Restarting IIS6 - Python

description: Restarting IIS6 - Python


code:
for img in soup.select("a.img-link img[src]"):
    print(img["src"])

rawDescription: BeatifulSoup HTML getting src link

description: BeatifulSoup HTML getting src link


code: set(A) <= set(B)

rawDescription: Compare List with different number of items


rawDescription: Twisted-PyQt4 segmentation faults

description: Twisted-PyQt4 segmentation faults


code: [i for i in Records if i['Price']]

rawDescription: Delete multiple dictionaries in a list

description: Delete multiple dictionaries in a list


code: a_separate_instance = Word("dissemble", [def_3])

rawDescription: Interfering objects (or something less sinister?)


rawDescription: Why does csv.DictReader skip empty lines?


code:
def find (self, event):

        self.Te.tag_remove('found', '1.0', 'end')
        pat = self.FW.En.get()
        if len(pat) > 1:
            index = '1.0'
            while True:
                index = self.Te.search(pat, index, nocase=1, stopindex='end')
                if not index:
                    break
                lastidex = '%s+%dc' % (index, len(pat))
                self.Te.tag_add('found', index, lastidex)
                index = lastidex

            self.Te.tag_config('found', background='#80ff00')

rawDescription: Variable updating one step behind in list searcher in Tkinter


code:
self.action = ('ActivateSqueezeboxMode', None, _('SqueezeboxTools'),
                None, _('Activate Squeezebox mode'),
                self.activate_button_press, True)
self.action_group = gtk.ActionGroup('SqueezeboxPluginActions')
self.action_group.add_toggle_actions([self.action])
# now get your action back out of the action group so you can modify it
action = self.action_group.get_action('ActivateSqueezeboxMode')
action.set_icon_name('my-custom-icon')

rawDescription: Custom Icon in gtk toggle_action

description: Custom Icon in gtk toggle_action


code:
n = 3
Channel1 = 'this'
Channel2 = 'use'
Channel3 = 'globals()'

print(' '.join(globals()['Channel' + str(i + 1)] for i in range(n)))

rawDescription: How to add certain number of variable names to a string

description: Add certain number of variable names to a string


code:
Optional( CaselessKeyword('order by') +
        delimitedList(Group(columnNameList('order') +
                            Optional(order_dir, default="asc")('order_dir')))('orderByColumns')
        )

rawDescription: pyparsing optional subfield

description: Pyparsing optional subfield


code:
def diode_detector(x,alpha):
    xmax = abs(x[0])
    y = np.array(x)
    for i in np.arange(len(x)):
        if (xmax < abs(x[i])):
            xmax = abs(x[i])
        else:
            xmax = alpha*xmax
        y[i] = xmax
    return y

# you may need to tweak the alpha parameter depending on your signal bandwidth
envelope = diode_detector(x,0.9997)

rawDescription: Determining the event location on an oscillatory signal


rawDescription: Find the first N elements of a list, until a condition is satisfied


code:
tup is lis
lis.append(10)
lis, tup

rawDescription: Time complexity of casting lists to tuples in python and vice versa


rawDescription: Pandas dataframe add a field based on multiple if statements


rawDescription: how to make my own mapping type in python

description: Make my own mapping type in python


rawDescription: Set timeout for FTP connection in Python with ftplib


code:
import pprint
import re
import string
from collections import Counter

p = re.compile(r'(\w+?):')

def get_text_line_items(text):
    for line in text.split('\n'):
        yield line

def bundle_dialogue_items(lines):
    cur_speaker = None
    paragraphs = Counter()
    for line in lines:
        if re.match(p, line):
            cur_speaker, dialogue = line.split(':')
            paragraphs[cur_speaker] += 1
        else:
            dialogue = line

        res = cur_speaker, dialogue, paragraphs[cur_speaker]
        yield res

def filter_dialogue_items(lines):
    for name, dialogue, paragraph in lines:
        if dialogue:
            res = name, dialogue, paragraph
            yield res

to_clean = string.whitespace + string.punctuation

def clean_word(word):
    res = ''.join(c for c in word if c not in to_clean)
    return res

def clean_dialogue_items(flines):
    for name, dialogue, paragraph in flines:
        s_dialogue = dialogue.strip().split()
        c_dialouge = [clean_word(w) for w in s_dialogue]
        res = name, c_dialouge, paragraph
        yield res

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

def clean_dict(speakers):
    for speaker in speakers:
        stats = speakers[speaker][speaker_stats]
        for paragraph in stats:
            stats[paragraph] = [''.join(c for c in word if c not in to_clean)
                                for word in stats[paragraph]]
    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

def get_text():
    text = '''BOB: blah blah blah blah
blah hello goodbye etc.

JERRY:.............................................
...............

BOB:blah blah blah
blah blah blah
blah.
BOB: boopy doopy doop
P1: Bla bla bla.
P2: Bla bla bla bla.
P1: Bla bla.
P3: Bla.'''
    text = get_text_line_items(text)
    return text

def process_catalogue(c_text):
    speakers = make_catalogue(c_text)
    s_speakers = sum_words_per_paragraph_items(speakers)
    t_speakers = total_word_count(s_speakers)
    return t_speakers

def process_text(text):
    b_text = bundle_dialogue_items(text)
    f_text = filter_dialogue_items(b_text)
    c_text = clean_dialogue_items(f_text)
    return c_text

def main():

    text = get_text()
    c_text = process_text(text)
    t_speakers = process_catalogue(c_text)

    # take a look at your hard work!
    pprint.pprint(t_speakers)

if __name__ == '__main__':
    main()

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


code: #!/usr/bin/env python -u

rawDescription: Python's print function that flushes the buffer when it's called?


code:
# if ctrls is a list of all lables to your checkboxes
# i is the count and j is the text of label
for i,j in enumerate(ctrls): #what ever loop you want
    var = IntVar()
    c = Checkbutton(self.master,text=j,variable=var)
    boxes.append([j.strip(),var,c])

rawDescription: Creating a window with an unknown amount of checkboxes - Python/tkinter


code:
from ctypes import c_void_p, c_char_p
from wand.api import library
from wand.image import Image

# Tell python about the MagickSetOption method
library.MagickSetOption.argtypes = [c_void_p,  # MagickWand * wand
                                    c_char_p,  # const char * option
                                    c_char_p]  # const char * value

# Read source image
with Image(filename="/path/to/source.tiff") as image:
    # -define quantum:polarity=min-is-white
    library.MagickSetOption(image.wand,          # MagickWand
                            "quantum:polarity",  # option
                            "min-is-white")      # value
    # Write min-is-white image
    image.save(filename="/path/to/min-is-white.tiff")

rawDescription: Python Wand change tiff to min-is-white

description: Python Wand change tiff to min-is-white


code: expected = ' ### + variable + avar + var[x] ' # <- this last 'var' should be ###

rawDescription: Replace variable in expression

description: Replace variable in expression


code:
r = [i for i, w in enumerate(dlist) if w == y]
print ("\nThis word appears",len(r),"times.")
print ("\nThis word appears in the places", r)

rawDescription: How do I display an item which is in the list multiple times?

description: Display an item which is in the list multiple times


code:
classes = set([t[-1] for t in data_list])

learning_set = []
test_set = []

for cl in classes:
    data_list_filtered = [t for t in data_list if t[-1]==cl]

    learning_set += data_list_filtered[:int(round(len(data_list_filtered)*border))]
    test_set += data_list_filtered[int(round(len(data_list_filtered)*border)):]

rawDescription: Python "input data"

description: Python "input data"


code:
if sys.platform.startswith('java'):
    from javaclient import JavaSSHClient as SSHClient
else:
    from pythonclient import PythonSSHClient as SSHClient

rawDescription: When does abstractSSHclass instantiate a concrete class instance in robotframework ssh library


code:
class EventQueue(object):
  def __init__(self):
    self.events = deque()
  def push(self, callable):
    self.events.append(callable)
  def process_next(self):
    self.events.popleft()()

rawDescription: Passing objects around an event queue in Python


code:
if b:
    a = b
else:
    a = {}

rawDescription: What is the official name of this construct?


code:
addTwo = lambda x: x+2
addTwo(2)

rawDescription: What does "lambda" mean in Python, and what's the simplest way to use it?


code:
grouplength = grouped.size().min()
cumcount = grouped.cumcount()
sub_df = df.loc[cumcount < grouplength, 'Sensor Reading']

rawDescription: Applying an average across groups in pandas


rawDescription: Django OR query using Extra and Filter

description: Django OR query using Extra and Filter


rawDescription: Is there an easy way to parse a list of tuples generated by python's print, using Python?


code:
def my_polar(theta, r, *args, **kwargs):
    """
    theta, r -- NumPy arrays with polar coordinates.
    """
    rect_coords = polar_to_rect(theta, r)
    pyplot.plot(rect_coords[0], rect_coords[1], *args, **kwargs)
    # You can customize the plot with additional arguments, or use `Line2D` on the points in rect_coords.

rawDescription: Mixing Matplotlib patches with polar plot?


code:
def modify_matrix(m1):
     m1[2,7] = 2
     return m1

rawDescription: Pythonic way to update a single element of a numpy matrix?


code:
g = ts.groupby(lambda x: x.minute)
g

rawDescription: Better way to aggregate timestamped data?


code:
def stat_entry(line):
    return line.startswith('STATISTICS')

def date_entry(line):
    return line.startswith('20')

def findIcommingStats():
    date = ''
    with open("result.log", "r") as replication_file:
        with open("incomingTemp.txt", "w") as tempFile:
            for line in replication_file:
                if date_entry(line):
                    date = ' '.join(line.split(' ')[:2]) # set new date
                elif stat_entry(line):
                    tempFile.write(date  + ' ' + line) # write to tempfile

findIcommingStats()

rawDescription: Find the first line containing a time stamp after a specific line in a file


code:
import inspect
foo = lambda x, y, z: x + y + z
inspect.getargspec(foo)

rawDescription: Determining the number of parameters in a lambda


code:
def get_user_by_user_key(user_key):
    # your logic code here, e.g.
    username = get_username()
    return username

rawDescription: How to get the User object from the user_key in Flask template

description: Get the User object from the user_key in Flask template


code: ", ".join('SUM({n}) AS {n}'.format(n=x) for x in a)

rawDescription: python string formatting: way to not use two lists?

description: Python string formatting: way to not use two lists


code:
from bs4 import Tag, NavigableString

def clone(el):
    if isinstance(el, NavigableString):
        return type(el)(el)

    copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix)
    # work around bug where there is no builder set
    # https://bugs.launchpad.net/beautifulsoup/+bug/1307471
    copy.attrs = dict(el.attrs)
    for attr in ('can_be_empty_element', 'hidden'):
        setattr(copy, attr, getattr(el, attr))
    for child in el.contents:
        copy.append(clone(child))
    return copy

rawDescription: clone element with beautifulsoup

description: Clone element with beautifulsoup


code:
regex = re.compile(r"^/api/0.6/([^/]+)/([^/]+)/?([^/]*)$")
regex.match("/api/0.6/changeset") is None
regex.match("/api/0.6/changeset/723").groups()
regex.match("/api/0.6/changeset/723/close").groups()
regex.match("/api/0.6/changeset/723/close/extragroup") is None

rawDescription: Help with a AppEngine Handler Regex?

description: Help with a AppEngine Handler Regex


code: y=x

rawDescription: Equal strings auto updating (List object reference)


code: __all__ = whereever.AllList()

rawDescription: Modifying module globals using externally defined function


code:
import string
acceptedChars = set(string.printable)
newL = ''.join([ x for x in l if x in acceptedChars])

rawDescription: Is digit, aplha or math symbol

description: Is digit, aplha or math symbol


code:
if "(" in line:
    columns = line.split()
    columns.insert(0, "i")
    g.write("  ".join(columns)+"  ")

rawDescription: Search a line in text file and write a word before it


code:
if Ticker.query.filter_by(ticker=new_ticker_value).first() is None:
    Ticker(ticker=new_ticker_value)
    session.commit()

rawDescription: How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?

description: A query a set of objects and return a set of object specific attribute in SQLachemy/Elixir


code:
if not app.debug:
    import logging
    from themodule import TheHandlerYouWant
    file_handler = logging.handlers.RotatingFileHandler(
         filename="/var/log/<flask_instance_name>",
         maxBytes=500000000,
         backupCount=4)
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

rawDescription: Two Flask Instances, One Console Message


rawDescription: django model object filter

description: Django model object filter


rawDescription: How to sort nested lists into seperate lists with unique values in python?

description: Sort nested lists into seperate lists with unique values in python


code: np.repeat(csum - occupations, occupations)

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
def unzip(source_filename, dest_dir):
    with zipfile.ZipFile(source_filename) as zf:
        zf.extractall(dest_dir)

rawDescription: Unzipping with python's ZipFile lib give a strange result


code: [ai and bi for ai,bi in zip(a,b)]

rawDescription: Python list of booleans comparison gives strange results


rawDescription: PyQt: QStyledItemDelegate in QTableView on Windows Vista/7?


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.master = master
        self.s1 = tk.Frame(self, background="pink", width=200, height=200)
        self.s2 = tk.Frame(self, background="blue", width=200, height=200)
        self.s3 = tk.Frame(self, background="bisque", width=200, height=200)

        self.s1.grid(row=0, column=0, sticky="nsew")
        self.s2.grid(row=0, column=1, sticky="nsew")
        self.s3.grid(row=1, column=0, columnspan=2, sticky="nsew")

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Python - using grid layout to format a window


code:
def recAlphaCount(s):
    if len(s) == 0:
        return 0
    elif s[0].isalpha():
        return 1 + recAlphaCount(s[1:])
    else:
        return recAlphaCount(s[1:])

rawDescription: Resetting a counter after recursion

description: Resetting a counter after recursion


code:
import base64
from PIL import Image
import StringIO

im = Image.new('L', (width, height))
output = StringIO.StringIO()
im.save(output, "JPEG", quality=89)

encoded_string = base64.b64encode(output.getvalue())

rawDescription: Python toDataUrl Equivalent

description: Python toDataUrl Equivalent


code:
dictstr = 'dict'
dictlist = [dictstr + str(i) for i in range(16)]

rawDescription: Create several dictionaries on the fly in a for-loop and reference them outside of the loop


code:
import csv
with open('users.txt', 'rb') as f,\
     open('users1.txt','wb') as users1,\
     open('users2.txt','wb') as users2:
    writer1 = csv.writer(users1, delimiter=',')
    writer2 = csv.writer(users2, delimiter=',')
    for line in f:
        words = line.split()
        writer1.writerow([words[0], words[-1]])
        writer2.writerow(words[1:3])

rawDescription: How do I specify which columns to print to a text file using Python?

description: Specify which columns to print to a text file using Python


code:
for name, val in foo.__dict__.iteritems(): # iterate through every module's attributes
    if callable(val):                      # check if callable (normally functions)
        val()                              # call it

rawDescription: How to iterate through a module's functions

description: Iterate through a module's functions


rawDescription: Element wise addition of two unequal lists in python


code:
with open("result.txt") as f:
   # find line starting with Residue XXX
   next(line for line in f if not line.startswith("Residue XXX"))
   # get next three lines into a list (empty string for nonexistent lines)
   results = [next(f, "").rstrip() for line in range(3)]

rawDescription: how to search in a file and read lines from there in python

description: Search in a file and read lines from there in python


code: differences = (test_array.reshape(1,-1) - known_array.reshape(-1,1))

rawDescription: NumPy: Vectorize finding closest value in an array for each element in another array


code:
f._spam
f._spam = 'ham'
f.spam

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


code: df[[x for x in df.columns if "_CLOSE" in x]]

rawDescription: Python data frames - how to select all columns that have a specific substring in their name


code:
tab = pd.read_sql('select stat,a,b_date from table', engine)
df.merge(tab, left_on=[...], right_on=[...], how='left')

rawDescription: Pandas, append column based on unique subset of column values


code:
import matplotlib.mlab as ml
zi = ml.griddata(x,y,z,xi,yi,interp='linear')

rawDescription: Interpolation resampling large irregular matrix or surface data points to regular grid


code:
import pandas as pd
df = pd.read_csv("test.csv")
df
df["sum"] = df.sum(axis=1)
df
df_new = df.loc[:,"value1":"value3"].div(df["sum"], axis=0)
df_new

rawDescription: Pandas sum across columns and divide each cell from that value


code:
Preprocessing
from sklearn.feature_extraction import DictVectorizer

data  = [
        {'location': 'store 1', 'quality': 8},
        {'location': 'store 1', 'quality': 9},
        {'location': 'store 2', 'quality': 2},
        {'location': 'store 2', 'quality': 3},
        ]
prices = [100.00, 99.9, 11.25, 9.99]
vec = DictVectorizer()
X = vec.fit_transform(data)
y = prices

rawDescription: Generating numpy arrays for scikit linear regression model


code:
from operator import itemgetter
dict_a = {e[0]: sum(map(itemgetter(1), filter(lambda a: a[0] == e[0], a))) for e in a}

rawDescription: How to merge value of key when I have a list-tuple object

description: Merge value of key when I have a list-tuple object


code: references = map(__import__, modules)

rawDescription: Dynamic module loading in python

description: Dynamic module loading in python


code:
def surface_property(api_property_name, docstring=None):
    def getter(self):
        return self.api_surface.__getattribute__(api_property_name)

    def setter(self, value):
        self.api_surface.__setattr__(api_property_name, value)

    return property(getter, setter, doc=docstring)

rawDescription: Python property factory or descriptor class for wrapping an external library


rawDescription: How to sort a list of tuples by the alphabetical ordering of one of its elements

description: Sort a list of tuples by the alphabetical ordering of one of its elements


code:
ans = 10
monthlyPayment = ans
id(ans)
id(monthlyPayment) # still the same objects
ans += 10 # creates new object
ans
monthlyPayment # still has original value
id(monthlyPayment)  # same id as original ans
id(ans)  # new id because it is a new object

description: Pset2 Python Problem3-UsingBisectionSearch.py


code:
import shutil
shutil.move(destination, source)

rawDescription: Cut and Paste a File or Directory in Python


code: df.iloc[0, df.columns.get_loc('COL_NAME')] = x

rawDescription: Set value for particular cell in pandas DataFrame with iloc


code: [x for d in dict1 for x in dict1[d] if d.startswith("s")]

rawDescription: how to get dict value by regex in python

description: Get dict value by regex in python


code:
from collections import defaultdict

itemdict = defaultdict(list)
for id, parent_id in itemlist:
   itemdict[parent_id].append(id)

rawDescription: Recursive? looping to n levels in Python


code:
nums = xrange(100000000)
-1 in nums

rawDescription: Why is my threading/multiprocessing python script not exiting properly?


code:
np_mwe_nocomma = [j for j in [" ".join(i.leaves()) for i in parsed_tree.subtrees() if i.label() == 'NP'] if j.count(' ') > 0 and j.count(',') == 0]
np_mwe_nocomma

rawDescription: Get entities from NLTK.tree result

description: Get entities from NLTK.tree result


code:
import numpy as np
score = np.array([
[0,0,0,0],
[1,2,1,1],
[2,-6,0,2],
[3,4,1,3]
])
players_to_include = [0,2,3]
score[players_to_include, 1]

rawDescription: slice numpy array by column except for 1 row

description: Slice numpy array by column except for 1 row


code:
A[np.ix_(*[np.arange(x) for x in J.shape])+(J,)]
A[np.ogrid[[slice(k) for k in J.shape]]+[J]]

rawDescription: How can I select values along an axis of an nD array with an (n-1)D array of indices of that axis?

description: Select values along an axis of an nD array with an (n-1)D array of indices of that axis


code:
keys = list(some_dict)
keys = some_dict.keys()
keys = list(some_dict.keys())
keys = list(some_dict.iterkeys())

rawDescription: Is there a better way to feed different parameters into a function with if-statements?


code:
tag = session.query(Tags).filter(Tags.tag == 'my_tag').first()
link = session.query(Link).filter(Links.link == 'my_link').first()

link.tags.add(tag)  # if it's already present, the hash will compare equal and nothing will happen
session.commit()

rawDescription: database for tags - updating many-to-many tables with unique columns

description: Database for tags - updating many-to-many tables with unique columns


code: [item for string in original for item in string.split(',') if item]

rawDescription: How to separate strings in a list in python?

description: Separate strings in a list in python


code: import pkg1.util as util

rawDescription: Basic Python imports question

description: Basic Python imports question


code:
import locale
locale.setlocale(locale.LC_ALL, 'pt_br.utf-8')
pd.set_option('display.float_format', lambda x: locale.format('%.2f', x, grouping=True))

rawDescription: How can I format a float to separate by thousands, inverting dot and commas?

description: Format a float to separate by thousands, inverting dot and commas


rawDescription: How to define values for RegularGridInterpolator

description: Define values for RegularGridInterpolator


code:
from itertools import permutations, product, chain

for lst1, lst2 in permutations(d.values(), 2):
    for e1, e2 in chain.from_iterable(product(lst1, lst2)):
        do_something_with(dist(e1, e2))

rawDescription: Finding Interfaces

description: Finding Interfaces


rawDescription: Python Regular expression for splitting mentions of two years appearing altogether


code:
import re
a = "I am a programmer"
reg = re.compile(r'I am (.*?)$')
print('How long have you been {}'.format(*reg.findall(a)))

rawDescription: Grabbing a part of a string using regex in python 3.x


rawDescription: Python removing duplicate lines

description: Python removing duplicate lines


code: import menu

rawDescription: Confusion with python global variables, pygame event


code:
lower, upper = np.percentile(a, [2.5, 97.5])
a[(a > lower) & (a < upper)]

rawDescription: Find the edges of a numpy array that 95% data within them


code: sensors = pd.concat([sensor1, sensor2], axis=1, ignore_index=True)

rawDescription: Append data in pandas

description: Append data in pandas


code:
lines = infile.readlines()
for lineno, line in enumerate(lines):
  targetline = lines[lineno + 2]

rawDescription: Reading specific data from a text file

description: Reading specific data from a text file


code:
np.nan == np.nan
np.nan != np.nan
np.isnan(np.nan)

rawDescription: Get mean value avoiding nan using numpy in python


rawDescription: Paging depending on grouping of items in Django


code:
plt.plot(size_class,counts_cumulative_normalised)
plt.plot(size_class,norm.cdf(size_class, 5, 1))

rawDescription: calculate percentile of 2D array

description: Calculate percentile of 2D array


rawDescription: List in List (Usage of Range with for)

description: List in List (Usage of Range with for)


rawDescription: Regex to pick days of the week from a string in Python


Name: Click this link to access Chevrolet : Corvette Base Coupe 2-Door

Name: Click this link to access Ford : Mustang Convertible 2-Door

Name: Click this link to access Chevrolet : Corvette Base Convertible 2-Door

Name: Click this link to access Ford : Mustang base coupe 2-door

Name: Click this link to access BMW : 5-Series Base Sedan 4-Door

Name: Click this link to access Ford : Mustang GT 2dr Convertible

Name: Click this link to access Ford : Mustang GT Coupe 2-Door

Name: Click this link to access Chevrolet : Camaro 2dr Coupe

Name: Click this link to access BMW : i8 Base Coupe 2-Door

Name: Click this link to access Rolls-Royce : Other Base Coupe 2-Door

Name: Click this link to access Chevrolet : Corvette Stingray Coupe 2-Door

Name: Click this link to access BMW : 3-Series Base Sedan 4-Door

Name: Click this link to access Ford : Other COUPE TWO DOOR

Name: Click this link to access Dodge : Other 4 door sedan

Name: Click this link to access Chevrolet : Corvette 2DR COUPE

Name: Click this link to access Chevrolet : S-10 Base 2 door

Name: Click this link to access Other Makes 2dr Coupe

Name: Click this link to access Chevrolet : Camaro 2DR CONVERTIBLE

Name: Click this link to access Chevrolet : Corvette Coupe C4

Name: Click this link to access Ford : Fusion SE Sedan 4-Door

Name: Click this link to access Chevrolet : Corvette Coupe 2-Door

Name: Click this link to access BMW : 7-Series Base Sedan 4-Door

Name: Click this link to access Audi : Other S Sedan 2-Door

Name: Click this link to access Ford : F-250 4WD SuperCab

Name: Click this link to access Ford : Other 2 door

Name: Click this link to access Chevrolet : Impala 2 Door Coupe

Name: Click this link to access Ford : Other Pickups F1

Name: Click this link to access Chevrolet : Corvette 2dr Convertible

Name: Click this link to access Dodge : Challenger 2DR COUPE

Name: Click this link to access Chevrolet : Corvette 2dr Coupe w/1LT

Name: Click this link to access BMW : M5 Base Sedan 4-Door

Name: Click this link to access Chevrolet : Nova Base Coupe 2-Door

Name: Click this link to access Ford : Mustang LX Notch Notchback Coupe

Name: Click this link to access Chevrolet : Camaro Z/28 Coupe 2-Door

Name: Click this link to access Audi : Other Base Coupe 2-Door

Name: Click this link to access Chevrolet : Corvette Coupe 2-door

Name: Click this link to access Ford : Other Pickups 4dr Crew Cab Pickup

Name: Click this link to access Cadillac : XLR Base Convertible 2-Door

Name: Click this link to access Cadillac : STS Base Sedan 4-Door

Name: Click this link to access Lamborghini : Gallardo Base Coupe 2-Door

Name: Click this link to access Ford : Falcon Sedan, 4 door

Name: Click this link to access Bentley : Mulsanne Base Sedan 4-Door

Name: Click this link to access Chevrolet : SS Base Sedan 4-Door

Name: Click this link to access Chevrolet : Camaro Z28 Coupe 2-Door

Name: Click this link to access Honda : Civic EX Sedan 4-Door

Name: Click this link to access Nissan : 350Z Touring Coupe 2-Door

Name: Click this link to access Honda : S2000 2DR Convertible

Name: Click this link to access Chevrolet : Camaro SS Coupe 2-Door

Name: Click this link to access Ford : Mustang COUPE STAGE 3

Name: Click this link to access Ford : Mustang Base Coupe 2-Door

Name: Click this link to access Ford : Other coupe

Name: Click this link to access Chevrolet : Other Pickups pickup

Name: Click this link to access Honda : Civic EX-L Sedan 4-Door

Name: Click this link to access Toyota : Camry LE Sedan 4-Door

Name: Click this link to access Chevrolet : Corvette Z51 Coupe 2-Door

Name: Click this link to access Audi : S5 Base Coupe 2-Door

Name: Click this link to access Chevrolet : Corvette ZR1 Coupe 2-Door

Name: Click this link to access Porsche : 914 Base Coupe 2-Door

Name: Click this link to access Chevrolet : Corvette 2dr Coupe w/3LT

Name: Click this link to access Chevrolet : Corvette 2 Doors Coupe

Name: Click this link to access Bugatti : Veyron 2dr Coupe

Name: Click this link to access Chevrolet : Tahoe 2WD 4dr

Name: Click this link to access Ford : Taurus SE Sedan 4-Door

Name: Click this link to access Acura : NSX Base Coupe 2-Door

Name: Click this link to access Ford : F-150 4dr Pickup

Name: Click this link to access Dodge : Charger Police Pursuit Sedan 4-Door

Name: Click this link to access Chrysler : Crossfire Base Coupe 2-Door

Name: Click this link to access Ford : F-450 4dr Pickup

Name: Click this link to access BMW : M4 2dr Coupe

Name: Click this link to access Chevrolet : Corvette Z06 Coupe 2-Door

Name: Click this link to access Ford : Mustang Mach I Coupe 2-Door

rawDescription: Why does python scrapy yields duplicated items in my code?


code:
import copy
def remove_fully_correct(answer, guess):
        """(list,list) -> list
        Return a list that removes the chars from the first list that are the same and in the same position in the second list
        >>>remove_fully_correct(['a','b','c','d'], ['d','b','a','d'])
        ['a','c']
        """
        res =  copy.copy(answer)
        for index in range(len(res)):
            for x, y in zip(res, guess):
                if res[index] == guess[index]:
                    res.remove(x)
        return res  # move outside

rawDescription: How to get a function to execute until the conditions are not sufficient

description: Get a function to execute until the conditions are not sufficient


code:
from __future__ import print_function
try:
    # Python 2
    from __builtin__ import print as builtin_print
except ImportError:
    from builtins import print as builtin_print

def print(*args, **kw):
    # do something extra with *args or **kw, etc.
    builtin_print(*args, **kw)

rawDescription: Customize compile function in python?

description: Customize compile function in python


code:
print(a[indices, 1])  # column 2
print(a[indices, 2])  # column 3

rawDescription: Show all values in an array for a particular number in one column


code: conv -= conv.min()

rawDescription: Python numpy grid transformation using universal functions


rawDescription: updating a numpy array efficiently when the conditions are two

description: Updating a numpy array efficiently when the conditions are two


rawDescription: Pandas DatetimeIndex vs to_datetime discrepancies


code:
from math import fmod

if fmod(xmax - x0, h) == 0:
    pass

rawDescription: Determining if a Variable is Numerically an Integer in Python


code:
df
df.columns.droplevel(1)
df.columns = df.columns.droplevel(1)
df

rawDescription: Flatten / Remove hierarchical column headers


code: counter = defaultdict(int)

rawDescription: Python Counter doesn't count

description: Python Counter doesn't count


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

clock = timeit.default_timer

fig, ax = plt.subplots()

alphab = ['A', 'B', 'C', 'D', 'E', 'F']
frequencies = [1, 44, 12, 11, 2, 10]

pos = np.arange(len(alphab))
width = 1.0     # gives histogram aspect to the bar diagram
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(alphab)

rects = plt.bar(pos, frequencies, width, color='r')
start = clock()

def animate(arg, rects):
    frameno, frequencies = arg
    for rect, f in zip(rects, frequencies):
        rect.set_height(f)
    print("FPS: {:.2f}".format(frameno / (clock() - start)))

def step():
    for frame, bin_idx in enumerate(np.linspace(0,1000000,100000000), 1):
        #Here we just change the first bin, so it increases through the animation.
        frequencies[0] = bin_idx
        yield frame, frequencies

ani = animation.FuncAnimation(fig, animate, step, interval=10,
                              repeat=False, blit=False, fargs=(rects,))
plt.show()

rawDescription: Animate a Histogram in Python

description: Animate a Histogram in Python


code: lst1 = [format(float(i), '.0f') for i in lst1]

rawDescription: Method to get two separate lists after parsing output


code:
with FTPConnector(params) as host:
    host.walk()
    # do something useful with the connection here

# here the connection gets closed again

rawDescription: How to return from with statement?

description: Return from with statement


code:
import matplotlib.mlab

data=np.array(
    [('Aaron','Digger',1),
     ('Bill','Planter',2),
     ('Carl','Waterer',3),
     ('Darlene','Planter',3),
     ('Earl','Digger',7)],
    dtype=[('name', np.str_,8), ('job', np.str_,8), ('income', np.uint32)])

result=matplotlib.mlab.rec_groupby(data, ('job',), (('income',np.mean,'avg_income'),))

rawDescription: pythonic way to aggregate arrays (numpy or not)

description: Pythonic way to aggregate arrays (numpy or not)


code: import webbrowser

rawDescription: Opening File Directory by using a button


code:
clean = df[~idx]
clean

rawDescription: Pandas Dataframe drop items where index condition is true


code:
if 'VGA' in line:
    return map(int, line.split('VGA')[1].split('.'))

rawDescription: Command output parsing in Python2.7

description: Command output parsing in Python2.7


code:
hashlib.md5("foo").hexdigest()
hashlib.md5("foo".encode("utf8")).hexdigest()
hashlib.md5("foo".encode("utf8")).hexdigest() == 'acbd18db4cc2f85cedef654fccc4a4d8'

rawDescription: Compare result from hexdigest() to a string


code: re.sub(r'\w*\d\w*', '', words).strip()

rawDescription: Python regex to remove all words which contains number


code:
from the_master_copy import AbstractCustomerData

class ThisCustomerData( AbstractCustomerData ):
    """All the various kinds of overrides and whatnot."""
    def the_matching_rule( self, master_data_object_or_collection_or_whatever ):
        """This customer's override."""

rawDescription: Where to put rules for creating a map between two data sets?


code:
from itertools import chain
dol_values = set(chain.from_iterable(dol.itervalues()))

rawDescription: complicated list and dictionary lookup in python

description: Complicated list and dictionary lookup in python


code:
# Generate a random list for example.
import random
some_list = random.sample(range(30), 4)

# Keep elements greater than 3.
filtered_list = [value for value in some_list if value >= 3]

# The same outcome, another way to write it.
filtered_list = filter(lambda x: x >= 3, some_list)

# The same outcome, but written as a loop.
filtered_list = []
for value in some_list:
    if value >= 3:
        filtered_list.append(value)

rawDescription: Python: How to remove values from a list that have a valence lower than a certain value


rawDescription: How can I set up token-based authentication for web services using Python?

description: Set up token-based authentication for web services using Python


code:
some_list = [d.get(x) or int(x) for x in some_list]
some_list = [d[x] if x in d else int(x) for x in some_list]

rawDescription: How to make my code more Pythonic?

description: Make my code more Pythonic


rawDescription: python - how to get the data from an plt.imshow()?

description: Python - how to get the data from an plt.imshow()


code:
import re
def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):
    return not bool(search(strg))
special_match("")
special_match("az09.")
special_match("az09.\n")
special_match("az09.#")
special_match("az09.X")

rawDescription: In Python, how to check if a string only contains certain characters?


code:
p1 = interpolate.PiecewisePolynomial(x1, y1[:, np.newaxis])
p2 = interpolate.PiecewisePolynomial(x2, y2[:, np.newaxis])

rawDescription: Python Pandas MatPlotLib Find The Intersection Of Two Lines (One Curved, One Straight)


code:
from collections import OrderedDict

od = OrderedDict()

import re

with open('in.log') as f:
    r = re.compile("(?<=ALERT:\s)\S+")
    for line in f:
        name, st, con, _, _ = r.search(line).group().split(";")
        od.setdefault(name, {"State": st, "StateType": con,"Count":0})
        od[name]["State"] = st
        od[name]["StateType"] = con
        od[name]["Count"] += 1

for k,v in od.items():
    print("{}, {}".format(k,v))

rawDescription: How to parse nagios log file to count host down in a given log file?

description: Parse nagios log file to count host down in a given log file


code:
def function(*, x, y, z):
    print(x,y,z)

rawDescription: python: is it possible to require that arguments to the functions are all keyword?

description: Python: is it possible to require that arguments to the functions are all keyword


rawDescription: how do I find special character in the path string and how many times are they present

description: Find special character in the path string and how many times are they present


rawDescription: Python: Comparison between list items that isn't redundant


code:
['' for _ in myList]

[a+d for a, _, _, d, _ in fiveTuples]

rawDescription: How can I get around declaring an unused variable in a for loop?

description: Get around declaring an unused variable in a for loop


code:
range_iter_a = iter(func_ranges)   # create generators that iterate over the
range_iter_b = iter(func_ranges)   # values in `func_ranges` without making copies
next(range_iter_b, None)           # advance the second generator by one
for f, start, end in itertools.izip(func_table, range_iter_a, range_iter_b):
    ...

rawDescription: Efficient algorithm for evaluating a 1-d array of functions on a same-length 1d numpy array


code:
import re

token_pattern = r"""
(?P<identifier>[a-zA-Z_][a-zA-Z0-9_]*)
|(?P<integer>[0-9]+)
|(?P<dot>\.)
|(?P<open_variable>[$][{])
|(?P<open_curly>[{])
|(?P<close_curly>[}])
|(?P<newline>\n)
|(?P<whitespace>\s+)
|(?P<equals>[=])
|(?P<slash>[/])
"""

token_re = re.compile(token_pattern, re.VERBOSE)

class TokenizerException(Exception): pass

def tokenize(text):
    pos = 0
    while True:
        m = token_re.match(text, pos)
        if not m: break
        pos = m.end()
        tokname = m.lastgroup
        tokvalue = m.group(tokname)
        yield tokname, tokvalue
    if pos != len(text):
        raise TokenizerException('tokenizer stopped at pos %r of %r' % (
            pos, len(text)))

rawDescription: Python - lexical analysis and tokenization


rawDescription: Convert SQL into json in Python

description: Convert SQL into json in Python


rawDescription: sorting by common item

description: Sorting by common item


rawDescription: SQLAlchemy Select with Exist limiting

description: SQLAlchemy Select with Exist limiting


code:
create_list_and_fix_max_and_min(10)
create_list_and_fix_max_and_min(20)
# No way to operate on the original array!

rawDescription: Python Alternatives to Global Variables

description: Python Alternatives to Global Variables


code:
data = {}
with open('file.txt', 'r') as f: # opens the file
    for line in f: # reads line by line
        key, value = line.split(' : ') # retrieves the key and the value
        data[key.lower()] = value.rstrip() # key to lower case and removes end-of-line '\n'

rawDescription: tokenizing and parsing with python

description: Tokenizing and parsing with python


rawDescription: Get html using Python requests?

description: Get html using Python requests


rawDescription: Wilcard matching substring in Python

description: Wilcard matching substring in Python


code:
wait = WebDriverWait(driver, 5)
wait.until(wait_for_display((By.XPATH, "//*[@id='inf-loader']/span[1]")))

rawDescription: make selenium driver wait until elements style attribute has changed

description: Make selenium driver wait until elements style attribute has changed


code:
import matplotlib.pyplot as plt
import numpy as np
a=np.random.rand(500,500)
plt.pcolor(a)
plt.savefig('pcolor.pdf')
plt.clf()
plt.pcolor(a,rasterized=True)
plt.savefig('pcolor_r.pdf', dpi=300)

rawDescription: Matplotlib: Pcolor creates huge images

description: Matplotlib: Pcolor creates huge images


code: myLang = 'en' if lang == 'en' else 'de' if lang == 'ger' else 'fa'

rawDescription: Using conditions in variable assignments in Python


code:
input = [{'id': 1, 'value1': 'value1', 'value2': 'value2'},{'id': 2, 'value1': 'value1', 'value2': 'value2'}, {'id': 2, 'value1': 'value1', 'value3': 'value4'}]
seen = set()
drepr = lambda d: tuple(sorted(d.items()))
output = {}
for el in input:
    if drepr(el) not in seen:
        output.setdefault(el['id'], []).append(el)
        seen.add(drepr(el))

from pprint import pprint
pprint(output)

rawDescription: Fastest way to create dict from a large list of Dict


code:
frames=[]
for i in range(42, 52):
    frames.append(pygame.image.load('Gfx/Dices/dice00'+str(i)+'.png').convert_alpha())

rawDescription: Frame animation from images. Pygame (python3)


code:
foo, bar, *baz = range(5)
foo, bar, baz
foo, *bar, baz = range(5)
foo, bar, baz
*foo, bar, baz = range(5)
foo, bar, baz

rawDescription: Unpack strip into combination of integer and list


rawDescription: How to define a decimal class holding 1000 digits in python?

description: Define a decimal class holding 1000 digits in python


code: Vec is type(other)

rawDescription: using isinstance () gives me True , using type() gives me False in Python

description: Using isinstance () gives me True , using type() gives me False in Python


code: l.sort(key=lambda element: (len(element), element))

rawDescription: Sorting a List of Strings, Ignoring ASCII Ordinal Values


code:
import os
os.path.abspath(directory + "../../etc/passwd")

rawDescription: What are the risks of not validating user input in this web service?


code:
from collections import Counter
def check(s):
    return sum(1 for count in Counter(s).itervalues() if count % 2 == 1) <= 1

rawDescription: Fast and pythonic way to find out if an anagram is a palindrome?


code: groups = df.groupby("e5")

rawDescription: Pandas get elements until value changes

description: Pandas get elements until value changes


rawDescription: Removing spaces from astring within a CSV in python


rawDescription: Force LaTeX font to match default matplotlib font


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

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        message =  threading.currentThread().getName()
        self.wfile.write(message)
        self.wfile.write('\n')
        return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', friendly user!\n')

def run_tornado():
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

def run_base_http_server():
    server = ThreadedHTTPServer(('localhost', 8080), Handler)
    server.serve_forever()

if __name__ == '__main__':
    threading.Thread(target=run_tornado).start()
    threading.Thread(target=run_base_http_server).start()

rawDescription: Python BaseHTTPServer and Tornado

description: Python BaseHTTPServer and Tornado


code:
data = bytearray(b'0123456789')
data[3:7] = data[5],data[6],data[3],data[4]
data

rawDescription: How do I rearrange bytes in a bytearray in Python?

description: Rearrange bytes in a bytearray in Python


code:
with open('test.txt') as x:
    print(x.read())

rawDescription: Reading from a text file with python - first line being missed


rawDescription: Verifying If key or value exists in dictionary, works for char and fails for number


code:
import binascii
h = "7F 9D AA 3E F7 0E 9C 75 7C 37"
binascii.unhexlify(''.join(h.split()))

# >> '\x7f\x9d\xaa>\xf7\x0e\x9cu|7'

rawDescription: process a string of ascii Hex values into a numerical hex value

description: Process a string of ascii Hex values into a numerical hex value


rawDescription: Reverse Y-Axis in PyPlot

description: Reverse Y-Axis in PyPlot


rawDescription: What if Chinese strings shown in the pandas DataFrame in Python


rawDescription: Python Flask : Route vs add_url_rule, SSE


code:
def qux(self, myvalue = None):
    first, second = myvalue or self.bar()
    return first + 3, second + 6

rawDescription: How can I make a method takes the value(s) from another method from within the same class in Python

description: Make a method takes the value(s) from another method from within the same class in Python


code:
for d in yourlst[0]:
    option = d['option']
    # do something with option

rawDescription: How to iterate through this dictionary

description: Iterate through this dictionary


code:
result = all([False] * 1000)
result = any([True] * 1000)

rawDescription: Does Python's reduce() short circuit?

description: Does Python's reduce() short circuit


code:
class ToolWrapper(object):
    def __init__(self, tool):
        self.tool = tool
        self.__name__ = tool.name
    def _get_doc(self):
        return compile_docstring(self.tool)
    __doc__ = property(_get_doc)
    def __call__(self, *args):
        validate_args(args)
        return execute_tool(tool, args)

rawDescription: Dynamic function docstring

description: Dynamic function docstring


rawDescription: Python: xticks and labels stuck on one side of the subplot


code: loop_one = lambda seq: [lambda el=el: el for el in seq]

rawDescription: Weird lambda behaviour in loops in python 2.7, anybody has a clue?


rawDescription: In Python how to obtain a partial view of a dict?


rawDescription: Unable convert to int from bytes

description: Unable convert to int from bytes


rawDescription: Initialising a large dict with unknown keys? Is there a better way than this?


code: idx = np.vstack(itertools.combinations(range(n), k)) # an (n, k) array of indices

rawDescription: Combinations of features using Python NumPy


rawDescription: SQLAlchemy - can you add custom methods to the query object?


code:
def get_selected_ids(self):
    ids = []
    store, paths = self.get_selection().get_selected_rows()

    # self.adapter is a mapping class from my data-model to a model column index.
    # If you know the column index from your gtk.ListStore, you don't need it.
    colindex = self.adapter.get_column_modelindex("id")

    for path in paths:
        treeiter = store.get_iter(path)
        # Pull value from liststore
        val = store.get_value(
            treeiter,
            colindex
        )
        ids.append(val)
    return ids

rawDescription: Sending treeview information from button_press_event in pygtk


rawDescription: convert curl to python

description: Convert curl to python


code: cl != cl.shift()

rawDescription: Pandas Label Sequences of 1 in a 0-1 valued Series


code:
import ast
s = "'8255'"
ast.literal_eval(s)
int(ast.literal_eval(s))

rawDescription: Double string to int

description: Double string to int


rawDescription: open file in finder or explorer on linux or unix

description: Open file in finder or explorer on linux or unix


code: file = open(srcfile, 'rb')

rawDescription: Python code to move file over socket

description: Python code to move file over socket


code:
text = ''
while True:
    dummy = input('''Enter the paragraph :''')+'\n'
    if dummy=='\n':
        break
    text += dummy

rawDescription: Accept newline character in python

description: Accept newline character in python


code:
from scandir import walk
import curses
from os import path

try:
    stdscr = curses.initscr()
    curses.noecho()
    _, width = stdscr.getmaxyx()
    for root, dirs, files in walk("/Users"):
        for file in files:
            file_path = path.join(root, file)
            stdscr.addnstr(0, 0, "Scanning: {0}".format(file_path), width-1)
            stdscr.clrtoeol()
            stdscr.clearok(1)
            stdscr.refresh()
finally:
    curses.endwin()

rawDescription: How do I deal with lines that are longer than the Curses window in Python?

description: Deal with lines that are longer than the Curses window in Python


code:
from itertools import *
list(islice(gen_weird_sequence(count(), count()), 16))

rawDescription: Generate ordered tuples of infinite sequences


rawDescription: python list to dict conversion confusion

description: Python list to dict conversion confusion


code:
gr_columns = [x for x in df.columns if x not in ['d','e']]
df.groupby(gr_columns).agg(lambda col: ','.join(col))

rawDescription: Python Pandas: concatenate rows with unique values


code: bottom_right = lambda N, k: np.fliplr(np.tri(N, k=k-N)) == 1

rawDescription: Zero out matrix higher diagonal using numpy


code:
import operator
map(operator.eq, a, b)

rawDescription: How to compare two arrays in python with 1s for hits and 0s for non-hits?

description: Compare two arrays in python with 1s for hits and 0s for non-hits


code:
import matplotlib.pyplot as plt

ax = plt.subplot(111)
ax.grid(clip_on=False, marker='o', markersize=10)
plt.savefig('crosses.png')
plt.show()

rawDescription: Instead of grid lines on a plot, can matplotlib print grid crosses?


code:
class CustomSearchView(SearchView):
    template_name='/path/to/template.html'

rawDescription: How to display search results(django+haystack+elasticsearch) on the SAME page?

description: Display search results(django+haystack+elasticsearch) on the SAME page


code:
home = 0
def basestate(base):
    if base == 0:
        return 1
    else:
        return 0

home = basestate(home)
print(home)

rawDescription: How to make a function with a parameter?

description: Make a function with a parameter


code:
link = site.select('.//td[@class="complaint"]/a/@href').extract()
if link:
    item['link'] = link[0]

rawDescription: using scrapy extracting data inside links

description: Using scrapy extracting data inside links


code:
from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
    # Executes every Monday morning at 7:30 A.M
    'every-monday-morning': {
        'task': 'tasks.add',
        'schedule': crontab(hour=7, minute=30, day_of_week=1),
        'args': (16, 16),
    },
}

rawDescription: How to execute a command at exact time once a day in Django?

description: Execute a command at exact time once a day in Django


code:
os.path.relpath('/foo/bar/baz', '/foo')
os.path.sep = '\\'   # I need this because i'm not on dos/cpm/vax/nt
os.path.relpath('c:\\foo\\bar\\baz', 'c:\\foo')

rawDescription: Get relative path of file1 (relative to path of file2, file1 is in subfolder of file2)


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

a = np.array([[ 1, 2, 3, 4, 5, 6, 7, 8 ],
              [ 9, 8, 7, 6, 5, 4, 3, 2 ]])

categories = np.array([0, 2, 1, 1, 1, 2, 0, 0])

colormap = np.array(['r', 'g', 'b'])

plt.scatter(a[0], a[1], s=50, c=colormap[categories])
plt.show()

rawDescription: Using multiple colors in matplotlib plot


code:
cnt = Counter(chain.from_iterable(substrings(line, 4) for line in lines))
cnt.most_common(2000)

rawDescription: Given a list of words, identify all identical substrings of length 4 or greater


code: match = re.search(pattern, line)

rawDescription: Selecting item in a string from a starting point retrieved via regex (Python)


code:
from collections import defaultdict
def monthdict():
    return defaultdict(list)

data = defaultdict(monthdict)
data[2013][3].append(23)
data

rawDescription: Which data structure to use in Python to store data like this?


code:
counter = 0;
while True:
    [x, y, z][counter % 3]()
    counter += 1

rawDescription: Inside a range how can I internally count up to 3?


code:
class Z:
    def __init__(self):
        self.a, self.b, self.c = 1,2,3

    def it(self):
        for x in 'abc':
            yield getattr(self, x), lambda y: setattr(self, x, y)

z = Z()
for x, setter in z.it():
    if x == 1:
       setter(42) # works!

rawDescription: Python: Assigning "through" an iterator

description: Python: Assigning "through" an iterator


rawDescription: Creating numpy array with empty columns using genfromtxt


rawDescription: divide by zero encountered in double_scalars for derivative calculations

description: Divide by zero encountered in double_scalars for derivative calculations


code:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import random

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure(1)
fig.clf()
ax = Axes3D(fig)
datasets = random((8,100,3))*512
my_labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

colors = ['k', "#B3C95A", 'b', '#63B8FF', 'g', "#FF3300",
          'r', 'k']
index = 0
for data, curr_color in zip(datasets, colors):
    ax.plot(np.log2(data[:, 0]), np.log2(data[:, 1]),
                   np.log2(data[:, 2]), 'o', c=curr_color, label=my_labels[index])
    index += 1

ax.set_zlim3d([-1, 9])
ax.set_ylim3d([-1, 9])
ax.set_xlim3d([-1, 9])

ax.set_xticks(range(0,11))
ax.set_yticks([1,2,8])
ax.set_zticks(np.arange(0,9,.5))

ax.legend(loc = 'upper left')

plt.draw()

plt.show()

rawDescription: plotting 3d scatter in matplotlib

description: Plotting 3d scatter in matplotlib


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

rawDescription: Fitting ARMA model to time series indexed by time in python


rawDescription: How to split a string by multiple characters and keep the split chars in return value?

description: Split a string by multiple characters and keep the split chars in return value


code:
#. Translators:
# Blah blah blah
_("String")

rawDescription: adding comments to pot files automatically

description: Adding comments to pot files automatically


code:
def remove_starts(lst):
    seen = []
    for elem in lst:
        if elem.startswith(tuple(seen)):
            continue
        yield elem
        seen.append(elem[:4])

rawDescription: remove later strings starting with a certain thing in a list python

description: Remove later strings starting with a certain thing in a list python


code:
class Foo:
    def __init__(self):
        print ("__int__() called.")

    def __del__(self):
        print ("__del__() called.")

    def __enter__(self):
        print ("__enter__() called.")
        return self # foo now stores the Foo() object

    def __str__(self):
        return 'returned_test_str'

    def __exit__(self, exc, value, tb):
        print ("__exit__() called.")

    def close(self):
        print ("close() called.")

    def test(self):
        print ("test() called.")

if __name__ == "__main__":
    with Foo() as foo:
        print ("with block begin???")
        print ("with block end???")

    print ("foo:", foo)  # line 1

rawDescription: Why is __del__ called at the end of a with block?


code:
without_reset * reset_at
np.maximum.accumulate(without_reset * reset_at)

rawDescription: Cumulative counts in NumPy without iteration


code: egroup

rawDescription: Find recurring events in time series with pandas


code:
def str_of_code(d):
    k, v = list(d.items())[0]
    kwargs = {}
    for k2, v2 in v.items():
        if isinstance(v2, dict):
            kwargs[k2] = str_of_code(v2)
        elif isinstance(v2, list):
            kwargs[k2] = '[{}]'.format(', '.join(
                (str_of_code(v3) if isinstance(v3, dict) else repr(v3)) for v3 in v2)
            )
        else:
            kwargs[k2] = repr(v2)
    return '{}({})'.format(k, ', '.join('{}={}'.format(*i) for i in kwargs.items()))

test_dict = {
    'test1': {
        't_arg': 1,
        't_arg2': [
            {'test2': {'t_arg': 2}},
            {'test2': {'t_arg': 3}},
        ]
    }
}

res = str_of_code(test_dict)
print(res)  # test1(t_arg=1, t_arg2=[test2(t_arg=2), test2(t_arg=3)])

rawDescription: Read python dict or yaml and call as python function with arguments and objects


code:
from datetime import datetime
from dateutil.parser import parse

d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strftime(parse(d), '%Y-%m-%d %H:%M:%S.%f')

rawDescription: Convert email (rfc 2822) date string to another format (ISO 8601 timestamp) in Python 2.7


code:
def findit3(fruits,color):
    mylist = []
    for indv in fruits:
        if color in indv['color']:
            mylist.append(  (indv['name'], indv['weight'])  )
    return mylist

rawDescription: How to retrieve a variable from a list located in a dictionary, located in a list? two

description: Retrieve a variable from a list located in a dictionary, located in a list? two


code:
def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.gray())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional

rawDescription: Multiple figures in a single window

description: Multiple figures in a single window


code:
qry = session.query(SomeTable)
dt_column =(func.substr(SomeTable.date, 7) + "-" +
            func.substr(SomeTable.date, 4, 2) + "-" +
            func.substr(SomeTable.date, 1, 2) + " " + SomeTable.time)
dt_column = func.datetime(dt_column)
qry = qry.filter(dt_column <= datetime(2013, 1, 1, 23, 59, 59))

rawDescription: Converting string to date timestamp in SQLAlchemy


code:
indexes = []
for i, triplet in enumerate(zip(a, b, c)):
    if any(e > max_limit for e in triplet):
        indexes.append(i)

rawDescription: Make this simple for/if block more pythonic


code:
import numpy as np

# Convert to numpy arrays
A_arr = np.array(A)
X_arr = np.array(X)

# Mask that represents "if a[k] <  x[i] < b[k]:" for all i,k
mask = (A_arr[:,None,0]<X_arr) & (X_arr<A_arr[:,None,1])

# Get indices where the mask has 1s, i.e. the conditionals were satisfied
_,C = np.where(mask)

# Setup output numpy array and set values in it from third column of A
# that has conditionals satisfied for specific indices
Y = np.ones_like(X_arr)
Y[C] = A_arr[C,2]

rawDescription: Build array from other array and table of values (Python)


code: [list(itertools.chain(*x)) for x in itertools.permutations(l, len(l))]

rawDescription: Making all possible combination of lists in lists


code:
# each value consists of printable words separated by at most a
# single space (a space that is not followed by another space)
value = Combine(OneOrMore(Word(printables) | White(' ',max=1) + ~White()))

rawDescription: pyparsing whitespace match issues

description: Pyparsing whitespace match issues


code:
#eg: myapp/5/copy/
#where 5 is the item I want to copy
url(r'^(?P<id>[0-9]+)/copy/$', views.item_copy, name='item_copy'),

rawDescription: Django: copy a model object using views and forms


code: self.menult = OptionMenu(randomwindow, var, *filter(None, self.array_lt))

rawDescription: Tkinter - Only show filled values of an array in a OptionMenu


code:
indexes = [0, 1]
for ind in indexes:
    val =  my_lst[ind]
    my_lst[ind] = rev_subs.get(val, val)

rawDescription: How to replace elements in a list using dictionary lookup

description: Replace elements in a list using dictionary lookup


code: a2[slice(None, a1.shape[0]), slice(None, a1.shape[1])]

rawDescription: How can I change values for a section of a numpy array?

description: Change values for a section of a numpy array


code:
def mydiff(L, acc=None):
    if not L:
        return acc
    else:
        if acc is None:
            acc = L[0] - L[1]
            L = L[2:]
        else:
            acc -= L[0]
            L = L[1:]
        return mydiff(L, acc)

rawDescription: Subtraction(list) recursively in Python 3


code:
import ast

dataInput = [ast.literal_eval(line) for line in fobj.splitlines()]

rawDescription: How to convert list lookalike into a list?

description: Convert list lookalike into a list


code:
from threading import Timer,Event

class perpetualTimer(object):

   # give it a cycle time (t) and a callback (hFunction)
   def __init__(self,t,hFunction):
      self.t=t
      self.stop = Event()
      self.hFunction = hFunction
      self.thread = Timer(self.t,self.handle_function)

   def handle_function(self):
      self.hFunction()
      self.thread = Timer(self.t,self.handle_function)
      if not self.stop.is_set():
          self.thread.start()

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

   def cancel(self):
      self.stop.set()
      self.thread.cancel()

rawDescription: Is it possible to execute function every x seconds in python, when it is performing pool.map?


code:
tmpeb = gtk.EventBox()
st = tmpeb.get_style().copy()
st.bg[gtk.STATE_PRELIGHT] = gtk.gdk.Color(65535,65535,0)
self.rowStyle = st

rawDescription: How can I highlight a row in a gtk.Table?

description: Highlight a row in a gtk.Table


code:
all_genres = pd.unique(movies[['Genre1','Genre2','Genre3']].values.ravel())

mean_series = pd.Series(index=all_genres)
for genre in all_genres:
    mean_series[genre] = movies.sales.loc[movies.eval(
        'Genre1 == "{0}" or Genre2 == "{0}" or Genre3 == "{0}"'
        .format(genre)).values].mean()

# Or in one (long) line:
mean_df = pd.DataFrame(columns=['Genre'], data=all_genres)
mean_df['mean'] = mean_df.Genre.apply(
    lambda x: movies.sales.loc[movies.eval(
        'Genre1 == "{0}" or Genre2 == "{0}" or Genre3 == "{0}"'
        .format(x)).values].mean())

rawDescription: np.mean for rows with specific values across multiple columns

description: Np.mean for rows with specific values across multiple columns


code:
def mainloop():
   while True:
       ...
       obj.update()
       if obj.getRect().colliderect(world[ID].getRect()): # don't do "== True" in `if's - it is just silly
             # take character back to the precious position
             obj.x -= obj.vx
             obj.y -= obj.vy
             # zero out velocities to make it stop:
             obj.vx = obj.vy = 0

rawDescription: Python rectangle collision handling with pygame


rawDescription: Matplotlib: data not showing on the two sides in heatmap using x, y, z values stored in lists


code:
from itertools import izip_longest
country_name = ['South Africa', 'India', 'United States', 'Netherlands']
country_code = ['ZA', 'IN', 'US']
list(izip_longest(country_name, country_code))

rawDescription: zip two strings in python

description: Zip two strings in python


code: df2 = df[pd.notnull(df.avg_2)].copy()

rawDescription: pandas: t-test and p-value of month over month mean difference in aggregated dataframe using groupby function

description: Pandas: t-test and p-value of month over month mean difference in aggregated dataframe using groupby function


code:
def new_getpass(username):
    with open("/etc/passwd", "r") as f:
        for entry in [l.split(":") for l in f.readlines()]:
            if entry[0] == username:
                return entry
    return None

rawDescription: Python Fabric load config from separate file


code:
import Image, ImageDraw

im = Image.open("Two_Dalmatians.jpg")

draw = ImageDraw.Draw(im)

# Locate the "moon" in the upper-left region of the image
xy=[x/4 for x in im.size+im.size]

# Bounding-box is 40x40, so radius of interior circle is 20
xy=[xy[0]-20, xy[1]-20, xy[2]+20, xy[3]+20]

# Fill a chord that starts at 45 degrees and ends at 225 degrees.
draw.chord(xy, 45, 45+180, outline="white", fill="white")

del draw

# save to a different file
with open("Two_Dalmatians_Plus_Moon.png", "wb") as fp:
    im.save(fp, "PNG")

rawDescription: Create a half circle in angle 45 in Python


rawDescription: Print two presorted lists into one output file in python


code: grouped = list(group_by_month(items))

rawDescription: How to group items in array?

description: Group items in array


code:
def __init__ (self, content,vis):
    self.content = content
    self.visibility = vis[:]    # here
    # etc.

rawDescription: Incomprehensible behaviour of class variables


code:
# main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

def process_my_data(input_data):
    return input_data+' I was processed!'

class MainLayout(BoxLayout):

    def update_label(self):
        input_data=self.ids.my_input.text
        #~ your logics goes here
        #~ do wathever you want with input data
        output_data=process_my_data(input_data)
        #~ and then update the label with the result
        self.ids.my_output.text=output_data

class Controller(App):

    def build(self):
        my_layout = MainLayout(orientation = "vertical")
        return my_layout

if __name__ == "__main__":
        Controller().run()

rawDescription: How to merge my working Python code with Kivy?

description: Merge my working Python code with Kivy


code:
# yourapp/views/filters.py

import random
from string import ascii_letters, digits

from flask import request, session, redirect
from yourapp import app

def generate_form_token():
    """Sets a token to prevent double posts."""
    if '_form_token' not in session:
        form_token = \
            ''.join([random.choice(ascii_letters+digits) for i in range(32)])
        session['_form_token'] = form_token
    return session['_form_token']

@app.before_request
def check_form_token():
    """Checks for a valid form token in POST requests."""
    if request.method == 'POST':
        token = session.pop('_form_token', None)
        if not token or token != request.form.get('_form_token'):
            redirect(request.url)

app.jinja_env.globals['form_token'] = generate_form_token

rawDescription: WTForms double POST submit prevention on refresh flask-wtf


rawDescription: Importing csv file into python and creating a table in python


code:
text = re.sub('\n+', '\n', text) # 2nd call to re.sub
text
'Brand：\n 777,Royal Lion\n Main Products:\n battery, 777, carbon zinc, paper jacket,'

rawDescription: Python: re.sub changes nothing

description: Python: re.sub changes nothing


code:
import numpy as np
from scipy.signal import butter, lfilter

##############################################################
# For generating sample-data
##############################################################
from scipy.integrate import odeint

def roessler_ode(y,t,omega=1,a=0.165,b=0.2,c=10):
    dy = np.zeros((3))
    dy[0] = -1.0*(omega*y[1] + y[2]) #+ e1*(y[3]-y[0])
    dy[1] = omega * y[0] + a * y[1]
    dy[2] = b + y[2] * (y[0] - c)
    return dy

class Roessler(object):
    """A single coupled Roessler oscillators"""
    def __init__(self, y=None, omega=1.0, a=0.165,b=0.2,c=10):
        self.omega = omega
        self.a = a
        self.b = b
        self.c = c
        if y==None:
            self.y = np.random.random((3))+0.5
        else:
            self.y = y

    def ode(self,y,t):
        dy = roessler_ode(y[:],t,self.omega,self.a,self.b,self.c)
        return dy

    def integrate(self,ts):
        rv = odeint(self.ode,self.y,ts)
        self.y = rv[-1,:]
        return rv
###############################################################

rawDescription: Most efficient way to filter a long time series Python


code:
class secret():
    def _default(self):
        raise web.notfound()

    def GET(self):
        ...

rawDescription: web.py: How to selectively hide resources with 404s for any HTTP method?

description: Web.py: How to selectively hide resources with 404s for any HTTP method


code: on_press: app.do_login()

rawDescription: Kivy run function from kv button

description: Kivy run function from kv button


code:
dim = 250
num_sticks = 300

rawDescription: Directly "plot" line segments to numpy array


code: diffusion_coefficient = dielectric_solvent * ((mesh.x > -0.5) & (mesh.x < 0.5))

rawDescription: Space dependent diffusion in fipy

description: Space dependent diffusion in fipy


rawDescription: What is the pythonic way to this dict to list conversion?


rawDescription: Get max length of multi-dimension tuple

description: Get max length of multi-dimension tuple


rawDescription: How to use urllib in python 3?

description: Use urllib in python 3


code:
a = ['0010010', '0011101']
for i, elem in enumerate(a):
    a[i] = ''.join(str(1 - int(char)) if random.random() < prob else char
                   for char in elem)

rawDescription: Flip 1s to 0s and viceversa in string elements


code:
from __future__ import print_function
print ("the value of x is","foo")

rawDescription: printing string containing variables in python

description: Printing string containing variables in python


code:
def my_join(x):
    return " ".join(map(str, x))

my_join([1, 2, 3, 4])

rawDescription: Converting a set to a string

description: Converting a set to a string


code:
for f in sys.argv[1:]:
    data = []
    with open(f) as inp:
           lines = set(line.rstrip() for line in  inp)
           data.append(lines)
    common_lines = data[0].intersection(*data[1:])

rawDescription: Intersection between multiple files

description: Intersection between multiple files


rawDescription: How can I use django-storages for both media and static files?

description: Use django-storages for both media and static files


code:
def verify(self):
    t.set_gravity(self.original)

rawDescription: Accessing the variable from another function of the same class


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

fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

rawDescription: Matplotlib table only

description: Matplotlib table only


code:
def permute(it):
    return itertools.product(*(itertools.permutations(i) for i in it))

rawDescription: Python permutations of both sequence and subsequences


code:
def customize_string(string,add_on):
    if "small" in string:
        line = string.split()
        line[0] += add_on
        line[-1] += add_on
        return "  ".join(line)
    else:
        return string

rawDescription: Find and replace a string in Python

description: Find and replace a string in Python


code:
SPIDER_MIDDLEWARES = {
    'myproject.middlewares.DomainDepthMiddleware': 900,
    'scrapy.contrib.spidermiddleware.depth.DepthMiddleware': None
}

rawDescription: Scrapy set depth limit per allowed_domains


code:
row = 5
columns = 5
for row in range(1, row+1):
    for col in range(1,columns+1):
        print("{: >3}".format(row * col), end="")
    print()

rawDescription: Allignment of multiplication table in Python


rawDescription: Recomended way to create a matrix containing strings in python


code: df

rawDescription: Read flat file to DataFrames using Pandas with field specifiers in-line


code:
class Post(Base):
    __tablename__ = 'post'

    id = Column(Integer, primary_key=True)
    text = Column(Unicode)

class Like(Base):
    __tablename__ = 'like'

    id = Column(Integer, primary_key=True)
    post_id = Column(Integer, ForeignKey(Post.id), nullable=False)

class Alert(Base):
    __tablename__ = 'alert'

    id = Column(Integer, primary_key=True)
    like_id = Column(Integer, ForeignKey(Like.id))

rawDescription: Sqlalchemy "double layer" query

description: Sqlalchemy "double layer" query


code:
list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
max(map(len, list1))

rawDescription: Return len of the longest word in a list


code:
def removeFromList(elementsToRemove):
    def closure(list):
        for element in elementsToRemove:
            if list[0] != element:
                return
            else:
               list.pop(0)
    return closure

def func(listOfLists):
    result = []
    for i, thisList in enumerate(listOfLists):
        result.append(thisList)
        map(removeFromList(thisList), listOfLists[i+1:])
    return result

rawDescription: How to breakup a list of list in a given way in Python

description: Breakup a list of list in a given way in Python


code: "OR ( AND ( maria sharapova ) tennis )"

rawDescription: Constructing a tree using Python

description: Constructing a tree using Python


code: [match.start() for match in re.finditer(re.escape(s2), string)]

rawDescription: Given 2 strings find the indexes where one string occurs in another


code:
from ciscoconfparse import CiscoConfParse

parse = CiscoConfParse('fullconfig.txt')

objs = list()
objs.extend(parse.find_objects(r'^policy-map'))    # Append policy-map obj
objs.extend(parse.find_objects(r'ip\saccess-list'))# Append ip access-list obj

for obj in objs:
    # When you delete a parent obj, it recurses through all children
    obj.delete()
parse.commit()

parse.save_as('basic_config.txt')  # Save the new configuration

rawDescription: Python ciscoconfparse - build a basic config file


code:
seen_set = set()
new_d = []
for i in d:
    if tuple([i['feature_a'],i['feature_b'],i['feature_c']]) not in seen_set:
        new_d.append(i)
        seen_set.add(tuple([i['feature_a'],i['feature_b'],i['feature_c']]))

rawDescription: How to make values in list of dictionary unique?

description: Make values in list of dictionary unique


code:
ii=[[i]*len(v) for i,v in enumerate(vectors)]
ii=list(chain(*ii))

rawDescription: scipy csr_matrix from several vectors represented as list of sets

description: Scipy csr_matrix from several vectors represented as list of sets


code:
import re
p = re.compile(r'[A-Z]+(?:_[A-Z]+)*_[A-Z0-9]+')
test_str = "QWERT A_B_C_1 UIOP\nQwert A_X_Y_Z uiop"

re.findall(p, test_str)

rawDescription: Using regular expression for fetching multiple keywords using python 3.4


code:
def map_many(iterable, function, *other):
    if other:
        return map_many(map(function, iterable), *other)
    return map(function, iterable)

rawDescription: Apply multiple functions with map

description: Apply multiple functions with map


code:
results = [item.text for item in find]
output.writerows(results)

rawDescription: Web scraper returning list of elements

description: Web scraper returning list of elements


rawDescription: working with combinations object in python

description: Working with combinations object in python


code:
n = 100
s = scipy.sparse.lil_matrix((n,n),dtype=int)
s[10, 12] = 1
(10, 12) in get_items(s)

rawDescription: Check if scipy sparse matrix entry exists


code:
f.read()
f.seek(0)
f.read()

rawDescription: Python, write in memory zip to file

description: Python, write in memory zip to file


code:
import numbers
isinstance(int, numbers.Real)
isinstance(int(), numbers.Real)
isinstance(float, numbers.Real)
isinstance(float(), numbers.Real)

rawDescription: Why does "isinstance(numpy.float64,numbers.Real)" return False?


code:
from urllib.parse import urlparse
o = urlparse('https://api.somedomain.co.uk/api/addresses?postcode=XXSDF&houseNo=34')
o
o.scheme
o.port
o.geturl()

rawDescription: splitting a full url into parts

description: Splitting a full url into parts


code:
with open('yourfile.txt') as f:
    lines_after_17 = f.readlines()[17:]

rawDescription: Skip first couple of lines while reading lines in Python file