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

# create an engine, and a base class
engine = create_engine('postgre://naa:123@localhost/tk')
DeclarativeBase = declarative_base(bind=engine)
metadata = DeclarativeBase.metadata

# create a session
Session = session_maker(engine)
session = Session()

# declare the models
class Cource(DelcarativeBase):
    __tablename__ = 'courses'

    course_nro = Column('course_nro', CHAR(12))

rawDescription: Converting SQL commands to Python's ORM

description: Converting SQL commands to Python's ORM


code:
"""
requests.session
~~~~~~~~~~~~~~~~
This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
"""

rawDescription: What's the difference using requests.get and requests_session.get?


code:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_SendAfamilyEmail(object):
    def setupUi(self, SendAfamilyEmail):
        SendAfamilyEmail.setObjectName(_fromUtf8("SendAfamilyEmail"))
        SendAfamilyEmail.resize(840, 600)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Arial"))
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        SendAfamilyEmail.setFont(font)
        self.centralwidget = QtGui.QWidget(SendAfamilyEmail)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayoutWidget = QtGui.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 0, 821, 581))
        self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setMargin(0)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        spacerItem = QtGui.QSpacerItem(40, 7, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.subjectLabel = QtGui.QLabel(self.verticalLayoutWidget)
        self.subjectLabel.setMinimumSize(QtCore.QSize(78, 0))
        self.subjectLabel.setObjectName(_fromUtf8("subjectLabel"))
        self.horizontalLayout.addWidget(self.subjectLabel)
        self.subject = QtGui.QLineEdit(self.verticalLayoutWidget)
        self.subject.setObjectName(_fromUtf8("subject"))
        self.horizontalLayout.addWidget(self.subject)
        self.verticalLayout.addLayout(self.horizontalLayout)
        spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem1)
        self.bodyLabel = QtGui.QLabel(self.verticalLayoutWidget)
        self.bodyLabel.setObjectName(_fromUtf8("bodyLabel"))
        self.verticalLayout.addWidget(self.bodyLabel)
        self.body = QtGui.QTextEdit(self.verticalLayoutWidget)
        self.body.setTabChangesFocus(True)
        self.body.setUndoRedoEnabled(False)
        self.body.setTabStopWidth(0)
        self.body.setAcceptRichText(False)
        self.body.setObjectName(_fromUtf8("body"))
        self.verticalLayout.addWidget(self.body)
        spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem2)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.send = QtGui.QPushButton(self.verticalLayoutWidget)
        self.send.setObjectName(_fromUtf8("send"))
        self.horizontalLayout_2.addWidget(self.send)
        self.quit = QtGui.QPushButton(self.verticalLayoutWidget)
        self.quit.setObjectName(_fromUtf8("quit"))
        self.horizontalLayout_2.addWidget(self.quit)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        SendAfamilyEmail.setCentralWidget(self.centralwidget)
        self.subjectLabel.setBuddy(self.subject)
        self.bodyLabel.setBuddy(self.body)

        self.retranslateUi(SendAfamilyEmail)
        QtCore.QMetaObject.connectSlotsByName(SendAfamilyEmail)
        SendAfamilyEmail.setTabOrder(self.subject, self.body)
        SendAfamilyEmail.setTabOrder(self.body, self.send)
        SendAfamilyEmail.setTabOrder(self.send, self.quit)

    def retranslateUi(self, SendAfamilyEmail):
        SendAfamilyEmail.setWindowTitle(QtGui.QApplication.translate("SendAfamilyEmail", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.subjectLabel.setText(QtGui.QApplication.translate("SendAfamilyEmail", "Subject", None, QtGui.QApplication.UnicodeUTF8))
        self.bodyLabel.setText(QtGui.QApplication.translate("SendAfamilyEmail", "Body", None, QtGui.QApplication.UnicodeUTF8))
        self.send.setText(QtGui.QApplication.translate("SendAfamilyEmail", "Send Mail", None, QtGui.QApplication.UnicodeUTF8))
        self.quit.setText(QtGui.QApplication.translate("SendAfamilyEmail", "Quit, Do Not Send", None, QtGui.QApplication.UnicodeUTF8))

rawDescription: Qt Push Button Only Respond To Return When Has Focus - Require Custom Event Handler?


code:
# A variable to keep track of the least-nested level of your hierarchy
top_lvl = ''
# More descriptive variable names can make everything easier to read/understand
mid_lvl = ''
for val in a:
    # Pre-compute this value so you don't have to do it twice or more
    c = val.count(' ')
    # This case is the topmost level
    if c == 0:
        top_lvl = val
        d[val] = []
    # This case is the middle level
    elif c == 1:
        d[val]=[]
        mid_lvl =val
        d[top_lvl].append(mid_lvl)
    # This case is the most deeply nested level
    else: # c==2
        d[mid_lvl].append(val)

rawDescription: when i try to append value in dict its showing key error

description: When i try to append value in dict its showing key error


rawDescription: How to get the optimal optimization variables in Pulp with Python?

description: Get the optimal optimization variables in Pulp with Python


code: strung = filter(None, re.split(r';(?![^\[\]]*\])', string))

rawDescription: Regex to select every semicolon except the ones enclosed within Square brackets []


code:
def mylex(x):
    lex = shlex.shlex(x, posix=True)
    lex.whitespace = ','
    lex.whitespace_split = True
    return list(lex)

def opts(x):
    ll = []
    dd = {}
    items = mylex(x)
    for item in items:
        if '=' in item:
            k, v = item.split('=',1)
            dd[k.strip(' "')] = v.strip(' "')
        else:
            ll.append(item.strip(' "'))
    return (ll,dd)

rawDescription: How to parse optional and named arguments into list and dict?

description: Parse optional and named arguments into list and dict


code:
with open(STATIC_SRC, 'r') as src_file:
  bracket_count = 0
  key = ''
  values = []
  my_dict = {}

  for line in src_file:
    print(values)
    line = line.strip()
    bracket_count += CountBrackets(line)

    # Finds line like 'name: "foo"' and stores 'foo' as key
    if line.startswith('name:'):
      key = re.findall('"([^"]*)"', line)
      key = ''.join(key)

    # Finds line like 'some_value: "a"' and adds 'a' to list
    if line.startswith('some_value:'):
      value = re.findall('"([^"]*)"', line)
      values.extend(value)  # append create a new list inside the existing list

    # When bracket count returns to 0, it's reached the end of a tupe
    # and should store the current key and list.
    if bracket_count == 0:
      my_dict[key] = values
      values = []

  print(my_dict)  # the name of the dict was wrong

rawDescription: Reset List When Condition Met

description: Reset List When Condition Met


code:
q = sess.query(Post).filter(
        and_(
            Post.tags.contains(tag2),
            Post.tags.contains(tag3),
            )
        ).all()

rawDescription: Searching many to many relationship

description: Searching many to many relationship


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

def main():
    data = [ 10.49531611,  22.49511583,  10.90891806,  18.99525417,
            21.57165972,   6.687755  ,   6.52137028,  15.86534639,
            18.53823556,   6.32563583,  12.99365833,  11.06817056,
            17.29261306,  15.31288556,  19.16236667,  10.38483333,
            14.51442222,  17.01413611,   6.96102278,  15.98508611,
            16.5287    ,  15.26533889,  20.83520278,  17.21952056,
             7.3225775 ,  16.42534361,  14.38649722,  21.63573111,  16.19249444]
    data = np.array(data)*60*60
    plot_clock(data)
    plt.show()

def plot_clock(data):
    def hour_formatAM(x, p):
        hour = x * 6 / np.pi
        return '{:0.0f}:00'.format(hour) if x > 0 else '12:00'

    def hour_formatPM(x, p):
        hour = x * 6 / np.pi
        return '{:0.0f}:00'.format(hour + 12) if x > 0 else '24:00'

    def plot(ax, theta, counts, formatter):
        colors = plt.cm.jet(theta / 12.0)
        ax.bar(theta, counts, width=np.pi/6, color=colors, alpha=0.5)
        ax.xaxis.set_major_formatter(tkr.FuncFormatter(formatter))

    plt.rcParams['font.size'] = 8

    bins = np.r_[0, 0.5:12, 12, 12.5:24,  23.99999]
    data = np.array(data) / (60*60)
    counts = np.histogram(data,bins)[0]

    counts[13] += counts[0]
    counts[-1] += counts[13]

    fig, axes = plt.subplots(ncols=2, figsize=(5.5, 3), dpi=200,
                             subplot_kw=dict(projection='polar'))
    fig.subplots_adjust(wspace=0.4)
    for ax in axes:
        ax.set(theta_offset=np.pi/2, theta_direction=-1,
               xticks=np.arange(0, np.pi*2, np.pi/6),
               yticks=np.arange(1, counts.max()))

    plot(axes[0], bins[1:13] * np.pi / 6, counts[1:13], hour_formatAM)
    plot(axes[1], bins[14:26] * np.pi / 6, counts[14:26], hour_formatPM)

main()

rawDescription: python + matplotlib: how to insert more space between the axis and the tick labels in a polar chart?

description: Python + matplotlib: how to insert more space between the axis and the tick labels in a polar chart


code:
def test(n):
    print("test", n)
    return n

test(1) and test(2)
test(0) and test(2)
test(0) and test(2) and test(3)
test(1) and test(0) and test(3)

rawDescription: Python: How to chain boolean tests to get False as soon as it gets the first False


code:
cProfile.run("replace1_word2('foo bar baz')")
cProfile.run("replace1_word('foo bar baz')")

rawDescription: Pythonic vs Unpythonic

description: Pythonic vs Unpythonic


code:
for i in dict:
    # i is now equal to (3, 13), or (11, 4) etc
    x, y = i

rawDescription: Working with tuples and dictionaries

description: Working with tuples and dictionaries


code:
intA=input("Integer A: ")
intB=input("Integer B: ")

rawDescription: How do I change a string to an integer?

description: Change a string to an integer


code:
from django.views.generic import TemplateView

urlpatterns = patterns('',
    url(r'^path/to/something/$', TemplateView.as_view(template_name="your_temlate.html"), name="something" ),
    url(r'^path/to/something/else/$', TemplateView.as_view(template_name="your_temlate_else.html"), name="something_else" ),
)

rawDescription: How to create url for generic template without view?

description: Create url for generic template without view


code: [ x for y in l for x in y]

rawDescription: Python, recursively reduce a list (combinations/permutations)


code:
[reduce(lambda c, d: c.update(d) or c, col, Counter())
    for col in izip_longest(*data.values(), fillvalue={})]

rawDescription: Sum the nested dictionary values in python


rawDescription: Python unique values in a list

description: Python unique values in a list


code: calc(base, alist, blist)

rawDescription: How can I solve this without list comprehensions

description: Solve this without list comprehensions


code:
row = ['','','',0,0,0,0]
#calculate correct length depending on your original df
df_len = len(orig_df)+orig_df.multiwordexpr.sum()

#allocate a new df
result_df = pd.DataFrame([row for x in xrange(df_len)],
                      columns=columns)
#write to it instead appending
result_df.ix[index] = ['Per','per','epsf',0,0,0,0]

rawDescription: Insert new rows in pandas dataframe

description: Insert new rows in pandas dataframe


code:
from PyQt4.QtGui import *
from PyQt4.QtCore import QTimer

app = QApplication([])
widget = QWidget()
widget.setLayout(QVBoxLayout())
label = QLabel()
widget.layout().addWidget(label)

def hideShow():
    widget.hide()
    QTimer.singleShot(25, showWidget)

def showWidget():
    widget.setGeometry(widget.geometry())
    widget.show()

widget.layout().addWidget(QPushButton('Hide/Show', clicked = hideShow))
widget.show()
app.exec_()

rawDescription: PyQt4: Window shows up at another position after hide() and show()


code:
import random

which_list, item = random.choice([(name, value)
                                     for name, values in lists.iteritems()
                                         for value in values])

rawDescription: How do I randomly pick an item from one of the lists inside a dictionary, and also get the key for the list?

description: Randomly pick an item from one of the lists inside a dictionary, and also get the key for the list


rawDescription: method to create variables

description: Method to create variables


rawDescription: Bit masking in Python

description: Bit masking in Python


code:
def f(s, *args, **kwargs):
    frame = sys._getframe(1)
    d = {}
    d.update(frame.f_globals)
    d.update(frame.f_locals)
    d.update(kwargs)
    return Formatter().vformat(s, args, d)

rawDescription: auto-name keyword arguments after variable names

description: Auto-name keyword arguments after variable names


code:
import sys

inp = sys.stdin.readline()
print(inp)

rawDescription: In Windows' cmd.exe shell, how can I pipe the output of a Perl script to a Python script?


code:
[
    {'ExportPath': 2, 'OrginalName': 1},
    {'ExportPath': 4, 'OrginalName': 3},
    {'ExportPath': 6, 'OrginalName': 5}
]

rawDescription: Insert nested value in mongodb using python


code:
myList = [(), (), ('',), ('c', 'e'), ('ca', 'ea'), ('d',), ('do',), ('dog', 'ear', 'eat', 'cat', 'car'), ('dogs', 'cars', 'done', 'eats', 'cats', 'ears'), ('don',)]
filter(None, myList)
[t for t in myList if t]
[t for t in myList if t != ()]

rawDescription: Python 3: Removing an empty tuple from a list of tuples


code:
with open('the_file.txt', 'r') as fin, open('result.txt', 'w') as fout:
    for line in fin:
        f0, f1 = line.split()
        fout.write('%s\t%s\n' % (f0, ','.join(sorted(f1.split(','), key=int)[1:-1])))

rawDescription: sort a field in ascending order and delete the first and last number

description: Sort a field in ascending order and delete the first and last number


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setAutoFillBackground(True)
        self.setBackgroundRole(QtGui.QPalette.Mid)
        self.setLayout(QtGui.QFormLayout(self))
        self.fonts = QtGui.QFontComboBox(self)
        self.fonts.currentFontChanged.connect(self.handleFontChanged)
        self.layout().addRow('font:', self.fonts)
        for text in (
            u'H\u2082SO\u2084 + Be',
            u'jib leaf jib leaf',
            ):
            for label in ('boundingRect', 'width', 'size'):
                field = QtGui.QLabel(text, self)
                field.setStyleSheet('background-color: yellow')
                field.setAlignment(QtCore.Qt.AlignCenter)
                self.layout().addRow(label, field)
        self.handleFontChanged(self.font())

    def handleFontChanged(self, font):
        layout = self.layout()
        font.setPointSize(20)
        metrics = QtGui.QFontMetrics(font)
        for index in range(1, layout.rowCount()):
            field = layout.itemAt(index, QtGui.QFormLayout.FieldRole).widget()
            label = layout.itemAt(index, QtGui.QFormLayout.LabelRole).widget()
            method = label.text().split(' ')[0]
            text = field.text()
            if method == 'width':
                width = metrics.width(text)
            elif method == 'size':
                width = metrics.size(field.alignment(), text).width()
            else:
                width = metrics.boundingRect(text).width()
            field.setFixedWidth(width)
            field.setFont(font)
            label.setText('%s (%d):' % (method, width))

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Qt - Get the pixel length of a string in a QLabel


code:
[['2014-04-09 16:43:15,136','PID: 1371','INFO','Test.Controller.Root','Finished processing request        in   0.003355s for https://website/heartbeat'],
...,
...]

rawDescription: Python regex, how to capture multiple rules from 1 string


rawDescription: Python variable scope in for loop

description: Python variable scope in for loop


rawDescription: how to change the title of an image upload to a name in a class in django

description: Change the title of an image upload to a name in a class in django


code: with open('dictfile') as f: my_dict = eval(f.read())

rawDescription: How to load a Python dict from a textfile into a variable

description: Load a Python dict from a textfile into a variable


rawDescription: How to minus one on multiple variable? python

description: Minus one on multiple variable? python


code: mylist = ['this', 'that', 'theother']

rawDescription: Import list variable from separate files in python


code: ['Anthony', 'Rudolph', 'Chuck', 'Chuck_2', 'Chuck_3', 'Rudolph_2', 'Bob']

rawDescription: How to create unique list from list with duplicates

description: Create unique list from list with duplicates


code:
from multiprocessing import Manager, cpu_count
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

def AsyncProcessQueue(maxsize=0):
    m = Manager()
    q = m.Queue(maxsize=maxsize)
    return _ProcQueue(q)

class _ProcQueue(object):
    def __init__(self, q):
        self._queue = q
        self._real_executor = None
        self._cancelled_join = False

    @property
    def _executor(self):
        if not self._real_executor:
            self._real_executor = ThreadPoolExecutor(max_workers=cpu_count())
        return self._real_executor

    def __getstate__(self):
        self_dict = self.__dict__
        self_dict['_real_executor'] = None
        return self_dict

    def __getattr__(self, name):
        if name in ['qsize', 'empty', 'full', 'put', 'put_nowait',
                    'get', 'get_nowait', 'close']:
            return getattr(self._queue, name)
        else:
            raise AttributeError("'%s' object has no attribute '%s'" %
                                    (self.__class__.__name__, name))

    @asyncio.coroutine
    def coro_put(self, item):
        loop = asyncio.get_event_loop()
        return (yield from loop.run_in_executor(self._executor, self.put, item))

    @asyncio.coroutine
    def coro_get(self):
        loop = asyncio.get_event_loop()
        return (yield from loop.run_in_executor(self._executor, self.get))

    def cancel_join_thread(self):
        self._cancelled_join = True
        self._queue.cancel_join_thread()

    def join_thread(self):
        self._queue.join_thread()
        if self._real_executor and not self._cancelled_join:
            self._real_executor.shutdown()

@asyncio.coroutine
def _do_coro_proc_work(q, stuff, stuff2):
    ok = stuff + stuff2
    print("Passing %s to parent" % ok)
    yield from q.coro_put(ok)  # Non-blocking
    item = q.get() # Can be used with the normal blocking API, too
    print("got %s back from parent" % item)

def do_coro_proc_work(q, stuff, stuff2):
    loop = asyncio.get_event_loop()
    loop.run_until_complete(_do_coro_proc_work(q, stuff, stuff2))

@asyncio.coroutine
def do_work(q):
    loop.run_in_executor(ProcessPoolExecutor(max_workers=1),
                         do_coro_proc_work, q, 1, 2)
    item = yield from q.coro_get()
    print("Got %s from worker" % item)
    item = item + 25
    q.put(item)

if __name__  == "__main__":
    q = AsyncProcessQueue()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_work(q))

rawDescription: Can I somehow share an asynchronous queue with a subprocess?

description: Somehow share an asynchronous queue with a subprocess


code:
import itertools as it # for brevity
import operator

def scale_12to16(image):
    new_image= image.copy()
    new_image.putdata(
        it.imap(operator.or_,
            it.imap(operator.lshift, image.getdata(), it.repeat(4)),
            it.imap(operator.rshift, image.getdata(), it.repeat(8))
        )
    )
    return new_image

rawDescription: Rescale intensities of a PIL Image

description: Rescale intensities of a PIL Image


code:
#!/usr/bin/env python
import ctypes
import sys
import time

MAX_TIME = max(int(sys.float_info.max),
               2**(8*ctypes.sizeof(getattr(ctypes, 'c_longlong', ctypes.c_long))))
BOUNDARY = 0.5
assert False < BOUNDARY < True # necessary for the binary search to work

class GmtimeOverflowTable:
    def __getitem__(self, timestamp):
        assert timestamp >= 0
        try:
            time.gmtime(timestamp)
        except (OSError, OverflowError, ValueError): # ValueError for Python <3.3
            return True # overflow
        return False

def find_max_gmtime_timestamp():
    overflow = GmtimeOverflowTable()
    assert overflow[float('+inf')] and not overflow[0]
    if overflow[MAX_TIME]:
        ts = binary_search(overflow, BOUNDARY, 0, MAX_TIME)
        assert overflow[ts] and not overflow[ts - 1]
        return ts - 1
    raise OverflowError("Max gmtime timestamp is larger than " + str(MAX_TIME))

print(find_max_gmtime_timestamp())

rawDescription: Get the highest possible gmtime for any architecture


code:
s = """TrnIq: Thread on CPU 37
TrnIq: Thread on CPU 37 but will be moved to CPU 44
IP-Thread on CPU 33
FANOUT Thread on CPU 37
Filter-Thread on CPU 38 but will be moved to CPU 51
TRN TMR Test 2 Supervisor Thread on CPU 34
HomographyWarp Traking Thread[0] on CPU 26"""

for line in s.splitlines():
    words = line.split()
    if not ("CPU" in words and "on" in words): continue # skip uninteresting lines
    prefix_words = words[:words.index("on")+1]
    prefix = ' '.join(prefix_words)
    cpu = int(words[-1])
    print (prefix, cpu)

rawDescription: Best Method to Find Multiple String Occurrences in Python


code: u'bla ble  blo'

rawDescription: How to eliminate the ☎ unicode?

description: Eliminate the ☎ unicode


code:
text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]

rawDescription: Strings won't compare properly

description: Strings won't compare properly


code:
def __eq__(self, other):
    return self.Value == other.Value

rawDescription: Python: finding an element in an array

description: Python: finding an element in an array


code:
import borg
b = borg.Borg(foo='bar')

rawDescription: Borg design with new-style classes

description: Borg design with new-style classes


rawDescription: Fetch the details from SOAP xml response


code:
deck = []
for suit in ('spades', 'hearts', 'diamonds', 'clubs'):
    for n in range(2, 10):
        deck.append('%i of %s' % (n, suit))

rawDescription: How to write this Python code shorter?

description: Write this Python code shorter


code:
def do_some_updates(game):
    # some code
    player = game.get_player()
    last_regen_call = player.last_regen_call
    now = game.current_frame()
    if now - last_regen_call >= 60:  # assuming 60FPS
        player.life += amount_of_life
        player.last_regen_call = now

rawDescription: In Python, how do I add 1 every second

description: In Python, how do I add 1 every second


code: df.resample('D', how='mean', axis=0)

rawDescription: Python Pandas Panel4D resample

description: Python Pandas Panel4D resample


code:
import numpy as np

x = np.array([0, 0, 1])
y = np.array([0, 0, 1])
z = np.array([0, 0, 3])
xedges = np.linspace(0, 4, 3)
yedges = np.linspace(0, 4, 3)
zedges = np.linspace(0, 4, 3)
xyz = np.vstack((x, y, z)).T
hist, edges = np.histogramdd(xyz, (xedges, yedges, zedges))
grid = np.vstack(np.meshgrid(*edges)).reshape(len(edges), -1).T

rawDescription: Generation of multidimensional Grid in Python


code:
ll = [
  {'title': 'Index Page', 'url': 'http://www.example.com/something/index.htm'},
  {'title': 'Other Page', 'url': 'http://www.example.com/something/other.htm'},
  {'title': 'About Page', 'url': 'http://www.example.com/thatthing/about.htm'},
  {'title': 'Detail Page', 'url': 'http://www.example.com/something/thisthing/detail.htm'},
]

# First build a list of all url segments: final item is the title/url dict
paths = []
for item in ll:
    split = item['url'].split('/')
    paths.append(split[2:-1])
    paths[-1].append({'title': item['title'], 'url': split[-1]})

# Loop over these paths, building the format as we go along
root = {}
for path in paths:
    branch = root.setdefault(path[0], [{}, []])
    for step in path[1:-1]:
        branch = branch[0].setdefault(step, [{}, []])
    branch[1].append(path[-1])

# As for the cleanup: because of the alternating lists and
# dicts it is a bit more complex, but the following works:
def walker(coll):
    if isinstance(coll, list):
        for item in coll:
            yield item
    if isinstance(coll, dict):
        for item in coll.itervalues():
            yield item

def deleter(coll):
    for data in walker(coll):
        if data == [] or data == {}:
            coll.remove(data)
        deleter(data)

deleter(root)

import pprint
pprint.pprint(root)

rawDescription: Representing a set of URLs in a list as a tree structure


code:
def sendGroupChatMessage():
    """
    Send Group Chat Messages.
    """
    import Skype4Py as skype
    skypeClient = skype.Skype()
    skypeClient.Attach()
    for elem in skypeClient.ActiveChats:
        if len(elem.Members) > 2:
            elem.SendMessage("SomeMessageHere")

rawDescription: How can I send a message to a group conversation with Skype4Py in Python

description: Send a message to a group conversation with Skype4Py in Python


code:
import json

with open('config.json') as f:
    pairs = json.load(f)

for item in pairs:
    category = item['category']
    url = item['url']
    # process them here...

rawDescription: Config File Help Too Many Values Needed

description: Config File Help Too Many Values Needed


rawDescription: Inputting data from file into tuple

description: Inputting data from file into tuple


code:
from itertools import product
products = product(['A', 'B', 'C'], repeat=10)
next(products)
next(products)
next(products)
from itertools import islice
skip_to_end = islice(products, (3 ** 10) - 6, None)
next(skip_to_end)
next(skip_to_end)
next(skip_to_end)

rawDescription: Python - How to generate permutations of size greater than the number of list elements


code:
temp = df.reset_index()
temp['b'] = temp['b'].str.decode('iso-8859-1').str.encode('utf-8')
df = temp.set_index(['a', 'b'])

rawDescription: Change string encoding of pandas MultiIndex


code:
@app.route('/school/')
@login_required(role="SCHOOL")
def restricted_view_for_school():
    pass

rawDescription: Implementing Flask-Login with multiple User Classes


code: seedresult = seed(addy)

rawDescription: Function Return But No Value

description: Function Return But No Value


code:
@decorate_all_functions(print_on_call)
class Foo:
    def func1(self):
        print('1')

    def func2(self):
        print('2')

rawDescription: Catch "before/after function call" events for all functions in class


code:
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress

class MyFileDropTarget(wx.FileDropTarget):

    #----------------------------------------------------------------------
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    #----------------------------------------------------------------------
    def OnDropFiles(self, x, y, filenames):
        self.window.SetInsertionPointEnd(y)
        #self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
        #                   (len(filenames), x, y), y)
        for filepath in filenames:
            self.window.updateText(filepath + '\n', y)

class MyPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        file_drop_target = MyFileDropTarget(self)
        file_drop_target2 = MyFileDropTarget(self)
        file_drop_target3 = MyFileDropTarget(self)

        #Create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        grid = wx.GridBagSizer(hgap=5, vgap=5)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        #Create a button
        self.button = wx.Button(self, label="Test")
        #self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)

        # Radio Boxes
        sysList = ['QEXL','QEX10','QEX7']
        wlList = ['1100', '1400', '1800']
        sys = wx.RadioBox(self, label="What system are you calibrating ?",
                          pos=(20, 40), choices=sysList,  majorDimension=3,
                          style=wx.RA_SPECIFY_COLS)
        grid.Add(sys, pos=(1,0), span=(1,3))

        WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?",
                         pos=(20, 100), choices=wlList,  majorDimension=0,
                         style=wx.RA_SPECIFY_COLS)
        grid.Add(WL, pos=(2,0), span=(1,3))

        self.lblname = wx.StaticText(self, label="Cal File 1 :")
        grid.Add(self.lblname, pos=(3,0))
        self.Cal_1 = wx.TextCtrl(self, name="Cal_1", value="", size=(240,-1))
        self.Cal_1.SetDropTarget(file_drop_target)
        grid.Add(self.Cal_1, pos=(3,1))

        self.lblname = wx.StaticText(self, label="Cal File 2 :")
        grid.Add(self.lblname, pos=(4,0))
        self.Cal_2 = wx.TextCtrl(self, value="", name="Cal_2", size=(240,-1))
        self.Cal_2.SetDropTarget(file_drop_target2)
        grid.Add(self.Cal_2, pos=(4,1))

        self.lblname = wx.StaticText(self, label="Cal File 3 :")
        grid.Add(self.lblname, pos=(5,0))
        self.Cal_3 = wx.TextCtrl(self, value="", name="Cal_3", size=(240,-1))
        self.Cal_3.SetDropTarget(file_drop_target3)
        grid.Add(self.Cal_3, pos=(5,1))

        hSizer.Add(grid, 0, wx.ALL, 5)

        mainSizer.Add(hSizer, 0, wx.ALL, 5)
        mainSizer.Add(self.button, 0, wx.CENTER)
        self.SetSizer(mainSizer)

class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(400,400))
        panel = MyPanel(self)

        self.CreateStatusBar() # A Statusbar in the bottom of the window

        # Creating the menubar.
        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        helpMenu = wx.Menu()

        menubar.Append(fileMenu, '&File')
        menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
        #self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
        fileMenu.AppendSeparator()
        menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)

        menubar.Append(helpMenu, '&Help')
        menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About",
                                   " Information about this program")
        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)

        self.SetMenuBar(menubar)

        self.Show(True)

    def OnAbout(self,e):
        # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
        dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
        dlg.ShowModal() # Show it
        dlg.Destroy() # finally destroy it when finished.

    def OnExit(self,e):
        # Close the frame.
        #del self.fdt
        self.Close(True)

app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()

rawDescription: unable to quit wxpython

description: Unable to quit wxpython


rawDescription: Reorder and select subset from dataframe based on other dataframe pandas


code:
import multiprocessing.managers as m
from multiprocessing import process

def RebuildProxyNoReferent(func, token, serializer, kwds):
    '''
    Function used for unpickling proxy objects.

    The Proxy object is always returned.
    '''
    incref = (
    kwds.pop('incref', True) and
    not getattr(process.current_process(), '_inheriting', False)
    )
    return func(token, serializer, incref=incref, **kwds)

m.RebuildProxy = RebuildProxyNoReferent  # Monkey-patch it

class Foo(object):

    def __init__(self):
        self.manager = MyManager()
        self.manager.register('Bar', Bar)
        self.manager.start()
        self.bar = self.manager.Bar()
        print(type(self.bar))
        self.bar.set_proxy(self.bar)

class Bar(object):

    def __init__(self):
        self.proxy = None

    def set_proxy(self, proxy):
        print("got {}".format(type(proxy)))
        self.proxy = proxy

class MyManager(m.BaseManager):
    pass

test = Foo()

rawDescription: Python: How to pass an Autoproxy object

description: Python: How to pass an Autoproxy object


rawDescription: how to intersect lists in python with respect to index

description: Intersect lists in python with respect to index


rawDescription: NumPy array indexing

description: NumPy array indexing


code: [random.random() for x in xrange(3)]

rawDescription: Populate list or tuple from callable or lambda in python


code: df=pd.DataFrame(s, columns=['c1'])

rawDescription: Deleting row from hierarchical Series in Pandas based on column value and position


code:
import socket
type(socket.socket)

rawDescription: Query about Creating a Socket in Python

description: Query about Creating a Socket in Python


code: p4.run("sync", "...@[labelname]")

rawDescription: Syncing code to a label using P4Python

description: Syncing code to a label using P4Python


code:
import copy
def listxgcd( Ain ):
    A = copy(Ain)
    ...

rawDescription: Why does sage treat local python variables as global?


code:
#using x as an index
for x in range(0, len(pHand)):

    if deck[x][0] == '1' or deck[x][0] == 'J' or deck[x][0] == 'Q' or deck[x][0] == 'K':
        pTotal += 10
    elif deck[x][0] == 'A':
        pTotal += 11
    else:
        pTotal += int(deck[x][0])

rawDescription: Python - For loop isn't kicking in (blackjack game)


code:
df.index = df['timestamp']
df.resample('20Min', 'count')

rawDescription: Working with dates in pandas

description: Working with dates in pandas


code:
with Image.open('test.png') as test_image:
    do_things(test_image)

rawDescription: How to close Pillow opened image - Python

description: Close Pillow opened image - Python


rawDescription: Matplotlib : how to label points individually?


code:
cmap = ListedColormap(['r', 'g']) # use the colors red and green
norm = BoundaryNorm([-1000,0,1000], cmap.N) # map red to negative and green to positive
                                            # this may work with just 0 in the list
fig, axes = plt.subplots()
colorline(x, data, data, cmap=cmap, norm=norm)

plt.xlim(x.min(), x.max())
plt.ylim(data.min(), data.max())

plt.show()

rawDescription: multi colored plots in matplotlib plt based on certain properties of data

description: Multi colored plots in matplotlib plt based on certain properties of data


code:
class TestClass(AbstractTestClass):
    # concrete class

    val = 7

    @property
    def luminance(self):
        # concrete property
        return self.val

    @luminance.setter
    def luminance(self, value):
        # concrete property setter
        # call base class first to activate the validator
        # AbstractTestClass.__dict__['luminance'].__set__(self, value)
        self.val = value

rawDescription: How to provide value validation at abstract class level?

description: Provide value validation at abstract class level


code:
class ComponentTestCase(BaseTestCase):
    xmlid = None
    var = None

    def test_var(self):
        assert self.var == "whatever_the_value_is_in self.xmlfile"

rawDescription: python unittest multiple mixins

description: Python unittest multiple mixins


code:
import contextlib
import socket
import threading

def pairs(iterable):
    return zip(*[iter(iterable)]*2)

def netstrings(conn):
    buf = ''
    while True:
        newbuf = conn.recv(1536*1024)
        if not newbuf:
            return
        buf += newbuf
        while True:
            colon = buf.find(':')
            if colon == -1:
                break
            length = int(buf[:colon])
            if len(buf) >= colon + length + 2:
                if buf[colon+length+1] != ',':
                    raise ValueError('Not a netstring')
                yield buf[colon+1:colon+length+1]
                buf = buf[colon+length+2:]

def client(conn):
    with contextlib.closing(conn):
        for filename, contents in pairs(netstrings(conn)):
            with open(filename, 'wb') as f:
                f.write(contents)

sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
with contextlib.closing(sock):
    sock.bind(('0.0.0.0', 12345))
    sock.listen(1)
    while True:
        conn, addr = sock.accept()
        t = threading.Thread(target=client, args=[conn])
        t.daemon = True
        t.start()

rawDescription: Python: Upload huge amount of files via FTP


rawDescription: Sort a dictionary of dictionaries python


rawDescription: Subdividing NumPy array into Regular Grid


code:
html.body = html.find('body')
my_h1 = ET.Element('h1', {'class': 'roflol'})
my_h1.text = 'BIG TITLE!12'
html.body.append(my_h1)
html.body.SOURCE = ET.tostring(html.body)
html.body.SOURCE

rawDescription: What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access?


code: #include <Python/Python.h>

rawDescription: Python.h header file missing on Mac OS X 10.6


code: self.metadata = re.sub('(?<=<file_name>)\d{4,}(?![.\d])','', self.metadata)

rawDescription: Modifying existing regex

description: Modifying existing regex


code:
from itertools import accumulate
lst = [(0, 0), (2, 3), (4, 3), (5, 1)]
list(zip(*map(accumulate, zip(*lst))))

rawDescription: Accumulate items in a list of tuples

description: Accumulate items in a list of tuples


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

def line(x, slope=1, zero=0):
    return zero + slope * x

x = np.array([-4,10])
y1 = line(x, 2, 2)
y2 = line(x, 1, 3)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y1)
ax.plot(x,y2)

ax.spines['left'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.show()

rawDescription: Graph, that crosses y axis

description: Graph, that crosses y axis


code:
import pyorient

db_name = 'Stack37277880'

print("Connecting to the server...")
client = pyorient.OrientDB("localhost",2424)
session_id = client.connect("root","root")
print("OK - sessionID: ",session_id,"\n")

if client.db_exists( db_name, pyorient.STORAGE_TYPE_PLOCAL ):
    client.db_open(db_name, "root", "root")
    dbClasses = client.command("SELECT name FROM (SELECT expand(classes) FROM metadata:schema)")
    newClass = "MyClass"
    classFound = False
    for idx, val in enumerate(dbClasses):
        if (val.name == newClass):
            classFound = True
            break
    if (classFound != True):
        client.command("CREATE CLASS " + newClass)
        print("Class " + newClass + " correctly created")
    else:
        print("Class " + newClass + " already exists into the DB")

client.db_close()

rawDescription: How to find out if a class exists on an OrientDB using PyOrient?

description: Find out if a class exists on an OrientDB using PyOrient


code: count = sum( connections[8080].values() )

rawDescription: Big graph in memory

description: Big graph in memory


rawDescription: separate list elements based on semicolon

description: Separate list elements based on semicolon


code: new_num1 = list(num1)

rawDescription: What is wrong with this alternative bitwise operator function?


code: codes['Generation'][1] # yeilds 'First'

rawDescription: How can I organize my data into a grid using Python Pandas?

description: Organize my data into a grid using Python Pandas


rawDescription: Python uuid4, How to limit the length of Unique chars


rawDescription: python string in-place modification

description: Python string in-place modification


rawDescription: MultiIndex for pandas dataframe

description: MultiIndex for pandas dataframe


rawDescription: loop for computing average of selected data in dataframe using pandas

description: Loop for computing average of selected data in dataframe using pandas


code: feval(myStruct.myFunction, 5)

rawDescription: save matlab function to disk using scipy

description: Save matlab function to disk using scipy


code: self.dict = func.__dict__.copy()

rawDescription: Reassign a function attribute makes it 'unreachable'


code:
def check(g,s):
    return any(s in vlist for vlist in g.values())

rawDescription: Code not iterating over whole dictionary


code:
def run(command):
    proc = subprocess.Popen(command, stdout=subprocess.PIPE)
    for line in proc.stdout:
        print(line.replace('\n', ''))

rawDescription: Trouble printing text live with Python subprocess.call


rawDescription: Replace a text in a text file in python

description: Replace a text in a text file in python


code:
for date in filteredDates:
    print(date.strftime('%Y-%m-%d %H:%M'))

rawDescription: Remove certain dates in list. Python 3.4


code:
import numpy
z = numpy.array([1., 1., 0., 0., 0., 2., 3., 4., 5., 6., 0., 7., 8., 9.])
a = z[z!=0]
b = numpy.argwhere(z == 0).flatten()
c = numpy.insert(a, b, numpy.nan)
numpy.insert(a, b - numpy.arange(len(b)), numpy.nan)

rawDescription: numpy.insert troubles

description: Numpy.insert troubles


rawDescription: Python pandas: retrieve the field associated to the min of another (cross apply equivalent)


code: df

rawDescription: Convert Varied Text Fields of Duration to Seconds in Pandas


code: _debugFunction(locals(), 'x y z')

rawDescription: Printing 'var' = var

description: Printing 'var' = var


code: reduce(lambda a,b:a*b, range(1,12+1)) # 12!

rawDescription: What hardware is required to run this program?


code:
X.a
x.a
x.a
X.a

rawDescription: Method delegation in python

description: Method delegation in python


rawDescription: GroupBy - Datetime diff() combining additional criteria


code:
import numpy as np

yt, xt = 3, 5
x = np.random.rand(10, 6, 7)
y = np.zeros((yt, xt))
idx = np.random.randint(0, 10, (yt, xt))

for j in range(yt):
    for i in range(xt):
        y[j, i] = x[idx[j, i], j, i]

J, I = np.ogrid[:yt, :xt]
np.all(x[idx, J, I] == y)

rawDescription: NumPy: Evaulate index array during vectorized assignment


code: averagewalk = numpy.sum(walks, 0)*1.0/numwalks # sums along the 0th axis and returns an array of length steps

rawDescription: how i can repeat loop for random walk?

description: How i can repeat loop for random walk


code:
@models.permalink
def get_absolute_url(self):
    return ('category_view', (), {'slug': self.slug})

rawDescription: Get Absolute URL in Django when using Class Based Views


code: where(condition, [x, y])

rawDescription: Is there universal if function in numpy?

description: Is there universal if function in numpy


code:
import requests
from bs4 import BeautifulSoup
url = 'http://www.ewn.co.za/Categories/Local'
r = requests.get(url).text
soup = BeautifulSoup(r)
for i in soup.find_all(class_='article-short'):
    title = (i.h6.text.replace('\n', '') if i.h6 else contents[0]).strip()
    if title:
        print(title)

rawDescription: How to get rid of whitespace above text, using bs4

description: Get rid of whitespace above text, using bs4


rawDescription: How can I format a float using matplotlib's LaTeX formatter?

description: Format a float using matplotlib's LaTeX formatter


code:
rows = input("enter the number of rows")

for num in range(1, rows // 2 + 1) + range((rows + 1) // 2, 0, -1):
    print(' '.join('*' * num).center(rows))

rawDescription: diamond structure using asterix in python

description: Diamond structure using asterix in python


code:
xmax = 1E6
nsubarray = 100000
x = np.arange(xmax)
start = np.random.randint(0, xmax - 10, nsubarray)
stop = start + np.random.randint(1, 10, nsubarray)

old = np.concatenate([x[b:e] for b, e in izip(start, stop)])
new = get_chunks(x, start, stop)
np.allclose(old,new)
True

rawDescription: Construct single numpy array from smaller arrays of different sizes


code: list.sort(key = lambda self: (self.c, self.a, self.b))

rawDescription: In Python how would I compare with multiple values using custom keys?


code:
from bs4 import BeautifulSoup

data = """

test1

test2

test3

test4

test5

test6

"""

soup = BeautifulSoup(data)

def class_filter(elm):
    try:
        classes = elm["class"]
        return classes[0].startswith("dog-") and classes[1].endswith("-cat")
    except (KeyError, IndexError, TypeError):
        return False

for elm in soup.find_all(class_filter):
    print(elm.text)

rawDescription: Searching for pieces of an attribute with Beautiful Soup


code:
def dp_coin(S, coins):
    # set all values to infinity in range S/sum needed
    mn = [float("inf") for j in range(S+1)]
    # takes 0 coins to sum 0
    mn[0] = 0
    # start at second index 1
    for i in range(1, S+1):
        for j in range(len(coins)):
            if coins[j] <= i and mn[i-coins[j]]+1 < mn[i]:
                mn[i] = mn[i-coins[j]] + 1
    return mn[-1]

print(dp_coin(11, [1, 3, 5]))
3

rawDescription: Using infinity in dynamic programming coins example - why does this not fail?


code:
li=[str(x) for x in range(5)]
li

rawDescription: Is a variable the name, the value, or the memory location?


code:
message[0]
message[1]

rawDescription: How do you calculate the amount of characters including spaces and numbers in a string

description: Calculate the amount of characters including spaces and numbers in a string


code: start_from = lambda hours, minutes, seconds, link: link + '&start=' + str((hours*60*60)+(minutes*60)+seconds)

rawDescription: Generating Links to Youtube Audio

description: Generating Links to Youtube Audio


code:
#ifdef _MSC_VER
  #define __BYTE_ORDER __LITTLE_ENDIAN
#endif

rawDescription: Error setting up thrift modules for python


code: len(mylist) == 2 and mylist[1] == "comment"

rawDescription: Check if a key exists in a Python list

description: Check if a key exists in a Python list


code:
class GraphGUI():

    def __init__(self, rootWin):
        self.textfield = ScrolledText.ScrolledText(rootWin,
                                                   width=30,
                                                   height=10)
        # Add some text:
        self.textfield.insert(INSERT, "Replace")
        self.textfield.grid(column=0, row=4)

        self.button = Button(rootWin, text="Process!", command=self.clicked)
        self.button.grid(column=1, row=4)

    def clicked(self):
        eText = self.textfield.get('1.0', END)
        converted = eText.encode('ascii', 'ignore')
        myarray = converted.splitlines()
        return myarray

rootWin = Tkinter.Tk()

app = GraphGUI(rootWin)
start = Tkinter.Button(rootWin, text="start!", command=app.clicked)
start.grid(column=7, row=8)  # your code assigned `start = None` btw
rootWin.mainloop()

rawDescription: Python: retrieve objects's value from a class object


rawDescription: Extracting specific src attributes from script tags


code:
data = """<FirstLevel>
    <item1>Val1</item1>
    <item2>Val2</item2>
    <item3>Val3</item3>
    <item4>Val4</item4>
    <item5>Val5</item5>
    <item1>Val1</item1>
    <item2>Val2</item2>
    <item3>Val3</item3>
    <item4>Val4</item4>
    <item5>Val5</item5>
    <item1>Val1</item1>
    <item2>Val2</item2>
    <item3>Val3</item3>
    <item4>Val4</item4>
    <item5>Val5</item5>
</FirstLevel>
"""

tree = fromstring(data)
node_start = "item1"
node_end = "item5"

parent = tree.xpath("//FirstLevel")[0]
# Remove first section
for node in parent.xpath("*[(preceding-sibling::item1)[1] and (following-sibling::item5)[3]]"):
    parent.remove(node)
# Remove second section
for node in parent.xpath("*[(preceding-sibling::item1)[2] and (following-sibling::item5)[2]]"):
    parent.remove(node)
# Remove last section
for node in parent.xpath("*[(preceding-sibling::item1)[3] and (following-sibling::item5)[last()]]"):
    parent.remove(node)

print(tostring(tree))

rawDescription: Deleting multiple XML elements between too elements


code:
class OrderTests(TestCase, ShopTest):
    _VIEW = views.order

    def test_gateway_answer(self):
        url = 'whatever url'
        request = self.request_factory(url, 'GET')
        OrderTests._VIEW(request, **{'sku': order.sku})

rawDescription: Call external function without sending 'self' arg


code: len(dict_test) + sum(len(v) for v in dict_test.itervalues())

rawDescription: Get the number of all keys in a dictionary of dictionaries in Python


code:
gprmc, hdop, altitude, state, ad, baseid, csq, journey = information.split('|')[:8]
data = gprmc.split(',')
ptime, gpsindicator, lttd, ns, lgtd, ew, speed, course, pdate, dd = data[:10]
checksum = data[-1]

rawDescription: list received is bigger than expected

description: List received is bigger than expected


rawDescription: How do I write this matlab example to python

description: Write this matlab example to python


code:
import random

def index(request):
    answers = Answer.objects.filter(user=request.user)
    questions = Question.objects.filter(user=request.user)

    mixed = list(answers) + list(questions)
    random.shuffle(mixed)

    return render(request,"welcome/index.html",locals())

rawDescription: how to randomize results from two querysets in django template

description: Randomize results from two querysets in django template


code:
def contact(request):
    if request.method == 'post':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            obj = ContactModel()
            obj.name = cd['name']
            obj.family = cd['family']
            ...
            obj.save()

rawDescription: How to save form fields in the model in a view

description: Save form fields in the model in a view


code:
import numpy as np

def view_fields(a, names):
    """
    `a` must be a numpy structured array.
    `names` is the collection of field names to keep.

    Returns a view of the array `a` (not a copy).
    """
    dt = a.dtype
    formats = [dt.fields[name][0] for name in names]
    offsets = [dt.fields[name][1] for name in names]
    itemsize = a.dtype.itemsize
    newdt = np.dtype(dict(names=names,
                          formats=formats,
                          offsets=offsets,
                          itemsize=itemsize))
    b = a.view(newdt)
    return b

def remove_fields(a, names):
    """
    `a` must be a numpy structured array.
    `names` is the collection of field names to remove.

    Returns a view of the array `a` (not a copy).
    """
    dt = a.dtype
    keep_names = [name for name in dt.names if name not in names]
    return view_fields(a, keep_names)

rawDescription: How to remove a column from a structured numpy array *without copying it*?

description: Remove a column from a structured numpy array *without copying it*


code:
def sieve(N):
        t = [0]*(N+1)
        for factor in range(1,N+1):
                for multiple in range(factor,N+1,factor):
                        t[multiple]+=1
        return t[1:]

rawDescription: How do you implement the divisor function in code?

description: Implement the divisor function in code


code: raise ValueError("Unexpected enum value")

rawDescription: How to ensure solid contracts without strong typing?

description: Ensure solid contracts without strong typing


code: user in ("paper", "Paper")

rawDescription: weird behaviour in python if clause

description: Weird behaviour in python if clause


code:
def mymethod():
    '''
    >>> request.vars.update(param1=9, param2='a', param3=3.7)
    >>> mymethod()
    [expected output of mymethod goes here]
    '''

rawDescription: web2py: creating doctests that pass parameters

description: Web2py: creating doctests that pass parameters


code:
# returns a.substructure2.subsubstructure2
#          or a.substructure1.subsubstructure1 based on the value of kind
substruct = get_the_substructure(a, kind)
substruct.name_of_data1 += 1

rawDescription: Pythonic ways to avoid Pointers

description: Pythonic ways to avoid Pointers


rawDescription: Convert a flat tab-delimited file into Json nested structure


code:
#!/usr/bin/env python
from __future__ import print_function
import sys
from subprocess import Popen, PIPE

p = Popen("./randomNumber", stdin=PIPE, stdout=PIPE,
          bufsize=1, # line-buffering
          universal_newlines=True) # enable text mode
p.stdout.readline() # discard welcome message: "This program gener...

readchar = lambda: p.stdout.read(1)
def read_until(char):
    buf = []
    for c in iter(readchar, char):
        if not c: # EOF
            break
        buf.append(c)
    else: # no EOF
        buf.append(char)
    return ''.join(buf).strip()

prompt = read_until(':') # read 1st prompt
lo, hi = 0, 100
while lo <= hi:
    mid = (lo + hi) // 2
    print(prompt, mid)
    print(mid, file=p.stdin) # send number
    prompt = read_until(':') # read prompt
    if "Congratulations" in prompt:
        print(prompt)
        print(mid)
        break # found
    elif "too high" in prompt:
        hi = mid - 1 # guess > num
    elif "too low" in prompt:
        lo = mid + 1 # guess < num
else:
    print('not found')
    p.kill()
for pipe in [p.stdin, p.stdout]:
    try:
        pipe.close()
    except OSError:
        pass
sys.exit(p.wait())

rawDescription: subprocess readline hangs waiting for EOF

description: Subprocess readline hangs waiting for EOF


code:
divtd(datetime.timedelta(hours = 12), datetime.timedelta(hours = 2))
divtd(datetime.timedelta(hours = 12), 2)
MyTimeDelta(hours = 12) / MyTimeDelta(hours = 2)

rawDescription: How can I perform divison on a datetime.timedelta in python?

description: Perform divison on a datetime.timedelta in python


code: 'Some text' in to_test

rawDescription: Python list value setting

description: Python list value setting


code:
text.rsplit('offset ', 1)
text.rsplit('offset ', 1)[1]

rawDescription: Extract specific characters from the string


rawDescription: pandas.to_datetime inconsistent time string format

description: Pandas.to_datetime inconsistent time string format


code:
string_to_match_against = """
SEND OK HTTP/1.1 200 OK
Access-Control-Allow- l-Allow-Methods: GET,POST,DELETE
Access-Control-Allow-Headers: X-Requested-With,
Phant-Private-Key Content-Type: text/plain X-Rate-Limit-Limit: 300
X-Rate-Limit-Remaining: 297
X-Rate-Limit-Reset: 1452931335.777
Date: Sat, 16 Jan 2016 07:50:17 GMT
Set-Cookie: SERVERID=; Expires=Thu, 01-Jan-197 0 00:00:01 GMT; path=/ Cache-control: private
Transfer-Encoding: chunked
"""

rawDescription: Extract timestamp from large string

description: Extract timestamp from large string


rawDescription: Pandas: Average over the same hour

description: Pandas: Average over the same hour


code: L

rawDescription: python, 2 operations: find closest value above and below a specified value in array, find associated values in another array

description: Python, 2 operations: find closest value above and below a specified value in array, find associated values in another array


code:
s = '11223344'
import binascii
binascii.unhexlify(s)
struct.unpack('>L',binascii.unhexlify(s))
hex(287454020)

rawDescription: Binary Data in Python

description: Binary Data in Python


rawDescription: select first column in a 3d ndarray

description: Select first column in a 3d ndarray


code:
import numpy as np
import matplotlib.pyplot as plt
import pandas
import pandas.tools.plotting
from pandas.compat import range, lrange, lmap, map, zip, string_types

def main():

    df = pandas.DataFrame(np.random.randn(1000,4 ), columns=['a', 'b', 'c', 'd'])
#     pandas.tools.plotting.scatter_matrix(df, alpha=0.2,
#         c='red', hist_kwds={'color':['burlywood']})
    custom_scatter_matrix(df, alpha=0.2, c='red')
    plt.show()

def custom_scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False,
                   diagonal='hist', marker='.', density_kwds=None,
                   hist_kwds=None, range_padding=0.05, **kwds):
    """
    Draw a matrix of scatter plots.

    Parameters
    ----------
    frame : DataFrame
    alpha : float, optional
        amount of transparency applied
    figsize : (float,float), optional
        a tuple (width, height) in inches
    ax : Matplotlib axis object, optional
    grid : bool, optional
        setting this to True will show the grid
    diagonal : {'hist', 'kde'}
        pick between 'kde' and 'hist' for
        either Kernel Density Estimation or Histogram
        plot in the diagonal
    marker : str, optional
        Matplotlib marker type, default '.'
    hist_kwds : other plotting keyword arguments
        To be passed to hist function
    density_kwds : other plotting keyword arguments
        To be passed to kernel density estimate plot
    range_padding : float, optional
        relative extension of axis range in x and y
        with respect to (x_max - x_min) or (y_max - y_min),
        default 0.05
    kwds : other plotting keyword arguments
        To be passed to scatter function

    Examples
    --------
    >>> df = DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
    >>> scatter_matrix(df, alpha=0.2)
    """
    import matplotlib.pyplot as plt
    from matplotlib.artist import setp

    df = frame._get_numeric_data()
    n = df.columns.size
    naxes = n * n
    fig, axes = pandas.tools.plotting._subplots(naxes=naxes, figsize=figsize, ax=ax,
                          squeeze=False)

    # no gaps between subplots
    fig.subplots_adjust(wspace=0, hspace=0)

    mask = pandas.tools.plotting.com.notnull(df)

    marker = pandas.tools.plotting._get_marker_compat(marker)

    hist_kwds = hist_kwds or {}
    density_kwds = density_kwds or {}

    # workaround because `c='b'` is hardcoded in matplotlibs scatter method
    kwds.setdefault('c', plt.rcParams['patch.facecolor'])

    boundaries_list = []
    for a in df.columns:
        values = df[a].values[mask[a].values]
        rmin_, rmax_ = np.min(values), np.max(values)
        rdelta_ext = (rmax_ - rmin_) * range_padding / 2.
        boundaries_list.append((rmin_ - rdelta_ext, rmax_+ rdelta_ext))

    for i, a in zip(lrange(n), df.columns):
        for j, b in zip(lrange(n), df.columns):
            ax = axes[i, j]

            if i == j:
                values = df[a].values[mask[a].values]

                # Deal with the diagonal by drawing a histogram there.
                if diagonal == 'hist':
                    N, bins, patches = ax.hist(values, **hist_kwds)
                    for bin_size, bin, patch in zip(N, bins, patches):
                        if bin_size > 200:
                            patch.set_facecolor("green")
                            patch.set_label("max")
                        elif bin_size < 50:
                            patch.set_facecolor("red")
                            patch.set_label("min")

                elif diagonal in ('kde', 'density'):
                    from scipy.stats import gaussian_kde
                    y = values
                    gkde = gaussian_kde(y)
                    ind = np.linspace(y.min(), y.max(), 1000)
                    ax.plot(ind, gkde.evaluate(ind), **density_kwds)

                ax.set_xlim(boundaries_list[i])

            else:
                common = (mask[a] & mask[b]).values

                ax.scatter(df[b][common], df[a][common],
                           marker=marker, alpha=alpha, **kwds)

                ax.set_xlim(boundaries_list[j])
                ax.set_ylim(boundaries_list[i])

            ax.set_xlabel('')
            ax.set_ylabel('')

            pandas.tools.plotting._label_axis(ax, kind='x', label=b, position='bottom', rotate=True)

            pandas.tools.plotting._label_axis(ax, kind='y', label=a, position='left')

            if j!= 0:
                ax.yaxis.set_visible(False)
            if i != n-1:
                ax.xaxis.set_visible(False)

    for ax in axes.flat:
        setp(ax.get_xticklabels(), fontsize=8)
        setp(ax.get_yticklabels(), fontsize=8)

    return axes

if __name__ == '__main__':
    main()

rawDescription: How to use color coding for intervals for scatter plot matrix in a python pandas code?

description: Use color coding for intervals for scatter plot matrix in a python pandas code


rawDescription: Remove duplicates with a different equality test in Python


code: myString = ''.join(map(chr, eventData))

rawDescription: python django decode array html codes to readable text

description: Python django decode array html codes to readable text


rawDescription: Linux: Split columns of file into multiple files


code:
qs = QuestionAnswer.objects.filter(pk=12345)
qa1 = qs.get()
qa1.graded
qa2 = qs.get()
qa2.graded = 1
qa3 = qs.get()
qa3.save()

rawDescription: Django objects.filter is not updating field but objects.get is


code:
my_list = [0] * 10
my_list

rawDescription: Python: Establishing List with List Comprehensions or Iterators


code:
'example@gmail.com'.split('@', 1)[0]
'example@gmail.com'.split('@', 1)[0] + '@hotmail.com'

rawDescription: python csv copy column

description: Python csv copy column


code:
for iid in img_ids:
    images.append(base64.b64encode(self.gfs.get(iid).read()))

rawDescription: Display images in django web app from mongo db


code:
from collections import defaultdict
d = defaultdict(list)
import  csv
with open(infile) as f:
    # skip header
    next(f)
    # use reader to get all rows
    r = csv.reader(f)
    # unpack from each row
    for _id, lt, ln in r:
        # use _id as key and append lat and lon
        d[_id].append("{},{}".format(lt,ln))
print(d)

rawDescription: Python: reorganize data and add it to dictionary


rawDescription: BeautifulSoup4 - python: how to merge two bs4.element.ResultSet and get one single list?


rawDescription: top n keys with highest values in dictionary with tuples as keys

description: Top n keys with highest values in dictionary with tuples as keys


code:
class CorsService(ServiceBase):
    origin = '*'

def _on_method_return_object(ctx):
    ctx.transport.resp_headers['Access-Control-Allow-Origin'] = \
                                              ctx.descriptor.service_class.origin

CorsService.event_manager.add_listener('method_return_object',
                                                        _on_method_return_object)

rawDescription: Where is the correct place to enable CORS?


code:
fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)

ax1 = ax.twinx()
x.plot(kind='kde', ax=ax1)
y.plot(kind='kde', ax=ax1, color='red')

rawDescription: Pandas: plotting two histograms on the same plot


rawDescription: Migrating from PuLP to Scipy

description: Migrating from PuLP to Scipy


code: pandas.options.display.max_columns = 50

rawDescription: Is python+pandas able to handle large amounts of data?


code:
import functools
import types

def metadec(func):

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # do stuff
        return func(*args, **kwargs)

    c = wrapper.func_code
    fname = "%s__%s" % (func.__name__, wrapper.__name__)

    code = types.CodeType(
                c.co_argcount,
                c.co_nlocals,
                c.co_stacksize,
                c.co_flags,
                c.co_code,
                c.co_consts,
                c.co_names,
                c.co_varnames,
                c.co_filename,
                fname, # change the name
                c.co_firstlineno,
                c.co_lnotab,
                c.co_freevars,
                c.co_cellvars,
            )

    return types.FunctionType(
            code, # Use our updated code object
            wrapper.func_globals,
            fname, # Use the updated name
            wrapper.func_defaults,
            wrapper.func_closure,
        )

rawDescription: Profiling a system with extensively reused decorators


code:
jill = Contact.objects.get(nickname='jill') # assuming you only have one jill
new_num = Telephone.objects.create(contact=jill,number=5551212)

rawDescription: How does a model relate to another model via Foreignkey?


code:
imputed[:5]
item_clusters[:5]
np.mean([b for b, i in zip(beta, item_clusters) if i == 506 and b != 0])

rawDescription: Missing value imputation in Python

description: Missing value imputation in Python


code:
sd = df.pop("superDuper")
df = df.unstack()

rawDescription: Yet Another Reshaping Issue

description: Yet Another Reshaping Issue


code:
class Thread(object):
    def __init__(self, a=None):
        self.a = a

    def b(self):
        pass

class Hotswap(Thread):
    def __init__(self, x=None):
        print("Before init: {}".format(self.__dict__))

        self.x = x

        super(Hotswap, self).__init__()

        print("After init: {}".format(self.__dict__))

    def y(self):
        pass

print("On Hotswap class: {}".format(Hotswap.__dict__))
h = Hotswap()
print("On Hotswap instance: {}".format(h.__dict__))

rawDescription: Overriding __init__ in threading.Thread

description: Overriding __init__ in threading.Thread


code: any(imap(function, iterable))

rawDescription: Python one-liner that answers: Do any of these inputs return True for this function?


rawDescription: How to dynamically load a Python class

description: Dynamically load a Python class


code:
def remove(glist):
    seen = set()
    def unseen():
        for val in glist:
            if not val in seen:
                yield val
                seen.add(val)
    glist[:] = unseen()
    return glist # if you must

rawDescription: Removing duplicates within list without creating a new list while preserving order


code:
for k in items:
     print("{} monthly  {}".format(k,items[k]["mon"]))
     print("{} total {}".format(k,items[k]["count"]))

rawDescription: CSV how to find the value, and edit its value


code:
from lxml import html

tree = html.fromstring("""

content a

content b

""")
for row in tree.xpath("//*[@class='asdf']"):
    print("row: ", row.text_content())

rawDescription: proper xpath to roll up text of children

description: Proper xpath to roll up text of children


rawDescription: How to build "many-hot" in Python/Pandas?

description: Build "many-hot" in Python/Pandas


code:
"in" in "indigo"
"in" in "violet"
"0" in "10"
"1" in "10"

rawDescription: Use and meaning of "in" in an if statement in python


code:
def plot(**kwargs):
    if 'make_plot' in kwargs:
        plot_dir = kwargs.get('plot_dir', "/default/plot/dir")
        # save or otherwise process the value of kwargs['make_plot']

rawDescription: How do we define optional keywords for a function?


code:
@csrf_exempt
def jobmst_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        DEV = Jobmst.objects.using('AdmiralDEV').all()
        serializer = JobmstSerializer(DEV, many=True)
        return XMLResponse(serializer.data)

    elif request.method == 'POST':
        data = XMLParser().parse(request)
        serializer = JobmstSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return XMLResponse(serializer.data, status=201)
        else:
            return XMLResponse(serializer.errors, status=400)

@csrf_exempt
def jobmst_detail(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        DEV = Jobmst.objects.using('AdmiralDEV').get(jobmst_id=pk)
    except Jobmst.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = JobmstSerializer(DEV)
        return XMLResponse(serializer.data)

    elif request.method == 'PUT':
        data = XMLParser().parse(request)
        serializer = JobmstSerializer(DEV, data=data)
        if serializer.is_valid():
            serializer.save()
            return XMLResponse(serializer.data)
        else:
            return XMLResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        DEV.delete()
        return HttpResponse(status=204)

rawDescription: django rest framework nested relationships

description: Django rest framework nested relationships


code:
import logging
logger = logging.getLogger() # get the default logger
logger.setLevel(50) # set the skip all log which is smaller than critical (50)

rawDescription: disable query logging - Google Appengine SDK Python

description: Disable query logging - Google Appengine SDK Python


rawDescription: How do you select choices in a form using Python?

description: Select choices in a form using Python


rawDescription: Deduping a complex list using a simplified copy of itself


code:
glb_var_1 = "some value"
glb_var_2 = "some other value"

def f1():
   local_var_1 = "this is local inside f1"

   print("f1(): We can use here all variables defined locally, i.e. inside f1():", local_var_1)
   print("f1(): We can use global var anywhere in program:", glb_var_1)

def f2():
   local_var_1 = "this is local inside f2"
   glb_var_1   = "this is local variable which is hiding global var of same name"

   print("f2(): locally inside f2():", local_var_1)
   print("f2(): same name as global var, but local to f2():", glb_var_1)

def f3():
    print("f3(): global var value would be one defined globally, not the one as defined in f2():", glb_var_1)

rawDescription: Global variables, member variables and instance variables in Python


rawDescription: trying to figure out a weird math formula

description: Trying to figure out a weird math formula


code:
rc = win32event.WaitForMultipleObjects(
    eventlist,    # Objects to wait for.
    0,            # Wait for one object
    timeout)      # timeout in milli-seconds.

rawDescription: What's the best way to transfer data from python to another application in windows?


code:
if (x, y) in dictionary_structure:
    print(dictionary_structure[(x, y)]["data"])

rawDescription: Fastest data structure for numerically indexed data structure?


code:
result = []
for x in some_list:
    if x > 2:
        result.append(x)

rawDescription: How can I add nothing to the list in list comprehension?

description: Add nothing to the list in list comprehension


code:
from collections import OrderedDict
dct = OrderedDict([(73, 'Mocha My Day'), (77, 'Coffee Cafe'), (83, 'Flavour Fusion'), (85, 'Mexican Grill')])
list(dct.items())

rawDescription: Convert from OrderedDict to list

description: Convert from OrderedDict to list


code: pos_count = merged.groupby(['index', 'Position'])['Station'].nunique().unstack(); pos_count

rawDescription: Pandas Create Columns From Rows in Other Data Frame with Criteria


code:
import numpy as np
superdiagonal = np.zeros((4, 4))
i, j = np.indices(superdiagonal.shape)
superdiagonal[i == j-1] = 1
print(superdiagonal)

rawDescription: How to make a diagonal matrix with canopy that has a displacement in the diagonal?

description: Make a diagonal matrix with canopy that has a displacement in the diagonal


code:
# A set of 64 characters, which allows a maximum chunk length of 6 .. because
# int('111111', 2) == 63 (plus zero)
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'

def encode(bin_string):
    # Split the string of 1s and 0s into lengths of 6.
    chunks = [bin_string[i:i+6] for i in range(0, len(bin_string), 6)]
    # Store the length of the last chunk so that we can add that as the last bit
    # of data so that we know how much to pad the last chunk when decoding.
    last_chunk_length = len(chunks[-1])
    # Convert each chunk from binary into a decimal
    decimals = [int(chunk, 2) for chunk in chunks]
    # Add the length of our last chunk to our list of decimals.
    decimals.append(last_chunk_length)
    # Produce an ascii string by using each decimal as an index of our charset.
    ascii_string = ''.join([charset[i] for i in decimals])

    return ascii_string

def decode(ascii_string):
    # Convert each character to a decimal using its index in the charset.
    decimals = [charset.index(char) for char in ascii_string]
    # Take last decimal which is the final chunk length, and the second to last
    # decimal which is the final chunk, and keep them for later to be padded
    # appropriately and appended.
    last_chunk_length, last_decimal = decimals.pop(-1), decimals.pop(-1)
    # Take each decimal, convert it to a binary string (removing the 0b from the
    # beginning, and pad it to 6 digits long.
    bin_string = ''.join([bin(decimal)[2:].zfill(6) for decimal in decimals])
    # Add the last decimal converted to binary padded to the appropriate length
    bin_string += bin(last_decimal)[2:].zfill(last_chunk_length)

    return bin_string

rawDescription: Compress a series of 1s and 0s into the shortest possible ascii string


code:
d = {}
for line in open('yourfile'):
    ym = year_month(line)
    if ym is None:
         continue
    x = d.setdefault(ym, [0])
    x[0] += 1
for ym in sorted(d):
    print('Year: {0}, Month: {1}, Hits: {2}'.format(ym[0], ym[1], d[ym][0]))

rawDescription: Python 2.7 - Find the number of web server hits


code:
with open('out.txt', 'w') as outtxt:
    outtxt.write('\n'.join(x))

rawDescription: Python program to extract text from a text file?


code:
a = [None, None, None, 1, 2, 3, 4, 5]
next(item for item in a if item is not None)

rawDescription: Getting the first non None value from list


rawDescription: Getting a sublist of a Python list, with the given indices?


code:
PLATINUM
SILVER
SILVER

rawDescription: How to parse this please i'm stuck

description: Parse this please i'm stuck


code:
class _Wrapper:

    def __init__(self, fd):
        self.fd = fd

    def readline(self, *args):
        try:
            return self.fd.readline(*args)
        except KeyboardInterrupt:
            print()
            return '\n'

class TestShell(cmd.Cmd):

    def __init__(self):
        super().__init__(stdin=_Wrapper(sys.stdin))
        self.use_rawinput = False
        self.prompt = '$ '

    def precmd(self, line):
        if line == 'EOF':
            return 'exit'
        return line

    def emptyline(self):
        pass

    def do_exit(self, line):
        return True

TestShell().cmdloop()

rawDescription: Handle CTRL-C in Python cmd module

description: Handle CTRL-C in Python cmd module


code:
aminoacids = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V']

pair_no_change = ['A', 'K']

original_pairs = [['A', 'K'], ['A', 'K'], ['A', 'K'], ['A', 'K'], ['A', 'K'],['D', 'E'], ['S', 'F'], ['B', 'C'], ['Y', 'V'], ['K', 'W']]

fq = 5

def frequency(original_pairs, pair_no_change, fq):
    updated_pairs = list(list())
    for pair in original_pairs:
        if pair != pair_no_change:
            pair[0] *= fq
            pair[1] *= fq
            updated_pairs.append([pair[0], pair[1]])
        else:
            continue
    return updated_pairs

updated_pairs = frequency(original_pairs, pair_no_change, fq)
#print(updated_pairs)
for pair in updated_pairs:
    for i ,j in zip(list(pair[0]), list(pair[1])):
        print [i,j]

rawDescription: python3, how to repeat a list of character

description: Python3, how to repeat a list of character


code:
import collections
import math
import timeit

def power_bit_length(x):
    return 2**(x-1).bit_length()

def shift_bit_length(x):
    return 1<<(x-1).bit_length()

def power_log(x):
    return 2**(math.ceil(math.log(x, 2)))

def test(f):
    collections.deque((f(i) for i in range(1, 1000001)), maxlen=0)

def timetest(f):
    print('{}: {}'.format(timeit.timeit(lambda: test(f), number=10),
                          f.__name__))

timetest(power_bit_length)
timetest(shift_bit_length)
timetest(power_log)

rawDescription: How can I find the smallest power of 2 greater than n in Python

description: Find the smallest power of 2 greater than n in Python


code:
class Person(object):
    def __init__(self, name, gender, single):
        self.name=name
        self.gender=gender
        self.single=single
    def __repr__(self):
        return 'Person({name!r}, {gender!r}, {single!r})'.format(**vars(self))

class FilterableList(list):
    def __getattr__(self, name):
        # assume non-existing attributes are boolean filters
        return [elem for elem in self if getattr(elem, name)]

members = FilterableList([Person("Jack","Male",False), Person("Jill","Female",True), Person("George","Male",True), Person("Sandy","Female",False)])
members
members.single

rawDescription: Add attribute to class list to return all objects with specific attribute


code:
import numpy as np

def get_stat_feats(data, winSize):
    from scipy.ndimage import generic_filter
    import numpy as np
    data = data.astype(float)
    mean = lambda x: x.mean()
    std = lambda x: x.std()

    meanData = generic_filter(data, mean, size=winSize)
    stdData = generic_filter(data, std, size=winSize)

    return np.round(meanData,2), np.round(stdData, 2)

rawDescription: Optimizing windowed feature generation from input image in Python


code:
df = pd.DataFrame({"data":range(1,30)}, index=['2015-04-{}'.format(d) for d in range(1,30)])

df.index.dtype
dtype('O')

df.index = df.index.to_series().apply(pd.to_datetime)

df.index.dtype
dtype('<M8[ns]')

rawDescription: Python Pandas - Reformat Datetime Index

description: Python Pandas - Reformat Datetime Index


code:
im = Image.frombuffer('RGB', (img.width, img.height), buff, 'raw', 'RGB', 0, 1)
im.save(filename)

rawDescription: Pixel manipulation with PIL.Image and ctypes


code:
#Data from your example
foo = (Decimal('17.5'), Decimal('9.9'), Decimal('8.9'), Decimal('4.0'), Decimal('9.3'), Decimal('53.8'), Decimal('227.1'), Decimal('280.90'), Decimal('125.4'), Decimal('28.1'), Decimal('5.0'), Decimal('4.7'))
bar = [float(i) for i in foo]

rawDescription: Isolating the elements of a row in python


code:
cars = """2010 Ferrari 599XX
2012 Ferrari 599XX Evoluzione
2007 Ferrari 430 Scuderia"""

res = []
for line in cars.splitlines():
    data = line.split(None, 1)
    res.append('|{}||'.format(data[0]) + data[1])
    res.append('|-')
print('\n'.join(res))

rawDescription: Adding characters to certain laces in string


rawDescription: Copy 'N' key value pairs from one python dictionary to another


code:
a = [1, 2, 3, 4, 5, 6, 7, 8]

f = open('myFile.txt', 'a')
for n in a:
    f.write('%d\t'%n)
f.write('\n')
f.close()

rawDescription: How to add values to existing columns in a text file (using Python)

description: Add values to existing columns in a text file (using Python)


code:
canvas.postscript(file="tmp.ps", colormode='color')
process = subprocess.Popen(["ps2pdf", "tmp.ps", "result.pdf"], shell=True)

rawDescription: Python tkinter save canvas as postscript and add to pdf


code:
import ruamel.yaml

file_name = 'test.yml'

with open(file_name) as infile:
    data = ruamel.yaml.round_trip_load(infile)

person = data['Person']
person['name'] = input('What is your name? ')
person['age'] = int(input('What is your age? '))
person['nationality'] = input('What is your nationality? ')
person['footed'] = input('What foot? ')
person['position'] = input('What is your position? ')

with open(file_name, 'w') as outfile:
    yaml.round_trip_dump(data, stream=outfile, indent=3)

rawDescription: Using Python with YAML

description: Using Python with YAML


code:
Import('env')

env.Object("test.cpp")
env.Object("sdl_test.cpp")

rawDescription: scons: objects, sources, executables, all in separate directories

description: Scons: objects, sources, executables, all in separate directories


rawDescription: Python: extract Cyrillic string from EXIF


code: subset = table[np.in1d(table.IDs, id_list)]

rawDescription: Numpy table - advanced multiple criteria selection


code: find_path(dct, next_, depth)

rawDescription: Mutable Default Argument Returns None

description: Mutable Default Argument Returns None


code:
import operator
new_list = [reduce(operator.mul, lst, 1) for lst in zip(a, b, c)]

rawDescription: How to multiple each object of several lists in Python

description: Multiple each object of several lists in Python


code:
d.get('hi')
d.get('come')    # nothing
d.get('welcome')

rawDescription: Search list: match only exact word/string


code:
#!/usr/bin/env python

import glob
import os

for i in glob.glob(u'*.txt'):
  os.unlink (i)

rawDescription: os.unlink multiple file in python

description: Os.unlink multiple file in python


rawDescription: Decode HTML entities in Python string?

description: Decode HTML entities in Python string


rawDescription: python collecting data from dataframe at specific row location

description: Python collecting data from dataframe at specific row location


code:
from Products.Five.browser import BrowserView
from plone.scale.scale import scaleImage
from plone.scale.storage import AnnotationStorage
from webdav.common import rfc1123_date
from zope.annotation import IAttributeAnnotatable
from zope.interface import alsoProvides

class PortraitScalingView(BrowserView):

    def __call__(self):
        form = self.request.form
        size = form.get('size', form.get('s', None))
        if size is None:
            # return original - no scaling required
            return self.context.index_html(self.request, self.request.RESPONSE)
        else:
            size = int(size)

        if not IAttributeAnnotatable.providedBy(self.context):
            alsoProvides(self.context, IAttributeAnnotatable)

        storage = AnnotationStorage(self.context, self.context.modified)
        scale = storage.scale(self.scale_factory,
                              width=size,
                              height=size)

        response = self.request.RESPONSE
        response.setHeader('Last-Modified', rfc1123_date(scale['modified']))
        response.setHeader('Content-Type', scale['mimetype'])
        response.setHeader('Content-Length', len(scale['data']))
        response.setHeader('Accept-Ranges', 'bytes')
        return scale['data']

    def scale_factory(self, **parameters):
        return scaleImage(self.context.data, **parameters)

rawDescription: Plone: get Portrait from getPersonalPortrait() scales with @@images or else


code: Entry.objects.extra(where=["weekdays & %s"], params=[WEEKDAYS.fri])

rawDescription: Representing a multi-select field for weekdays in a Django model


code:
from collections import OrderedDict
od = OrderedDict()
with open("match.txt") as f:
    key = next(f)
    for line in f:
        if line.startswith(("a","b")):
            od.setdefault(key,[]).append(line)
        else:
            key = line

rawDescription: I want to list up string in python followed example


rawDescription: Python Hexadecimal

description: Python Hexadecimal


code: sum( magnitude(x[i]-x[i+1]) for i in range(len(points)-1) )

rawDescription: how to calculate arc length of the arc consisting of 3D points in opencv using python?

description: Calculate arc length of the arc consisting of 3D points in opencv using python


rawDescription: Regarding ascii and python packing

description: Regarding ascii and python packing


rawDescription: Does Python import statement also import dependencies automatically?


code:
In [54]: os.getcwd()
Out[54]: '/tmp'

In [55]: os.path.join(os.getcwd(), 'foo')
Out[55]: '/tmp/foo'

In [56]: os.path.join(os.getcwd(), '/foo/bar')
Out[56]: '/foo/bar'

rawDescription: Why does os.path.join throw away arguments?


code:
df.columns.names = df.columns[0]
del df[df.columns[0]]
df

rawDescription: Read csv file with many named column labels with pandas


code:
library(sos)
findFn('Venn diagramm')

rawDescription: Using R or Matplotlib (Python), how can I create a venn diagram based on value comparisons for each row of a CSV file?


rawDescription: Pandas DataFrame: How to natively get minimum across range of rows and columns


code:
class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=50)
    body = models.TextField()

class PostImage(models.Model):
    image = models.ImageField(
        upload_to='<path_from_s3_tutorial>'
    )
    width_x = models.IntegerField()
    width_y = models.IntegerField()

    # Foreign Key to Post
    post = models.ForeignKey('Post', null=True, blank=True)

rawDescription: What is the right way to attach multiple images to a post? [Django]


code: "qwerty.".replace('.', '', 1) # 1 -> replace count (only once)

rawDescription: Python Regex sub on single character

description: Python Regex sub on single character


code: [[u'12', u'F5684', u'20182', u'VELOCITY SOLUTIONS INC.', u'EQPRAN77717', u'RANPAK FILLPAK TT 2', u'W/UNIVERSAL STAND S/N 51345563', u'1', u'51345563'], [u'Grand Total']]

rawDescription: Python & BS4: Exclude blank and Grand Total Row


rawDescription: Parse FB Graph API date string into python datetime


code: x = np.arange(100).reshape(10, 10)

rawDescription: Mask numpy array using intervals

description: Mask numpy array using intervals


code:
class foo:
    def bar(self):
        print(__class__)

rawDescription: How to make super() work by manually filling the __class__ cell?

description: Make super() work by manually filling the __class__ cell


code:
import operator

dictionary = {
    'Louie Scored': [3, 5, 2],
    'Thomas Scored': [8, 4]
}

averages = {}

for user_info, v in dictionary.items():
    average = float(sum(v))/len(v)
    averages[user_info] = average

sorted_averages = sorted(averages.items(), key=operator.itemgetter(1), reverse=True)
for user_name, average in sorted_averages:
    print ("{} average score {}".format(user_name, average))

rawDescription: How to find an average of a key with multiple values?

description: Find an average of a key with multiple values


code:
for job in jobList:
     jobIDs = GroupResult.restore(job)
     results = jobIDs.get()

rawDescription: Celery - One task calls a smaller task n times with different parameters


rawDescription: Zero padding between values in Python

description: Zero padding between values in Python


code:
import matplotlib.pyplot as plt
fig = plt.figure()

magnetValues = [i/50 for i in range(24)]
for i in magnetValues:
    plt.axvline(i)

plt.xlim(0,1)
plt.ylim(0,1)

def pick(event):
    if event.xdata: # ???
        nearestMagnetValue = min(magnetValues, key=lambda x: abs(event.xdata - x))
        plt.ion()
        plt.hlines(event.ydata,nearestMagnetValue-0.01,nearestMagnetValue+0.01,colors='r',linestyle='solid')
    else:
        pass

fig.canvas.mpl_connect('button_press_event',pick)
plt.show()

rawDescription: Plot hlines on fixed x values when click happens between x values


code:
inds = range(len(Questions))
random.shuffle(inds)
print(Questions[inds[0]])
...
print(Answers[inds[0]])

rawDescription: Python - Lists checking if something has been randomised already


code:
# Constants in Chudnovsky's series
CHUD_A = MPZ(13591409)
CHUD_B = MPZ(545140134)
CHUD_C = MPZ(640320)
CHUD_D = MPZ(12)

def bs_chudnovsky(a, b, level, verbose):
    """
    Computes the sum from a to b of the series in the Chudnovsky
    formula. Returns g, p, q where p/q is the sum as an exact
    fraction and g is a temporary value used to save work
    for recursive calls.
    """
    if b-a == 1:
        g = MPZ((6*b-5)*(2*b-1)*(6*b-1))
        p = b**3 * CHUD_C**3 // 24
        q = (-1)**b * g * (CHUD_A+CHUD_B*b)
    else:
        if verbose and level < 4:
            print("  binary splitting", a, b)
        mid = (a+b)//2
        g1, p1, q1 = bs_chudnovsky(a, mid, level+1, verbose)
        g2, p2, q2 = bs_chudnovsky(mid, b, level+1, verbose)
        p = p1*p2
        g = g1*g2
        q = q1*p2 + q2*g1
    return g, p, q

@constant_memo
def pi_fixed(prec, verbose=False, verbose_base=None):
    """
    Compute floor(pi * 2**prec) as a big integer.
    This is done using Chudnovsky's series (see comments in
    libelefun.py for details).
    """
    # The Chudnovsky series gives 14.18 digits per term
    N = int(prec/3.3219280948/14.181647462 + 2)
    if verbose:
        print("binary splitting with N =", N)
    g, p, q = bs_chudnovsky(0, N, 0, verbose)
    sqrtC = isqrt_fast(CHUD_C<<(2*prec))
    v = p*CHUD_C*sqrtC//((q+CHUD_A*p)*CHUD_D)
    return v

rawDescription: How does sympy calculate pi?

description: How does sympy calculate pi


code: OrderedDict([('launchers', OrderedDict([('say hello', OrderedDict([('command', 'echo "hello" | festival --tts'), ('icon', 'shebang.svg')])), ('say world', OrderedDict([('command', 'echo "world" | festival --tts'), ('icon', 'shebang.svg')])), ('say date', OrderedDict([('command', 'date | festival --tts')]))]))])

rawDescription: How could I read a Markdown list into a Python OrderedDict?


code:
with open('mypasswords.txt') as fh:
    for line in fh:
        ...

rawDescription: Connection to wi-fi using python

description: Connection to wi-fi using python


code:
r = re.compile(r"^\s+", re.MULTILINE)
r.sub("", "a\n b\n c") # "a\nb\nc"

# or without compiling (only possible for Python 2.7+ because the flags option
# didn't exist in earlier versions of re.sub)

re.sub(r"^\s+", "", "a\n b\n c", flags = re.MULTILINE)

# but mind that \s includes newlines:
r.sub("", "a\n\n\n\n b\n c") # "a\nb\nc"

rawDescription: Python: use regular expression to remove the white space from all lines


code:
import numpy as np
a = np.zeros((2, 2, 3)) # 2x2 matrix, 3 variants for each element
a[0, 0] = [0, 1, 2] # filling one element of the "matrix"
a[0, 1] = 1
a[1, 1] = 0 # this
a[1, 0] = 0 # and this are "all zeros"
a

rawDescription: How to modify specific field in ndarray matrix

description: Modify specific field in ndarray matrix


rawDescription: Count the occurence of specific number from column // convert column data to list


code:
delta = included.date - prev_dates
delta = delta.astype("timedelta64[D]")
delta

rawDescription: Pandas days between in a single column

description: Pandas days between in a single column


code:
import re
match = re.match( r'(disc|dis|se|oti)(\d+)\s', line)

rawDescription: How can I check for specific strings in python?

description: Check for specific strings in python


rawDescription: Python: Load CSV, first column as row names, first row as column names


code:
timeit.timeit('foowrap([1,2])', setup='from __main__ import foowrap', number=10000000)
timeit.timeit('foo([1,2])', setup='from __main__ import foo', number=10000000) # this is your lambda term

rawDescription: A performance concern when using minimizing a two-parameter function with scipy


code:
import pyodbc
from unittest.mock import patch

with patch("pyodbc.connect") as mock_connect:
    pyodbc.connect("Credentials")
    mock_connect.assert_called_with("Credentials")

rawDescription: Mocking pyodbc module calls for django unit tests


code:
import re

def decode(s):
    for c, n in re.findall(r'(\w)(\d+)', s):
        yield c * int(n)

rawDescription: python encoder and decoder

description: Python encoder and decoder


code:
import pytumblr
client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)
# Now that you're established, look at the client.create_video method.
client.create_video(**kwargs)

rawDescription: How can I post to Tumblr an embedded video using the Tumblr API?

description: Post to Tumblr an embedded video using the Tumblr API


rawDescription: How to calculate a column in a Row using two columns of the previous Row in Spark Data Frame?

description: Calculate a column in a Row using two columns of the previous Row in Spark Data Frame


code:
with open("data.txt", "r") as your_file:
    lines = your_file.readlines()

lines = ''.join(line.strip() for line in lines)
lines = ''.join(letter for letter in lines if letter.isalpha())

char_per_line = 5

result = [lines[i:i+char_per_line] for i in range(0, len(lines), char_per_line)]

rawDescription: Load text file into single string and table


code: foo, bar = DELETEMIN( bar )

rawDescription: Python classes -- mutability

description: Python classes -- mutability


rawDescription: Python: Iterate over two dictionaries that has lists as its values


rawDescription: Intersection of 2d and 1d Numpy array

description: Intersection of 2d and 1d Numpy array


rawDescription: Python: how to create a function pointer with a set argument?


code:
class _mystring(object):

    __metaclass__ = abc.ABCMeta

    @partialAP
    @abc.abstractmethod
    def str(self):
        pass

    @str.setter
    def str(self,value):
        self._str = value

class uppercase(_mystring):

    @_mystring.str.getter
    def str(self):
        return self._str.upper()

rawDescription: Inheriting setter, overwriting getter in python abstract class


code:
def main(num_days=5):
    sales = []
    print('Enter the sales for each day.')
    for day in range(num_days):
        sales.append(float(input("Sales for day #{}: ".format(day+1))))
    print('the total is', sum(sales))

main()

rawDescription: Creating a list of integers, adding the list and displaying the sum


code:
def map_args(func):
    @functools.wraps(func)
    def wrapper(**kwargs):
        all_args = dict(request.args, **kwargs)
        return func(**all_args)

    return wrapper

rawDescription: Pythonic way to access Flask request arguements


code:
for year, month in itertools.product(range(2000, 2017), range(1, 13)):
    requests.get(base_url.format(month=month, year=year))

rawDescription: Scraping URLs using BeautifulSoup

description: Scraping URLs using BeautifulSoup


code:
if not hasattr(ctypes, 'get_errno'):
    # Python 2.5 or older
    if sys.platform == 'win32':
        standard_c_lib._errno.restype = ctypes.POINTER(ctypes.c_int)
        def _where_is_errno():
            return standard_c_lib._errno()

    elif sys.platform in ('linux2', 'freebsd6'):
        standard_c_lib.__errno_location.restype = ctypes.POINTER(ctypes.c_int)
        def _where_is_errno():
            return standard_c_lib.__errno_location()

    elif sys.platform in ('darwin', 'freebsd7'):
        standard_c_lib.__error.restype = ctypes.POINTER(ctypes.c_int)
        def _where_is_errno():
            return standard_c_lib.__error()
    ctypes.get_errno = lambda: _where_is_errno().contents.value

rawDescription: Access to errno from Python?

description: Access to errno from Python


code:
import imp # Standard module to do such things you want to.

# We can import any module including standard ones:
os1=imp.load_module('os1', *imp.find_module('os'))

# Here is another one:
os2=imp.load_module('os2', *imp.find_module('os'))

# This returns True:
id(os1)!=id(os2)

rawDescription: How to make a copy of a python module in runtime?

description: Make a copy of a python module in runtime


rawDescription: Python weekday() for getting Sunday as 1 & Saturday as 7


code:
import re
pat = re.compile(r'(?:/bdata:/b)?\w$')
string = " dnfhndkn data: ndknfdjoj pop"
res = re.search(pat,string)
res
res.group()

rawDescription: regex to match a word and everything after it?

description: Regex to match a word and everything after it


rawDescription: Difference in text file saved manually and with Python codecs : Lemur Malformed document


code:
import pandas as pd
import matplotlib.pyplot as plt

#import your data here

#Plot a histogram of frequencies
df.country.value_counts().plot(kind='barh')
plt.title('Number of appearances in dataset')
plt.xlabel('Frequency')

rawDescription: Unable to pie-plot my data in pandas python


code:
A = K.dot(np.array([Y, Z]).transpose())
B = K.dot(np.array([X]).transpose())

rawDescription: Loops to minimize function of arrays in python


code:
def random_id2(x):
    return np.random.choice(x['ID2'], p=x['Conversion Rate'].values)

rawDescription: Random sampling and Pandas dataframes

description: Random sampling and Pandas dataframes


code: self.tail.next = self.tail = Element(element, None)

rawDescription: Issue with Python implementation of assignment chaining


rawDescription: Finding a ratio to multiply RGB values by to get multiple tints of a color in Python


rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
class Prototype(object):
    def __init__(self, **attrs):
        self.__dict__.update(attrs)

def myobj():
    count = 0
    def addOne(n):
        return n + 1
    def addOneTimesTwo(n):
        """This is like a 'bound' method. The self in this context will refer to the same
        Prototype even if this function is transferred to a different Prototype."""
        return self.addOne(n) * 2
    self = Prototype(**locals())
    return self

myObj = myobj()
assert myObj.addOneTimesTwo(1) == 4

rawDescription: Effective closures in python

description: Effective closures in python


rawDescription: Converting CSV data to list in dictionary


code: pd.melt(frame, id_vars=['genotype', 'environment'], value_vars=['Base', 'State23', 'State42', 'End'])

rawDescription: How to melt/stack a 2-factorial multivariate DataFrame from wide to long format?

description: Melt/stack a 2-factorial multivariate DataFrame from wide to long format


code:
def twoDigits(x):
    return int(100*x)/100.0

rawDescription: defining precision in python(2.6) division

description: Defining precision in python(2.6) division


code:
_period_context_fmt = r"""
    \S*                          # some word material
    %(SentEndChars)s             # a potential sentence ending
    \s*                       #  <-- THIS is what I changed
    (?=(?P<after_tok>
        %(NonWord)s              # either other punctuation
        |
        (?P<next_tok>\S+)     #  <-- Normally you would have \s+ here
    ))"""

rawDescription: Preserve empty lines with NLTK's Punkt Tokenizer


code:
from urlparse import urljoin

import requests
from bs4 import BeautifulSoup

base_url = "http://advances.sciencemag.org"
response = requests.get(base_url)
soup = BeautifulSoup(response.content, "lxml")

headlines = soup.find_all(class_="highwire-cite-linked-title")
for headline in headlines:
    print(urljoin(base_url, headline["href"]))

rawDescription: Scraping a page for URLs using Beautifulsoup


code:
class MyClass:

  def _method(self):
    "I have a docstring, but I won't be published"
    return 'done'

rawDescription: Using Sphinx's autodoc with Zope 2 (docstring issue)