code:
def find_closest(dt,x):
    dt2 = datetime.strptime(x,"%m/%d/%Y %H:%M")
    return abs(dt2 - dt) if dt > dt2 else dt2 - datetime.today()

for k,d in dtDict.items():
    diff = allDatetimes - d.viewkeys()
    for k in diff:
        dt1 = datetime.strptime(k, "%m/%d/%Y %H:%M" )
        d[k] = d[min(d, key=lambda x:find_closest(dt1,x))]

rawDescription: see if list of keys exist in dictionaries of a dictionary in python

description: See if list of keys exist in dictionaries of a dictionary in python


code:
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

with open(attachment_path) as pdf_file, open(email_body_path) as text_file:
    pdf = MIMEApplication(pdf_file.read(), _subtype = 'pdf')
    pdf.add_header('content-disposition', 'attachment', filename=basename(attachment_path))
    text = MIMEText(text_file.read(), _charset='UTF-8')

msg = MIMEMultipart(_subparts=(text, pdf))
msg['Subject'] = 'Test multipart message'

rawDescription: Multipart email PDF attachment blank

description: Multipart email PDF attachment blank


code:
d = {'(': 'a'}
''.join(map(lambda letter: d.get(letter, letter), 'text with m(ny letters'))

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
message_string = json.loads(m.get_body())['Message']
message_string
message = json.loads(message_string)
message['AlarmName']

rawDescription: How to read the AWS Status Check Alarm message with Boto

description: Read the AWS Status Check Alarm message with Boto


code: pair_sets = list(set().union(*x) for x in combinations(lol,2))

rawDescription: Generate Joined Lists of Given Size in python


code:
from abc import ABCMeta
from typing import Any, TypeVar

class Comparable(metaclass=ABCMeta):
    @abstractmethod
    def __lt__(self, other: Any) -> bool: ...

CT = TypeVar('CT', bound=Comparable)

rawDescription: How can I hint that a type is comparable with typing

description: Hint that a type is comparable with typing


code:
name_from_hash1 =  {v:k for k, v in file1.items()}
name_from_hash2 =  {v:k for k, v in file2.items()}

rawDescription: Comparing 2 dicts, if values are the same, but key is different, add key to a new list in python


code:
import numpy as np

def fast_wdist(A, B, W):
    """
    Compute the weighted euclidean distance between two arrays of points:

    D{i,j} =
    sqrt( ((A{0,i}-B{0,j})/W{0,i})^2 + ... + ((A{k,i}-B{k,j})/W{k,i})^2 )

    inputs:
        A is an (k, m) array of coordinates
        B is an (k, n) array of coordinates
        W is an (k, m) array of weights

    returns:
        D is an (m, n) array of weighted euclidean distances
    """

    # compute the differences and apply the weights in one go using
    # broadcasting jujitsu. the result is (n, k, m)
    wdiff = (A[np.newaxis,...] - B[np.newaxis,...].T) / W[np.newaxis,...]

    # square and sum over the second axis, take the sqrt and transpose. the
    # result is an (m, n) array of weighted euclidean distances
    D = np.sqrt((wdiff*wdiff).sum(1)).T

    return D

rawDescription: Fast weighted euclidean distance between points in arrays


rawDescription: python get substring from regex

description: Python get substring from regex


code:
block_size = 256
Y = np.zeros((M, M), dtype=float)
for j in xrange(0, N, block_size):
    Xb = X[:,j:(j+block_size)]
    Y += Xb.dot(Xb.T)

rawDescription: Multipy matrix by its transpose in constant memory


code:
x,y = x*km_per_pixel + km_offset_x, y*km_per_pixel + km_offset_y
im = ax.imshow(...,exent=lims_in_km)
q = ax.quiver(x,y,...)

rawDescription: matplotlib change extent in quiver plot

description: Matplotlib change extent in quiver plot


code:
datetime.datetime(2015, 7, 26, 22, 42) + delta
datetime.datetime(2015, 12, 26, 22, 42) + delta
datetime.datetime(2016, 2, 23, 22, 42) + delta

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


rawDescription: BeautifulSoup4 table

description: BeautifulSoup4 table


code:
...
return redirect(request.form.get('next', '/'))

rawDescription: Returning user to referrer in flask in smartest pythonic way


code:
{'children': [{'children': [{'children': [{'children': [{'children': [{'name': 'param-6'}],
         'name': 'param-5'},
        {'name': 'ntp-servers'},
        {'children': [{'children': [{'children': [{'name': 'weekly'}],
             'name': 'recurring'}],
           'name': 'global-protect-datafile'}],
         'name': 'update-schedule'}],
       'name': 'param-3'}],
     'name': 'param-3'},
    {'children': [{'children': [{'children': [{'children': [{'children': [{'children': [{'name': 'dpd'}],
               'name': 'param-Xv1'}],
             'name': 'protocol'},
            {'children': [{'name': 'nat-traversal'},
              {'name': 'fragmentation'}],
             'name': 'protocol-common'}],
           'name': '<name>'}],
         'name': 'gateway'},
        {'children': [{'children': [{'children': [{'name': 'A'},
              {'name': 'B'},
              {'name': 'C'},
              {'name': 'D'}],
             'name': '<name>'}],
           'name': 'param-X-param-Z'},
          {'children': [{'children': [{'children': [{'name': 'encryption'},
                {'name': 'authentication'}],
               'name': 'esp'},
              {'children': [{'name': 'authentication'}], 'name': 'ah'},
              {'name': 'lifetime'},
              {'name': 'lifesize'}],
             'name': '<name>'}],
           'name': 'ipsec-param-Z'}],
         'name': 'param-Z'}],
       'name': 'param-X'}],
     'name': 'param-2'}],
   'name': 'param-1'}],
 'name': 'root'}

rawDescription: Text file with repeated elements to JSON


code:
class accountCurve():
    def __init__(self, forecasts, prices):
        self.curve = pd.DataFrame(columns=['Capital','Holding','Cash','Trade', 'Position'], dtype=float)
        # forecasts.dropna(inplace=True)
        self.curve['Forecast'] = forecasts.dropna()
        self.curve['Price'] = prices
        # helper np.array:
        self.arr = np.array(self.curve)
        self.arr[0,:5] = [10000, 0, 10000, 0, 0]

        for i in range(1, self.arr.shape[0]):
            this = self.arr[i]
            prev = self.arr[i-1]
            cash = prev[2] - prev[3] * this[6]
            position = ...
            holding = ...
            capital = ...
            trade = ...
            this[:5] = [capital, holding, cash, trade, position]

        # back to data frame:
        self.curve[['Capital','Holding','Cash','Trade', 'Position']] = self.arr[:,:5]
        # or maybe this would be faster:
        # self.curve[:] = self.arr

rawDescription: Improving Pandas iteration performance

description: Improving Pandas iteration performance


code:
class subclassed_dict(dict):
    def __missing__(self, key):
        item = self[key] = very_expensive_initializer(key)
        return item

rawDescription: How do I initialize values in a dictionary?

description: Initialize values in a dictionary


rawDescription: How can I add a decorator to an existing object method?

description: Add a decorator to an existing object method


code:
import lxml.html
html = """

\n
\nYour order was delivered
\non
\n6/4
\n@
\n4:44 PM
\n
"""
tree = lxml.html.etee.fromstring(html)
print(tree.xpath("string()"))

rawDescription: Parsing HTML tree in lxml : how can I retrieve the text inside the element?


code: print(u"T\u00fcrk K\u0131z\u0131lay\u0131 Genel Ba\u015fkan\u0131m\u0131z Sn. @AhmetLutfiAkar yar\u0131n sabah 08:00'e TV8'de canl\u0131 yay\u0131n konu\u011fu olacak... @TurkKizilayi")

rawDescription: Somali encoding

description: Somali encoding


rawDescription: Get Authenticated user from token in Django Rest Framework


code:
def consumer_callback(ch, method, properties, body):
        logging.info("[x] Received %r" % (body,))
        # The messagge is brodcast to the connected clients
        for itm in clients:
            itm.write_message(body)

rawDescription: Easiest way to push RabbitMQ events to browser using WebSockets in Python?


code:
def adder(producer1, producer2, consumers):
    while True:
        x = next(producer1)
        y = next(producer2)
        for consumer in consumers:
            consumer.send(x+y)

rawDescription: How to unify sender- and receiver-based coroutines?

description: Unify sender- and receiver-based coroutines


code:
import itertools

def insert_letters(sequence, rest):
    if not rest:
        yield sequence
    else:
        letter, number = rest[0]
        rest = rest[1:]
        possible_locations = range(len(sequence)+1)
        for locations in itertools.combinations_with_replacement(possible_locations, number):
            result = []
            count = 0
            temp_sequence = sequence
            for location in locations:
                while location > count:
                    result.append(temp_sequence[0])
                    temp_sequence = temp_sequence[1:]
                    count += 1
                result.append(letter)
            if temp_sequence:
                result.append(temp_sequence)
            for item in insert_letters(''.join(result), rest):
                yield item

def generate_sequences(*args):
    '''
    arguments : squence of (letter, number) tuples
    '''
    (letter, number), rest = args[0], args[1:]
    for sequence in insert_letters(letter*number, rest):
        yield sequence

rawDescription: Finding all sequences of A, B such that have a specified number of each element


code: {i: {k[1]: n for n, k in enumerate(j, 1)} for i, j in grouped}

rawDescription: How can I split a 2D array into an array with unique values and a dictionary?

description: Split a 2D array into an array with unique values and a dictionary


rawDescription: Python - Tuple generation from list

description: Python - Tuple generation from list


code:
@password.setter
def password(self, value):
    self._password = hash(value)

rawDescription: SQL Alchemy overriding ==

description: SQL Alchemy overriding ==


code:
parents, children = zip(*links)
root_nodes = {x for x in parents if x not in children}

rawDescription: recursively build hierarchical JSON tree in python

description: Recursively build hierarchical JSON tree in python


code:
try:
    import _winreg
except ImportError:
    import cygwinreg as _winreg

rawDescription: Cygwin Python Script using cygwinreg that can run on the Windows Python


code:
template('mytemplate.tpl', name="Anne", address="4 Elm Street",
                          dob=datetime.datetime(1977,12,2,1,2,3))

rawDescription: Bottle multiple template variables

description: Bottle multiple template variables


rawDescription: Extract first date from string in a data frame


code:
for x in itertools.islice(itertools.cycle(range(4)), 10):
    print(x)

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

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


code:
def doubleChar(doubleit):
    doubled = []
    for letter in doubleit:
        doubled.append(letter * 2)
    print("".join(doubled))

doubleChar('the')

rawDescription: How to make a program that doubles letters (input = hello, returns = hheelllloo)

description: Make a program that doubles letters (input = hello, returns = hheelllloo)


code:
for i, doc_terms in enumerate(docs):
    fv = fvs[i]
    for term in doc_terms:
        fv[corpus[term]] += 1

rawDescription: Python: implementing feature vectors efficiently


code:
def format_date_col(x):
    x = str(x)
    return '-'.join([x[:4], x[4:6], x[6:]])

    # or maybe like that for better readability:
    x = str(x)
    return '{year}-{month}-{day}'.format(year=x[:4], month=x[4:6], day=x[6:])

df['date'] = df['date'].apply(format_date_col)

rawDescription: How do I change the date format in a dataframe column.

description: Change the date format in a dataframe column.


code:
from cel_test.celery import app

@app.task(ignore_result=False)
def qry(sql, writing=False):
    import psycopg2
    conn = psycopg2.connect(dbname='space_test', user='foo', host='localhost')
    cur = conn.cursor()
    cur.execute(sql)
    if writing == True:
        cur.close()
        conn.commit()
        conn.close()
        return

    a = cur.fetchall()
    cur.close()
    conn.close()
    return a

rawDescription: Celery task PENDING

description: Celery task PENDING


code:
s = bytearray(1000000)   # a million zeroed bytes
t = buffer(s, 1)         # slice cuts off the first byte
s[1] = 5                 # set the second element in s
t[0]                     # which is now also the first element in t!

rawDescription: What is Python buffer type for?

description: What is Python buffer type for


code:
class Foo(object):
    @register(many,decos,here)
    def bar(self):
        pass

rawDescription: Introspection to get decorator names on a method?


code:
roles = list(obj.get_local_roles_for_userid(crtor_obj))
if 'Owner' not in roles:
    roles.append('Owner')
    obj.manage_setLocalRoles(crtor_obj, roles)

rawDescription: Plone: How to change ownership of an archetype content?


code:
import string
k, v = zip(*BYTE_REPLACE.iteritems())
k, v = ''.join(map(chr, k)), ''.join(map(chr, v))
tbl = string.maketrans(k, v)
def subs(st):
    return st.translate(tbl)

rawDescription: Fastest way to substitute a set of characters in a string


code:
import datetime
datetime.datetime.strptime("September 17, 2013", '%B %d, %y')
x = datetime.datetime.strptime("September 17, 2013", '%B %d, %Y')
x

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


code:
elow >= ehigh

energy = []

stepsize < 0

rawDescription: Returning and empty array

description: Returning and empty array


code:
class SomeSpider(Spider):

  ...

  def parse(self, response):
    # some code to parse the webpage

    for some_line in webpage:
        item = YourItem()
        # parse items

        yield item

rawDescription: Export scrapy objects into one file per item


rawDescription: Real distance between two points over image


code:
def func1():
    pass
def func2():
    pass
def main():
    return 0

if __name__ == '__main__':
    sys.exit(main())

rawDescription: How to make an executable to use in a shell - Python

description: Make an executable to use in a shell - Python


rawDescription: Change specific value in CSV file via Python


code: freopen('/dev/null', 'w', sys.stdout)

rawDescription: How do I change that which is inherited by stdout=None in subrocess.Popen(stdout=None)?

description: Change that which is inherited by stdout=None in subrocess.Popen(stdout=None)


code:
a
a.shape += (1,)
a
a.shape
a.ndim

rawDescription: get "1" for a one-dimensional numpy.array using a shape-like function

description: Get "1" for a one-dimensional numpy.array using a shape-like function


code:
scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
               (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
letter_score = {letter: score for score, letters in scrabble_scores
                              for letter in letters.split()}
letter_score
letter_score['Q']

rawDescription: dict comprehensions for mapping scrabble letter distribution

description: Dict comprehensions for mapping scrabble letter distribution


code:
if __name__ == '__main__':
    import os
    path = os.path.expanduser(r'~\Desktop\desktop.ini')
    pidl = _shell.SHParseDisplayName(path, 0)[0]
    assert isinstance(pidl, list)

    flags = (shellcon.SHGFI_PIDL |
             shellcon.SHGFI_ICON |
             shellcon.SHGFI_DISPLAYNAME |
             shellcon.SHGFI_TYPENAME |
             shellcon.SHGFI_ATTRIBUTES |
             shellcon.SHGFI_SYSICONINDEX)

    hImageList, finfo = SHGetFileInfo(pidl, 0, flags)

    print('hImageList:', hImageList)
    for name, typ in finfo._fields_:
        print(name, ': ', ascii(getattr(finfo, name)), sep='')

    if finfo.hIcon:
        _user32.DestroyIcon(finfo.hIcon)

rawDescription: How to use SHGetFileInfo with SHGFI_PIDL in python

description: Use SHGetFileInfo with SHGFI_PIDL in python


code:
import pandas as pd
import numpy as np
import pandas.io.data as web
aapl = web.get_data_yahoo("AAPL")
f  = np.median(np.diff(aapl.index.values))
days = f.astype('timedelta64[D]').item().days
aapl = aapl.asfreq('{}D'.format(days), method='ffill')
print(aapl)

rawDescription: How can I approximate the periodicity of a panda time Series

description: Approximate the periodicity of a panda time Series


code:
number = 523.637382
rounded = round(number, 3) # 3 decimal places, for example
rounded

rawDescription: How can I stop printing a float 3 spaces after decimal?

description: Stop printing a float 3 spaces after decimal


code:
from enum import Enum, IntEnum

hand1 = [1,2,4,5,3,7,2,12,3,1,0]
hand2 = [2,3,3,3,4,3,1,3,4,1,0]

class Suits(Enum):
    Hearts = 1
    Spades = 2
    Diamonds = 3
    Clubs = 4
class Ranks(IntEnum):
    Ace = 1    # writing this was the first time I thought to myself
    Two = 2    # "...gee, I wish I were writing in golang right now"
    Three = 3  # iotas are wonderful.
    Four = 4
    Five = 5
    Six = 6
    Seven = 7
    Eight = 8
    Nine = 9
    Ten = 10
    Jack = 11
    Queen = 12
    King = 13

class Card(object):
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    @classmethod
    def from_tuple(cls, tup):
        suit, rank = tup
        return cls(Suits(suit), Ranks(rank))

    def __str__(self):
        return "{0.rank.name} of {0.suit.name}".format(self)

    # This is allllll framework stuff so that it's easier to handle these later!

import itertools

def grouper(iterator, n):
    """From itertools recipes"""
    args = [iter(iterator)] * n
    return itertools.zip_longest(fillvalue=0, *args)

hand = [Card.from_tuple(group) for group in grouper(hand1, 2)
        if 0 not in group]
other_hand = [Card.from_tuple(group) for group in grouper(hand2, 2)
              if 0 not in group]

rawDescription: PokerGame deciding cards

description: PokerGame deciding cards


code:
import numpy as np
from numpy import asarray
x = np.random.rand(100,1)
y = np.random.rand(100,1)
z = np.random.rand(100,1)

rawDescription: Numpy meshgrid points

description: Numpy meshgrid points


code:
list_of_list = [['One', 'Two', 'Three', 'Four'], ['Five', 'Six', 'Seven']]
[[numberDict.get(value, "") for value in lst] for lst in list_of_list]

rawDescription: Changing values of a list by getting them from a dictionary (Python)


code:
# Rolling avg, windows size is the size of the entire DataFrame, with minimum of 1
df['rolling_avg'] = pd.rolling_mean(df.price, n, 1)

rawDescription: Python and Pandas - column that "count direction" and show "avarage until now"


code:
class TransactionForm(ModelForm):
    class Meta:
        model = Transaction

    # def __init__(self, *args, **kwargs):
        # user = kwargs.pop('user', User.objects.get(pk_of_default_user))
    def __init__(self, user, *args, **kwargs):
        super(TransactionForm, self).__init__(*args, **kwargs)
        self.fields['category'] = forms.ModelChoiceField(
                                     queryset=Category.objects.filter(user=user))

rawDescription: Django: Filter ModelChoiceField by user

description: Django: Filter ModelChoiceField by user


code: c3 = csv.DictWriter(out_res, fieldnames=fieldnames[None])

rawDescription: Python: Concatenate two dictReader strings for header row


code: board = [[d*d-1-i-d*j for i in range(d)] for j in range(d)]

rawDescription: How to create a game board on Python

description: Create a game board on Python


code: 1 not in l

rawDescription: Test if value exists in several lists

description: Test if value exists in several lists


code:
def search(directory):
    global file_count
    excludes = ['Yes', 'Maybe', 'Skipped']
    for root, subdirs, files in os.walk(directory, topdown=True):
        subdirs[:] = [d for d in subdirs if d not in excludes]
        for file in files:
            if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg'):
                img = os.path.join(root, file)
                file_count += 1
                yield img

rawDescription: How do I get my tkinter picture viewer working?

description: Get my tkinter picture viewer working


rawDescription: Extract items of integers from a regularly spaced list in Python


code: R = np.abs(np.cos(PHI**2))

rawDescription: Spherical coordinates plot in matplotlib


code:
S = np.row_stack((s0,s1))
out = np.where((np.in1d(Z,S).reshape(Z.shape)).all(2))

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


code:
def primer(x):
    if x == 2:
        return True
    if x % 2 == 0 or x < 3:
        return False
    return not any(x % i == 0 for i in range(3, int(x ** .5) + 1, 2))

from random import randint

def fermat_little_theorem(p, conf):
    """
     int p to test if prime
     conf is the confidence level/how many times to try n ** (p - 1) % p == 1
    returns with confidence p is prime based on 1/2^conf
    """
    if p <= 1:
        return False
    for _ in range(conf):
        n = randint(1, p - 1)
        if not n ** (p - 1) % p == 1:
            return False
    return True

rawDescription: Failing to change bool var state in loop


rawDescription: Why do I lose precision while multiplying and dividing whole ints?


code: d = numpy.empty((n, 0)).tolist()

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


code:
import numpy as np
from operator import itemgetter
import csv
with open("sample.txt") as f:
   from itertools import islice
   r = csv.reader(f)
   print(np.fromiter(map(itemgetter(0), islice(r,  start, end+1)), dtype=float))

rawDescription: load a certain number of rows from csv with numpy

description: Load a certain number of rows from csv with numpy


code:
import Tkinter

def test(event=None):
    tl = Tkinter.Toplevel()
    tl.wait_window(tl)

root = Tkinter.Tk()
btn = Tkinter.Button(text=u'hi')
btn.bind('<Button-1>', test)
btn.pack(padx=10, pady=10)
root.mainloop()

rawDescription: Why does Tkinter hang when I call tkSimpleDialog.askstring from a lambda?


code:
a = (1, 2)

empty__func = 0
def empty():
    for i in xrange(N_RUNS):
        empty__func

lambda_func = lambda t: t[0]
def using_lambda():
    for i in xrange(N_RUNS):
        lambda_func(a)

getter_func = itemgetter(0)
def using_getter():
    for i in xrange(N_RUNS):
        getter_func(a)

rawDescription: Python OrderedDict ordered by date

description: Python OrderedDict ordered by date


code:
class Son_1(object):

    son_func = staticmethod(func_1)

class Son_2(object):

    son_func = staticmethod(func_2)

rawDescription: Python, how to keep a non-class method as non-class method?


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


code:
# create instances of my user object
u = User('nosklo')
u.address = '66 Some Street #500'

u2 = User('lakshmipathi')
u2.password = 'ihtapimhskal'

# testing
s.add_all([u, u2])
s.commit()

rawDescription: Is it possible to store Python class objects in SQLite?


code:
def f(struct):
    return (struct.a+struct.b)**struct.s

rawDescription: Python multiprocessing: avoid communication via module between processes


code:
with open(file) as f:
    dictionary = sorted(line.rstrip() for line in f)

rawDescription: list(file) appends \n to each line

description: List(file) appends \n to each line


code:
from lxml import etree

content = '''<?xml version="1.0" encoding="iso-8859-1" standalone="yes"?>
<SPB name="PolygonList">
  <SPB name="0">
    <NTP_BOOL name="Active" value="true"/>
    <NTP_TXT name="Custom" value=""/>
    <NTP_TXT name="CustomMatch" value=""/>
    <NTP_TXT name="Polygon" value="example1"/>
  </SPB>
  <SPB name="1">
    <NTP_BOOL name="Active" value="true"/>
    <NTP_TXT name="Custom" value=""/>
    <NTP_TXT name="CustomMatch" value=""/>
    <NTP_TXT name="Polygon" value="example2"/>
  </SPB>
  <SPB name="2">
    <NTP_BOOL name="Active" value="true"/>
    <NTP_TXT name="Custom" value=""/>
    <NTP_TXT name="CustomMatch" value=""/>
    <NTP_TXT name="Polygon" value="example3"/>
  </SPB>
  <NTP_INT name="Count" value="3"/>
</SPB>'''

tree = etree.XML(content)
values = tree.xpath('//NTP_BOOL[@value="true"]/following-sibling::NTP_TXT[@name="Polygon"]/@value')
print(values)

rawDescription: Python - Trouble Parsing XML

description: Python - Trouble Parsing XML


code:
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import ClauseElement
from sqlalchemy import literal

class Match(ClauseElement):
    def __init__(self, columns, value):
        self.columns = columns
        self.value = literal(value)

@compiles(Match)
def _match(element, compiler, **kw):
    return "MATCH (%s) AGAINST (%s)" % (
               ", ".join(compiler.process(c, **kw) for c in element.columns),
               compiler.process(element.value)
             )

my_table.select(Match([my_table.c.a, my_table.c.b], "some value"))

rawDescription: Proper use of MySQL full text search with SQLAlchemy


code: [list(g) for _,g in groupby(t,lambda x : x[0])]

rawDescription: Reorganise list in list python

description: Reorganise list in list python


code:
import re
lines = (line for line in open('data', 'rb')  if re.match(r'^\s*[1-9]', line) )

rawDescription: NumPy genfromtxt - skipping rows that start with specific number


code:
import re
import csv
import itertools

line = next(f1)
coding = re.match('^#\s*coding\s*(:|=|:=)\s*([\w\d\-_]+)\s*$', line)
reader = csv.reader(itertools.chain([line], f1))

rawDescription: Neat way to check first line of a file before reading CSV


code:
tokens = ['arg:Title=SampleTitle', 'arg:Note=SampleNote']
dict(s[4:].split("=") for s in tokens)

rawDescription: Replacing "tokens" in Python string with alternate values


code:
variable = copy.copy(initial_variable)
#in order to keep safe the initial value

rawDescription: How to restart a program?

description: Restart a program


code: print(u"\N{RABBIT FACE}")

rawDescription: Unicode Characters in Twitter (Python)

description: Unicode Characters in Twitter (Python)


code:
def bucket(v):
    # of course, the thresholds can be arbitrary
    if v < 20000:
        return 1
    if v < 30000:
        return 2
    if v < 40000:
        return 3
    return 4

df['inc_index'] = df.mn_earn_wne_p6.apply(bucket)

rawDescription: Python/Pandas - Best way to group by criteria?


code:
current_max = 0
for v in values:
    if v>current_max:
        current_max = v

rawDescription: Python: Find the longest word in a string


code:
site = urllib.urlopen('http://duckduckgo.com/html/?q=example')
data = site.read()
parsed = BeautifulSoup(data)

first_link = parsed.findAll('div', {'class': re.compile('links_main*')})[0].a['href']

rawDescription: duckduckgo API not returning results

description: Duckduckgo API not returning results


code:
from itertools import product, combinations, chain

reg_lines = {'primary': ['ETH', 'UDP', 'TCP'], 'secondary': ['ETH', 'TCP'], 'private': ['UDP', 'TCP']}

def all_combinations(lst):
    return chain(*[combinations(lst, i+1) for i in range(len(lst))])

for comb in all_combinations(reg_lines):
    for prod in product(*(reg_lines[k] for k in comb)):
        use = dict(zip(comb, prod))
        print("use", use)
        for comb2 in all_combinations(comb):
            disc = {k: use[k] for k in comb2}
            print("disc", disc)

rawDescription: Create permutations of a nested dict

description: Create permutations of a nested dict


code: JPEG_ROOT = libinclude("/usr/lib")

rawDescription: install pil on virtualenv with libjpeg

description: Install pil on virtualenv with libjpeg


code: all(len(set(random.sample(word_drills, 3))) == 3 for i in range(10**5))

rawDescription: Pull random keys from dictionary in Python that are not equal to one another


code:
from __future__ import print_function

def my_function(a, b, c, d):
    e=a*b*c*d

def f1():
    for n in range(0, 1000000):
        a = my_list[n] * 2
        b = my_list[n] + my_list[n+1]
        c = my_list[n] * my_list[n+1]
        d = my_list[n] - my_list[n+1]
        my_function(a, b, c, d)

def f2():
    for n in range(0, 1000000):
        my_list_n = my_list[n]
        my_list_np1 = my_list[n+1]
        a = my_list_n  * 2
        b = my_list_n  + my_list_np1
        c = my_list_n  * my_list_np1
        d = my_list_n  - my_list_np1
        my_function(a, b, c, d)

def f3():
    for n in range(0, 1000000):
        my_function(my_list[n] * 2,
                    my_list[n] + my_list[n+1],
                    my_list[n] * my_list[n+1],
                    my_list[n] - my_list[n+1])

if __name__ == '__main__':
    import timeit
    import sys
    print(sys.version)
    my_list=range(1000001)
    n=2
    for f in (f1, f2, f3):
        res=timeit.timeit("{}()".format(f.__name__), setup="from __main__ import {}, my_list".format(f.__name__), number=n)
        print("{}: {:.3} secs".format(f.__name__, res))

rawDescription: Python code speedup by storing commonly used list elements in local variables


code: hash("foo")

rawDescription: How does the dictionary add keys in python?


code:
import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"

rawDescription: Python PANDAS, change one value based on another value


code:
def clean_label(label_list, margins='False'):
    ''' This function takes the column index list from a crosstab (or pivot table?) in pandas and removes the
    part of the label before and including the "_".  This allows the user to order the columns manually by creating
    an alphabetical index followed by "_" and then the label that they would like to use.  For example, a label such as
    ['a_Positive', 'b_Negative'] will be converted to ['Positive', 'Negative'].  Another example would be to order dates
    in a table from ['12 10_Oct 12', '12 11_Nov 12'] to ['Oct 12', 'Nov 12']

    margins = False if the crosstab was created without margins and therefore does not have an "All" at the end of the list
    margins = True if the crosstab was created with margins and therefore has an "All" at the end of the list
    '''
    corrected_list=list()

    # If one creates margins in pivot/crosstab, will get the last column of "All"
    # This has to be removed from the following code or it will throw an error.
    if margins:
        convert_list = label_list[:-1]
    else:
        convert_list = label_list

    for l in convert_list:
        x,y=l.split('_')
        corrected_list.append(y)

    if margins:
        corrected_list.append('Total')  # Renames "All" to "Total"

    return corrected_list

# Change the labels on the crosstab table
table_1.columns=clean_label(table_1.columns, margins=True)

# Change name of columns
table_1.columns.name = 'Month of Collection'

# Change name of rows
table_1.index.name = 'Region'

rawDescription: Pandas Crosstab: Change Order of Columns That Are Named as Formatted Dates (mmm yy)


code: df.to_html(classes = 'my_class" id = "my_id')

rawDescription: JS dataTables from pandas

description: JS dataTables from pandas


code:
import os
def search_file(directory = None, file = None):
    assert os.path.isdir(directory)
    current_path, directories, files = os.walk(directory).next()
    if file in files:
        return os.path.join(directory, file)
    elif directories == '':
        return None
    else:
        for new_directory in directories:
            result = search_file(directory = os.path.join(directory, new_directory), file = file)
            if result:
                return result
        return None

rawDescription: Do I understand os.walk right?

description: Do I understand os.walk right


code:
SC.new_attr
SC.new_attr.value
SC.new_attr.add('other')
SC.new_attr.value

rawDescription: Method that applies to instance of a class in python // Apply a method to an instance of a class in python


code: df["year"] = df["schedule"].apply (lambda x : x.year if x.month < 9 else x.year + 1)

rawDescription: Pandas: Extracting just the Calendar Year from Datetime column


code: s.reset_index(name='s').groupby('level_0').apply(lambda s: s.sort('s')).set_index(['level_0', 'level_1'])['s']

rawDescription: In Pandas How to sort one level of a multi-index based on the values of a column, while maintaining the grouping of the other level


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

data = np.array([1,3,70,924,3])

plt.bar(np.arange(data.size), data)
plt.ylim([0, 300])

plt.show()

rawDescription: matplotlib - Allow bar to extend beyond chart limits?

description: Matplotlib - Allow bar to extend beyond chart limits


code: [dict(d, count=n) for d, n in zip(l1, l2)]

rawDescription: Updating a list of python dictionaries with a key, value pair from another list


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


code:
from flask import jsonify

@app.route('/failing_jobs/', methods= ['GET' , 'POST'])
def failing_jobs():
    real_list = generate_failing_jobs() #normal method that will generate a list
    return jsonify(jobs=real_list)

rawDescription: Need to load a dynamically generated list of strings from an AJAX call (flask backend)


code:
AE_ar
AM_hy
AM_ru

rawDescription: Concatenate values in a list (XML,Python)


rawDescription: How to use the regular Expression in python

description: Use the regular Expression in python


code:
inter = js["txs"][0]
k1 = next((d["prev_out"].get("addr_tag") for d in inter["inputs"] if "prev_out" in d), None)
k2 = next((d.get("addr_tag") for d in inter["out"] if "addr_tag" in d), None)

rawDescription: Fetch specific data from JSON

description: Fetch specific data from JSON


rawDescription: Sum of values in list of dictionaries

description: Sum of values in list of dictionaries


code: ways = [1]+[0]*target

rawDescription: Understanding change-making algorithm

description: Understanding change-making algorithm


code:
myrealsecret = b'Hey there this is a real secret'
secret + myrealsecret

rawDescription: Dealing with a string and byte in python


rawDescription: two's complement of numbers in python

description: Two's complement of numbers in python


code: A.T.dot(A).dot(x) == A.T.dot(b)

rawDescription: Solve seemingly (but not actually!) overdetermined sparse linear system in Python


code:
import unittest

def print_suite(suite):
    if hasattr(suite, '__iter__'):
        for x in suite:
            print_suite(x)
    else:
        print(suite)

print_suite(unittest.defaultTestLoader.discover('.'))

rawDescription: How to list available tests with python?

description: List available tests with python


code:
import ssl
from pymongo import MongoClient
client = MongoClient(
    '<server hostname>',
    27017,
    ssl=True,
    ssl_certfile='~/client.pem',
    ssl_cert_reqs=ssl.CERT_REQUIRED,
    ssl_ca_certs='~/ca.pem'
 )

rawDescription: Self-signed SSL connection using PyMongo


code:
from django.db import models

class model2(models.Model):
    name = models.CharField(max_length=100)

class model1(models.Model):
    name  = models.CharField(max_length=100)

class Meta:
    managed = False
    db_table = 'app2_model1'

rawDescription: How to move a model between two Django apps (Django 1.7)

description: Move a model between two Django apps (Django 1.7)


code:
def foo():
    funcstr='''\
def func(x, {p}):
    return x * 2*a + 4*b - 5*c
'''

rawDescription: Dynamically define a function

description: Dynamically define a function


rawDescription: Python dictionary merge values and delete previous


code:
import requests
s = requests.session()
s.get('http://httpbin.org/cookies/set', params={'foo': 'bar'})
s.cookies.keys()
s.get('http://httpbin.org/cookies').json()
s.cookies.clear()
s.cookies.keys()
s.get('http://httpbin.org/cookies').json()

rawDescription: Clear cookies from Requests Python

description: Clear cookies from Requests Python


code:
from itertools import zip_longest
list(zip_longest([1, 2, 3], [4, 5]))
m = [[1, 2, 3], [4, 5, 6], []]
list(zip_longest(*m, fillvalue=0))

rawDescription: Transpose this matrix(python3)

description: Transpose this matrix(python3)


rawDescription: UnicodeWarning: special characters in Tkinter


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


code:
{'podcasts': [{'description': 'Description 1',
               'link': 'link1.mp3',
               'title': 'Title 1'},
              {'description': 'Description 2',
               'link': 'link2.mp3',
               'title': 'Title 2'}]}

rawDescription: BeautifulSoup scraping information from multiple divs using loops into JSON


code:
a[1, 1] = 5
a.data
b.data

rawDescription: scipy sparse matrices, copy argument

description: Scipy sparse matrices, copy argument


code:
##  Styles:
##  0 : OK
##  1 : OK | Cancel
##  2 : Abort | Retry | Ignore
##  3 : Yes | No | Cancel
##  4 : Yes | No
##  5 : Retry | No
##  6 : Cancel | Try Again | Continue

rawDescription: How can I create a simple message box in Python?

description: Create a simple message box in Python


code: any('' in x for x in example_list)

rawDescription: Best way to check if an item is present in a list of lists?

description: Check if an item is present in a list of lists


code: a = [two for one, two in zip(a, a[1:]) if two[1] > one[1]]

rawDescription: How to select increasing elements of a list of tuples?

description: Select increasing elements of a list of tuples


code: import tempfile

rawDescription: Best way to generate random file names in Python

description: Generate random file names in Python


code:
from sphinx.ext.intersphinx import fetch_inventory
import warnings

uri = 'http://docs.python.org/2.7/'

# Read inventory into a dictionnary
inv = fetch_inventory(warnings, uri, uri + 'objects.inv')

rawDescription: How to properly write coss-references to external documentation with intersphinx?

description: Properly write coss-references to external documentation with intersphinx


code: myobj.set_triggermode = value

rawDescription: How to view the instance variables of a class

description: View the instance variables of a class


code:
setup.py
from setuptools import setup

setup(
    name='example',
    version='0.1.0',
    py_modules=['example'],
    install_requires=[
        'exampledep',
    ],
    entry_points='''
        [console_scripts]
        example=example:example
    ''',
)

rawDescription: How can a Python module single file be installed using pip and PyPI?


rawDescription: python numpy array slicing

description: Python numpy array slicing


code:
import json

script_rest = scripttag.string.split('Sw.preloadedData["overview"]', 1)[1].lstrip(' =')
decoder = json.JSONDecoder()
data, _ = decoder.raw_decode(script_rest)

rawDescription: How to make Python Dict from JSON data using BeautifulSoup

description: Make Python Dict from JSON data using BeautifulSoup


rawDescription: How to use only a specific amount of elements in a for loop

description: Use only a specific amount of elements in a for loop


code:
t = np.arange(10)
dt = np.dtype([('t',int),('pos',[('x',float),('y',float)])])
alldata = np.array(zip(t, zip(x,y)), dtype=dt)
alldata
alldata['t']
alldata['pos']
alldata['pos']['x']

rawDescription: Is there a standard way to store XY data in python?


code: f.bar.__func__ is f.bar.__func__

rawDescription: What is the right way to test for equality between a Python variable and a callable?


code:
def magic(original, update):
    for i in range(len(update)):
        found_match = False

        for j in range(len(original)):
            # if there's a matching 'key' in an index of the original list
            if update[i][0] == original[j][0]:
                found_match = True
                original[j][1] = update[i][1]

        # if there's no entry to override, place a new entry in
        if not found_match:
            original.append(update[i])

rawDescription: How can lists in a list be overwritten by new lists in a new list in Python?


rawDescription: Is this an issue with my method of recursion?


code:
class mimicKwargs:
    def __init__(self, labelLong, labelShort, defautValue,kwargDic):
        if kwargDic.get(labelLong) and kwargDic.get(labelShort):
            cmds.error("same flag used two times")
        else:
            self.userInput = kwargDic.get(labelLong) or kwargDic.get(labelShort) or defautValue
    def output(self):
        return self.userInput

def myExample(**kwargs):

    myWidth = mimicKwargs("width", "w", 150, kwargs).output()

    print(myWidth)

myExample(width=200)#
myExample()#print 150

rawDescription: Aliasing in the names of function arguments (double naming)


rawDescription: Add percent of total column to Pandas pivot_table


rawDescription: Sorting files in a list

description: Sorting files in a list


code:
{'description': [u"\n\t\tHave a nice, sturdy, compact car hauler/trailer.  May be used for other hauling like equipstment, ATV's and the like,   Very solid and in good shape.   Parice to sell at only $995.   Call Bill at 541 944 2929 top see or Roy at 541 9733421.   \n\t"],
 'link': [u'/cto/4354771900.html'],
 'price': [u'$995'],
 'title': [u'compact sturdy car trailer ']}

rawDescription: Python Recursive Scraping with Scrapy

description: Python Recursive Scraping with Scrapy


code:
class PointColumnProxy(object):
    def __init__(self, x, y):
        ''' these x and y's are the actual sqlalchemy columns '''
        self.x, self.y = x, y

    def __eq__(self, pos):
        return sqlalchemy.and_(self.x == pos.x,
                               self.y == pos.y)

rawDescription: storing list/tuples in sqlite database with sqlalchemy

description: Storing list/tuples in sqlite database with sqlalchemy


code: Tools > Prefences > General

rawDescription: How do I run two separate instances of Spyder

description: Run two separate instances of Spyder


code:
class StudentAdmin(admin.ModelAdmin):

    class Media:
        css = {"all":("css/your.css",)}

rawDescription: Changing entire background color of table cell in Django Admin


code:
class Reversable(object):
    def __init__(self, seq):
        self.seq = seq

    def __len__(self):
        return len(self.seq)

    def __getitem__(self, item):
        return self.seq[item]

    def __reversed__(self):
        for elem in 'Reversing: ' + self.seq[::-1]:
            yield elem

rawDescription: Python __reverse__ magic method

description: Python __reverse__ magic method


code:
momx = f.reshape(-1,f.shape[2]).dot(ex).reshape(f.shape[:2])
momx = np.einsum('ijk,k->ij',f,ex)

rawDescription: multiply-accumulate using numpy

description: Multiply-accumulate using numpy


code:
import urllib
import re

def get_quote(symbol):
    base_url = 'http://finance.google.com/finance?q='
    content = urllib.urlopen(base_url + symbol).read()
    m = re.search('id="ref_694653_l".*?>(.*?)<', content)
    if m:
        quote = m.group(1)
    else:
        quote = 'no quote available for: ' + symbol
    return quote

rawDescription: How to create a stock quote fetching app in python

description: Create a stock quote fetching app in python


rawDescription: Norvig's spell checker, how he implements the conditional probability?


code:
with open(inputfilename) as ifh:
    for line in ifh:
        if line.startswith('for(') and line.endswith(';\n'):
            line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh)

rawDescription: How do I check for next to next line while reading a file in python and strip the newline character at its end?

description: Check for next to next line while reading a file in python and strip the newline character at its end


code:
import csv

with open('output', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=['Age', 'Name', 'Score'])
    writer.writeheader()
    writer.writerows(dicts)

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

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


rawDescription: New colum in pandas, based on another colums last value


code:
from struct import Struct

class Message(object):
    format = Struct(
        "!" # Network endian; always good form.
        "2s" # FD AA
        "150s" # realtimeData
        "4s" # CC DD FD CC
        "190s" # extra1
        "4s" # CC DD FD CC
        "192s" # extra2
        "2s" # CC DD
    )

    def __init__(self, realtimeData, extra1, extra2):
        self.realtimeData = realtimeData
        self.extra1 = extra1
        self.extra2 = extra2

    def toBytes(self):
        return self.format.pack(
            b"\xFD\xAA", self.realtimeData, b"\xCC\xDD\xFD\xCC", self.extra1,
            b"\xCC\xDD\xFD\xCC", self.extra2, b"\xCC\xDD"
        )

    @classmethod
    def fromBytes(cls, octets):
        [fdaa, realtimeData, ccddfdcc, extra1, ccddfdcc2, extra2,
         ccdd] = cls.format.unpack(octets)
        # verify message integrity
        assert fdaa == b"\xFD\xAA"
        assert ccddfdcc == b"\xCC\xDD\xFD\xCC"
        assert ccddfdcc2 == b"\xCC\xDD\xFD\xCC"
        assert ccdd == b"\xCC\xDD"
        return cls(realtimeData, extra1, extra2)

    @classmethod
    def parseStream(cls, streamBytes):
        sz = cls.format.size
        messages = []
        while len(streamBytes) >= sz:
            messageData, streamBytes = streamBytes[:sz], streamBytes[sz:]
            messages.append(cls.fromBytes(messageData))
        return messages, streamBytes

rawDescription: Twisted protocol to handle concantenated TCP stream with custom frame structure?


code:
keyMapping = { 'From': 'msg_from',
               'To': 'msg_to',
               'Body': 'msg_body' }
for k, v in keyMapping.items():
    if form.getfirst(k):
        setattr(msg, v, form.getfirst(k))

rawDescription: How to set a Python object's field/member by name

description: Set a Python object's field/member by name


code:
class Test_me(MockerTestCase):
    def mockup(self, p, f, m):
        methodToCall = getattr(p, f)
        methodToCall()
        m.result(1)

    def test_null(self):
        m = Mocker()
        o = Cls()
        p = m.patch(o)
        self.mockup(p, 'submthd', m)
        self.mockup(p, 'submthd2', m)
        m.replay()
        self.assertEqual(o.mthd(), 1)
        self.assertEqual(o.mthd2(), 1)
        m.verify()

rawDescription: Can we pass a function and the mocker to another function for mocking?


code:
import numpy as np
import matplotlib.pyplot as plt
from PyQt4 import QtGui
import sys
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.initUI()

    def initUI(self):
       self.msg = '0'

       # a figure instance to plot on
       self.figure = plt.figure()
       self.canvas = FigureCanvas(self.figure)
       self.toolbar = NavigationToolbar(self.canvas, self)

       # a label
       self.lbl = QtGui.QLabel(self.msg)

       # set the layout
       layout = QtGui.QVBoxLayout()
       layout.addWidget(self.toolbar)
       layout.addWidget(self.canvas)
       layout.addWidget(self.lbl)
       self.setLayout(layout)

       self.plot()

    def changelabel(arg):
        main.lbl.setText(str(arg[0])+' '+str(arg[1]))

    def plot(self):
        # random data
        data = [np.random.random() for i in range(10)]
        # create an axis
        ax = self.figure.add_subplot(111)
        # discards the old graph
        ax.hold(False)
        # plot data
        line, = ax.plot(data, 'o', picker=5)  # 5 points tolerance
        self.canvas.draw()
        self.canvas.mpl_connect('pick_event',  Window.onpick)

    def onpick(self):
        thisline = self.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = self.ind

        # show data
        self.msg = (xdata[ind], ydata[ind])
        print(self.msg)
#        Window.changelabel(self.msg)
        main.lbl.setText(str(self.msg[0])+' '+str(self.msg[1]))

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

rawDescription: How to display a value in a PyQt text field using matplotlib's object picking function?

description: Display a value in a PyQt text field using matplotlib's object picking function


code:
MyApp/MyApp/view.py/...
MyApp/MyApp/Template/...
MyApp/App1/...
MyApp/App2/...

rawDescription: Where do I include django-admin-tools menu for my project


rawDescription: Could someone explain the logic here or what I am asking? (Boolean operations)


rawDescription: Create a time series from data

description: Create a time series from data


code:
def cycle_file(filename):
    while True:
        with open(filename) as f:
            for line in f:
                yield line

rawDescription: Re-reading file when cycling over a file object in Python


code:
import numpy as np

# x = Position Data
# y = Temperature Data
x = np.random.permutation([0, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9])
y = (x + np.random.rand(len(x)) * 1 - 0.5).round(2)

# Find unique sorted values for x
x_new = np.unique(x)

# Use bincount to get the accumulated summation for each unique x, and
# divide each summation by the respective count of each unique value in x
y_new_mean= np.bincount(x, weights=y)/np.bincount(x)

rawDescription: Python Numpy: Replace duplicate values with mean value


code: newest = sorted(glob.glob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)[-1]

rawDescription: Python max() takes no keyword arguments

description: Python max() takes no keyword arguments


code:
import scrapy

class FuriousmeItem(scrapy.Item):
    emails = scrapy.Field()
    entity_id = scrapy.Field()  # this will hold the argument

rawDescription: Scrapy Passing Arguments and Writing to MySQL


code:
def action_icon_clicked(self, treeview, path, column):
    # If the column clicked is the action column remove the clicked row
    if column is self.column_action_icon:

        # Get the iter that points to the clicked row
        iter = self.store.get_iter(path)

        # Remove it from the ListStore
        self.store.remove(iter)

rawDescription: Button for row deletion in GTK 3

description: Button for row deletion in GTK 3


rawDescription: Iterate through a file and process it

description: Iterate through a file and process it


code: browser.execute_script("window.onblur = function() { window.onfocus() }")

rawDescription: Feign focus in Selenium chrome browser

description: Feign focus in Selenium chrome browser


code: parser.parse_args('--eia key1 1,2 --eia key2 2,1'.split())

rawDescription: How to create an adb shell am like argument parser in python?

description: Create an adb shell am like argument parser in python


code:
n = 10
p = 20000
V = np.random.rand(n, p)
F = np.random.rand(n, n)

def op_code(V, F):
    n, p = V.shape
    A = np.zeros(p)
    for i in xrange(n):
        for j in xrange(i+1):
            A += F[i,j] * V[i,:] * V[j,:]
    return A

def isaac_code(V, F):
    n, p = V.shape
    F = F.copy()
    F[np.triu_indices(n, 1)] = 0
    M = (V.reshape(n, 1, p) * V.reshape(1, n, p)) * F.reshape(n, n, 1)
    return M.sum((0, 1))

rawDescription: numpy vectorization of double python for loop

description: Numpy vectorization of double python for loop


code:
path = 'YOUR/FOLDER'
# get all files in path
all_files = [os.path.join(path, f) for f in os.listdir(path) if f.startswith("test")]
# filter to keep only directories
folders = filter(os.path.isdir, all_files)

rawDescription: Python Script greping directories

description: Python Script greping directories


code:
from django.forms.models import model_to_dict
my_dict = model_to_dict(my_instance,fields=[],exclude=[])

rawDescription: How do I "pickle" instances of Django models in a database into sample python code I can use to load sample data?


code: grid = ["abc", "def", "xyz"]

rawDescription: I want to format my list differently

description: I want to format my list differently


code: [sum([c.isupper() for c in a]) for a in s]

rawDescription: Python - how to count number of uppercase letters in a string that is in a list


code:
d = {'a':1, 'b':[]}
d['b'].append(1) #modify [] inplace to [1]
l #l "knows" that
d
l[1].append('asdf') #modify [1] inplace to [1, 'asdf']
l
d #d "knows" that

rawDescription: How to point to python dictionary value?

description: Point to python dictionary value


code:
a=np.zeros((3000,300),dtype=np.float32)
with open(filename) as f:
    for i,line in enumerate(f):
        a[i,:]=line.split()

rawDescription: Convert a string list to float32 efficiently


rawDescription: How to alter a part of an array

description: Alter a part of an array


rawDescription: Best way to encode tuples with json

description: Encode tuples with json


code: [word for word in lowers if len(word)>=5 and sorted(word)==list(word)]

rawDescription: making a string into a list within a list comprehension

description: Making a string into a list within a list comprehension


rawDescription: Can I just get the first item in a Cursor object (pymongo)?

description: Just get the first item in a Cursor object (pymongo)


code:
# say A & B are like this:
n, N = 3, 5
A = np.array( np.random.randn(N, N ) )

B = np.zeros_like( A )
B[ n ] = np.random.randn( N )
B[:, n] = np.random.randn( N )

rawDescription: NumPy Matrix Multiplication Efficiency for Matrix With Known Structure


code: legends = [c for c in ax.get_children() if isinstance(c, mpl.legend.Legend)]

rawDescription: How to get all legends from a plot?

description: Get all legends from a plot


code:
for i in data:
    print(str(i['Month'])+": "+str(i['the_days']))

rawDescription: Having some problems printing out an array in Python3


code:
#!/usr/bin/env python

''' Find means of graph data '''

def mean_graph(graphs):
    abscissa = graphs[0][0]

    #Extract ordinate lists
    ylists = [g[1] for g in graphs]

    #Find means of corresponding ordinates
    size = float(len(graphs))
    means = [sum(v) / size for v in zip(*ylists)]

    return abscissa, means

abscissa = range(1, 4)
graphs = [
    (abscissa, [1, 2, 3]),
    (abscissa, [4, 5, 6]),
    (abscissa, [7, 8, 9]),
]

print(mean_graph(graphs))

rawDescription: Mean function given a list of graphs

description: Mean function given a list of graphs


rawDescription: Pandas: rolling mean by time interval

description: Pandas: rolling mean by time interval


code:
def simul(n):
    score = sum(rps(choose_rps(), choose_rps()) for _ in range(n))

rawDescription: Simulate several rounds of rock, paper and scissors


code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
options.add_extension('Adblock-Plus_v1.4.1.crx')

driver = webdriver.Chrome(chrome_options=options)

rawDescription: how can I use selenium with my normal browser

description: Use selenium with my normal browser


code:
clips = [
ImageClip(os.path.join(folder,pic))
         .resize(width=w*9.3/16)
         .set_start(start)
         .set_end(stop)
         .set_pos(lambda t:(max((402), (int(w-3*w*t))), "center"))

    for start, stop, pic in
    (
        itertools.count(1, step=2),
        itertools.count(3, step=2),
        enumerate(picfiles)
    )
]

rawDescription: Placing variables inside a python list comprehension


code:
# Server Side:
import re
import uuid

# Obtain the base64 string
image_string = request.data

image_string = re.search(r'base64,(.*)', image_string).group(1)

# Generate a file name.
# We can assume PNG format in my specific implementation, but you could search
# the image_string variable to detect filetype.
output = open(str(uuid.uuid4()) + '.png', 'wb')
output.write(image_string.decode('base64'))
output.close()

rawDescription: Interpret binary string as image in Python, generated by Javascript native method


code:
binary = bin(20)[2:]
binary.count('1')

rawDescription: count number of ones in a given integer

description: Count number of ones in a given integer


code:
import gc

class B():
    def __init__(self,c):
        self.c = c

    def getA(self):
        for i in gc.get_referrers(self):
            if not isinstance(i, dict):
                continue

            for j in gc.get_referrers(i):
                if isinstance(j, A) and getattr(j, 'b', None) is self:
                    return j

        return

class A():
    def __init__(self,d):
        self.b = B(d)

a = A(42)
print(a.b.getA() is a)

rawDescription: how to get the object from its attribute in python?

description: Get the object from its attribute in python


code:
with open("Output.txt", "w") as output_file, open("Input.txt") as input_file:
    output_file.write("".join(transform_line(line) for line in input_file))

rawDescription: python replace word in text file without going line by line

description: Python replace word in text file without going line by line


rawDescription: Are there any benefits from using a @staticmethod?


code: list1.sort()  # sorts original list

rawDescription: How to sort a list from user input?

description: Sort a list from user input


code:
e.sum(axis=0).shape == (2, 2)
e.sum(axis=1).shape == (3, 2)
e.sum(axis=2).shape == (3, 2)

rawDescription: How does the axis parameter from NumPy work?


rawDescription: python [:] notation and range

description: Python [:] notation and range


code:
@instrument_operator_hooks
class CatchAll(object):
    pass

rawDescription: How to catch any method called on an object in python?

description: Catch any method called on an object in python


code:
from django.contrib import admin
from models import MyModel

class TaskAdmin(admin.ModelAdmin):

    def queryset(self, request):
        return super(TaskAdmin, self).queryset(request).filter(owner = request.user)

admin.site.register(Task, TaskAdmin)

rawDescription: Don't want show all items of a model object in django


code:
window = sdl2.ext.Window("Test", size=(800,600))
renderer = sdl2.ext.Renderer(window)
#     use renderer.blendmode = ... to change the blend mode
factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE, renderer=renderer)
rsystem = factory.create_sprite_render_system(window)

rawDescription: How do you access pySDL2 SoftwareSpriteRenderSystem Blendmode?

description: Access pySDL2 SoftwareSpriteRenderSystem Blendmode


code:
def grouper(x):
    '''bins matching the semantics:
    [0,10] (10,20] (20, 30]'''
    return (x-1)//10 if x > 0 else 0

rawDescription: Elegant way to slice a list with a condition


code:
def mean_impute(self):
    imputed = np.column_stack(self.masked[:,i].filled(self.masked[:,i].mean())
               for i in range(np.shape(self.masked)[1]))
    self.imputed = np.array(imputed, dtype=np.float64)

rawDescription: Getting AttributeError: sqrt in vq.whiten


code:
def get_subclasses(c):
    subs = set(c.__subclasses__())
    return subs.union(*(get_subclasses(i) for i in subs))

rawDescription: Add subclass to super class' list when subclass is created in Python?


rawDescription: Turn URL into String (decode URL)

description: Turn URL into String (decode URL)


rawDescription: Converting EPOC datetime to PST in python/ruby


code:
def main():

    ...

    # Remove sys.setdefaultencoding() so that users cannot change the
    # encoding after initialization.  The test for presence is needed when
    # this module is run as a script, because this code is executed twice.
    if hasattr(sys, "setdefaultencoding"):
        del sys.setdefaultencoding

rawDescription: Persist UTF-8 as default encoding

description: Persist UTF-8 as default encoding


code:
threshold = datetime.timedelta(days=1)
now = datetime.datetime.now()
entries[:] = (e for e in entries if now - e.date < threshold)

rawDescription: Best way to keep the elements of a structure up to date

description: Keep the elements of a structure up to date


code:
filepath = "/folder/*.*/"

for path in glob.glob(filepath):
    dirname, filename = os.path.split(path)
    print( filename )[0:-19]

Var1 = filename
Var2 = filename[0:-25]

rawDescription: Looking to assign print output (string) to a variable


code:
def on_message(msg):
    q.put(msg)
rabbitmq_channel.register_callback(on_message)

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

description: Wakeup thread from thread pool in python


code:
class VocalAttribute:

    def __init__(self, name, feedback):
        """Called when you first create the descriptor."""
        self.name = name  # the name of the attribute 'behind' the property
        self.feedback = feedback  # the feedback to show when the value changes

    def __get__(self, obj):
        """Called when you get the descriptor value."""
        return getattr(obj, self.name)

    def __set__(self, obj, value):
        """Called when you set the descriptor value."""
        prev = getattr(obj, self.name, None)
        if value != prev:
            setattr(obj, self.name, value)
            print(self.feedback)

    def __delete__(self, obj):
        """Called when you delete the descriptor value."""
        delattr(obj, self.name)

class Foo:

    bar = VocalAttribute('_bar', 'I have been edited!')

foo = Foo()

print('1.')

foo.bar = 'hello'

print('2.')

foo.bar = 'hello'

print('3.')

foo.bar = 'world'

rawDescription: Overwrite several methods of a class with a loop


rawDescription: Rounding Error in Python

description: Rounding Error in Python


code:
from SimpleCV.base import *
from SimpleCV.Camera import *
from SimpleCV.Color import *
from SimpleCV.Display import *
from SimpleCV.Features import *
from SimpleCV.ImageClass import *
from SimpleCV.Stream import *
from SimpleCV.Font import *
from SimpleCV.ColorModel import *
from SimpleCV.DrawingLayer import *
from SimpleCV.Segmentation import *
from SimpleCV.MachineLearning import *

rawDescription: SimpleCV Code Completion with Eclipse

description: SimpleCV Code Completion with Eclipse


code:
def ThSep(num, sep = ','):
    num = int(num)

    if not num:
        return '0'

    ret = ''
    dig = 0
    neg = False

    if num < 0:
        num = -num
        neg = True

    while num != 0:
        dig += 1
        ret += str(num % 10)
        if (dig == 3) and (num / 10):
            for ch in reversed(sep):
                ret += ch
            dig = 0

        num /= 10

    if neg:
        ret += '-'

    return ''.join(reversed(ret))

rawDescription: Generate tailor made thousand delimiter

description: Generate tailor made thousand delimiter


code:
def random_forest_regression(data):
    """
    Run the random forest (regression) algorithm on the data to perform the prediction
    """
    # Split the data into training and test sets (30% held out for testing)
    (trainingData, testData) = data.randomSplit([0.7, 0.3])

    model = RandomForest.trainRegressor(trainingData, categoricalFeaturesInfo={}, numTrees=100, featureSubsetStrategy="auto", impurity='variance', maxDepth=10, maxBins=32)
    #increase number of trees to have a better prediction

    # Evaluate model on TEST instances and compute test error
    predictions_test = model.predict(testData.map(lambda x: x.features))
    real_and_predicted_test = testData.map(lambda lp: lp.label).zip(predictions_test)

    #get the list of real and predicted values FOR ALL THE POINTS
    predictions = model.predict(data.map(lambda x: x.features))
    real_and_predicted = data.map(lambda lp: lp.label).zip(predictions)
    real_and_predicted=real_and_predicted.collect()
    print("real and predicted values")
    for value in real_and_predicted:
        print(value)

    return model, real_and_predicted

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

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


code:
import ast
je = ("3,5&6,7")
ast.literal_eval(je.replace('&', ','))

rawDescription: How to split numbers in string?

description: Split numbers in string


code:
import io
filename = 'd:\\DRA_ACTORDEF_T0.x'
size = os.stat(filename).st_size
with io.open(filename, 'r', encoding='your_encoding') as f:
    while f.tell() < size:
         # Do what you want
         line = f.readline()

rawDescription: Reading file stops at halfway

description: Reading file stops at halfway


code: copy_of_A = list(A)

rawDescription: Python list help

description: Python list help


code:
cell_s=cell.set_index(['Description','Name']).stack().reset_index()
cell_s.columns = ['Description', 'Name', 'cell', 's1']

rawDescription: Set DataFrame row index to a different column


code:
res = expr.parseString(test)
from pprint import pprint
pprint(res.asList())

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


code:
# extract_links(url) should be async because it uses async func download() inside
async def extract_links(url):
    # download() was created async to get benefit of I/O
    data = await download(url)
    # parse() doesn't work with I/O, no sense to make it async
    links = parse(data)
    return links

rawDescription: When to use and when not to use Python 3.5 `await` ?


code:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

def plot_implicit(fn, bbox=(-2.5,2.5)):
    ''' create a plot of an implicit function
    fn  ...implicit function (plot where fn==0)
    bbox ..the x,y,and z limits of plotted interval'''
    xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    A = np.linspace(xmin, xmax, 100) # resolution of the contour
    B = np.linspace(xmin, xmax, 15) # number of slices
    A1,A2 = np.meshgrid(A,A) # grid on which the contour is plotted

    for z in B: # plot contours in the XY plane
        X,Y = A1,A2
        Z = fn(X,Y,z)
        cset = ax.contour(X, Y, Z+z, [z], zdir='z')
        # [z] defines the only level to plot for this contour for this value of z

    for y in B: # plot contours in the XZ plane
        X,Z = A1,A2
        Y = fn(X,y,Z)
        cset = ax.contour(X, Y+y, Z, [y], zdir='y')

    for x in B: # plot contours in the YZ plane
        Y,Z = A1,A2
        X = fn(x,Y,Z)
        cset = ax.contour(X+x, Y, Z, [x], zdir='x')

    # must set plot limits because the contour will likely extend
    # way beyond the displayed level.  Otherwise matplotlib extends the plot limits
    # to encompass all values in the contour.
    ax.set_zlim3d(zmin,zmax)
    ax.set_xlim3d(xmin,xmax)
    ax.set_ylim3d(ymin,ymax)

    plt.show()

rawDescription: Plotting implicit equations in 3d

description: Plotting implicit equations in 3d


code: import numpy as np

rawDescription: Python Pandas removing substring using another column


code:
#plt.imshow(Intensity,vmax=0.01,cmap='hot')
#plt.gray()
#plt.show()
np.savetxt('bessel.txt', Intensity)

rawDescription: Density plot with python making a Diffraction pattern with Bessel Integrals but it wont stop running


rawDescription: python tuple is immutable - so why can I add elements to it

description: Python tuple is immutable - so why can I add elements to it


code:
from collections import Counter

phrases = ['cat dog', 'cat cat', 'dog', 'cat cat cat']
all_counts = Counter()
occurrence_counts = Counter()

for phrase in phrases:
    words = phrase.split()
    distinct_words = set(words)
    all_counts.update(words)
    occurrence_counts.update(distinct_words)

all_counts['cat']        # 6
occurrence_counts['cat'] # 3

rawDescription: Counting occurrences of words per each item in a list


rawDescription: Sum lists of variable lengths element-wise


code:
extractors = {
    'position' : positionExtractor,
    'velocity' : velocityExtractor,
    'forces' : forcesExtractor}

rawDescription: Code smell - if/else construct

description: Code smell - if/else construct


code:
from . import utils
compiler_repo = utils.compiler.repo

rawDescription: Clone git repository and import object elsewhere


code:
apns_dict = {'aps':{'alert':'inner message','sound':'mySound.caf'}}
apns_string = json.dumps(apns_dict,ensure_ascii=False)
message = {'default':'default message','APNS_SANDBOX':apns_string}
messageJSON = json.dumps(message,ensure_ascii=False)
sns.publish(message=messageJSON,target_arn=device_arn,message_structure='json')

rawDescription: Format APNS-style JSON message in Python for use with Amazon SNS


code:
def draw(self, surface):
    wrap = 0
    for s in self.sprites():
        r = s.rect
        if r.left<0:
            r.move_ip(800, 0)
            wrap = 1
        elif r.right > 800:
            r.move_ip(-800, 0)
            wrap = 1
        if r.top < 0:
            r.move_ip(0, 600)
            wrap = 1
        elif r.bottom > 600:
            r.move_ip(0, -600)
            wrap = 1
        if wrap:
            surface_blit(s.image, r)
            wrap = 0

rawDescription: Moving a sprite to the other side when a sprite moves off screen Pygame


code:
def my_range(start, end, how_many):
    incr = float(end - start)/how_many
    return [start + i*incr for i in range(how_many)]

rawDescription: Is there a built-in Python function to generate 100 numbers from 0 to 1?


code:
def customeradd(request, id=None):
    if id:
        customer = Customer.objects.get(pk = id)
    else:
        customer = Customer()

    if request.method == 'POST':
        form = CustomerAddForm(request.POST, instance=customer)
        if form.is_valid():
            form.save()
            messages.success(request, 'Customer added succesfully')
            return HttpResponseRedirect('/customeroverview/')
        else:
            messages.error(request, 'Customer save error, please check fields below')
    else:
        form = CustomerAddForm(instance = customer)

    return render_to_response("customer-add.html",
                              {"customer_add_form": form},
                              context_instance=RequestContext(request))

rawDescription: Django Open / Edit record instead of Creating new


code:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('your_localhost_app_uri')

rawDescription: How to make Selenium cooperate with Chrome?

description: Make Selenium cooperate with Chrome


code:
def mySortKey(p):
    return abs(p[0] - x)

def closest(points):
    return sorted(points, key = mySortKey)[:2]

rawDescription: Finding the points nearest to a given x?

description: Finding the points nearest to a given x


rawDescription: Making random phone number xxx-xxx-xxxx

description: Making random phone number xxx-xxx-xxxx


code: g = df.groupby('Type')

rawDescription: making multiple pandas data frames using a loop or list comprehension

description: Making multiple pandas data frames using a loop or list comprehension


code:
Linux
import os

os.system("eject -t cdrom")

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

description: Eject a CD from MacOS with Python


code:
total = Vendas.objects.extra(select={
    'price': 'sum(item_price * purchase_count)'
}).values_list('price', flat=True)[0]

rawDescription: Arithimetic operation before aggregation


code:
# t is an instance of Tran class

t.doclinks.all()

rawDescription: Django: Creating editable default values for model instance based on foreignkey existance


rawDescription: print specific word(number) out of a line

description: Print specific word(number) out of a line


code:
def foo():
    return 1, 2, 3, 4 # Returns a tuple
foo()
a, b, c, d = foo()
a
b
c
d

rawDescription: Is it possible for a python function to return more than 1 value?


code:
do_not_select = [1, 2, 3]

cursor.execute("""SELECT * FROM table_a
                    WHERE id NOT IN ({}, {}, {})""".format(do_not_select[0],
                                                           do_not_select[1],
                                                           do_not_select[2]))
data.cursor.fetchall()

rawDescription: Python MySQL executemany in WHERE clause


code:
import sqlite3

conn = sqlite3.connect('test.sqlite')

cursor = conn.cursor()

cursor.execute('''
CREATE TABLE people (
    FirstName text,
    LastName text,
    Age int,
    Sex text
    )''')

cursor.execute('''
INSERT INTO people values ('John', 'Deer', 20, 'M')''')

cursor.execute('''
INSERT INTO people values ('Ada', 'Lovelace', 23, 'F')''')

conn.commit()

for record in cursor.execute('''SELECT * FROM people'''):
    print(record)

rawDescription: How to give multiple values to a single key using a dictionary?

description: Give multiple values to a single key using a dictionary


code:
import x
i = x.getMyClassInstance()
i.somePureVirtualMethod()

rawDescription: How do I invoke a method on a C++ class pointer with swig wrappers?

description: Invoke a method on a C++ class pointer with swig wrappers


code:
import zmq

ctx = zmq.Context.instance()
s = ctx.socket(zmq.PUSH)
url = 'tcp://127.0.0.1:5555'
s.connect(url)

while True:
    msg = raw_input("msg > ")
    s.send(msg)
    if msg == 'quit':
        break

rawDescription: PyZMQ one-way communication

description: PyZMQ one-way communication


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

images = np.random.uniform(0, 255, size=(40, 50, 50))

fig, ax = plt.subplots()

im = ax.imshow(images[0])
fig.show()
for image in images[1:]:
    im.set_data(image)
    fig.canvas.draw()

rawDescription: Why does my pylab animation slow down with each update?


code:
import networkx as nx
import matplotlib.pyplot as plt

g = nx.Graph()
g.add_nodes_from(subs)
g.add_nodes_from(words)
g.add_edges_from(edges)
pos=nx.spring_layout(g)

nx.draw_networkx_nodes(g, pos,
                       nodelist=subs,
                       node_color='r',
                       node_size=1000,
                       alpha=0.8)

nx.draw_networkx_nodes(g, pos,
                       nodelist=words,
                       node_color='b',
                       node_size=1000,
                       alpha=0.8)

nx.draw_networkx_edges(g, pos, width=1.0, alpha=0.5)

nx.draw_networkx_labels(g, pos, dict(zip(subs,subs)) )
nx.draw_networkx_labels(g, pos, dict(zip(words,words)) )

rawDescription: How to represent this as a Network?

description: Represent this as a Network


code:
# get the palette
palette = lcd.palette()

# foreground color
palette.setColor(palette.WindowText, QtGui.QColor(85, 85, 255))
# background color
palette.setColor(palette.Background, QtGui.QColor(0, 170, 255))
# "light" border
palette.setColor(palette.Light, QtGui.QColor(255, 0, 0))
# "dark" border
palette.setColor(palette.Dark, QtGui.QColor(0, 255, 0))

# set the palette
lcd.setPalette(palette)

rawDescription: Changing the Digit Color of QLCD Number

description: Changing the Digit Color of QLCD Number


code:
def my_controller(self):
   # ...

   return to_response(request, response, myobject)

# elsewhere
def to_response(req, resp, obj):
    # this would be more robust, look in
    # req, resp, catch key errors, whatever.
    # xxx_serialize are just functions.  don't need state
    serializer = {
       'application/json':json_serialize,
       'application/xml':xml_serialize,
       # ...
    }[req.headers['content-type']]

    return serializer(obj)

rawDescription: Serializing SQLAlchemy models for a REST API while respecting access control?


code:
a = Task.objects.create(status='C')
b = Task.objects.create(status='A')
b.prerequisites.add(a)
c = Task.objects.create(status='P')
c.prerequisites.add(b)
prerequisites_complete = Task.objects.exclude(prerequisites__status__in=['A','P','F'])
set([t.id for t in prerequisites_complete]) == set([a.id, b.id])

rawDescription: In Django, how do I filter based on all entities in a many-to-many relation instead of any?


code:
s = set()
for item in iterable:
    s.add(item)

rawDescription: How to construct a set out of list items?

description: Construct a set out of list items


code:
from functools import wraps
from fabric.network import needs_host
from fabric.api import run, env

def runs_final(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        if env.host_string == env.all_hosts[-1]:
            return func(*args, **kwargs)
        else:
            return None
    return decorated

@needs_host
def hello():
    run('hostname')
    atexit()

@runs_final
def atexit():
    print ('this is at exit command.')

rawDescription: fabric cleanup operation with atexit

description: Fabric cleanup operation with atexit


code: [[sum(list(a)) for a in b] for b in list(zip(*b) for b in zip(*a))]

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


rawDescription: Find float in ndarray

description: Find float in ndarray


code:
while True:
    moduleName = raw_input("Please enter module name: ")
    if moduleName == '-1':
        break
    grade = raw_input("Please enter students grade for " + moduleName+": ")
    students.append(student)

rawDescription: Loop to obtain two pieces of user input and save to a global list


code: tuple(x if x[0] != (givenX, givenY) else (x[0], True) for x in your_tuple)

rawDescription: Python modify tuple with lambda

description: Python modify tuple with lambda


code:
class AnyNumber(object):
    def __eq__(self, other):
        return True
    def __ne__(self, other):
        return False

ANY = AnyNumber()
ANY == 0
ANY == 1
tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776)]
[t for t in tups if t == (1, ANY, ANY)]
[t for t in tups if t == (ANY, 1, ANY)]

rawDescription: How do I find all tuples with a specific value?

description: Find all tuples with a specific value


code:
class A(object):
    x = 1
    def __getattribute__(self, name):
        if name == 'x':
            raise AttributeError
        return super(A, self).__getattribute__(name)
    def __setattr__(self, name, value):
        if name == 'x':
            raise AttributeError
        return super(A, self).__setattr__(name, value)
    def __delattr__(self, name):
        if name == 'x':
            raise AttributeError
        return super(A, self).__delattr__(name)

rawDescription: Can Python classes have members that are accessible, but not from an instance of the class?


code: [(x,y) for x,y in zip(x.ravel(),y.ravel())]

rawDescription: numpy mgrid shapely for linestring coordinates

description: Numpy mgrid shapely for linestring coordinates


code: t + np.roll(t,-1)

rawDescription: Get sums of pairs of elements in a numpy array


code:
with open(path) as f:
    lines = [query for query in f.read().split("\n\n") if query]

rawDescription: Retrieve text blocks from file

description: Retrieve text blocks from file


code: print(sum(sum(map(int,(w for w in line.split() if w.isdigit()))) for line in data))

rawDescription: Find all occurrences of integer within text in Python


code: mask = A < 2

rawDescription: Replacing elements in Numpy 2D array with corresponding elements of another Numpy 2D array depending on a condition


rawDescription: Merging two arrays under numpy

description: Merging two arrays under numpy


code:
import re
pattern = re.compile(r'\b[a-z][*]{2}1(?!\d)')
pattern.search('x**1')
pattern.search('x**10') is None
pattern.search('x**10') is None

rawDescription: how to write regular expression makes sure that there is no digits after

description: Write regular expression makes sure that there is no digits after


code: math.pow(math.e, x)

rawDescription: Python: Questions about math and negative power


code: a[i] if mask[i] else b[i]

rawDescription: Difference between nonzero(a), where(a) and argwhere(a). When to use which?


code:
if classchoice == "A":
    write_flag = True
    with fileinput.input("classa.txt", inplace=1) as f:
        for line in f:
            line = line.rstrip()
            if name in line:
                line = line + " " + str(score)
                write_flag = False
            print(line)
        #This is if `name` was never found, meaning we have to add the name to the file with the score.
    if write_flag:
        with open("classa.txt",'a') as f:
            f.write("{} {}\n".format(name,score))

rawDescription: Python: Storing data in a text file and appending particular/individual lines


code:
s = set(fus_d.keys())
s.update(fus_s.keys())
fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in s]

rawDescription: How can I create a list from two dictionaries?

description: Create a list from two dictionaries


code: df

rawDescription: Strip all characters from column header before a :


code: data.reset_index().to_csv('foo.csv', index=False, header=True, decimal=',', sep=' ', float_format='%.3f')

rawDescription: pandas to_csv arguments float_format and decimal not working for index column

description: Pandas to_csv arguments float_format and decimal not working for index column


code:
[
    {'id': 1, 'user_id': 1, 'product_type': 'chair'},
    {'id': 1, 'user_id': 1, 'product_type': 'table'},
    {'id': 2, 'user_id': 3, 'product_type': 'chair'},
    ...
]

rawDescription: Django query in One to Many relationship


code:
a = "-hlocalhost-uuser-ppassword"
localhost, user, password = [x[1:] for x in a.split("-")[1:]]

rawDescription: get text via re in python

description: Get text via re in python


code:
def eventFilter(self, tableView, event,
    FILTER_EVENT_TYPE=QtCore.QEvent.KeyPress
    ):
    if event.type() == FILTER_EVENT_TYPE:
        if event.modifiers() in (QtCore.Qt.NoModifier, QtCore.Qt.KeypadModifier):
            key = event.key()
            if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
                self.menu.editItem.trigger()
                return True

rawDescription: Optimizing `in`

description: Optimizing `in`


code:
import os
os.stat(filename).st_size

rawDescription: Why no len(file) in Python?

description: Why no len(file) in Python


code:
def update_index():
    call_command("update_index", remove=True)
update_index = job('default')(update_index)

rawDescription: How to get arguments to a decorator?

description: Get arguments to a decorator


code:
from requests.auth import HTTPBasicAuth
url = "http://example.com/path"
auth = HTTPBasicAuth("appuser", "apppass")
req = requests.get(url, auth=auth)

rawDescription: Login, Navigate and Retrieve data behind a proxy with Python


code:
def replace_first_x(group_df, x, value):
    group_df.iloc[:x, :] = value
    return group_df

rawDescription: How to Update Value in First N Rows by Group in a Multi-Index Pandas Dataframe?


code: File > Settings > Keymap

rawDescription: Can I use another shortcut for auto import in pycharm?

description: Use another shortcut for auto import in pycharm


code:
df.columns = ['id', 'value']
df.set_index('id')

rawDescription: dict to dataframe with value in list

description: Dict to dataframe with value in list


code:
def count_runs_of(seq, val):
    return [len(list(group)) for key, group in groupby(seq) if key == val]

rawDescription: How to count in a row results from text file

description: Count in a row results from text file


code:
import copy

# Now when you modify newHand (i.e appending or removing items)
# the original hand list from the caller's frame will not be affected.
newHand = copy.copy(hand)

# You can alternatively copy the list using...
newHand = hand[:]

# However, if there are other mutable objects inside of `hand` you wished
# to copy, you'd have to use the `deepcopy` method of `copy`.

rawDescription: python can't seem to get a list to return properly

description: Python can't seem to get a list to return properly


rawDescription: html select option into a list

description: Html select option into a list


code:
dups = {checksum: names for checksum, names in dups.items() if len(names) > 1}
dups

rawDescription: In a list of tuples, return tuple[1] if tuple[0] is a duplicate of another tuple[0] in the list


code:
str = "blah blah @~@ blah blah @~@ blah blah @~@";
split = str.split('@~@');

rawDescription: Creating Variables Based Off A String

description: Creating Variables Based Off A String


code:
import sqlite3
conn = sqlite3.connect('output.db')

count = 0
items = []
for item in InfStream: # assume I have an infinite stream
    items.append((item,))
    count += 1
    if count == 10000:
        conn.executemany("INSERT INTO table VALUES (?)", items)
        conn.commit()
        items = []

rawDescription: How do I continue iterating without having to wait output to finish?

description: Continue iterating without having to wait output to finish


rawDescription: Not Getting proper links from google search results using mechanize and Beautifulsoup


code: from variables import mylist

rawDescription: Import list variable from separate files in python


rawDescription: Interval containing specified percent of values


code:
iA, iB, iC, iD = sat[:-h, :-w], sat[:-h, w:], sat[h:, :-w], sat[h:, w:]
lookup = iD - iB - iC + iA

rawDescription: Determine if an image exists within a larger image, and if so, find it, using Python


code:
def argmax_list(matrix):
    m = matrix[0].copy()
    idx = np.zeros(len(m), dtype=np.int)
    for i, a in enumerate(matrix[1:], 1):
        mask = m < a
        m[mask] = a[mask]
        idx[mask] = i
    return idx

rawDescription: Numpy max slow when applied to list of arrays


rawDescription: dealing with dimensions in scikit-learn tree.decisiontreeclassifier

description: Dealing with dimensions in scikit-learn tree.decisiontreeclassifier


code:
regex = re.compile(r'/some/[pattern]+')
found_keys = filter(regex.match, h5file)

rawDescription: How to feed a regular expression to a method that requires a string?

description: Feed a regular expression to a method that requires a string


code:
print("hi")
print(1)

rawDescription: How to gather return value from function in another script in python?

description: Gather return value from function in another script in python


code:
import datetime, pytz
zoneName = 'America/New_York'
now = datetime.datetime.now(pytz.timezone(zoneName))

rawDescription: How to convert string timezones in form (Country/city) into datetime.tzinfo

description: Convert string timezones in form (Country/city) into datetime.tzinfo


rawDescription: How to get text from inside a TEXT I WANT in Python

description: Get text from inside a TEXT I WANT in Python


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

rawDescription: missing dimension in numpy array shape

description: Missing dimension in numpy array shape


code:
from matplotlib import pyplot as plt
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
plt.show()                                    # you get normal size
mng.frame.Maximize(True)                      # now mpl window maximizes

rawDescription: matplotlib window layout questions

description: Matplotlib window layout questions


code:
class Mylist(list):

    def __init__(self, l):
        list.__init__(self,l)

    def map(self, f):
        return Mylist(map(f, self[:]))

rawDescription: Clean code for sequence of map/filter/reduce functions


rawDescription: python, numpy boolean array: negation in where statement

description: Python, numpy boolean array: negation in where statement


rawDescription: Python 2.7 pandas to fill missing number/series


code:
from django.db.models import Sum
total_price = Quotes.objects.all().annotate(total=Sum('purchase_quote_products__subtotal'))

rawDescription: Django sum of row in template for loop

description: Django sum of row in template for loop


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

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


code:
Field('user_id', 'reference auth_user',
      requires=IS_EMPTY_OR(IS_IN_DB(db, 'auth_user.id',
                                    db.auth_user._format)))

rawDescription: web2py, one to many, not required relationship

description: Web2py, one to many, not required relationship


rawDescription: Pretty-printing of numpy.array

description: Pretty-printing of numpy.array


code:
from django.contrib.auth.models import User

class Essay(models.Model):
    title = models.CharField(max_length=666)
    body = models.TextField()
    author = models.ForeignKey(User, null=True, blank=True)

rawDescription: How to auto insert the current user when creating an object in django admin?

description: Auto insert the current user when creating an object in django admin


code:
'blah.APDS.UnitTests.vbproj'[:-len('.vbproj')]
import os.path
os.path.splitext('blah.APDS.UnitTests.vbproj')[0]

rawDescription: Can't get simple loop working right

description: Can't get simple loop working right


code:
def f(x):
    if x.value <5:
        l= 'other'
    else:
        l =x.letter
    return l

rawDescription: Python pandas: accumulate data frame rows by condition


code:
class DevNull(object):
    def write(self, str):
        pass
twill.set_output(DevNull())
html = show()

rawDescription: Using show() with twill spams the console with HTML


rawDescription: How to make a chronological list of files, with the file modification date

description: Make a chronological list of files, with the file modification date


code:
numberList = []
for num in range(number_1, number_2 + 1):
    numberList.append(str(num))
numbers = ','.join(numberList)
print(numbers)

rawDescription: Print user inputted number with commas and the numbers in between


rawDescription: Scrapy: Do form login and then work with that session


code:
stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
#maxlength = max([len(s) for s in stringlist])
maxlength = max(len(s) for s in stringlist)  # omitting the brackets causes max
                                             # to operate on an iterable, instead
                                             # of first constructing a full list
                                             # in memory, which is more efficient

rawDescription: Longest strings from list

description: Longest strings from list


code:
import M2Crypto
import hashlib
rsa = M2Crypto.RSA.load_key("privkey.pem")
digest = hashlib.new('md5', 'test').digest()
open("sig_m2crypto", "w").write(rsa.sign(digest, "md5"))

rawDescription: M2Crypto RSA.sign vs OpenSSL rsautl -sign


code: from settings import *

rawDescription: basic python module design question

description: Basic python module design question


code:
vs = np.array(var_s[4::3],dtype=np.float64)  #could slice after array conversion too ...
med_mag = np.median(vs[vs!=99.])

rawDescription: Speed up python loop

description: Speed up python loop


code:
LPAR,RPAR = map(Suppress, "()")
ident = Word(alphas, alphanums + "-_")
integer = Word(nums)

# treat consecutive quoted strings as one combined string
quoted_string = OneOrMore(quotedString)
# add parse action to concatenate multiple adjacent quoted strings
quoted_string.setParseAction(lambda t: '"' +
                            ''.join(map(lambda s:s.strip('"\''),t)) +
                            '"' if len(t)>1 else t[0])
data_item = ident | integer | quoted_string

# section defined with no nesting
section = ident + Group(LPAR + delimitedList(data_item) + RPAR)

rawDescription: Parsing text file in python using pyparsing


code:
for i in range(a, b):
    print(" ", end=" ")

rawDescription: remove asterisk symbol inside diamond shape

description: Remove asterisk symbol inside diamond shape


code:
association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Child",
                    secondary=association_table)

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

rawDescription: sqlalchemy multiple foreignkey

description: Sqlalchemy multiple foreignkey


code:
with open('file.txt', 'w', encoding='utf8') as fw:
    fw.write("Number of files processed within 512\u00B1 1 samples:  "+str(count))

rawDescription: Python 3.4 unicode character displayed correctly on console but no in text file


code: textbeingread = f.readline()[:-2]

rawDescription: How to erase part of a read only file when printing it

description: Erase part of a read only file when printing it


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

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


rawDescription: Combine two columns to a datetime in pandas


code: output = """<div class="form-group" id="{info_id}_container">""".format(info_id=info['id'])

rawDescription: string.template with arrays as placeholders

description: String.template with arrays as placeholders


code:
for e in csv.reader(st.splitlines(), **kwargs):
    e=[x.strip() for x in e]
    # ... process the split list of elements from a line of csv...

rawDescription: To split strings using Python

description: To split strings using Python


code:
from subprocess import _Popen

def Popen(*args, **kwds):
    res = _Popen(*args, **kwds)

    if not hasattr(res, "args"):
        res.args = args[0]

    return res

rawDescription: Python: how to get command run with subprocess Popen


code:
class MyClass(object):
    bar = AttributeGroup()
    a = bar(5)
    b = bar("foo")
    c = False
dir(MyClass.bar)    # ['a', 'b']

rawDescription: python decorator for field

description: Python decorator for field


code:
ans = []
file = open("sample.csv")
text = file.read()
lst = text.split("\n")
for l in lst:
    p = l.split(",")
    ans.add(p[1])

rawDescription: How do I create a list from a column of a file?

description: Create a list from a column of a file


code:
from collections import defaultdict # using defaultdict makes the sums easier

correlations = defaultdict(int) # default to int (i.e. 0)

for i1, i2, correl in strScoresDict: # loop through data
    correlations[i1] += correl # add score for first item
    correlations[i2] += correl # and second item

output = sorted(correlations,
                key=lambda x: correlations[x],
                reverse=True) # sort keys by value

rawDescription: Sorting a list based on associated scores


code:
# This gets used by stochastic to check for long-format logp and random:
if probe:
    # Define global tracing function (I assume this is for debugging??)
    # No, it's to get out the logp and random functions, if they're in there.
    def probeFunc(frame, event, arg):
        if event == 'return':
            locals = frame.f_locals
            kwds.update(dict((k,locals.get(k)) for k in keys))
            sys.settrace(None)
        return probeFunc

    sys.settrace(probeFunc)

    # Get the functions logp and random (complete interface).
    # Disable special methods to prevent the formation of a hurricane of Deterministics
    cur_status = check_special_methods()
    disable_special_methods()
    try:
        __func__()
    except:
        if 'logp' in keys:
            kwds['logp']=__func__
        else:
            kwds['eval'] =__func__
    # Reenable special methods.
    if cur_status:
        enable_special_methods()

for key in keys:
    if not kwds.has_key(key):
        kwds[key] = None

for key in ['logp', 'eval']:
    if key in keys:
        if kwds[key] is None:
            kwds[key] = __func__

rawDescription: Decorators in PyMC

description: Decorators in PyMC


code: "{0} {1}, {2} {3}:{4}:{5}".format(date.month, date.day, date.year, date.hour, date.minute, date.second)

rawDescription: Convert LinkedIn APIs time to a standard date in Python


rawDescription: Spearman rank correlation in Python with ties


code:
def get_char(is_valid = lambda c: True):
    while True:
        c = raw_input('enter a character > ')
        if is_valid(c):
            keep = raw_input('do you want to use {0}? (Y/N)> '.format(c)).lower()
            if 'n' in keep:
                continue # go back to While True line
            return c
        print('{0} is not a valid character'.format(c))

rawDescription: raw_input check to allow for reinitiation of same function

description: Raw_input check to allow for reinitiation of same function


code:
while len(macTable) < numOfMACs:
    mac = input("Enter the MAC of the phone: "+".cfg")
    macTable.append(mac)
    open(mac, 'w')
    macTable.append(mac)

rawDescription: Creating new text files with names from an array in Python


code:
from collections import Iterable
def flatten(collection):
  for element in collection:
    if isinstance(element, Iterable):
      for x in flatten(element):
        yield x
    else:
      yield element

rawDescription: Sum a nested list of a nested list of a nested list of integers


code:
[['group Head', '']]
[['data1', ' abc'], ['data2', ' def']]
[['2word data3', ' ghi'], ['data4', ' jkl']]
[['data3', ' mno'], ['three word data4', ' pqr stu']]

rawDescription: How to improve a python regex data file parsing efficiency?

description: Improve a python regex data file parsing efficiency


code:
for matrix in ttranspose:
    Q_by_transpose_ind = np.matmul(matrix, Qmatrix)
    Q_by_transpose.append(Q_by_transpose_ind)

rawDescription: element wise matrix multiplication python

description: Element wise matrix multiplication python


code:
class Wrapper(str):
    def __repr__(self):
        return str(self)

raise KeyError(Wrapper('hello\nthere'))

rawDescription: Python KeyError and ValueError inconsistency?


code:
tag_equals('value', 'foobar')
attribute_exists('value', 'value_attr')

rawDescription: Writing declarative configuration checks in Python?


code:
images.T.reshape(60000,28*28)
images.T.reshape(60000,-1)   # short hand

rawDescription: reshape an array of images

description: Reshape an array of images


code:
def packer(s):
    groups = []
    last_char = None
    for c in s:
        if c == last_char:
            groups[-1].append(c)
        else:
            groups.append([c])
        last_char = c
    return ''.join('%s%s'%(g[0], len(g)) for g in groups)

rawDescription: Python - packing/unpacking by letters

description: Python - packing/unpacking by letters


code:
library(data.table) # v1.9.7 (devel version)

df <- fread("C:/folderpath/data.csv") # load your data
setDT(df) # convert your dataset into data.table

rawDescription: subset recursively a data.frame

description: Subset recursively a data.frame


code:
from scipy.linalg import blas as FB
vx = FB.dgemm(alpha=1., a=v1, b=v2, trans_b=True)

rawDescription: Is there an "enhanced" numpy/scipy dot method?


rawDescription: Accessing hierarchical columns in pandas after groupby