title: 【推荐】成都空压机|四川空压机|成都空气压缩机|四川空气压缩机|成都螺杆空压机|四川螺杆空压机|成都双螺杆空压机|四川双螺杆空压机|成都福道贸易有限公司

title: 餐饮世界人才网-中国厨师人才网-中国酒店人才网

title: 恩施旅游网--恩施大峡谷 腾龙洞 利川 清江闯滩 土司城 欢迎您！

title: 莱阳论坛_莱阳吧_莱阳人的网络社区 -

title: フォトスタジオ・タウン-就職証明写真・お受験写真・オーディション写真-

title: 上海商铺出租/转让,上海门面房出租信息/上海门面转让-上海商铺网

title: MSDS查询网 英文MSDS查询网 MSDS MSDS报告 MSDS下载 msds是什么意思 MSDS安全网

title: 上海精工阀门厂总代理★上海精工阀门|上工牌阀门|精工阀门厂|上海阀门|精工阀门|广东阀门|广州阀门|惠州阀门|东莞阀门|佛山阀门|深圳阀门|中山阀门|潮州阀门|珠海阀门|河源阀门|汕头阀门|肇庆阀门|

title: Bookings Caribbean | Barbados Bookings Center. Book barbados Hotels and Activities. Search, tourism

rawDescription: decoding json in python

description: Decoding json in python


code:
for col in prob.columns:
    idx = (prob[col].idxmax())
    print('{}: {}'.format(prevstate.loc[idx, col], prob.loc[idx, col]))

rawDescription: Python: Pandas DataFrame for tuples

description: Python: Pandas DataFrame for tuples


code:
decoded = json.loads(encoded, 'gbk')
pprint(decoded)

rawDescription: How to convert a JSON string into a Python data structure

description: Convert a JSON string into a Python data structure


rawDescription: Python - Don't Understand The Returned Results of This Concatenated Regex Pattern


code:
def digit_match_greater(n):
    digits = str(n)
    variations = []
    # Anything with more than len(digits) digits is a match:
    variations.append(r"\d{%d,}" % (len(digits)+1))
    # Now match numbers with len(digits) digits.
    # (Generate, e.g, for 15, "1[6-9]", "[2-9]\d")
    # 9s can be skipped -- e.g. for >19 we only need [2-9]\d.
    for i, d in enumerate(digits):
        if d != "9":
            pattern = list(digits)
            pattern[i] = "[%d-9]" % (int(d) + 1)
            for j in range(i+1, len(digits)):
                pattern[j] = r"\d"
            variations.append("".join(pattern))
    return "(?:%s)" % "|".join("(?:%s)" % v for v in variations)

rawDescription: generate python regex at runtime to match numbers from 'n' to infinite

description: Generate python regex at runtime to match numbers from 'n' to infinite


code:
from sqlalchemy import create_engine, Column, String, Integer, MetaData, Table
from sqlalchemy.orm import mapper, create_session
import csv
CSV_FILE = 'foo.csv'
engine = create_engine('sqlite://') # memory-only database

table = None
metadata = MetaData(bind=engine)
with open(CSV_FILE) as f:
    # assume first line is header
    cf = csv.DictReader(f, delimiter=',')
    for row in cf:
        if table is None:
            # create the table
            table = Table('foo', metadata,
                Column('id', Integer, primary_key=True),
                *(Column(rowname, String()) for rowname in row.keys()))
            table.create()
        # insert data into the table
        table.insert().values(**row).execute()

class CsvTable(object): pass
mapper(CsvTable, table)
session = create_session(bind=engine, autocommit=False, autoflush=True)

rawDescription: Database on the fly with scripting languages


rawDescription: How to encode categorical values in Python

description: Encode categorical values in Python


code:
df2['index'] = df2.index
df3 = df2.drop_duplicates(cols='index', take_last=True).reindex(df.index, method='ffill')
del df3['index']
df3

rawDescription: pandas reindex a dataframe with duplicate keys

description: Pandas reindex a dataframe with duplicate keys


code:
import code, traceback, signal

def debug(sig, frame):
    """Interrupt running process, and provide a python prompt for
    interactive debugging."""
    d={'_frame':frame}         # Allow access to frame object.
    d.update(frame.f_globals)  # Unless shadowed by global
    d.update(frame.f_locals)

    i = code.InteractiveConsole(d)
    message  = "Signal received : entering python shell.\nTraceback:\n"
    message += ''.join(traceback.format_stack(frame))
    i.interact(message)

def listen():
    signal.signal(signal.SIGUSR1, debug)  # Register handler

rawDescription: Showing the stack trace from a running Python application


code:
p = []
a = ['s', 'l', 'y']
for s in a:
    p.append(('size',  s))

print(p)

rawDescription: Converting an array to hash in python

description: Converting an array to hash in python


code: cur.execute("CREATE TABLE C(Id PRIMARY KEY)");

rawDescription: Make sqlite3 column update faster

description: Make sqlite3 column update faster


code:
paths = ['path1', 'path2', 'path3']
sounds = [ pygame.mixer.Sound(path) for path in paths ]

# play all sounds sequentially
for sound in sounds:
    sound.play()

rawDescription: Variable Variables in Python

description: Variable Variables in Python


code:
#!/usr/bin/env python
import calendar
from datetime import datetime
import pytz # $ pip install pytz

now = datetime.now(pytz.timezone('Asia/Tokyo')) # you could pass `timezone` object here
weekday = now.weekday()
print(calendar.day_name[weekday])

rawDescription: Getting the current day of another country python


code: zip(*values)

rawDescription: Sum float values at each index point in nested lists


code:
from flask import session

@app.route('/login')
def login():
    # ...
    if login_user(user):
        session.permanent = True
        return redirect(request.args.get('next') or url_for('index'))
    # ...

rawDescription: flask-login: Chrome ignoring cookie expiration?

description: Flask-login: Chrome ignoring cookie expiration


code:
'x' * 100000 # or,

''.join('x' for x in xrange(100000)) # or,

from itertools import repeat
''.join(repeat('x', times=100000))

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

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


code:
# using grid
# +------+-------------+
# | btn1 |    btn2     |
# +------+------+------+
# | btn3 | btn3 | btn4 |
# +-------------+------+
root = Tk()
btn1 = Button(text='btn1', font=helv36)
btn2 = Button(text='btn2', font=helv36)
btn3 = Button(text='btn3', font=helv36)
btn4 = Button(text='btn4', font=helv36)
btn5 = Button(text='btn5', font=helv36)
root.rowconfigure((0,1), weight=1)  # make buttons stretch when
root.columnconfigure((0,2), weight=1)  # when window is resized
btn1.grid(row=0, column=0, columnspan=1, sticky='EWNS')
btn2.grid(row=0, column=1, columnspan=2, sticky='EWNS')
btn3.grid(row=1, column=0, columnspan=1, sticky='EWNS')
btn4.grid(row=1, column=1, columnspan=1, sticky='EWNS')
btn5.grid(row=1, column=2, columnspan=1, sticky='EWNS')

rawDescription: How to change font and size of buttons and frame in tkinter using python?

description: Change font and size of buttons and frame in tkinter using python


code:
from pprint import pprint
def recursive_remap(d, keymap):
    if isinstance(d, dict):
        return {keymap[k]: recursive_remap(v, keymap) for k, v in d.items()}
    return d
dict1 = {'ar': {'az': {'ae': {'aq': 'talo', 'ai': {'aq': 'go', 'ay': 'wed', 'as': {'aq': 'so', 'ay': 'to', 'as': 'mo', 'al': 'kato'}, 'am': 'yo'}}, 'aj': {'ai': {'ay': 'ryan', 'am': 'masan.com', 'ao': 'swan toro'}, 'ax': 'qua-la-sa'}, 'ap': {'ak': 'stepg-sdd:sdf', 'au': 'asfd.asf'}, 'at': 'pirat9333', 'aw': {'aq': '1234bfh', 'ai': {'aq': 'ejs-33', 'ay': 'mnhfg', 'as': {'ay': 'qwqwa-wnnf', 'as': '213bvn'}}}, 'av': {'ac': {'aa': 'http://swan.com', 'ah': 'ryan', 'am': '1123'}, 'af': 'Tran swa'}}, 'ad': 'tues', 'ag': 'mon'}}
dict2 = {'key1': 'aa', 'key2': 'ab', 'key3': 'ac', 'key4': 'ad', 'key5': 'ae', 'key6': 'af', 'key7': 'ag', 'key8': 'ah', 'key9': 'ai', 'key10': 'aj', 'key11': 'ak', 'key12': 'al', 'key13': 'am', 'key14': 'an', 'key15': 'ao', 'key16': 'ap', 'key17': 'aq', 'key18': 'ar', 'key2': 'as', 'key19': 'at', 'key20': 'au', 'key21': 'av', 'key22': 'aw', 'key23': 'ax', 'key24': 'ay', 'key25': 'az'}
dict2_inverse = {v: k for k, v in dict2.items()}
recursive_remap(dict1, dict2_inverse)
pprint(_)

rawDescription: Remap keys of a recursive dictionary, using another dictionary


code:
import numpy
x = numpy.array([[0,0],[1,1]])
y = numpy.array([[1,0],[0,1]])
x ^ y

rawDescription: Numpy Modular arithmetic

description: Numpy Modular arithmetic


code:
years_dict = dict()

for line in list:
    if line[0] in years_dict:
        # append the new number to the existing array at this slot
        years_dict[line[0]].append(line[1])
    else:
        # create a new array in this slot
        years_dict[line[0]] = [line[1]]

rawDescription: append multiple values for one key in Python dictionary

description: Append multiple values for one key in Python dictionary


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import class_mapper

Base= declarative_base()

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    type = Column(String)
    __mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "a"}

class B(A):
    pass

mapper = class_mapper(B)
mapper.polymorphic_identity = "b"
mapper.polymorphic_map["b"] = mapper

e = create_engine("sqlite://", echo=True)

Base.metadata.create_all(e)

s = Session(e)

s.add_all([A(), B(), B(), A(), A()])
s.commit()

s.close()

assert [obj.type for obj in s.query(B).order_by(A.id)] \
            == ['b', 'b']

assert [type(obj) for obj in s.query(B).order_by(A.id)] \
            == [B, B]

assert [obj.type for obj in s.query(A).order_by(A.id)] \
            == ['a', 'b', 'b', 'a', 'a']

rawDescription: How can I set Polymorphic Identity after a class is defined?

description: Set Polymorphic Identity after a class is defined


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

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


code:
olist = myImage_mask.outline()
pygame.draw.lines(blankSurf,(200,150,150),1,olist)

rawDescription: Display PyGame Mask on screen

description: Display PyGame Mask on screen


code:
a
b
b*a[...,None]

rawDescription: Multiplying 2d array by 1d array

description: Multiplying 2d array by 1d array


code:
RandomDoorCreator(level) #Create a random door BEFORE we create walls
x = y = 0
for row in level:
    for col in row:
        if col == "W" or col == "R": #Only row changed -- we just want to account for our new R values
            Wall((x, y))
        x += 16
    y += 16
    x = 0
for wall in walls:
        pygame.draw.rect(screen, (255, 255, 255), wall.rect)

rawDescription: Create a random door in pygame

description: Create a random door in pygame


code:
s = bitstring.BitString(hex=hex(i))
('0x0' + s if s.len%8 else s).bytes

rawDescription: How to convert an integer to variable length byte string?

description: Convert an integer to variable length byte string


rawDescription: Split an array according to it's information


code:
import time
epoch = int(time.mktime(mydate.timetuple())*1000)

rawDescription: django Datefield to Unix timestamp

description: Django Datefield to Unix timestamp


code:
data = open('works.log', 'rb').read()
all(d < '\x80' for d in data)

rawDescription: Python kludge to read UCS-2 (UTF-16?) as ASCII


code: newvalue

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

description: Store a list as a dictionary - python


code:
word_freq
filtered_word_freq = dict((word, freq) for word, freq in word_freq.items() if word not in stopwords)
filtered_word_freq

rawDescription: Dropping specific words out of an NLTK distribution beyond stopwords


code:
tmp = (df
   .withColumn("ind", ind)
   .groupBy("individual", "area_id", "ind")
   .agg(f.min("datetime").alias("datetime"))
   .drop("ind"))

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


code:
if 'test' in sys.argv:
    DATABASE_ENGINE = 'sqlite3'

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

description: Run Django's test database only in memory


code: print (pd.merge(df1, df2, on='company'))

rawDescription: how to merge two data frames based on particular column in pandas python?

description: Merge two data frames based on particular column in pandas python


code: a = {k: d.get(k, 0) for k in d}

rawDescription: Simple syntax error in Python if else dict comprehension


code:
from collections import defaultdict

freq = defaultdict(int)
freq['182666828988'] += 1
freq['182666828988'] += 1
freq['183a2d4e3a12'] += 1

print(freq)

rawDescription: Searching and updating hexadecimal values in python


code:
df.columns.names = ['IDX4', 'ValueType']
series = df.stack(['IDX4', 'ValueType'], dropna=False)

rawDescription: How can I use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place?

description: Use melt() to reshape a pandas DataFrame to a list, creating an index from a crosstab column and creating a new variable in its place


rawDescription: Dividing in Python

description: Dividing in Python


code:
def getent1():
    return ent1var.get()

rawDescription: How to save entry field values to disk in Tkinter?

description: Save entry field values to disk in Tkinter


code:
from django.template.defaultfilters import slugify

u'http://domain.com/%s/' % slugify(some_string_with_spaces)

rawDescription: using unicode strings with white space as Django url variable

description: Using unicode strings with white space as Django url variable


code:
import re

sentences = [""""'This has punctuation, and it's hard to remove. ?" """,
             "Did you see Cress' haircut?.",
             "This 'thing' hasn't a really bad habit, you know?.",
             "'I bought this for $30 from Best Buy it's. What a waste of money! The ear gels are 'comfortable at first, but what's after an hour."]

for s in sentences:
    # Remove the specified characters
    new_s = re.sub(r"""["?,$!]|'(?!(?<! ')[ts])""", "", s)

    # Deal with the final dot
    new_s = re.sub(r"\.", " .", new_s)
    print(new_s)

rawDescription: how to not remove apostrophe only for some words in text file in python

description: Not remove apostrophe only for some words in text file in python


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

def scale_xaxis(number):
    return(number+1001)

def my_form(x,pos):
    return '%d'%scale_xaxis(x)

data = np.array([range(10),range(10,20)])
fig = plt.figure(figsize=(3,5))
ax = fig.add_subplot(111)
ax.imshow(data,aspect='auto')
ax.autoscale(False)
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(int(2)))
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(my_form))

rawDescription: Custom ticks autoscaled when using imshow?


rawDescription: How to strip the string which contain forward slash?

description: Strip the string which contain forward slash


code:
def find_minimum(l):
    min_value = float('inf') # use the positive infinite value per default
    for elt in l:
        if elt < min_value:
            min_value = elt
    return min_value

def find_maximum(l):
    max_value = 0
    for elt in l:
        if elt > max_value:
            max_value = elt
    return max_value

rawDescription: Getting specific values from different lists and how to


code:
generatorTransport = reactor.spawnProcess(..., childFDs={1: write})
ffmpegTransport = reactor.spawnProcess(..., childFDs={0: read})

rawDescription: Twisted pipe two processes with spawnProcess


code: tcProcess = subprocess.Popen( ['app','tc']) # assuming tc is going as an argument to app

rawDescription: Running test cases for C program in run time via python


code:
with open('data.p', 'rb') as fp:
    data = pickle.load(fp)

rawDescription: Storing Python dictionaries

description: Storing Python dictionaries


code:
if value not in database:
    session.add(value)
session.commit()

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

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


code:
def count (result):
    if isinstance (result, list):
        total = 0
        positive = 0
        for e in result:
            r = count (e)
            total += r [1]
            positive += r [0]
        return (positive, total)
    else: return (0 if result == '' else 1, 1)

a = byPath (x, 'top.middle.XX.nested')
b = byPath (x, 'top.last.XX.nested.XX.first')
c = byPath (x, 'top.last.XX.nested.XX.second')
d = byPath (x, 'other')

for x in [a, b, c, d]: print (count (x) )

rawDescription: Count non-empty end-leafs of a python dicitonary/array data structure - recursive algorithm?


code:
import win32api, win32con
def move(x,y,press=False):
    win32api.SetCursorPos((x,y))
    if press:
        click(x,y)
def click(x,y):
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
move(10,10,True)

rawDescription: PyGame Moniter dimming during game

description: PyGame Moniter dimming during game


rawDescription: How do you get the magnitude of a vector in Numpy?

description: Get the magnitude of a vector in Numpy


code:
from sympy import binomial, latex
sympy.init_printing(use_latex='mathjax')
n, r = sympy.symbols("4, 2", real=True, positive=True)
binomial(n, r)

rawDescription: How to construct combinatorics expressions in Python Sympy Latex?

description: Construct combinatorics expressions in Python Sympy Latex


code: reduce(lambda x, y: {y: x}, keys[::-1], value)

rawDescription: Create Nested Python Dictionary From Tuple of Keys


code:
scipy.linalg.cholesky([[1,2], [1,9]])
scipy.linalg.cholesky([[1,2], [1,9]], lower=True)
np.linalg.cholesky([[1,2], [1,9]])

rawDescription: What is the difference between cholesky in numpy and scipy?


code:
for k, v in data.items():
    if v[0] > 30:
        del data[k]

rawDescription: deleting entries in a dictionary based on a condition

description: Deleting entries in a dictionary based on a condition


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

description: Return more than one value over multiple lines


code:
from lxml import objectify
import StringIO
tree = objectify.parse(StringIO.StringIO('<parent><child>Billy</child><child>Bob</child></parent>'))
root = tree.getroot()
root.tag
[(foo.tag, foo.text) for foo in root.getchildren()]

description: Lxml[.objectify] documentElement tagName


code:
def my_awesome_grouping_function(shv, n):
    return [shv[i:i+n] for i in range(0, len(shv)-(n-1), n)]

rawDescription: Return a list of string letters grouped by two


code:
from collections import deque

class Tree(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

    def __iter__(self):
        if self.left:
            for x in self.left:
                yield x

        yield self.value

        if self.right:
            for x in self.right:
                yield x

    def bfs(self):
        q = deque([self])
        while q:
            x = q.popleft()
            if x:
                yield x.value
                q.extend([x.left, x.right])

rawDescription: Can you define multiple different iterators for a Python class?

description: Define multiple different iterators for a Python class


code:
from django.contrib.auth.views import login

def login_with_preview(request, extra_context=None, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    extra_context['object_list'] = Request.objects.all()
    return login(request, authentication_form=LoginForm, extra_context=extra_context, *args, **kwargs)

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


code:
print("How many teams would you like?")
numberteam = int(input("Number: "))
# Create a dictionary, where each team has an emtpy list
teams = dict([('Team{}'.format(i), []) for i in range(numberteam)])
# The following also works
# teams = {'Team{}'.format(i):[] for i in range(numberteam)}

rawDescription: Alternative to Using Expression as Variable?


rawDescription: Python Regex - Capturing a sentence based on the beginning and ending


code:
class Helper(object):
    def __init__(self):
        self.allowed = self.funcA
    def funcA(self):
        if self.allowed is not self.funcA:
            raise Error("Cannot run funcA now")
        # do stuff
        self.allowed = self.funcB
        return whatever
    # etc

rawDescription: How can I split a long function into separate steps while maintaining the relationship between said steps?

description: Split a long function into separate steps while maintaining the relationship between said steps


rawDescription: how to do a left,right and mid of a string in a pandas dataframe

description: Do a left,right and mid of a string in a pandas dataframe


code:
def foo(thelist, i, n):
     thelist.insert(i , n)
     return thelist

rawDescription: Reassigning a value returned from a function in Python


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

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


code:
numbers = re.compile(r'(\d+)')

a = numbers.sub(r'\ref{\1}', a)

rawDescription: python search string for numbers, put brackets around them

description: Python search string for numbers, put brackets around them


code:
for tail_num, xposition, yposition in tails:  # tuple assignment in for-loop
    pygame.draw.rect(windowSurface, RED, (xposition, yposition, 16, 16))

rawDescription: Getting a specific value from a tuple within a list


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

rawDescription: Pass a variable from python to shell script


code:
from threading import Thread

def bind(input_pipe, output_pipe, line_filter):
    def f():
        try:
            for line in iter(input_pipe.readline, b''):
                line = line_filter(line)
                if line:
                    output_pipe.write(line) # no flush unless newline present
        finally:
            try:
                output_pipe.close()
            finally:
                input_pipe.close()
    t = Thread(target=f)
    t.daemon = True # die if the program exits
    t.start()

rawDescription: How to thread multiple subprocess instances in Python 2.7?

description: Thread multiple subprocess instances in Python 2.7


code: string_representation = ' '.join(','.join(row) for row in nums)

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


rawDescription: Pass an array of math.functions as parameters with multiple variables


code: print(min(values, key = my_dist_fn)[-1])

rawDescription: Python: search in file with multiple criteria


code:
import marshal
def foo(x): return x*x
code_string = marshal.dumps(foo.func_code)

rawDescription: Pass client-side function to celery task


code: msg = MIMEMultipart('html')

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


code:
data = []
while True:
    line = input('Enter a line; leave it blank to stop: ')
    if not line:
        break
    data.append(line)

rawDescription: How to show EOF in Python? / how to identify lines?

description: Show EOF in Python? / how to identify lines


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

rawDescription: Tell python to wait/pause a for loop

description: Tell python to wait/pause a for loop


code:
s="""<script>
    [irrelevant javascript code here]
    sources:[{file:"http://url.com/folder1/v.html",label:"label1"},
    {file:"http://url.com/folder2/v.html",label:"label2"},
    {file:"http://url.com/folder3/v.html",label:"label3"}],
    [irrelevant javascript code here]
</script>"""
re.findall(r'"(http.*?)"',s,re.MULTILINE|re.DOTALL)

rawDescription: Using Regular Expressions to extract specific urls in python


rawDescription: Work with tuple of dictionaries

description: Work with tuple of dictionaries


code: c0 = [worksheet.row_values(i)[0] for i in range(worksheet.nrows) if worksheet.row_values(i)[0]]

rawDescription: Using xlrd to get list of excel values in python


code: re.search(u'(\N{COPYRIGHT SIGN}|\N{TRADE MARK SIGN}|\N{REGISTERED SIGN})', text)

rawDescription: Python Regex and the Copyright Symbol

description: Python Regex and the Copyright Symbol


code: df[["IV", "Vega"]] = df.apply(newtonRap, axis=1)

rawDescription: Create multiple columns in Pandas Dataframe from one function


code:
class Product(models.Model):
    ...
    def __unicode__(self):
        return u"{}({})".format(self.name, self.cost)

rawDescription: How to create form which will show fields from two models?

description: Create form which will show fields from two models


code: b= BasicInfoPage(...)

rawDescription: Python-passing variable between classes

description: Python-passing variable between classes


rawDescription: word count problem

description: Word count problem


rawDescription: Parse Excel Report

description: Parse Excel Report


code:
import re
rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
re.sub(rx, '', subj)

rawDescription: Removing a list of characters in string

description: Removing a list of characters in string


code:
def fill(matrix, x, y, color1, color2):
    def fill(x, y):
        if 0 <= x < matWidth and 0 <= y < matHeight and matrix[x][y] == color1:
            matrix[x][y] = color2
            fill(x - 1, y)
            fill(x + 1, y)
            fill(x, y - 1)
            fill(x, y + 1)
    matWidth = len(matrix)
    matHeight = len(matrix[0])
    fill(x, y)
    return matrix

rawDescription: Need help to modify flood fill algorithm


code:
df
g = df.groupby(pd.TimeGrouper("M"))

rawDescription: Iterate over chunks of dataframe by time period


code:
def genfactors(fdict):
    factors = [1]

    for factor, count in fdict.iteritems():
        newfactors = factors
        for ignore in range(count):
            newfactors = map(lambda e: e*factor, newfactors)
            factors += newfactors

    return factors

rawDescription: Python factorization

description: Python factorization


code:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.properties import ObjectProperty

class Testy(Screen):

    ttext = 'Screen 2'
    #other code

class ScreenTwo(Screen):
    pass

class Manager(ScreenManager):

    testy = ObjectProperty(None)
    screen_2 = ObjectProperty(None)

class ShowcaseApp(App):

    def build(self):
        return Manager(transition=FadeTransition())

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

rawDescription: Kivy class in .py and .kv interaction

description: Kivy class in .py and .kv interaction


code:
def forget_torpedoes(mylist):
    return reduce(lambda acc, x: {x : acc}, reversed(mylist))

rawDescription: Dictionary of dictionaries in python!

description: Dictionary of dictionaries in python!


rawDescription: Flatten Arbitrary Length of Dictionary Items Into List of Paths in Python


code:
data = np.random.randn(100, 1, 4)
pf = pd.Panel(data)
pf.shape

(100, 1, 4)

rawDescription: Reduce dimensionality in pandas.Panel

description: Reduce dimensionality in pandas.Panel


code:
host = 'http://www.wikipedia.org/somepath/tosome/file.mp3'
req = urllib2.Request(host, headers={'User-Agent' : "Magic Browser"})
response = urllib2.urlopen(req).read(4*1024)

rawDescription: Limit return size of GAE url_fetch get method?


rawDescription: How to use symbolic group name using re.findall()

description: Use symbolic group name using re.findall()


code: x = x or y

rawDescription: Most idiomatic way to provide default value in python?


code: df_input['Color'] = [', '.join(c) for c in resultlist]

rawDescription: Not getting the proper output with re.findall


code:
import threading
file_lock = threading.Lock()
class WriteThread(threading.Thread):
    def __init__(self, text, output):
        threading.Thread.__init__(self)
        self.text = text
        self.output = output
    def run(self):
        # Acquire Lock
        file_lock.acquire()
        output.write(text)
        # Release Lock
        file_lock.release()

with open("output.txt", "a+") as f:
    # Create threads
    a = WriteThread("foo", f)
    b = WriteThread("bar", f)
    # Start threads
    a.start()
    b.start()

rawDescription: How to make mechanize script multthread in python

description: Make mechanize script multthread in python


code:
a = [[1,2], [3,4,5], [6,7,8,9]] # Tim Pietzcker's example
[sum(p) for p in product(*a)]

rawDescription: Sum of elements in a list of lists with varying lengths in Python


code:
from pyspark.ml import Pipeline
pipeline = Pipeline(stages=[indexer, encoder, vector_indexer, assembler])
model = pipeline.fit(df)
transformed = model.transform(df)

rawDescription: Encode and assemble multiple features in PySpark


rawDescription: 2d array structure python

description: 2d array structure python


code: run('echo \'Server = http://repo.archlinux.fr/$arch\' | sudo -s tee -a /etc/pacman.conf')

rawDescription: "Escaping" $ when executing a remote bash command from python fabric


code:
# calculcate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

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

description: Return a value from a python script


code:
import csv
with open(filename, 'w') as outfile:
    writer = csv.writer(outfile)
    writer.writerow(['Word', 'Length'])
    for line in mylist:
        for word in line.split(", "):
            writer.writerow([word, str(len(word))])

rawDescription: Python Extract Word/Token counts from items in a list?


code:
import itertools as IT
list(IT.combinations(range(4), 2))

rawDescription: Every way to organize N objects in M list slots


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


rawDescription: Convert triangle matrix to square (Python | NumPy)?


rawDescription: Convert date-time format to Unix Time stamp Pandas


rawDescription: Python Emulate strptime behavor

description: Python Emulate strptime behavor


code:
data=[u'Intake Received Date:',
 u'9/11/2012',
 u'Intake ID:',
 u'CA00325127',
 u'Allegation Category:',
 u'Infection Control',
 u'Investigation Finding:',
 u'Substantiated',
 u'Intake Received Date:',
 u'5/14/2012',
 u'Intake ID:',
 u'CA00310421',
 u'Allegation Category:',
 u'Quality of Care/Treatment',
 u'Investigation Finding:',
 u'Substantiated',
 u'Intake Received Date:',
 u'8/15/2011',
 u'Intake ID:',
 u'CA00279396',
 u'Allegation Category:',
 u'Quality of Care/Treatment',
 u'Sub Categories:',
 u'Screening',
 u'Investigation Finding:',
 u'Unsubstantiated',]

rawDescription: Transform Python list into columnar data


code:
key1 = {'df1' : df1TableHTML, 'df2' : df2TableHTML}
labels = ['label1', 'label2']

rawDescription: Looping over multiple lists in Django Template


rawDescription: Python regex for detecting additions

description: Python regex for detecting additions


code:
result = {
    key: value[0] if len(value) == 1 else value
    for key, value in result.items()}

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

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


code:
import numpy as np
a = np.array([1,2,3,4,5])
np.mean(a)
np.mean(a[a<=3])
np.mean(a[a!=4])

rawDescription: How to calculate mean of values in the list omitting a special value?

description: Calculate mean of values in the list omitting a special value


rawDescription: How to find strings in pandas

description: Find strings in pandas


code:
def prime_factors(n):
    factors = []
    if n % 2 == 0:
        factors.append(2)
        while n % 2 == 0:
            n //= 2
    candidate = 3
    while candidate * candidate <= n:
        if n % candidate == 0:
            factors.append(candidate)
            while n % candidate == 0:
                n //= candidate
        candidate += 2
    if n != 1:
        factors.append(n)
    return factors

rawDescription: Speed of different prime factor functions


rawDescription: How do I run code when a Python class is evaluated

description: Run code when a Python class is evaluated


rawDescription: Splitting a list in python

description: Splitting a list in python


code:
def func(animalType):
    """
    This is a sample function.

    @param animalType: "It takes one of these animal types %(ANIMAL_TYPES)s"
    """ % {'ANIMAL_TYPES': ANIMAL_TYPES}

rawDescription: How to put a variable into Python docstring

description: Put a variable into Python docstring


code:
import time
from multiprocessing import Process

def thing_1():
    """We'll run this in a subprocess."""
    for i in range(10):
        print('thing_1: {}'.format(i))
        # let's make it take a bit longer
        time.sleep(1)

def thing_2():
    """We'll run this as a normal function in the current python process."""
    time.sleep(1)
    c = 5 * 2
    print('thing_2: {}'.format(c))
    # let's make this take a bit longer too
    time.sleep(1)

if __name__ == '__main__':
    # start the first thing running "in the background"
    p = Process(target=thing_1)
    p.start()
    # keep a record of when we started it running
    start_thing_1 = time.time()

    # let's run the other thing
    start_thing_2 = time.time()
    thing_2()
    end_thing_2 = time.time()

    # this will wait for the first thing to finish
    p.join()
    end_thing_1 = time.time()

    print('thing 1 took {}'.format(end_thing_1 - start_thing_1))
    print('thing 2 took {}'.format(end_thing_2 - start_thing_2))

rawDescription: Python multithreading/subprocess with functions


code:
cv = sklearn.feature_extraction.text.CountVectorizer(vocabulary=['hot', 'cold', 'old'])
cv.fit_transform(['pease porridge hot', 'pease porridge cold', 'pease porridge in the pot', 'nine days old']).toarray()

rawDescription: Can I use CountVectorizer in scikit-learn to count frequency of documents that were not used to extract the tokens?

description: Use CountVectorizer in scikit-learn to count frequency of documents that were not used to extract the tokens


code:
#!/usr/bin/env python

import csv

dict={}
with open('gene_test.csv','rB') as f:
    reader = csv.reader(f)
    for line in reader:
        try:
            dict[line[1]].append(line[0])
        except:
            dict[line[1]]=[line[0]]

with open('out_gene_test.csv','wb') as f:
    writer = csv.writer(f, delimiter='|')
    for key in dict:
        writer.writerow([','.join(dict[key]),key])

rawDescription: Is there a python code to concatenate values into 1 cell in excel


code: sum(text.count(word) for word in words)

rawDescription: Find particular words in a string, Python


code:
DEPTH_PRIORITY = 1
SCHEDULER_DISK_QUEUE = 'scrapy.squeue.PickleFifoDiskQueue'
SCHEDULER_MEMORY_QUEUE = 'scrapy.squeue.FifoMemoryQueue'

rawDescription: Scrapy doesn't seem to be doing DFO

description: Scrapy doesn't seem to be doing DFO


code: johns = names.count("John")

rawDescription: How to make a longer if rather than a for loop

description: Make a longer if rather than a for loop


code:
for i, line in enumerate(ifile, start=1):
    parts = line.split()
    parts[0] = "%d" % i
    new_line = ' '.join(parts)
    ofile.write(new_line + '\n')

rawDescription: change the numbers in the 1st column

description: Change the numbers in the 1st column


code:
from ctypes import *

file = CDLL('./file.so')

file.function()
cdll.LoadLibrary('libdl.so').dlclose(file._handle)

rawDescription: Can I explicitly close a ctypes CDLL?

description: Explicitly close a ctypes CDLL


code: isintance(goblina, Enemy)

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


code:
from collections import defaultdict
res = defaultdict(list)
for word, start, end in w_list:
    res[word].append({'start':time_dict[start[1:]], 'end': time_dict[end[1:]] })

rawDescription: Extracting (interval) values from multiple dictionaries inside one large list, and combining these with corresponding lists inside another large list


code: packed_v = struct.pack('>l', b)

rawDescription: convert unsigned integer to float in python

description: Convert unsigned integer to float in python


code:
def _one_frame(text):                 # text is supposed to be a list of lines
    lt = len(text[0])
    horz = '+' + '-'*lt + '+'         # Make the horizontal line +-------+
    result = [horz]                   # Top of the frame
    for line in text:
        result.append( '|'+line+'|' ) # Add the borders for each line
    result.append(horz)               # Bottom of the frame
    return result

def frame(text, repeat, thickness):
    text = [" %s "%text]*repeat       # add spaces and repeat as a list
    for i in range(thickness):
        text = _one_frame(text)       # draw one frame per iteration
    return '\n'.join(text)            # join lines

print(frame('Hello World', 3, 2))

rawDescription: Python: How to print a message within a "frame", using if,for and while control statements? Really confused


code:
def angles(x):
    return [ i * x / 5 - x for i in xrange(11)]

rawDescription: How to write this elegantly in Python?

description: Write this elegantly in Python


rawDescription: Can same file object be used to read a file multiple times?


code:
# much used module: mymodule
def set_trace():
    import ipdb
    ipdb.set_trace()

rawDescription: Does importing a module (but not using it) decrease performance in Python?


code:
# note that the signature has changed
def manipulate_inbound_documents(docs):
    # no need to branch on the resource name
    for doc in docs:
        doc['id_field'] = '001'
        doc['qr'] = 'mycqcode'

app = Eve()
# only fire the event on 'activity' endpoint
app.on_insert_activity += manipulate_inbound_documents

rawDescription: How to add some self process when using Python eve?

description: Add some self process when using Python eve


code: [np.arange(1 if l==i else 0, e) for l,e in enumerate(shape)]

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

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


code:
for r in p.xpath('.//w:t[./ancestor::w:r[(.//w:b or .//w:bCs[@w:val="0"]) and count(.//w:b|.//w:bCs)=1]]',namespaces={'w': w}):
     text2 += r.text

rawDescription: Conditioning xpath on presence of sibling , lxml


code:
class TestFilewise():
    def setup(self):
        import os
        self.fixture_dir = os.path.abspath(os.path.dirname(__file__)) \
              + "/fixtures/"
        assert os.access( self.fixture_dir, os.F_OK ), \
            "Oops! the fixture dir should be here " + self.fixture_dir
        assert os.access( self.fixture_dir+"profiles-source1.csv", os.F_OK )

rawDescription: how to break up lines most reasonably, staying "within 80 chars" in python?

description: Break up lines most reasonably, staying "within 80 chars" in python


code:
dice1 = roll()
while True: # Loop until either lost or won
    if dice1 == 7:
        break # Player lost, don't do anything
    elif dice1 == dice:
        count += 1 # Player won, increase count
        break
    else:
        dice1 = roll()

rawDescription: New to Python, creating a craps game when given n games


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

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

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


code:
class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        video_id = forms.cleaned_data.get('video_id', None)
        # If we are creating the object, and the video id is present
        if video_id and not change:
            obj.embed_code = video_id
        obj.save()

rawDescription: How to differentiate capital and small letters in using Django admin "prepopulated_fields"?

description: Differentiate capital and small letters in using Django admin "prepopulated_fields"


rawDescription: Changing the colour of the tk.optionmenu widget


code:
Output
h
e
l
l
o
w
o
r
l
d

rawDescription: super call to DjangoSpider's parse method not working

description: Super call to DjangoSpider's parse method not working


code:
split_indices = np.cumsum([len(x) for x in duplicates])[:-1]
np.split(flat_labels,split_indices)

# [array([2, 3]), array([3, 2]), array([0, 0, 0])]

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


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


code:
from itertools import product, chain

def choose_from_2d_lol(lol):
    flattened_options = list(chain.from_iterable(lol))
    for p in product(*flattened_options):
        p_iter = iter(p)
        new_list = [[next(p_iter) for elem in row] for row in lol]
        yield new_list

rawDescription: How to generate a permutation list of lists in python

description: Generate a permutation list of lists in python


code:
x = ['Ceo and founder at xyz labs', 'bartender | manager', 'Buyer & Seller at sailaway']
import re
[re.split(r"\band\b|\||&", y)[0].strip() for y in x]

rawDescription: RegEx up to a certain group of characters


code: midday = datetime.time(hour=12)

rawDescription: get time in past from current time

description: Get time in past from current time


code:
a = 'apple'
o = 'orange'
'%s' % a
'%s and' % a
'%s and %s' % (a,o)

rawDescription: What does `features['contains(%s)' % word.lower()] = True` mean in NLTK?


code:
class MyStrOrder:
    def __init__(self, inner):
        self.inner = inner

    def __lt__(self, other):
        for i in range(min(len(self.inner), len(other.inner))):
            a = POS.get(self.inner[i])
            b = POS.get(other.inner[i])
            if a != b:
                return a < b
        return len(self.inner) < len(other.inner)

lst = ["abc", "ab", "aá"]
lst.sort()
print(lst)

lst = ["abc", "ab", "aá"]
lst.sort(key = MyStrOrder)
print(lst)

rawDescription: How to sort a list of strings with a different order?

description: Sort a list of strings with a different order


code:
import numpy as np

custom = {
    1: {'a': np.zeros(10), 'b': np.zeros(100)},
    2:{'c': np.zeros(20), 'd': np.zeros(200)}
}

#Create a *list* of tuples:
converted_data = [
    (np_array, subkey, key)
    for (key, a_dict) in custom.items()
    for subkey, np_array in a_dict.items()
]

for np_array, subkey, key in converted_data:
    print(key, subkey, np_array)

rawDescription: Python equivalent of C++ begin() and end() for custom classes


code:
from __future__ import print_function

print(file_contents, end='')

rawDescription: remove empty last line from string (output from pipe)

description: Remove empty last line from string (output from pipe)


code:
import csv

with open('mycsv.csv') as infd, open('mycsv.out', 'w') as outfd:
  reader = csv.reader(infd)
  writer = csv.writer(outfd)

  # read the header
  header = next(reader)

  # modify the column title
  header[1] = 'hTwo'

  # write the new header out
  writer.writerow(header)

  # copy all other rows unmodified
  for row in reader:
    writer.writerow(row)

# and then rename mycsv.out to mycsv.csv if you wish.

rawDescription: How to rename key/header in csv DictReader

description: Rename key/header in csv DictReader


code:
def has_many_properties(cls):
    return has_prop1(has_prop2(has_prop3(cls)))

@has_many_properties
class C(object):
    pass

rawDescription: How to share attributes without an is-a relationship in Python?

description: Share attributes without an is-a relationship in Python


code:
...
schools = School.query

if form.name.data:
    schools = schools.filter(School.name == form.name.data)

if form.city.data:
    schools = schools.filter(School.city == form.city.data)

if form.state.data:
    schools = schools.filter(School.state == form.state.data)

# at this point schools is a query filtered with whatever was given
...

rawDescription: SQLAlchemy Flask, match some or all

description: SQLAlchemy Flask, match some or all


code: directoryPath = os.path.join(directoryPath, directoryName)

rawDescription: os.chdir() is not working in mac

description: Os.chdir() is not working in mac


rawDescription: join function of a numpy array composed of string

description: Join function of a numpy array composed of string


code:
_columns = {
    'partner_id': fields.many2one('res.partner', 'Partner', ondelete='cascade'),
    'course_id': fields.many2one('training.course', 'Course', ondelete='cascade'),
    'date': fields.date('Joining date'),
}

_sql_constraints = [
    ('rel_unique', 'unique(partner_id, course_id, date)', 'This course already give to this company!!'),
]

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

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


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

rawDescription: slicing a matrix in python vs matlab

description: Slicing a matrix in python vs matlab


code: list(np.where(np.logical_and(x == 1, y == 4))[0])

rawDescription: Find location of pair of elements in two arrays in numpy


rawDescription: how to merge duplicate elements?

description: Merge duplicate elements


code:
loc0 = p0                       # local origin
locx = p1 - loc0                # local X axis
normal = cross(locx, p2 - loc0) # vector orthogonal to polygon plane
locy = cross(normal, locx)      # local Y axis

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


code:
import pylab

counter = 0
def filename_generator():
    global counter
    to_return = 'myfig{0}.png'.format(counter)
    counter += 1
    return to_return

def my_show():
    return pylab.savefig(filename_generator())

rawDescription: How do I send NLTK plots to files?

description: Send NLTK plots to files


code:
from webapp2_extras.routes import DomainRoute

app = webapp2.WSGIApplication([

    DomainRoute('www.domain.com', [
            webapp2.Route(r'/<:.*>', handler=RedirectWWW),
    ]),

    ('/', IndexPage),
    ('/discover', DiscoverPage),
    ('/about', AboutPage),
    ('/help', HelpPage),
    ('/terms-and-privacy', TermsPage)
], debug=True)

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

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


code:
import urllib2
import lxml.html as LH
from PyQt4 import QtGui, QtCore, QtWebKit
import sys

class Render(QtWebKit.QWebPage):
    def __init__(self, url):
        self.app = QtGui.QApplication(sys.argv)
        QtWebKit.QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().load(QtCore.QUrl(url))
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        self.app.quit()

def main():
    liste = []
    for k in range(2, 3):
        url = "http://www.spiegelfechter.com/wordpress/page/" + str(k)
        r = Render(url)
        content = unicode(r.frame.toHtml())
        doc = LH.fromstring(content)
        for span in doc.xpath('//span[@class="commentbutton"]'):
            a = span.xpath('a')[0]
            post = a.attrib['href']
            kommentare = a.text_content()
            # kommentare is expected to be a string such as '14 Kommentare'
            comments = int(kommentare.split()[0])

            iframe = span.xpath('iframe')[0]
            flattr_url = (iframe.attrib['src'])
            flattr_doc = LH.parse(flattr_url)
            span = flattr_doc.xpath('//span[@class="flattr-count"]')[0]
            flattr_count = int(span.text_content())
            liste.append((comments, flattr_count, post))
        for elt in sorted(liste):
            print(elt)

if __name__ == '__main__':
    main()

rawDescription: Python: Get flattr count

description: Python: Get flattr count


code:
class PersonForm(ModelForm):
    class Meta:
        model = Person
        exclude = ('user',)
    ...

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

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


code:
print("ONLY IN TEST 1:")
for thing in TEST_1 - TEST_2:
    print('\t'.join(",".join(x) for x in thing))

print()

print("ONLY IN TEST 2:")
for thing in TEST_2 - TEST_1:
    print('\t'.join(",".join(x) for x in thing))

print()

print("IN BOTH:")
for thing in TEST_1 & TEST_2:
    print('\t'.join(",".join(x) for x in thing))

#>>> ONLY IN TEST 1:
#>>> 5  4231    N   AD
#>>>
#>>> ONLY IN TEST 2:
#>>> 5  4231    N   PL
#>>> 6  5231    T   PAL
#>>>
#>>> IN BOTH:
#>>> 1  1231    L   LA
#>>> 3  1634    L   T
#>>> 4  6034    L   LAL,LALLAL
#>>> 1  1234    L   T
#>>> 2  1434    A   C

rawDescription: Compare lists, the order of content within a given column is unimportant


code:
import numpy as np
import math
alpha = 0.1
n = 5
tmp = [1. / (math.pow(float(i), alpha)) for i in range(1, n+1)]
zeta = reduce(lambda sums, x: sums + [sums[-1] + x], tmp, [0])
tmp
zeta

rawDescription: Python Custom Zipf Number Generator Performing Poorly


code:
leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

rawDescription: Remove or adapt border of frame of legend using matplotlib


code: Model.objects.filter(foo__lt = 4, bar__iexact = 'bar')

rawDescription: Why use **kwargs in python? What are some real world advantages over using named arguments?


code:
import cElementTree as ElementTree

class XmlListConfig(list):
    def __init__(self, aList):
        for element in aList:
            if element:
                # treat like dict
                if len(element) == 1 or element[0].tag != element[1].tag:
                    self.append(XmlDictConfig(element))
                # treat like list
                elif element[0].tag == element[1].tag:
                    self.append(XmlListConfig(element))
            elif element.text:
                text = element.text.strip()
                if text:
                    self.append(text)

class XmlDictConfig(dict):
    '''
    Example usage:

    >>> tree = ElementTree.parse('your_file.xml')
    >>> root = tree.getroot()
    >>> xmldict = XmlDictConfig(root)

    Or, if you want to use an XML string:

    >>> root = ElementTree.XML(xml_string)
    >>> xmldict = XmlDictConfig(root)

    And then use xmldict for what it is... a dict.
    '''
    def __init__(self, parent_element):
        if parent_element.items():
            self.update(dict(parent_element.items()))
        for element in parent_element:
            if element:
                # treat like dict - we assume that if the first two tags
                # in a series are different, then they are all different.
                if len(element) == 1 or element[0].tag != element[1].tag:
                    aDict = XmlDictConfig(element)
                # treat like list - we assume that if the first two tags
                # in a series are the same, then the rest are the same.
                else:
                    # here, we put the list in dictionary; the key is the
                    # tag name the list elements all share in common, and
                    # the value is the list itself
                    aDict = {element[0].tag: XmlListConfig(element)}
                # if the tag has attributes, add those to the dict
                if element.items():
                    aDict.update(dict(element.items()))
                self.update({element.tag: aDict})
            # this assumes that if you've got an attribute in a tag,
            # you won't be having any text. This may or may not be a
            # good idea -- time will tell. It works for the way we are
            # currently doing XML configuration files...
            elif element.items():
                self.update({element.tag: dict(element.items())})
            # finally, if there are no child tags and no attributes, extract
            # the text
            else:
                self.update({element.tag: element.text})

rawDescription: How to convert an xml string to a dictionary in Python?

description: Convert an xml string to a dictionary in Python


code:
import clr
clr.AddReference("White.Core")
clr.AddReference("White.NUnit")
from White.NUnit import *
from White import *
from White.Core import *
from White.Core.Configuration import *
from White.Core.UIItems import *
from White.Core.UIItems.WindowItems import *
from White.Core.UIItems.ListBoxItems import *
from White.Core.UIItems.Container import *
from White.Core.UIItems.Finders import *
from White.Core.Factory import *
from White.Core.Finder import *
from White.Core.AutomationElementSearch import *
from White.Core.WindowsAPI import *

rawDescription: How do I import the white project into an IronPython program?

description: Import the white project into an IronPython program


code: entry_list.extend([entry.title.text for entry in feed.entry])

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


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

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


code:
class Member(models.Model):
    name = models.CharField(max_length=100)
    dob = models.DateField()
    group = modes.ForeignKey('Group', related_name='members')

class Group(models.Model):
    name = models.CharField(max_length=100)
    owner = models.ForeignKey('Member', related_name='owned_groups')

class Activity(models.Model):
    group = models.ForeignKey('Group', related_name='activities')
    topic = models.CharField(max_length=100)
    start_by = models.ForeignKey('Member', related_name='started_activities')
    participants = models.ManyToManyField('Member', related_name='participating_activities')

rawDescription: Django ModelForm Field Filtering with multiple model dependancies


rawDescription: Split if not within brackets

description: Split if not within brackets


code: airodump = subprocess.Popen(..., stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))

rawDescription: is python subprocess module quirky?

description: Is python subprocess module quirky


code:
import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()

rawDescription: Matplotlib color according to class labels


code:
b = Solution()
dis.dis(b.hasCycle)

rawDescription: What makes my python code so slow (Linked List Cycle)?


code:
1 # just a number, so no quotes
"hi" # just a string, displayed with quotes
print("hi") # being *printed* to the screen, so do not show quotes
"'hello'" # string with embedded single quotes
print("'hello'") # *printing* a string with embedded single quotes

rawDescription: Python return without " ' "

description: Python return without " ' "


code:
func.current_date(type_=types.Date, bind=engine1)
func.current_timestamp(type_=types.Time, bind=engine2)

rawDescription: How to get current date and time from DB using SQLAlchemy

description: Get current date and time from DB using SQLAlchemy


code:
with open(filename, 'r') as f:
    c = Counter(line.strip() for line in f if line.strip())

rawDescription: Counting number of occurance of a string in python


code:
import sys
for line in sys.stdin:
    x,y = [ord(x)-48 for x in line.split()]

rawDescription: Is there a faster way to get input in python?


code:
def partition_by(l, f):
    t = []
    for e in l:
        if f(e):
            if t: yield t
            t = []
        t.append(e)
    yield t

blocks = partition_by(content, lambda l: l.startswith('['))

rawDescription: Parsing specific contents in a file

description: Parsing specific contents in a file


code:
a = saved_money()
a.set_amount(20)
globalTotal
b = saved_money()
b.set_amount(50)
globalTotal

rawDescription: How do you add integer variables from objects?

description: Add integer variables from objects


rawDescription: How to set a time limit to a task if not excute within a certain time then just remove it in celery

description: Set a time limit to a task if not excute within a certain time then just remove it in celery


code:
class recipe:
    def __init__(self,name,ingredients):
        self.name = name
        self.ingredients = ingredients
    def __str__(self):
        return "{name}: {ingredients}".format(name=self.name,ingredients=self.ingredients)

toast = recipe("toast",("bread"))
sandwich = recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))

rawDescription: is it possible to create a dictionary "template" in python?

description: Is it possible to create a dictionary "template" in python


code:
class Monster(object):
    def __init__(self, traits):
        self.__dict__.update(traits)

rawDescription: Python properties as instance attributes


code: D = np.argsort(B)[C].reshape(A.shape)

rawDescription: Numpy Lookup (Map, or Point)

description: Numpy Lookup (Map, or Point)


code:
class Point(object):
    def __init__(self, *args):
        self.coords = args

    def __add__(self, other):
        return Point(*[(x + y) for (x, y) in zip(self.coords, other.coords)])

    def __repr__(self):
        coord = ', '.join("{}".format(x) for x in self.coords)
        return "<Point ({})>".format(coord)

rawDescription: python condensing functions for +-*

description: Python condensing functions for +-*


code:
max_key = {}
for key, values in mydict.iteritems():
    for value in myset.intersection(values):
        if key > max_key.get(value, float('-inf')):
            max_key[value] = key

result = {key: val for val, key in max_key.iteritems()}

rawDescription: return key under condition

description: Return key under condition


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

    def __getattr__(self, attr):
        return getattr(self.value, attr)

rawDescription: Is it possible to create a class that represents another type in Python, when directly referenced?


code:
from django.db import models

class MyModel(models.Model):
    duration = models.DurationField()

rawDescription: How should I use DurationField in my model?


code: hours = td.total_seconds() / 3600

rawDescription: Datetime to decimal to pull into matplotlib with Python


code:
hour  | Occurences
21    |1
22    |2
23    |1

rawDescription: How do I optimize Python Code?

description: Optimize Python Code


code:
import csv
from collections import defaultdict

seen = defaultdict(list)

with open('file.csv', 'rb') as my_file:
    reader = csv.reader(my_file)
    for row in reader:
        key = (row[0], row[1], row[2])  # sender, receiver, id
        seen[key].append(row)

    with open('new.csv', 'wb') as outf:
        writer = csv.writer(outf)
        for collected in seen.values():
            if len(collected) > 1:
                writer.writerows(collected)

rawDescription: Python - order columns and compare rows in csv


code:
import os
import shutil
with zipfile.ZipFile(tDir + mainapk[0]) as z:
    with z.open(icon[1]) as zf, open(os.path.join(tDir, os.path.basename(icon[1])), 'wb') as f:
        shutil.copyfileobj(zf, f)

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


code:
import time
Move+=["/","|","\\","-"]
text = input('Text to be displayed: ')
for i in text:
    print(i, end='', flush=True)
    time.sleep(0.1)
print('\n')

rawDescription: Making Text look like it's being typed in the Python Shell


code:
from bs4 import BeautifulSoup
sample = '''\

This has an id

This has none

This one has an id too

But this one has no clue (or id)

'''
soup = BeautifulSoup(sample)
soup.find_all('div', id=True)
soup.find_all('div', id=False)
soup.select('div[id]')

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


code:
import matplotlib.pyplot as plt
import cartopy
ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.add_feature(cartopy.feature.COASTLINE)
gridlines = ax.gridlines(draw_labels=True)
# this would not function, due to the gridliner
# ax.set_xlabel('lon')
# ax.set_ylabel('lat')
plt.show()

rawDescription: cartopy set_xlabel set_ylabel (not ticklabels)

description: Cartopy set_xlabel set_ylabel (not ticklabels)


code:
sorted_x = np.matrix(sorted_sample_values_of_x)
sorted_x = np.transpose(sorted_x).astype(float)
ns = sorted_x/np.array([1,counts.sum()])
ns

rawDescription: saving an ordered pair from a list of numbers using python

description: Saving an ordered pair from a list of numbers using python


rawDescription: How to get the filtered dataframe for calculations while retaining the original one in pandas?

description: Get the filtered dataframe for calculations while retaining the original one in pandas


rawDescription: python writing a list to a file incorrectly

description: Python writing a list to a file incorrectly


code:
s = bytearray('Hello World')
s
import string
zero = string.maketrans(buffer(bytearray(range(256))),buffer(bytearray(256)))
s.translate(zero)

rawDescription: How can I quickly set a Python bytearray to 0

description: Quickly set a Python bytearray to 0


code:
import re

class Views(object):
    """Empty object for holding as_view method"""
views = Views()

def convert_name(name):
    """convert CapWords into cap_words"""
    return name[0].lower() + re.sub(r'([A-Z])', lambda m:"_" + m.group(0).lower(), name[1:])

def as_view(views):
    """Adds decorated class-based views' as_view methods to views container"""
    def decorator(cls):
        name = convert_name(cls.__name__)
        setattr(views, name, cls.as_view)
        return cls
    return decorator

rawDescription: Could as_view() (for class-based views) be implemented in a decorator?


code:
observed_comma_indices = [index for index, p in enumerate(perm) if p == ","]
if comma_indices == observed_comma_indices:
    lst.append(perm)

rawDescription: Python - Narrowing down itertools permutations results with "if" statements. How to with repeated element?


code: (arbitrary_day - first_sunday) // timedelta(days=7)

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


code:
df.resample("24H", how=sum, label='left', closed='left', base=5)
df.ix[:5].sum()
df.ix[5:].sum()

rawDescription: Change starting and ending hour of pandas timestamp


code:
from StringIO import StringIO
import sys

stringio = StringIO()
previous_stdout = sys.stdout
sys.stdout = stringio

# do stuff

sys.stdout = previous_stdout

myString = stringio.getvalue()

rawDescription: Read python stdout as string

description: Read python stdout as string


code: returncode = call(*args, **kwargs)

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


rawDescription: 2D NumPy array comparison in given range


code: hash(repr(d))

rawDescription: Python, checksum of a dict

description: Python, checksum of a dict


code:
def hangman(secret, guessCount=7):
    assert guessCount > 0  # Never really good to hard code magic numbers.

    w = ['_'] * len(secret)  # Make 'w' a list instead because list is mutable
    while guessCount > 0:
        guess = input("Guess: ")
        if guess in secret:
            indices = indexes(secret, guess)  # I'm guessing indexes is defined elsewhere?
            for i in indices:
                w[i] = guess  # Make it explicit. secret[i] == guess anyway.
            print("".join(w))  # Join w into a word
        else:
            guessCount -= 1  # More concise
            print("Incorrect. ", guessCount, " incorrect guesses remaining.")

rawDescription: I need help fixing this hangman function


code: a = None

rawDescription: Null a dictionary inside a function in python


code:
def temp(row):
    index = df2[((row-df2).abs() < .3).all(axis=1)].index
    return df2.loc[index[0], :] if len(index) else [None]*df2.shape[1]

rawDescription: Pandas Datframe1 search for match in range of Dataframe2


code:
from itertools import groupby

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

rawDescription: Python: Replacing values in an array

description: Python: Replacing values in an array


code: function(bob="Hi bob", sally="Hello sally", **values)

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


code:
isinstance(True, int)
True & True
True & 1

rawDescription: What do the binary operators mean when applied to logicals?


code:
def _do_something():
    if exists('/etc/', use_sudo=True):
        sudo('/etc/init.d/nginx stop')

rawDescription: Exit in a function using Python

description: Exit in a function using Python


code:
import functools

@functools.total_ordering
class ReverseCompare(object):
    def __init__(self, obj):
        self.obj = obj
    def __eq__(self, other):
        return isinstance(other, ReverseCompare) and self.obj == other.obj
    def __le__(self, other):
        return isinstance(other, ReverseCompare) and self.obj >= other.obj
    def __str__(self):
        return str(self.obj)
    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self.obj)

rawDescription: Pop max value from a heapq python, Is there a max-heap in Python?


code: template_var['settings'] = settings

rawDescription: print list of dictonaries to template

description: Print list of dictonaries to template


rawDescription: Optimizing MasterMind Code and string operations in python


code:
text = 'a,b,c'
text = text.split(',')
text

rawDescription: convert a string to an array

description: Convert a string to an array


rawDescription: For list of dicts: merge same key values, sum another diff. values, count each merge iteration +1


code:
myvar = "String " + str(value) + " more string"  # string concatenation
myvar = "String %d more string" % (value,)       # old-style string formatting
myvar = "String {0} more string".format(value)   # new-style string formatting

rawDescription: How to eliminate {} brackets from message box

description: Eliminate {} brackets from message box


code:
ax = df.plot(kind='bar')
ax.set_xticklabels(['|'.join(t) for t in df.index])

rawDescription: Is it possible to hierarchically label a matplotlib (pyplot) bar plot?


code:
import matplotlib
import matplotlib.pyplot as plt

import numpy

x = numpy.random.normal(size=10000)
y = numpy.random.normal(size=10000)

fig = plt.figure()
s = fig.add_subplot(1, 1, 1, aspect=1)
s.set_xlim(-4, 4)
s.set_ylim(-4, 4)
s.scatter(x, y)
fig.savefig('t1.png')

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

description: Calculate python 2D scatter points occupied area


code: menuitem = gtk.MenuItem('This is the label')

rawDescription: How can I change the display text of a MenuItem in Gtk2?

description: Change the display text of a MenuItem in Gtk2


code:
from urllib import unquote
unquote('%7B%22rajNames%22%3A%5B%22WAR%22%5D%7D')

rawDescription: Python requests module url encode

description: Python requests module url encode


code: super(NameOfCurrentClass, self)

rawDescription: PyQt4: why do we need to pass class name in call to super()


code:
reactor.listenTCP(8123, TCPEventReceiverFactory())
loop_http = twisted.intertnet.task.LoopingCall(thing_that_does_http)
# run once per minute, starting now.
loop_http.start(60)

rawDescription: Twisted / perform asynchronous http requests


code: acids = [codon_lookup[codon] for codon in mutated_codon]

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

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


code:
if sys.platform=='win32':
    os.startfile(d)

rawDescription: Is there a cross-platform way to open a file browser in Python?


code:
f = open('/tmp/temperature.txt', 'w')
f.write(temperature)
f.close()

rawDescription: Passing python data to php webserver Apache


code:
import pickle
stats = {'hp': 150, 'mp': 100, 'speed': 15}
pickle.dump(stats, open('stats.p', 'wb'))

rawDescription: Save game feature for Python?

description: Save game feature for Python


code: import numpy as np

rawDescription: Doubling the matrix in numpy

description: Doubling the matrix in numpy


rawDescription: Numpy Array Broadcasting with different dimensions


code:
from isodate import parse_duration
parse_duration('P1M')

rawDescription: How to convert string date interval to number of days or seconds (ISO_8601)?

description: Convert string date interval to number of days or seconds (ISO_8601)


rawDescription: How do I get the IP address from a http request using the requests library?

description: Get the IP address from a http request using the requests library


code:
seenIds = [ 3, 5 ];
lastScore = 5;

rawDescription: Efficiently page query results

description: Efficiently page query results


code:
def ips_in_log(log_name):
   with open(log_name, 'r') as f:
      log = f.read()
   ipcount = len(re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',log))
   print(ipcount)

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


rawDescription: Performance issue in python with nested loop


code:
nodes = 3
res=[[0]*nodes]*nodes
res
res[0][0] = 'echo'
res

rawDescription: generating a grid in a function

description: Generating a grid in a function


code:
@defer.inlineCallbacks
def doStuff():
    result = yield takesTwoSeconds()
    nextResult = yield takesTenSeconds(result * 10)
    defer.returnValue(nextResult / 10)

rawDescription: python generator "send" function purpose?

description: Python generator "send" function purpose


code:
dict1 = json.loads(s1)
dict2 = json.loads(s2)
result = combine(dict1, dict2)

rawDescription: Python - convert strings into json and combine


code:
df
df.loc[3100, 'attributes']

rawDescription: How to read part of the line into array with python-pandas?

description: Read part of the line into array with python-pandas


rawDescription: Add only the first value in my list of arrays


code:
with open('input_file','r') as f:
    distinct_content=set(f.readlines())

to_file=""
for element in distinct_content:
    to_file=to_file+element
with open('output_file','w') as w:
    w.write(to_file)

rawDescription: Python how to find out the unique elements in a text file and output in another text file


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

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


code:
import datetime

now = datetime.datetime.now().timestamp()

rawDescription: converting unix timestamp to local time

description: Converting unix timestamp to local time


code:
ave=['Avg']
lst = []
for x in range(24):
    lst.extend((x,ave[0]))

rawDescription: zip multiple values with single value

description: Zip multiple values with single value


code:
daniel, password
user, password

rawDescription: Reading pairs of rows from a file

description: Reading pairs of rows from a file


rawDescription: Pandas to form clusters based on diff column


code:
class SplitpointTest(unittest.TestCase):
    def testFloatRounding(self):
        # Due to rounding error, the cumulative sums for these inputs are
        # [1.1, 3.3000000000000003, 3.3000000000000003, 5.5, 6.6]
        # and [0.1, 0.7999999999999999, 0.7999999999999999, 1.5, 1.6]
        # Note that under default settings, numpy won't display
        # enough precision to see that.
        self.assertEquals(2, splitpoint([1.1, 2.2, 1e-20, 2.2, 1.1]))
        self.assertEquals(2, splitpoint([0.1, 0.7, 1e-20, 0.7, 0.1]))

    def testIntRounding(self):
        self.assertEquals(1, splitpoint([1, 1, 1]))
    def testIntPrecision(self):
        self.assertEquals(2, splitpoint([2**60, 1, 1, 1, 2**60]))
    def testIntMax(self):
        self.assertEquals(
            2,
            splitpoint(numpy.array([40, 23, 1, 63], dtype=numpy.int8))
        )

    def testIntZeros(self):
        self.assertEquals(
            4,
            splitpoint(numpy.array([0, 1, 0, 2, 0, 2, 0, 1], dtype=int))
        )
    def testFloatZeros(self):
        self.assertEquals(
            4,
            splitpoint(numpy.array([0, 1, 0, 2, 0, 2, 0, 1], dtype=float))
        )

rawDescription: Find the equilibrium point in a numpy array


rawDescription: Convert redundant array to dict (or JSON)?


code:
class ClusterAssignment(object):

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

    __repr__ = __str__

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


code:
n = 5
b = 0.5
toeplitz(b**np.arange(n), np.zeros(n)).T

rawDescription: Fastest way to compute upper-triangular matrix of geometric series (Python)


code:
import dis
dis.dis(compile('for num in foo():pass', '', 'exec'))

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


code:
def lines(fname, numbers):
    with open(fname) as f:
        lines = f.readlines()
        return [lines[i] for i in numbers]

rawDescription: Cutting some specific lines from a text and putting them into another file


code:
@app.route("/worker", methods=["GET", "POST"])
def worker():
#refresh the interface or whatever is necessary
    if flask.request.method == 'POST':
        return 'Worker endpoint reached'
    elif flask.request.method == 'GET':
        worker = IronWorker()
        task = worker.queue(code_name="hello", payload={"WORKER_DB_URL": app.config['WORKER_DB_URL'],
                            "WORKER_CALLBACK_URL": app.config['WORKER_CALLBACK_URL']})
        details = worker.task(task)
        flask.flash("Work queued, response: ", details.status)
        return flask.redirect('/')

rawDescription: Ironworker job done notification

description: Ironworker job done notification


code:
for i in range(360):
    mercury.circle(58, 1)
    venus.circle(108, 1)
    earth.circle(150, 1)
    mars.circle(228, 1)

rawDescription: How to make items draw at the same time in python using turtle?

description: Make items draw at the same time in python using turtle


rawDescription: Match and index all substrings, including overlapping ones


code:
first = nth(iteration, 0)
tenth = nth(iteration, 8)  # since we've already taken one
hundredth = nth(iteration, 89)  # since we've already taken ten
# etc

rawDescription: Get multiple individual values from generator in Python


rawDescription: Finding dict objects with duplicated key values in array


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

rawDescription: Simple Image viewer

description: Simple Image viewer


code:
import numpy as np

def rank1(x):
    # Sort values i = 0, 1, 2, .. using x[i] as key
    y = sorted(range(len(x)), key = lambda i: x[i])
    # Map each value of x to a rank. If a value is already associated with a
    # rank, the rank is updated. Iterate in reversed order so we get the
    # smallest rank for each value.
    rank = { x[y[i]]: i for i in xrange(len(y) -1, -1 , -1) }
    # Remove gaps in the ranks
    kv = sorted(rank.iteritems(), key = lambda p: p[1])
    for i in range(len(kv)):
        kv[i] = (kv[i][0], i)
    rank = { p[0]: p[1] for p in kv }
    # Pre allocate a array to fill with ranks
    r = np.zeros((len(x),), dtype=np.int)
    for i, v in enumerate(x):
        r[i] = rank[v]
    return r

def rank2(x):
    x_sorted = sorted(x)
    # creates a new list to preserve x
    rank = list(x)
    for v in x_sorted:
        rank[rank.index(v)] = x_sorted.index(v)
    return rank

rawDescription: map array of numbers to rank efficiently in Python

description: Map array of numbers to rank efficiently in Python


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


code:
role = ... # some role
role.users

rawDescription: SQLAlchemy relationships, when to use which relationship?


code: Button( ..., text="knight", command=foo.knight)

rawDescription: Long elif chains vs dictionary with exec()


rawDescription: Pandas/Python ruining JSON data in DataFrames


code:
deposits = ["0434512", "03145234", "012341347", "0511112345", "0475746","03654534", "02112"]
deposits.sort()

from collections import OrderedDict

mydict = OrderedDict()

for i in deposits:
    mydict[i[:2]] = 0

for i in deposits:
    mydict[i[:2]] += float(i[2:])/100

rawDescription: adding two items in a list to make into one item

description: Adding two items in a list to make into one item


code: merge = self.inline_merge.diff_apply_bulk(text3, [diff1, diff2], reverse=True)

rawDescription: How can I diff and patch/merge strings instead of files?

description: Diff and patch/merge strings instead of files


code: id_to_name = dict((id, name) for name, id in name_to_id.iteritems())

rawDescription: CSV of Distances to Triangular Distance Matrix in Python


code:
import time

timestamp = time.time()
while time.time() < timestamp + 10:
    print("start loop at " + str(i))
    try:
        if self.driver.find_element_by_link_text(text).is_displayed():
            break
    except:
        print("pass")
        pass
else:
    print("failing on timeout")
    self.fail("time out")

rawDescription: Python Sleep is way off

description: Python Sleep is way off


code:
my_dict = {'John': 23, 'Matthew': 8, 'Peter': 45}
data = [{"name": key, "age": value} for key, value in my_dict.items()]
data

rawDescription: Move data from key to value in Python dictionary


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

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


code:
albums_dict = {}
for album in albums:
    if not album.singer_name in albums_dict:
        albums_dict[album.singer_name] = []
    albums_dict[album.singer_name].append(album.album_name)

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

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


code:
for target in mac_addr:
    print("'{}' vs '{}' -> {}".format(addr, target, addr == target))

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

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


code:
def find_word_horizontal (crosswords, word):
    for row_index, row in enumerate(crosswords):
        print('input: ', row_index, row)
        row_string = ''.join(row)
        print('joined row: ', row_string)
        column_index = row_string.find(word)
        if(column_index > -1):
            return [row_index, column_index]

find_word_horizontal(crosswords, word)

rawDescription: Python: Find a word in a 2d list and return the intersection that is the row index and column index of that word in a list


code:
filename
filename_001
filename_002
filename_003

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

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


code:
from functools import partial

foo2 = partial(foo, my_string="my_string_example")

rawDescription: Passing SOME of the parameters to a function in python


code:
from flask import Flask, request, send_from_directory

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

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

rawDescription: How to serve static files in Flask

description: Serve static files in Flask


code:
cursor.execute("Select LastUpdatedTime from Timing")
# Note that I'm not converting this to a string.
lastUpdatedTime=datetime.strptime(list(cursor.fetchone())[0],'%Y-%m-%dT%H:%M:%SZ')

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


code:
def my_func():
    # do useful stuff
    pass

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


code:
from threading import Thread

def open_website(url):
    return urllib2.urlopen(url)

Thread(target=open_website, args=["http://google.com"]).start()

rawDescription: Python & URLLIB2 - Request webpage but don't wait for response


code:
tree = xml.getroot()
nsmap = {"ix":tree.nsmap["ix"]}

fractions = xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap)

for fraction in fractions:
    print(fraction.get("name"))
    print(fraction.text)

rawDescription: Code transformation from BS4 to lxml parser


code:
import collections as coll
import itertools

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

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


rawDescription: How to treat a hex as string?

description: Treat a hex as string


code: params = [c1, mu1, sigma1, c2, mu2, sigma2]

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

description: Fit a double Gaussian distribution in Python


rawDescription: How To Change Lists of Unicode to ASCII

description: How To Change Lists of Unicode to ASCII


rawDescription: pandas selects a set of columns from a dataframe

description: Pandas selects a set of columns from a dataframe


code:
m[0][0]
Out[22]: b'BKNIF'

type(m[0][0])
Out[23]: numpy.bytes_

rawDescription: Numpy loadtxt Behavior change with Python 3


code:
from sklearn.feature_extraction.text import CountVectorizer
word_vectorizer = CountVectorizer(ngram_range=(1,2), analyzer='word')
sparse_matrix = word_vectorizer.fit_transform(df['description'])
frequencies = sum(sparse_matrix).toarray()[0]
pd.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])

rawDescription: How to find ngram frequency of a column in a pandas dataframe?

description: Find ngram frequency of a column in a pandas dataframe


code:
from itertools import product, chain

tuples = chain.from_iterable(product(vs, [k]) for k, vs in orig_dict.items())
# note this is identical to:
# # tuples = []
# # for k, vs in orig_dict.items():
# #     for tup in [(v, k) for v in vs]:
# #         tuples.append(tup)

rawDescription: flip keys and values in dictionary python

description: Flip keys and values in dictionary python


code:
req = req.fields(params);
req = req.field("data", f);

rawDescription: Translate Python requests code to Java (UniRest)


rawDescription: searching an element in list of list

description: Searching an element in list of list


code:
_sentinel = object()

class makeCode:
    def echo(self, start=0, stop=_sentinel, search=None):
        if stop is _sentinel:
            stop = len(self.codeSegment)

rawDescription: Python code, self not defined

description: Python code, self not defined


code:
def tryconvert(value, default, *types):
    """Converts value to one of the given types.  The first type that succeeds is
       used, so the types should be specified from most-picky to least-picky (e.g.
       int before float).  The default is returned if all types fail to convert
       the value.  The types needn't actually be types (any callable that takes a
       single argument and returns a value will work)."""
    value = value.strip()
    for t in types:
        try:
            return t(value)
        except (ValueError, TypeError):
            pass
    return default

rawDescription: String checking on multiple types

description: String checking on multiple types


code: [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]

rawDescription: Find indices of a value in 2d matrix

description: Find indices of a value in 2d matrix


code:
import csv
import xlrd

workbook = xlrd.open_workbook('test.xlsm')
for sheet in workbook.sheets():
    if sheet == "Sheet_name_to_be_saved":
        with open('{}.csv'.format(sheet.name), 'wb') as f:
            writer = csv.writer(f)
            for row in range(sheet.nrows):
                out = []
                for cell in sheet.row_values(row):
                    if isinstance(cell, float):
                        out.append(cell)
                    else:
                        out.append(cell.encode('utf8'))
                writer.writerow(out)

rawDescription: How to extract sheet from *.xlsm and save it as *.csv in Python?

description: Extract sheet from *.xlsm and save it as *.csv in Python


code:
def textLower(x):
    return x.lower()

dfCities = dfCities["Text"].apply(textLower)
dfCities

#    0          chicago
#    1         new york
#    2         portland
#    3    san francisco
#    4           austin
#    5           boston
#    Name: Text, dtype: object

rawDescription: Apply custom function on text on a pandas dataframe rather than iterating individual element


rawDescription: How to delete a value in a list without using .remove?

description: Delete a value in a list without using .remove


rawDescription: Creating dictionaries from a text file

description: Creating dictionaries from a text file


code: method = Class2.__dict__["method"]

rawDescription: Is it possible to do partial inheritance with Python?


code:
import test

def run_tests(module):
    module.unittest.main(module.__name__)

if __name__ == '__main__':
    run_tests(test)

rawDescription: Invoking Test Methods with a Method for a unittest.TestCase Subclass Python


code:
from pprint import pprint
import math
import csv

# function to massage each row into desired values
def calc_new_vals(row):
    newQuantity = float(row[2]) + 1.0
    newCompetitiveScore = float(row[1]) + math.log(newQuantity, 100)
    return [ float(row[1]),
             float(row[2]),
             newQuantity,
             float(row[4]),
             newCompetitiveScore ]

# read data from file and recalculate each row
f = open('./data.csv', 'r')
reader = csv.reader(f)
records = [ calc_new_vals(record) for record in reader ]

# This sorts by the three columns in reverse
# see this page for more: http://wiki.python.org/moin/HowTo/Sorting/
records = sorted(records, key=lambda record: record[3], reverse = True)
records = sorted(records, key=lambda record: record[2], reverse = True)
records = sorted(records, key=lambda record: record[4], reverse = True)

new_records = []
rank = 1
for row in records:
    row.append( rank )
    new_records.append( row )
    rank += 1
pprint(new_records)

rawDescription: create a data frame using lists

description: Create a data frame using lists


code:
it = iter(l)
zip(it, it, it)

rawDescription: How to iterate through list in number of elements at once?

description: Iterate through list in number of elements at once


rawDescription: Fasted Python way to bulk csv convert outside of using pandas


code:
[p.get('name') for p in bookmarks[0].findParents('folder')]
[p.get('name') for p in bookmarks[0].findParents()]

rawDescription: How do I get a list of all parent tags in BeautifulSoup?

description: Get a list of all parent tags in BeautifulSoup


code:
x = get_first(get_first_list())
if x:
    ...
y = get_first(get_second_list())
if y:
    ...

rawDescription: Python idiom to return first item or None


rawDescription: Writing Greek in matplotlib labels, titles


code:
most_common_food = max(food_groups, key=lambda f: len(food_groups[f]))  # just the food group name
most_common_food_items = max(food_groups.values(), key=len)  # just the food group name

rawDescription: Using counter on array for one value while keeping index of other values


code:
x = ['apples', 'oranges', 'bananas']
for i, item in enumerate(x):
    item=item.replace('app', 'spam')
    x[i] = item
    #Or just
    #x[i] = item.replace('app', 'spam')

rawDescription: How can I replace parts of strings in a list?

description: Replace parts of strings in a list


rawDescription: Transform filter function to Python code


code:
severities = ['Green', 'Yellow', 'Red']

db.define_table('repo',
    Field('body','text',requires=IS_LENGTH(500,1),label="report"),
    Field('severity', requires=IS_IN_SET(severities)),
    Field('posted_on','datetime', readable=False, writable=False),
    Field('posted_by','reference auth_user', writable=False))

rawDescription: web2py - for loop and function to change background color?

description: Web2py - for loop and function to change background color


rawDescription: Binning values of a function in Python (numpy)


code: client.send('HTTP/1.0 200 OK\r\n')

rawDescription: Sending http headers with python

description: Sending http headers with python


code:
df["SUBMISSION_DATE"] = pd.to_datetime(df["SUBMISSION_DATE"],dayfirst=True)
df

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

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


code:
for word in wordlist:
    q.put(word)
for i in range(numthreads):
    q.put(terminate)          # terminate all the worker threads
for t in threadlist:
    t.join()                  # wait for them all to finish

rawDescription: Concurrent insertions in a Suffix Tree

description: Concurrent insertions in a Suffix Tree


rawDescription: Getting the maximum value from dictionary


code:
def replace(t, a, b):
    # Flatten the list
    t1 = []
    l = len(t)-1
    for items in [t[i][0:(1 if i>-1 and i<l else 2)] for i in range(0,l+1)]:
        t1.extend(items)
    replaced = []
    # Iterate the elements of the flattened list
    # Let the elements that do not match a in and replace the ones that
    # do not match with the elements of b
    for elem in t1:
        if elem == a:  # this element matches, replace with b
            replaced.extend(b)
        else:          # this element does not, add it
            replaced.append(elem)
    # break up the replaced, flattened list with groups of 2 elements
    return [replaced[x:x+2] for x in range(len(replaced)-1)]

rawDescription: Digram list manipulation with Python

description: Digram list manipulation with Python


code: inlinkDict[docid] = adoc[1:]

rawDescription: Creating a dictionary with list of lists in Python


code: np.in1d(A, B, assume_unique=True)

rawDescription: Efficient way to compute intersecting values between two numpy arrays


code:
import numpy as np
import h5py
f = h5py.File('trial.mat','r')
zz = f['a'].value.view(np.double).reshape((10,10,10,2))
zzj = zz[:,:,:,0] + 1j*zz[:,:,:,1]
zzk = f['a'].value.view(np.complex)
np.all(zzk == zzj)  # result is "True"
zzj.shape  # result is (10, 10, 10)
zzk[9,9,9].imag == f['a'][9,9,9][1]  # result is "True"
zzk[9,9,9]  # result is (0.8667498969993187+0.36728591513136899j) consistent with Matlab

rawDescription: Importing complex data from .mat file as a numpy array


rawDescription: tkinter and configparser : looking for a more beautiful solution

description: Tkinter and configparser : looking for a more beautiful solution


rawDescription: How to set a variable with pressing a button on an html file to the flask server route

description: Set a variable with pressing a button on an html file to the flask server route


code:
def print_text():
    print('foo bar baz')

print_text()

rawDescription: py.test - How to inherit other tests

description: Py.test - How to inherit other tests


code:
while x != orig_x:
    height_needed = shadow_map[( (x - orig_x) % x_len)]

rawDescription: Speed up NumPy loop

description: Speed up NumPy loop


code:
if input is not None and (
   not var_a or var_a not in input or  # Should this be 'or' or 'and'? 'or' looks unusual here
   not var_b or var_b not in input):
    pass

rawDescription: Python: more concise logic/syntax on empty strings


rawDescription: Numpy array loss of dimension when masking


rawDescription: Creating a spiral structure in Python, using hyperbolic tangent


code: next((x for x in test_list if x.value == value), None)

rawDescription: Find object in list that has attribute equal to some value (that meets any condition)


code:
url = '/your/recieving/end'
files = {'report.xls': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text # response json

rawDescription: How to post a file to django WITHOUT using html form

description: Post a file to django WITHOUT using html form


code:
import matplotlib as plt

X = [0, 1, 2]
Y = [0, 1, 2]
plt.plot(X, Y)
plt.show()

rawDescription: Looking into getting into Python specifically for a project that involves threads and graphs


code:
import urllib2
myobject = ET.parse(urllib2.urlopen(url))

rawDescription: saving an 'lxml.etree._ElementTree' object

description: Saving an 'lxml.etree._ElementTree' object


code:
import re

with open('input.txt', 'r') as f:
    data = f.read()

found = re.findall(r'\n*(A.*?\n\$\$)\n*', data, re.M | re.S)

[open(str(i)+'.txt', 'w').write(found[i-1]) for i in range(1, len(found)+1)]

rawDescription: How can I split a text file into multiple text files using python?

description: Split a text file into multiple text files using python


code: labels, nshapes = ndimage.label(a, structure=np.ones((3, 3)))

rawDescription: Variable area threshold for identifying objects - python


rawDescription: How to iterate link inside unknown total page number?

description: Iterate link inside unknown total page number


code: re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)

rawDescription: Python regex search AND split

description: Python regex search AND split


code:
print(repr(sumVal))
# datetime.datetime(2012, 10, 28, 3, 30, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)

rawDescription: Python DST & Time Zone Detection After Addition


code: minVal = min(dict, key=lambda i: sum(dict[i]))

rawDescription: Minimum sum from a dictionary of lists in Python


rawDescription: Numpy: Creating an (x,y,2,2) array from 4 (x,y) arrays


rawDescription: I can not use the import command

description: I can not use the import command


rawDescription: python descriptors sharing values across classes

description: Python descriptors sharing values across classes


code:
def bar():
    x = ((x + 1) % 2)

dis.dis(bar)

rawDescription: if statement vs. expression

description: If statement vs. expression


code:
[...]
author = Author.objects.filter(slug=slug)
is_fav = author.users_with_stars.filter(pk=user_id).exists()
return render_to_response('app/author_detail.html',
                          { 'author': author,
                            'is_fav': is_fav },
                          context_instance=RequestContext(request))

rawDescription: Django ORM - How to combine annotate and filter


code:
import matplotlib
matplotlib.use('Agg')

rawDescription: Suppress matplotlib figures when running .py files via python or ipython terminal


code:
with open('test', 'r') as f:
    for line in f:
        print(line.strip())

rawDescription: Read large text file without read it into RAM at once


code:
import numpy as np
idxLsts = np.array([[1, 2], [0,2,4]], dtype = object)
idx = 99
f = np.vectorize(lambda x: x.append(idx))
f(idxLsts)
print(idxLsts)

rawDescription: Why is numpy vectorized function apparently called an extra time?


code:
scores = [None]*user_n
for userrem in range(user_n):
    usefulness = int(input('Rate the usefulness of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
    significance = int(input('Rate the significance of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
    difficulty = int(input('Rate the difficulty of the work performed by shareholder# '+str(userrem+1)+' [Range=0-5]'))
    scores[userrem] = (usefulness, significance, difficulty)

rawDescription: How do I input the items in a list using a variable as the identifier?

description: Input the items in a list using a variable as the identifier


code:
index = np.array([3,2,1,0])
arr[index]

rawDescription: Convert a 3D array to 2D array based on dictionary


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
fig.set_figheight(10)
fig.set_figwidth(12)
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
        linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
fig.savefig("myfig.png", dpi=600) # useful for hi-res graphics
plt.show()

rawDescription: Matplotlib PDF plots don't respond to figsize


code:
d[frozenset(['foo', 'bar'])] = 'baz'
d[frozenset(['bar', 'foo'])]
d[frozenset(['bar', 'foo', 'bar'])]

rawDescription: How to use a list of strings [which may contain any character] as keys?

description: Use a list of strings [which may contain any character] as keys


code:
d
d.setdefault(1, 3)
d
d.setdefault(3, 3)
d

rawDescription: How to write this snippet in Python?

description: Write this snippet in Python


rawDescription: Pandas Dataframe.describe() : Which kind of standard deviation?


code:
d2["price"] = d2["price"].str.replace("p","").astype(float)
d2

rawDescription: Get last "column" after .str.split() operation on column in pandas DataFrame


code: min(lst, key=lambda item: float(item['cost']))

rawDescription: Get dictionary with lowest key value from a list of dictionaries


rawDescription: Pyserial using default system serial configuration


rawDescription: Python - Find sequence in array: start when two values below threshold, end when two values above threshold


code:
#!/usr/bin/env python
from datetime import datetime
from email.util import parsedate_tz, mktime_tz

def to_local_time(tweet_time_string):
    """Convert rfc 5322 -like time string into a local time
       string in rfc 3339 -like format.

    """
    timestamp = mktime_tz(parsedate_tz(tweet_time_string))
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

time_string = to_local_time('Thu Mar 19 12:37:15 +0000 2015')
# use time_string here..

rawDescription: Convert Time Zone + format in Python from Twitter API


code: s = 'ABCD' + u''.join(map(unichr, range(0x2713, 0x271d)))

rawDescription: How to iterate a Unicode string in Python?

description: Iterate a Unicode string in Python


rawDescription: Deleting elements in a given list only?

description: Deleting elements in a given list only


code:
if isinstance(trends_all, list):
    trends_all = trends_all[0]
for x in trends_all['trends']:
    ...

rawDescription: How to work with multiple JSON formats?

description: Work with multiple JSON formats


code:
import dis
dis.dis(compile('(n for n in stream if n % 2 == 0)', '', 'exec').co_consts[0])
dis.dis(compile('''\
def evens(stream):
    for n in stream:
        if n % 2 == 0:
            yield n
''', '', 'exec').co_consts[0])

rawDescription: Generator expressions vs yield

description: Generator expressions vs yield


code: sortedlist = sorted(alist, key=lambda x: (x.firstname , x.lastname))

rawDescription: How do I sort a list of class intances(objects) based on multiple values of the objects in Python

description: Sort a list of class intances(objects) based on multiple values of the objects in Python