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

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

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


code:
qry = (session.query(Movie)
        .filter(~Movie.possessions.any(Possession.master_id == master_id))
        .order_by(desc(Movie.id))
        )
movies = qry.all()

rawDescription: translate from SQL to SQLAlchemy

description: Translate from SQL to SQLAlchemy


rawDescription: lxml: Append 'None' or Null value when html tag text content is None

description: Lxml: Append 'None' or Null value when html tag text content is None


code:
if validUser:
        context = {'validUser': validUser}
        return request, 'userform/success.html', context

rawDescription: Unable to Render Django Template using Method


code:
def main():
    for filename in sys.argv[1:]:
        run_validation(filename)

def run_validation(filename):
    # import all "built-in" names for validations
    from mychecks import tag_equals, etc
    execfile(filename, locals())

if __name__ == '__main__':
    main()

rawDescription: Writing declarative configuration checks in Python?


code:
import re

with open("test","r+") as t:
  data = t.read()
  for m in re.finditer("apples_", data):
    t.seek(m.start())
    t.write("lettuce")

rawDescription: Using 'r+' mode to overwrite a line in a file with another line of the same length


rawDescription: Check if a character equals quotes in python


code: reduce(lambda x,y: x.combine_first(y), [df1, df2, df3])

rawDescription: Combinatorial explosion while merging dataframes in pandas


code: {k:round(v,2) if isinstance(v,float) else v for k,v in d.iteritems()}

rawDescription: Printing a mixed type dictionary with format in python


code:
import csv

class CsvWriterPipeline(object):
    @classmethod
    def from_crawler(cls, crawler):
        settings = crawler.settings
        file_name = settings.get("FILE_NAME")
        return cls(file_name)

    def __init__(self, file_name):
        header = ["URL"]
        self.csvwriter = csv.writer(open(file_name, 'wb'))
        self.csvwriter.writerow(header)

    def process_item(self, item, internallinkspider):
        # build your row to export, then export the row
        row = [item['url']]
        self.csvwriter.writerow(row)
        return item

rawDescription: Pass file_name argument to pipeline for csv export in scrapy


code:
def allpaths(source_node, sink_node):
    if source_node == sink_node: # Handle trivial case
        return frozenset([(source_node,)])
    else:
        result = set()
        for new_source in source_node.children:
            paths = allpaths(new_source, sink_node, memo_dict)
            for path in paths:
                path = (source_node,) + path
                result.add(path)
        result = frozenset(result)
        return result

rawDescription: list of all paths from source to sink in directed acyclic graph

description: List of all paths from source to sink in directed acyclic graph


code:
def count_borrowed_equipment_per_user(self):
    nb_bikes = Bike.objects.filter(lender=self.user).count()
    nb_helmets = Helmet.objects.filter(lender=self.user).count()
    nb_gloves = Glove.objects.filter(lender=self.user).count()
    return nb_bikes, nb_helmets, nb_gloves

rawDescription: Django OneToMany design?

description: Django OneToMany design


code:
import wxversion
wxversion.select("2.8")
import wx
import wx.media

import itertools as IT
import os

IMAGE_DIR = os.path.expanduser('~/tmp/images')
SOUND_DIR = os.path.expanduser('~/tmp/sounds')

class MainWindow(wx.Frame):

    title = "Main Menu"

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Window', size=(1000, 700))
        panel = wx.Panel(self, -1)
        self.SetBackgroundColour(wx.Colour(100, 100, 100))
        self.Centre()
        self.Show()

        status = self.CreateStatusBar()

        menubar = wx.MenuBar()
        filemenu = wx.Menu()
        exitmenu = filemenu.Append(wx.NewId(), "Exit", "Exit Program")

        menubar.Append(filemenu, "File")
        self.Bind(wx.EVT_MENU, self.onExit, exitmenu)
        self.SetMenuBar(menubar)

        font1 = wx.Font(
            30, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas')

        Text1 = wx.StaticText(panel, -1, "Rhythm Trainer", (10, 15))
        Text1.SetFont(font1)
        Text1.SetForegroundColour('white')

        btn1 = wx.Button(panel, label='Basic', pos=(100, 200), size=(150, 50))
        btn1.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))

        self.Bind(wx.EVT_BUTTON, self.newwindow, btn1)

        btn2 = wx.Button(
            panel, label='Advanced', pos=(100, 270), size=(150, 50))
        btn2.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))

        btn3 = wx.Button(
            panel, label='Notations', pos=(100, 340), size=(150, 50))
        btn3.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))

        btn4 = wx.Button(
            panel, label='Settings', pos=(100, 410), size=(150, 50))
        btn4.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))

        btn5 = wx.Button(panel, label="Quit", pos=(820, 550), size=(150, 50))
        btn5.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))
        self.Bind(wx.EVT_BUTTON, self.OnClick, btn5)

    def OnClick(self, event):
        self.Close()

    def OnQuitButton(self, event):
        wx.Sleep(1)
        self.Destroy()

    def onExit(self, event):
        self.Destroy()

    def newwindow(self, event):
        secondWindow = Window2(parent=None, id=-1)
        secondWindow.Show()
        self.Close()

class Window2(wx.Frame):

    title = "new Window"

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Window2', size=(1000, 700))
        panel = wx.Panel(self, -1)

        self.SetBackgroundColour(wx.Colour(100, 100, 100))
        self.Centre()
        self.Show()

        status = self.CreateStatusBar()

        menubar = wx.MenuBar()
        filemenu = wx.Menu()
        exitmenu = filemenu.Append(wx.NewId(), "Exit", "Exit Program")

        menubar.Append(filemenu, "File")
        self.Bind(wx.EVT_MENU, self.onExit, exitmenu)
        self.SetMenuBar(menubar)

        font2 = wx.Font(
            30, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas')

        Text2 = wx.StaticText(panel, -1, "Rhythm Trainer", (10, 15))
        Text2.SetFont(font2)
        Text2.SetForegroundColour('white')
        self.Show(True)

        btn1 = wx.Button(panel, label="Back", pos=(820, 550), size=(150, 50))
        btn1.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))
        self.Bind(wx.EVT_BUTTON, self.OnClick, btn1)

        btn2 = wx.Button(panel, label="Play", pos=(820, 100), size=(150, 50))
        btn2.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))
        self.Bind(wx.EVT_BUTTON, self.onPlaySound, btn2)

        btn3 = wx.Button(panel, label="Stop", pos=(820, 150), size=(150, 50))
        btn3.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))
        self.Bind(wx.EVT_BUTTON, self.onStopSound, btn3)

        btn4 = wx.Button(panel, label="Next", pos=(820, 200), size=(150, 50))
        btn4.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, u'Consolas'))
        self.Bind(wx.EVT_BUTTON, self.loadImage, btn4)
        self.panel = wx.Panel(self, -1, pos=(50, 50), size=(800, 200))

        self.images = IT.cycle(
            [filename for filename in os.listdir(IMAGE_DIR)
             if any(filename.lower().endswith(ext)
                    for ext in ('.png', '.jpg', '.jpeg'))])
        self.image_file = next(self.images)

        img = wx.EmptyImage(240,240)
        self.imageCtrl = wx.StaticBitmap(self.panel, wx.ID_ANY,
                                         wx.BitmapFromImage(img), pos=(200, 50))

    def loadImage(self, event):
        self.image_file = next(self.images)
        print(self.image_file)
        image_file = os.path.join(IMAGE_DIR, self.image_file)
        img = wx.Image(image_file, wx.BITMAP_TYPE_ANY)
        img = img.Scale(240,240)
        # The idea of using imageCtrl.SetBitmap comes from
        # http://www.blog.pythonlibrary.org/2010/03/26/creating-a-simple-photo-viewer-with-wxpython/
        self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))

    def onPlaySound(self, event):
        sound_file, ext = os.path.splitext(self.image_file)
        sound_file = os.path.join(SOUND_DIR, sound_file + '.wav')
        print(sound_file)
        sound = wx.Sound(sound_file)
        sound.Play(wx.SOUND_ASYNC)

    def onStopSound(self, event):
        wx.Sound.Stop()

    def onExit(self, event):
        self.Destroy()
        wx.Sound.Stop()

    def OnClick(self, event):
        wx.Sound.Stop()
        self.Close()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MainWindow(parent=None, id=-1)
    app.MainLoop()

rawDescription: wxPython Button to load multiple images

description: WxPython Button to load multiple images


code:
import jsonpath_rw as jp
obj = {'y':{'x':1,'g':{'t':0}}}
jp.parse('`parent`.g').find(jp.parse("y.x").find(obj)[0])[0].value

rawDescription: jsonpath_rw for Python: How to navigate relatively?

description: Jsonpath_rw for Python: How to navigate relatively


code:
with open(fileName, 'br+') as f:
    for number in numbers:
        f.write(bytes(splitNumber(number)))

rawDescription: Python writing binary

description: Python writing binary


rawDescription: Calculate CRC-CCITT (0xFFFF) for HEX string


code:
row_iterator = df.iterrows()
_, last = row_iterator.next()  # take first item from row_iterator
for i, row in row_iterator:
    print(row['value'])
    print(last['value'])
    last = row

rawDescription: iterrows pandas get next rows value

description: Iterrows pandas get next rows value


rawDescription: Getting rid of parentheses after dictionary intersection


code:
set_property(driver, 'Alpha', 5)
set_property(driver, 'Width division', 15)

rawDescription: How to automate webpage span control like slider values by using like driver. findElement_by_xpath () , Ubuntu Linux and chromium Autotest

description: Automate webpage span control like slider values by using like driver. findElement_by_xpath () , Ubuntu Linux and chromium Autotest


code:
d = dict(zip(nodes.Label, nodes.Id))
d

rawDescription: Replacing Names with Index From Separate File using Pandas


code:
Output
b'\xf0\x9f\x98\x8a\r\n'

rawDescription: Decode poweshell output possibly containing non-ascii unicode characters into a python string


code:
# python representation of my_type
class my_type(object):
    def __init__(self, name, value, key):
        self.name = name
        self.value = value
        self.key = key

rawDescription: Passing in Oracle custom user types from Python/Django


code:
def differenciate(coefficients):
    return [c * (len(coefficients) - i) for i, c in enumerate(coefficients[:-1])]

rawDescription: Horner's method to return P(x) and its derivative


code:
def function(x,y,z):
    return x+y+z

rawDescription: Reading multiple numbers from a text file


code:
fig2 = plt.figure(figsize=(8, 6))
ax3 = fig2.add_subplot(211)

rawDescription: creating and referencing separate matplotlib plots

description: Creating and referencing separate matplotlib plots


code: mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql --defaults-file=credentials.cnf"

rawDescription: Supplying password to wrapped-up MySQL

description: Supplying password to wrapped-up MySQL


code:
from collections import Counter
count = Counter(df['time'])
df['count'] = df['time'].apply(lambda x: count[x])

rawDescription: Timeseries Resampling

description: Timeseries Resampling


code:
tree = etree.XML('<c/>TAIL<d><e><f/></e></d>')
node_b = tree.xpath('/a/b')[0]
node_d = tree.xpath('/a/d')[0]
node_d.append(node_b)
etree.tostring(tree)

rawDescription: Move an entire element in with lxml.etree


rawDescription: How do I send data from JS to Python with Flask?

description: Send data from JS to Python with Flask


code:
import sys
from subprocess import Popen, PIPE

L = [2, 7, 1] # numbers to be squared
p = Popen([sys.executable or 'python', 'square.py'], stdin=PIPE, stdout=PIPE,
          universal_newlines=True, bufsize=-1)
answers = map(int, p.communicate("\n".join(map(str, L)))[0].splitlines())

rawDescription: How to Achieve Continuous Interactive Dialog with a Subprocess in Python?


code:
from lxml import etree

parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse('thread_group.xml', parser)

for e in tree.xpath('//*'):
    name = e.get('name')
    if name == 'LoopController.loops':
        e.text = '10+10'
    elif name == 'ThreadGroup.num_threads':
        e.text = '1000+1000'

print(etree.tostring(tree, pretty_print=True))

rawDescription: Find and replace value in XML (dynamically)


code:
for line in file:
    line = line.rstrip('\n')

rawDescription: Copy/write line on to another file with minor change on the line


code: my_id = next(c)

rawDescription: return constantly changing variable python

description: Return constantly changing variable python


code:
def recur_method(self, key=None, val=None):
    if key is None and val is None:
       raise exception("You fail it")

rawDescription: Generic arguments in recursive functions: terrible habit?


code: lb = preprocessing.MultiLabelBinarizer(classes=("new york","london","England"))

rawDescription: Using MultilabelBinarizer on test data with labels not in the training set


code:
from itertools import product

values = [1, 2, 3]
[[num * mul for num, mul in zip(values, combo)]
 for combo in product([1, -1], repeat=len(values))]

rawDescription: create list with negative value permutation

description: Create list with negative value permutation


code:
from bs4 import BeautifulSoup

data = """

Field1:" Value1"

Field2:" Value2"

Field3:" Value3"

Field4:" Value4"

Field5:" Value5"

"""
soup = BeautifulSoup(data, 'html.parser')

for b in soup.find_all("b"):
    label = b.get_text(strip=True)
    value = b.next_sibling.strip()

    print(label, value)

rawDescription: Parsing text after bold tag using XPath

description: Parsing text after bold tag using XPath


code:
def get_value(arg):
    self.arg = arg
    if arg == 0:
        self.window.btn_submit.connect(check_value)
        self.window.exec_()

rawDescription: Returning value from QObject's method that uses signals


rawDescription: OpenCV-Python: What is correct shape of points for finding epipolar lines?


code:
class Contact(object):
  def __init__(self, name, address, age, phone, ctype):
    self.name = name,
    self.address = address
    self.age = age
    self.phone = phone
    self.ctype = ctype

# Read off the first line of your data file.
fh = open('contacts.txt')
count = int(fh.readline())

Contacts = [Contact(*c) for c in [[next(fh) for i in range(5)] for j in range(count)]]

rawDescription: Creating list of Class Objects

description: Creating list of Class Objects


rawDescription: Selenium python click button

description: Selenium python click button


code:
import ast
ast.literal_eval("0x123")
ast.literal_eval("012")
ast.literal_eval("36#foo")

rawDescription: How to convert any numeric string value in int?

description: Convert any numeric string value in int


code:
class SimpleKivy(App):
    big_dict = DictProperty({'ch1':False,'ch2':False,'ch3':False,'ch4':False})

rawDescription: How to create a dynamic kivy app with checkboxes?

description: Create a dynamic kivy app with checkboxes


code:
import csv
reader = csv.DictReader(open(file, "rb"), dialect="excel") # Python 2.x
# Python 3: reader = csv.DictReader(open(file, newline=""), dialect="excel")

rawDescription: Python script reading from a csv file

description: Python script reading from a csv file


code: x = 'foo'

rawDescription: Constants - How do you know what a constant is?


code: {x:c[x] for x in keys}

rawDescription: numpy - how do I count the occurrence of items in nested lists by index?

description: Numpy - how do I count the occurrence of items in nested lists by index


code:
from __future__ import division # this must be the very first import statement
xx = set(x)
yy = set(y)
score = sum(i*w(i) for i in xx & yy) / sum(i * w(i) for i in x)

rawDescription: Syntax of Mathemathical formula in Python


code: result = np.abs(b[:, None] - a[None, :])

rawDescription: Euclidean Distance Between All Points in an 2 Vectors


code:
from PIL import Image
from PIL import ImageChops
image1 = Image.open("image1.jpg") # no cats
image2 = Image.open("image2.jpg") # with cats

image = ImageChops.subtract(image2, image1)

mask1 = Image.eval(image, lambda a: 0 if a <= 24 else 255)
mask2 = mask1.convert('1')

blank = Image.eval(image, lambda a: 0)

new = Image.composite(image2, blank, mask2)
new.show()

rawDescription: PIL remove background image from image

description: PIL remove background image from image


rawDescription: python list tree indexing

description: Python list tree indexing


rawDescription: how to retrieve field value (values are itself string)in given line using regular expression in python

description: Retrieve field value (values are itself string)in given line using regular expression in python


code:
class AppIndex(indexes.SearchIndex, indexes.Indexable):

    ngram_text = indexes.EdgeNgramField()

    def prepare(self, obj):
        """Add the content of text field from final prepared data into ngram_text field
        """
        prepared_data = super(AppIndex, self).prepare(obj)
        prepared_data['ngram_text'] = prepared_data['text']
        return prepared_data

rawDescription: Matching only some words in query using Django Haystack


rawDescription: Django related_table() with extra()

description: Django related_table() with extra()


code:
class Article(Base):
    ...
    name = Column(Text, nullable=False, unique=True)
    ...

    @validates('name')
    def validate_name(self, key, value):
        assert value != ''
        return value

rawDescription: Validation in SQLAlchemy

description: Validation in SQLAlchemy


code:
selmodel = self.listing.selectionModel()
selmodel.selectionChanged.connect(self.handleSelectionChanged)

rawDescription: How to react to keyboard selection on QtTreeView?

description: React to keyboard selection on QtTreeView


rawDescription: Regex returning <_s instead of decimal value


code:
import lxml.etree
import lxml.html

doc = lxml.html.fromstring("
")
body = doc.find('body')
body.tag = "body-not"
print(lxml.etree.tostring(doc))

rawDescription: How to rename a node with Python LXML?

description: Rename a node with Python LXML


code:
pageIndex = 1
while True:  # Keep looping through all pages
    # Navigate to the search page
    browser.get("https://www.houz.com/page_num="+ str(pageIndex))
    time.sleep(6)

    links = browser.find_elements_by_css_selector('div > h3 > a')
    jobs = browser.find_elements_by_css_selector('div > div.description')

    for link, title in zip(links, jobs):
        url = link.text
        jobtitle = title.text

        with open("1Exportdata.csv", "a") as csvFile:
            csvFile.write(url + "," + jobtitle + "\n")

    pageIndex += 1
    if pageIndex == 5010:
        browser.close()

rawDescription: How to Print the information using selenium

description: Print the information using selenium


code: proc.pid # returns the id of process

rawDescription: Stop a command line command in script

description: Stop a command line command in script


code:
gen = email.generator.Generator(out)  # create a generator
gen.flatten(msg)   # write the message to the file object

rawDescription: Saving to .msg file in Python, or alternatively, sending mail to the file system


code:
import logging
import mylib
logger = logging.getLogger(__name__)

def main():
    logging.basicConfig(format='%(asctime)s %(module)s %(levelname)s: %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
    logger.info('Started')
    mylib.do_something()
    logger.info('Finished')

if __name__ == '__main__':
    main()

rawDescription: Is it better to use root logger or named logger in Python


code:
def strip_blanks(f):
    def decorated_func(*args, **kwargs):
        # Strip blanks from non-keyword arguments
        new_args = [ " ".join(arg.split()) for arg in args]
        # Strip blanks from keyword arguments
        new_kwargs = { key:" ".join(arg.split()) for key,arg in kwargs.items()}
        # Pass the modified arguments to the decorated function
        # And forward its result in case needed
        return f(*new_args, **new_kwargs)
    return decorated_func

@strip_blanks
def func(a, b, c):
    for i in a, b, c:
        print(i)

rawDescription: What is the proper way to loop through the required keyword arguments of a function and perform the same action on each of their values?


code:
def proxy_wrapper(name, docstring):
    def wrapper(self, *args, **kwargs):
        return self.proxy.__getattribute__(name)(*args, **kwargs)
    wrapper.__doc__ = docstring
    wrapper._is_wrapper = True
    return wrapper

class Something(object):
    def __init__(self):
        self.proxy = {}

    @classmethod
    def get_proxy_wrappers(cls):
        return [m for m in dir(cls) if hasattr(getattr(cls, m), "_is_wrapper")]

    update = proxy_wrapper("update", "wraps the proxy's update() method")
    proxy_keys = proxy_wrapper("keys", "wraps the proxy's keys() method")

rawDescription: Access a subset of functions of a Python class


code:
#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])

rawDescription: Python popen command. Wait until the command is finished


code:
import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

rawDescription: Create empty file using python

description: Create empty file using python


code:
import pandas as pd
import numpy as np
np.random.seed(1)

index = pd.date_range(start='2010-01-20 5:00', end='2010-05-20 17:00', freq='2T')
N = len(index)
df = pd.DataFrame({'val': np.random.random(N)}, index=index)
# the number of 2 second intervals in 8 days
window_size = pd.Timedelta('8D')/pd.Timedelta('2min')    # 5760.0

df['std'] = pd.rolling_std(df['val'], window=window_size)
print(df.tail())

rawDescription: Python: look back n days rolling standard deviation


code:
[path for path in glob.iglob('./' + ('[0-9]' * 14))]
[path for path in glob.iglob('./' + ('[0-9]' * 14)) if os.path.isdir(path)]

rawDescription: use python glob to find a folder that is a 14 digit number

description: Use python glob to find a folder that is a 14 digit number


code: ((self.list[L][0] == operand.list[R][0]) and op == '*') or op == '**' or op == '+' or op == '-' or (op == '/' and operand.list[R][1] != 0)

rawDescription: How to do this conditional statement?

description: Do this conditional statement


rawDescription: grouping or merging? dataframes pandas python

description: Grouping or merging? dataframes pandas python


rawDescription: How to exclude some indexes in a python loop?

description: Exclude some indexes in a python loop


code: from script import *

rawDescription: python module paths that I set have gone when I restart python

description: Python module paths that I set have gone when I restart python


code: import cPickle as pickle

rawDescription: saving the file content in the memory

description: Saving the file content in the memory


code:
class Xobject(object):

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

    def dec_me_1(self):
        print("In dec_me1")
        return 0

    def dec_me_2(self):
        print("In dec_me2")
        return 1

def decorator(func):

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

    return wrapped

x = Xobject(decorator)

x.dec_me_1()
x.dec_me_2()

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

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


code: '\n'.join('{}' for _ in range(len(myList))).format(*myList)

rawDescription: print list elements line by line - is it possible using format

description: Print list elements line by line - is it possible using format


code: Mul(x, x, evaluate=False)

rawDescription: Expanding algebraic powers in python (sympy)


rawDescription: Control Charts in Python

description: Control Charts in Python


code:
# FrozenSortedTuple Tests
a = ['a','b']
b = ['b','a']
c = ['a','b']

fa = FrozenSortedTuple(a)
fb = FrozenSortedTuple(b)
fc = FrozenSortedTuple(c)

fa == fb
fa == fc
fa == ['a','b']
fa == ['b','a']
fa == ('a','b')
fa == ('b','a')

a = set([fa, fb, fc])
b = set([fa, fb, fc])
c = set([fa, fc, fb])
a == b
b == c
fa in a
fb in b

d = set([fb])
fa in d

rawDescription: Python class: Why can't I use the method len() inside __eq__(self, other)?


code: res = np.concatenate((a[indices], a[~indices]))

rawDescription: Efficient way to sort an array with a condition


code:
i=itertools.combinations_with_replacement((1,2,3), 4)
next(i)
next(i)
next(i)
next(i)

rawDescription: List all combinations

description: List all combinations


code:
print("Most Common:", ", ".join([item for item in count_dict if count_dict[item] == maxi]))
# Most Common: duck, goose

rawDescription: Without using Counter(), how to find most common element in a list?


rawDescription: Python: Split numpy array

description: Python: Split numpy array


code:
f4 = open("genomekey2.txt", 'rb')
keygenomes = []
for keyline in f4.readlines():
    if keyline:
        keygenomes.append(eval(keyline.strip()))

rawDescription: Python: Why does list import using quotation marks, how can I avoid this/get rid of them?


code: from myapi.common.utils import A, B

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


rawDescription: How can I store a 2D array in python, like table in MySQL?

description: Store a 2D array in python, like table in MySQL


code:
def shift(ch, k):
    #
    # k_delta
    # ────>
    #
    # ch_delta                 k_delta
    # ────────────────────────>────>
    # a....f.........m....r....w..zab
    # ──────────────>────>         ┊
    # ch_delta       k_delta       ┊
    #                              ┊
    #                             %26

    ch_delta = ord(ch) - ord('a')
    k_delta = ord(k) - ord('a')
    return chr(ord('a') + (ch_delta + k_delta) % 26)

rawDescription: How to make shift('w','f') return 'b'?

description: Make shift('w','f') return 'b'


code:
ast=np.lib.stride_tricks.as_strided(a,a.shape*2,a.strides*2)
#ast.shape is (3, 3, 4, 3, 3, 4).

rawDescription: Numpy extract arbitrary subarray along one axis


code:
while True:
    name = input("What is your name?")
    print("Hi", name ,'!')

rawDescription: Rebooting program after input() automatically on python


code:
def memo(f):
    f.cache = {}
    def _f(*args, **kwargs):
        if args not in f.cache:
            f.cache[args] = f(*args, **kwargs)
        return f.cache[args]
    return _f

@memo
def mult_comb(factors):
    result = set()
    result.add(tuple(sorted(factors)))
    for i, f1 in enumerate(factors):
        factors2 = list(factors[:i] + factors[i+1:])
        for k in range(i, len(factors2)):
            factors2[k] *= f1
            result.update(mult_comb(tuple(factors2)))
            factors2[k] /= f1
    return result

rawDescription: Return the different multiplicative combinations of a list of numbers in Python


code:
file_like_object = io.BytesIO(my_zip_data)
zipfile_ob = zipfile.ZipFile(file_like_object)

rawDescription: Python in-memory zip library

description: Python in-memory zip library


rawDescription: Simpler way to concatenate 3 or more lists in Numpy


rawDescription: Regular expression in python to capture first operator


code: {'word3_1': 'word3', 'word3_3': 'word3', 'word3_2': 'word3', 'contr': 'contracting', 'contract': 'contracting', 'contractor': 'contracting', 'contra': 'contracting', 'identify': 'identification', 'contractors': 'contracting', 'word3_n': 'word3', 'ID': 'identification'}

rawDescription: Python: normalizing a text file

description: Python: normalizing a text file


code:
set1, set2 = set(Arr1), set(Arr2)
set1 - set2

rawDescription: Pythonic way to write for x in Y and not in Z


code:
with open("seq2.txt", "a") as f:
    f.write( "\n".join([header, seq, new_disorder]))

rawDescription: How to align disorder region and sequence in a larger scale (python)

description: Align disorder region and sequence in a larger scale (python)


code:
if out['acknowledged'] is 1:
    while not all_acknowledged(dict): # custom function to check whether all users have made an acknowledgement
        ack = out['acknowledged_by']
        for k in dict:
            if ack in k:
                acked = dict[k]
                dict[k]['ack'] = True #We must update this when we come across an acknowledged user
                t = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M')
                print (acked + " acknowledged at " + t)
        v = requests.get("https://api.pushover.net/1/receipts/"+ d + ".json?token=" + app)
        out = v.json() #update the out, so you can check again

rawDescription: python acknowlage in pushover using dict

description: Python acknowlage in pushover using dict


code:
def foo(x):
    if x:
        pass
    else:
        return x+2

rawDescription: How about 'empty if statement' in python


rawDescription: Deleting and inserting a score into a text file form python


rawDescription: Searching a Pandas series using a string produces a KeyError


code:
my_dictionary = {'foo' : 10, 'bar' : 20}

variable = my_dictionary['foo']
new_variable = 0 # Get the value from another place
my_dictionary['foo'] += new_variable

rawDescription: How do I assign a dictionary value to a variable in Python?

description: Assign a dictionary value to a variable in Python


rawDescription: OpenCV & Python: quickly superimpose mask over image without overflow


rawDescription: Where is the sqlite database file created by Django?


code: df_big = pd.concat([df1, df2, df3], axis=1)

rawDescription: reading multiple csv file into a big pandas data frame by appending the columns of different size

description: Reading multiple csv file into a big pandas data frame by appending the columns of different size


code:
# twoscoops/conf/envs/current.py
"""
Imports the proper settings, based on the deployment environment's name (set
as an environment variable), defaulting to local settings.
"""
import os

from django.core.exceptions import ImproperlyConfigured

# Environments (these can be called anything you want)
ENV_LOCAL = 'local'
ENV_PROD = 'prod'
DEPLOYMENT_ENVS = (ENV_LOCAL, ENV_PROD)

# Get the deployment environment's name from the os environment
DEPLOYMENT_ENV = os.getenv('DJANGO_DEPLOYMENT_ENV', ENV_LOCAL)

# Ensure the deployment env's name is valid
if DEPLOYMENT_ENV not in DEPLOYMENT_ENVS:
    raise ImproperlyConfigured(
        u'Invalid `DJANGO_DEPLOYMENT_ENV`: {d}'.format(d=DEPLOYMENT_ENV)
    )

# Import env-specific settings

if DEPLOYMENT_ENV == ENV_LOCAL:
    # Local, native testing
    from twoscoops.conf.envs.local import *

if DEPLOYMENT_ENV == ENV_PROD:
    # Production
    from twoscoops.conf.envs.prod import *

rawDescription: how to import the custormed settings.py variable in django project?

description: Import the custormed settings.py variable in django project


code:
IMAP_HOST = "imap.mail.outlook.com"
IMAP_PORT = 993
TEST_HOST = "test.com"
TEST_PORT = 666
s1 = fn_connect(IMAP_HOST, IMAP_PORT, 2)
s2 = fn_connect(TEST_HOST, TEST_PORT, 1)
#and so on....

rawDescription: Python's 2.7 socket.timeout behavior

description: Python's 2.7 socket.timeout behavior


code:
from django.db.models import Sum
Post.objects.annotate(vote_total=Sum('vote__value')).order_by('-vote_total')

rawDescription: Order by dig-like rating in django

description: Order by dig-like rating in django


code: logger = logging.getLogger()

rawDescription: Defining python loggers for shared modules


code:
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
        args = [iter(iterable)] * n
        return izip_longest(fillvalue=fillvalue, *args)

for x, y in grouper(seq, 2):
    print [x, y]

rawDescription: Iterate every 2 elements from list at a time


code:
data="""Spec 2 Included : TRUE
Spec 2 Label: 19-Flat2-HS3
Spec 3 Included : FALSE
Spec 3 Label: 4-1-Bead1-HS3"""

#data=open("data.txt").read()

import re

data=dict(re.findall('(Spec \d+ (?:Included|Label))\s*:\s*(\S+)',data))

rawDescription: Editing the XML texts from a XML file using Python


code: all_links = soup.select('p a[href]')

rawDescription: How to find all links in all paragraphs in Beautiful Soup

description: Find all links in all paragraphs in Beautiful Soup


rawDescription: Mysterious bytes in GZIP (bytestream) compression Python3


code: ' '.join([''.join(sorted(word)) for word in sentence.split()])

rawDescription: Python lambda to print formatted nested list


code: runTimerAround(test, 3, 4, 5);

rawDescription: sandwich pattern in javascript code

description: Sandwich pattern in javascript code


rawDescription: Accessing / modifying submatrix of sparse scipy matrix


code:
from collections import Counter
with open(file) as f:
    c = Counter()
    for x in f:
        c += Counter(x.strip())

rawDescription: Count frequency of letters in a text file


code: getattr(o, "A")(1)

rawDescription: Call a method of an object with arguments in Python


code:
#!/usr/bin/env python3
import os
import time
from datetime import datetime, timezone

os.environ['TZ'] = 'Australia/Adelaide'
time.tzset()
print(datetime.now(timezone.utc).astimezone())
# -> 2015-09-25 05:02:52.784404+09:30

rawDescription: Python subprocess.call issue

description: Python subprocess.call issue


code:
column_lengths = [len(x) for x in longest_per_column]

model = RandomForest.trainRegressor(
    categoricalFeaturesInfo=dict(enumerate(column_lengths)),
    maxBins=max(column_lengths),
    # ...
    )

rawDescription: How to select certain columns from a csv file in pyspark based on the list of index of columns and then determine their distinct lengths

description: Select certain columns from a csv file in pyspark based on the list of index of columns and then determine their distinct lengths


code:
import pandas as pd
df = pd.read_csv('GOLD.csv', parse_dates='Date', index_col='Date', sep='\s+')
df2 = pd.read_csv('SPX.csv', parse_dates='Date', index_col='Date', sep='\s+')
result = pd.concat([df, df2], keys=['GOLD', 'SPX'], names=['ticker']).unstack('ticker')
result = result.reorder_levels([1, 0], axis=1).sortlevel(level=0, axis=1)
print(result)

rawDescription: pandas - merging multiple DataFrames

description: Pandas - merging multiple DataFrames


code: df = pd.DataFrame([[1,2,3]]*2, index=['ColA', 'ColB']).T

rawDescription: Pandas data-frame creation as permutations of 2 series?


code:
ticks = np.arange(min_logx, max_logx, 1)
ticklabes = [r"$10^{}$".format(tick) for tick in ticks]

pl.yticks(ticks, ticklabels)

rawDescription: Aspect ratio in semi-log plot with Matplotlib


code:
import tokenize
import io

def nocomment(s):
    result = []
    g = tokenize.generate_tokens(io.BytesIO(s).readline)
    for toknum, tokval, _, _, _  in g:
        # print(toknum,tokval)
        if toknum != tokenize.COMMENT:
            result.append((toknum, tokval))
    return tokenize.untokenize(result)

with open('script.py','r') as f:
    content=f.read()

print(nocomment(content))

rawDescription: python regex to remove comments

description: Python regex to remove comments


code: d *= e[:,np.newaxis,np.newaxis]

rawDescription: multiply array of matrices by a vector

description: Multiply array of matrices by a vector


code:
m = CCollection()
m.a = CCollection()
m.a.b = CCollection()
m.a.b.x = 1
m.a.b.y = 2
m.a.c = 3
m.d = 4

m.print_tree("m")
m.a.print_tree("m.a")
m.a.b.print_tree("m.a.b")

rawDescription: Printing all the attributes in a class

description: Printing all the attributes in a class


code:
x = "John Marry Joseph"
print(re.sub("([^\s]+)", "\\1@company.com", x))

rawDescription: Python regex - extend string

description: Python regex - extend string


code: isinstance(other,Number) #from numbers import Number

rawDescription: Override __mul__ from a child class using parent implementation: leads to problems


rawDescription: Python array manipulation

description: Python array manipulation


code:
sys.stdout.write("Bart: ")
sys.stdout.write(str(id))
sys.stdout.write(" ")

rawDescription: Python Increment Int variable in a String


code:
#! /usr/bin/env python3

"""Provide a GUI for easy interactions with Multichat servers.

This program is an example of a first attempt at implementing a client
for interacting with a Multichat server through purely graphical means."""

__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '11 October 2012'
__version__ = 1, 0, 0

################################################################################

from tkinter.messagebox import *
from tkinter.constants import *
from safetkinter import *
import logging
import traceback
import _thread
import socket
import os
import traceback
import sys
import threadbox

################################################################################

class SimpleClient(Frame):

    "SimpleClient(master, **kw) -> SimpleClient instance"

    @classmethod
    def main(cls):
        "Create a GUI root and demonstrate the SimpleClient widget."
        root = Tk()
        root.title('Chat Client')
        root.minsize(675, 450)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.bind_all('<Control-Key-a>', cls.handle_control_a)
        frame = cls(root)
        frame.grid(sticky=NSEW)
        root.mainloop()

    @staticmethod
    def handle_control_a(event):
        "Process Ctrl-A commands by widget type."
        widget = event.widget
        if isinstance(widget, Text):
            widget.tag_add(SEL, 1.0, END + '-1c')
            return 'break'
        if isinstance(widget, Entry):
            widget.selection_range(0, END)
            return 'break'

    def __init__(self, master, **kw):
        "Initialize the SimpleClient instance with the widgets it contains."
        super().__init__(master, **kw)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        # Build Widgets
        self.output_area = ScrolledText(self, width=25, height=4, wrap=WORD)
        self.input_area = Entry(self)
        self.corner = Sizegrip(self)
        # Place Widgets
        self.output_area.grid(row=0, column=0, columnspan=2, sticky=NSEW)
        self.input_area.grid(row=1, column=0, sticky=EW)
        self.corner.grid(row=1, column=1, sticky=SE)
        # Setup Widgets
        self.output_area['state'] = DISABLED
        self.input_area.bind('<Return>', self.send)
        self.after_idle(self.connect)

    def connect(self):
        "Try connecting to a server to begin chatting."
        self.connection = Connector(self, 'Chat Client').connection
        if self.connection is None:
            self._root().destroy()
        else:
            self.connection.setblocking(False)
            self.after_idle(self.update)

    def send(self, event):
        "Send a message across the connection from the given widget."
        self.connection.sendall(event.widget.get().encode() + b'\r\n')
        event.widget.delete(0, END)

    def update(self):
        "Update the output area with any incoming messages."
        self.output_area['state'] = NORMAL
        try:
            self.output_area.insert(END, self.connection.recv(1 << 12).decode())
        except socket.error:
            pass
        else:
            self.output_area.see(END)
        finally:
            self.output_area['state'] = DISABLED
        self.after(100, self.update)

################################################################################

def start_thread(function, *args, **kwargs):
    "Start a new thread of execution while logging any errors."
    _thread.start_new_thread(log_errors, (function, args, kwargs))

def log_errors(function, args=(), kwargs={}):
    "Execute a function with its arguments and log any exceptions."
    try:
        function(*args, **kwargs)
    except SystemExit:
        pass
    except:
        basename = os.path.basename(sys.argv[0])
        filename = os.path.splitext(basename)[0] + '.log'
        logging.basicConfig(filename=filename)
        logging.error(traceback.format_exc())

################################################################################

class Dialog(Toplevel): # Copies tkinter.simpledialog.Dialog

    "Dialog(parent, title=None) -> Dialog instance"

    def __init__(self, parent, title=None):
        "Initialize a Dialog window that takes focus away from the parent."
        super().__init__(parent)
        self.withdraw()
        if parent.winfo_viewable():
            self.transient(parent)
        if title:
            self.title(title)
        self.parent = parent
        self.result = None
        body = Frame(self)
        self.initial_focus = self.body(body)
        body.grid(sticky=NSEW, padx=5, pady=5)
        self.buttonbox()
        if not self.initial_focus:
            self.initial_focus = self
        self.protocol('WM_DELETE_WINDOW', self.cancel)
        if self.parent is not None:
            self.geometry('+{}+{}'.format(parent.winfo_rootx() + 50,
                                          parent.winfo_rooty() + 50))
        self.deiconify()
        self.initial_focus.focus_set()
        try:
            self.wait_visibility()
        except tkinter.TclError:
            pass
        else:
            self.grab_set()
            self.wait_window(self)

    def destroy(self):
        "Destruct the Dialog window."
        self.initial_focus = None
        super().destroy()

    def body(self, master):
        "Create the body of this Dialog window."
        pass

    def buttonbox(self):
        "Create the standard buttons and Dialog bindings."
        box = Frame(self)
        w = Button(box, text='OK', width=10, command=self.ok, default=ACTIVE)
        w.grid(row=0, column=0, padx=5, pady=5)
        w = Button(box, text='Cancel', width=10, command=self.cancel)
        w.grid(row=0, column=1, padx=5, pady=5)
        self.bind('<Return>', self.ok)
        self.bind('<Escape>', self.cancel)
        box.grid()

    def ok(self, event=None):
        "Validate and apply the changes made by this Dialog."
        if not self.validate():
            self.initial_focus.focus_set()
            return
        self.withdraw()
        self.update_idletasks()
        try:
            self.apply()
        finally:
            self.cancel()

    def cancel(self, event=None):
        "Close the Dialong window and return to its parent."
        if self.parent is not None:
            self.parent.focus_set()
        self.destroy()

    def validate(self):
        "Verify that the Dialog is in a valid state."
        return True

    def apply(self):
        "Make any changes the Dialog wishes to accomplish."
        pass

################################################################################

class Connector(Dialog):

    "Connector(parent, title=None) -> Connector instance"

    def body(self, master):
        "Customize the Dialog window with some custom widgets."
        self.connection = None
        self.resizable(False, False)
        # Build Widgets
        self.prompt = Label(master, text='Enter server IP address:')
        self.address = Entry(master)
        # Place Widgets
        self.prompt.grid(sticky=W, padx=30, pady=2)
        self.address.grid(sticky=W, padx=30)

    def buttonbox(self):
        "Redefine the buttons at the bottom of the window."
        w = Button(self, text='Connect', width=10, command=self.ok,
                   default=ACTIVE)
        w.grid(sticky=E, padx=5, pady=5)
        self.bind('<Return>', self.ok)
        self.bind('<Escape>', self.cancel)

    def validate(self):
        "Ask a Consumator to make a connection with the given address."
        c = Consumator(self, 'Chat Client', (self.address.get(), 8989))
        if c.connection is None:
            Message(self, icon=WARNING, type=OK, title='Warning',
                    message='Could not connect to address!').show()
            return False
        self.connection = c.connection
        return True

################################################################################

class Consumator(Dialog):

    "Consumator(parent, title, address) -> Consumator instance"

    def __init__(self, parent, title, address):
        "Initialize the Consumator with the server's address."
        self.server_address = address
        super().__init__(parent, title)

    def body(self, master):
        "Create the widgets for this Dialog and start the connection process."
        self.connection = None
        self.resizable(False, False)
        # Build Widgets
        self.message = Label(master, text='Trying to connect to address ...')
        self.progress = Progressbar(master, orient=HORIZONTAL)
        # Place Widgets
        self.message.grid(sticky=W, padx=10, pady=2)
        self.progress.grid(sticky=EW, padx=10, pady=2)
        # Setup Widgets
        self.progress.configure(mode='indeterminate', maximum=30)
        self.progress.start()
        result = []
        start_thread(self.connect, result)
        self.after_idle(self.poll, result)

    def buttonbox(self):
        "Cancel the creation of the buttons at the bottom of this Dialog."
        pass

    @threadbox.MetaBox.thread
    def connect(self, result):
        "Try connecting to the server address that was given."
        try:
            result.append(socket.create_connection(self.server_address, 10))
        except socket.timeout:
            result.append(None)

    def poll(self, result):
        "Find out if the any connection information is available yet."
        if result:
            self.connection = result[0]
            self.cancel()
        else:
            self.after(100, self.poll, result)

################################################################################

if __name__ == '__main__':
    log_errors(SimpleClient.main)

rawDescription: Send/sync variable/text over LAN in Python 3


code: var1, var2 = divmod(delta_ms,1000);mins,secs,ms = divmod(var1,60) + (var2,)

rawDescription: An elegant one-line solution to extract data from Nested Tuples from divmod


code: codons = [file_data[i:i+3] for i in range(0,len(file_data),3)]

rawDescription: count the number of a certain triplet in a file (DNA codon analysis)

description: Count the number of a certain triplet in a file (DNA codon analysis)


code:
min_idx = np.argmin(A,axis=1)
min_val = A[np.arange(A.shape[0]),min_idx]

rawDescription: Efficiently getting numpy.argmin and numpy.amin at the same time


code: [sum(cols) for cols in zip(*j)]

rawDescription: Quick way to sum the ith item of a list of lists in python


code:
ch = logging.StreamHandler()
fh = MyFileHandler('file.log')

ch_formatter = logging.Formatter('%(asctime)s - %(levelname)-4s - '
                                 '%(message)s',
                                 datefmt='%Y.%m.%d_%H:%M:%S_%Z')
fh_formatter = logging.Formatter('%(asctime)s - %(levelname)-4s - '
                                 '%(message)s',
                                 datefmt='%Y.%m.%d_%H:%M:%S_%Z')

ch.setFormatter(ch_formatter)
fh.setFormatter(fh_formatter)
logger.addHandler(ch)
logger.addHandler(fh)

rawDescription: How to decorate console logger messages in Python?

description: Decorate console logger messages in Python


code: #2 Peak RAM consumption: 0.164 GB

rawDescription: Split of numpy array into unequal chunks


code:
from itertools import cycle
color = cycle(['r', 'g', 'b', 'c', 'm', 'y', 'k'])
next(color)

rawDescription: Color and Line writing using MatPlotLib

description: Color and Line writing using MatPlotLib


rawDescription: How to know if a data contains non-ascii character?

description: Know if a data contains non-ascii character


code: print(*(url + "?" + str(guid) for guid in sampleguid), sep="\n")

rawDescription: List to string and for loop

description: List to string and for loop


rawDescription: Proxying variables in Python

description: Proxying variables in Python


code:
import pandas as pd
import numpy as np

rawDescription: How do I take a column of pandas data based on a scalar condition AND a column comparison?

description: Take a column of pandas data based on a scalar condition AND a column comparison


code:
def shrink(data, rows, cols):
    return data.reshape(rows, data.shape[0]/rows, cols, data.shape[1]/cols).sum(axis=1).sum(axis=2)

rawDescription: Reduce resolution of array through summation


code:
class MyClass(object):
    # This works (slow)
    query = select(...).where(...).order_by('distance').limit(1)
    ...

    @classmethod
    def issue_query(cls, **params):
        cls.engine.execute(cls.query, params)

rawDescription: Is there a way to make SQLAlchemy pre-compile a query?


code:
from ctypes import *
from ctypes.wintypes import *

kernel32 = WinDLL('kernel32', use_last_error=True)
advapi32 = WinDLL('advapi32', use_last_error=True)

SE_PRIVILEGE_ENABLED = 0x00000002
TOKEN_ALL_ACCESS = 0x000F0000 | 0x01FF

class LUID(Structure):
    _fields_ = (('LowPart',  DWORD),
                ('HighPart', LONG))

class LUID_AND_ATTRIBUTES(Structure):
    _fields_ = (('Luid',       LUID),
                ('Attributes', DWORD))

class TOKEN_PRIVILEGES(Structure):
    _fields_ = (('PrivilegeCount', DWORD),
                ('Privileges', LUID_AND_ATTRIBUTES * 1))
    def __init__(self, PrivilegeCount=1, *args):
        super(TOKEN_PRIVILEGES, self).__init__(PrivilegeCount, *args)

PDWORD = POINTER(DWORD)
PHANDLE = POINTER(HANDLE)
PLUID = POINTER(LUID)
PTOKEN_PRIVILEGES = POINTER(TOKEN_PRIVILEGES)

def errcheck_bool(result, func, args):
    if not result:
        raise WinError(get_last_error())
    return args

kernel32.CloseHandle.argtypes = (HANDLE,)

kernel32.GetCurrentProcess.errcheck = errcheck_bool
kernel32.GetCurrentProcess.restype = HANDLE

# https://msdn.microsoft.com/en-us/library/aa379295
advapi32.OpenProcessToken.errcheck = errcheck_bool
advapi32.OpenProcessToken.argtypes = (
    HANDLE,  # _In_  ProcessHandle
    DWORD,   # _In_  DesiredAccess
    PHANDLE) # _Out_ TokenHandle

# https://msdn.microsoft.com/en-us/library/aa379180
advapi32.LookupPrivilegeValueW.errcheck = errcheck_bool
advapi32.LookupPrivilegeValueW.argtypes = (
    LPCWSTR, # _In_opt_ lpSystemName
    LPCWSTR, # _In_     lpName
    PLUID)   # _Out_    lpLuid

# https://msdn.microsoft.com/en-us/library/aa375202
advapi32.AdjustTokenPrivileges.errcheck = errcheck_bool
advapi32.AdjustTokenPrivileges.argtypes = (
    HANDLE,            # _In_      TokenHandle
    BOOL,              # _In_      DisableAllPrivileges
    PTOKEN_PRIVILEGES, # _In_opt_  NewState
    DWORD,             # _In_      BufferLength
    PTOKEN_PRIVILEGES, # _Out_opt_ PreviousState
    PDWORD)            # _Out_opt_ ReturnLength

def enable_privilege(privilege):
    hToken = HANDLE()
    luid = LUID()
    advapi32.LookupPrivilegeValueW(None, privilege, byref(luid))
    try:
        advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
                                  TOKEN_ALL_ACCESS,
                                  byref(hToken))
        tp = TOKEN_PRIVILEGES()
        tp.Privileges[0].Luid = luid
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
        advapi32.AdjustTokenPrivileges(hToken, False,
                                       byref(tp),
                                       sizeof(tp),
                                       None, None)
    finally:
        if hToken:
            kernel32.CloseHandle(hToken)

def disable_privilege(privilege):
    hToken = HANDLE()
    luid = LUID()
    advapi32.LookupPrivilegeValueW(None, privilege, byref(luid))
    try:
        advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
                                  TOKEN_ALL_ACCESS,
                                  byref(hToken))
        tp = TOKEN_PRIVILEGES()
        tp.Privileges[0].Luid = luid
        tp.Privileges[0].Attributes = 0
        advapi32.AdjustTokenPrivileges(hToken, False,
                                       byref(tp),
                                       sizeof(tp),
                                       None, None)
    finally:
        if hToken:
            kernel32.CloseHandle(hToken)

rawDescription: Find the path of every running process in Python


rawDescription: efficient way to count the element in a dictionary in Python using a loop

description: Efficient way to count the element in a dictionary in Python using a loop


code: A.reshape((-1, 3, 3)).swapaxes(-1, 1).reshape(A.shape)

rawDescription: Transposing arrays in an array

description: Transposing arrays in an array


code:
models.py
class Post(MPTTModel):
    poster = models.ForeignKey(User)
    content = models.TextField(verbose_name='Text', max_length=1000)
    parent = models.TreeForeignKey('self', null=True, blank=True, related_name='children')
    class MPTTMeta:
        order_insertion_by = ['poster']

rawDescription: Loading tree of relations at once

description: Loading tree of relations at once


code:
for k,v in cn.items():
    print("[{}][{}]".format(k,v))

[thus][2]
[count][1]
[one][2]
[once][2]
[this][1]

rawDescription: Counting number of strings in a List with Python


code: df = pd.concat([df1, df2], join='inner', ignore_index=True)

rawDescription: Pandas: merging two dataframes and retaining only common column names


code:
im2 = np.zeros(lattice.shape + (4,))
im2[:, :, 3] = lattice # assuming lattice is already a bool array

imshow(im2)

rawDescription: Making image white space transparent, overlay onto imshow()


code:
class Breakfast(object):
    @classmethod
    def from_eggs(cls, eggs):
        obj = cls()
        obj.spam, obj.eggs = 5, eggs
        return obj

    @classmethod
    def from_spam_and_eggs(cls, spam, eggs):
        obj = cls()
        obj.spam, obj.eggs = spam, eggs
        return obj

rawDescription: Multiple constructors in python, using inheritance


code:
fin = vec[(1-T.isinf(vec)).nonzero()]
f = theano.function([vec], fin)

f([1,2,np.inf])
array([ 1.,  2.])

rawDescription: Remove inf from Theano array

description: Remove inf from Theano array


code:
import inspect
orig_members = []
for name, ref in inspect.getmembers(o):
  orig_members.append(name)
...

rawDescription: Restore Python class to original state

description: Restore Python class to original state


code: df['Vehicle Class'].shift()

rawDescription: How to plot selective data from a text file?

description: Plot selective data from a text file


code:
import sys
import trace

class MyTrace(trace.Trace):
    def __init__(self, *args, **kwargs):
        trace.Trace.__init__(self, *args, **kwargs)
        self.enabled = False

    def localtrace_trace_and_count(self, *args, **kwargs):
        if not self.enabled:
            return None
        return trace.Trace.localtrace_trace_and_count(self, *args, **kwargs)

tracer = MyTrace(ignoredirs=[sys.prefix, sys.exec_prefix],)

def main():
    a = 1
    tracer.enabled = True
    a = 2
    tracer.enabled = False
    a = 3

# run the new command using the given tracer
tracer.run('main()')

rawDescription: How to check which part of app is consuming CPU?

description: Check which part of app is consuming CPU


code: r"([bcdfghjklmnpqrstvwxz][aeiou])+"

rawDescription: Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant


rawDescription: Pythonic way of manipulating nested list into nested chunked list


code:
from wand.image import Image

with Image(filename="rose:") as rose:
    x = 0
    chunk_size = 10
    while True:
        try:
            with rose[x:x+chunk_size, 0:rose.height] as chunk:
                chunk.save(filename='rose_{0}.png'.format(x))
                x += chunk_size
        except IndexError:
            break

rawDescription: Slice image with Wand

description: Slice image with Wand


rawDescription: Get the object with the max attribute's value in a list of objects


rawDescription: add string to first item in list of list of strings in python

description: Add string to first item in list of list of strings in python


code:
input = [10, ["ETSc", "Juniper Hairstreak"], ["ETSc", "Spotted Turtle"], ["ETSc", "Blanding's Turtle"], "IWWH"]
output = [elt[0] + " (" + elt[1] + ")" if type(elt) == list and elt[0] == "ETSc" else str(elt) for elt in input]
output

rawDescription: setting a condition for a mixed list

description: Setting a condition for a mixed list


code:
from multiprocessing import Queue
from multiprocessing.managers import SyncManager

HOST = ''
PORT0 = 5011
PORT1 = 5012
PORT2 = 5013
AUTHKEY = 'authkey'

name0 = 'qm0'
name1 = 'qm1'
name2 = 'qm2'

description = 'Queue Server'

def CreateQueueServer(HOST, PORT, AUTHKEY, name = None, description = None):
    name = name
    description = description
    q = Queue()

    class QueueManager(SyncManager):
        pass

    QueueManager.register('get_queue', callable = lambda: q)
    QueueManager.register('get_name', callable = name)
    QueueManager.register('get_description', callable = description)
    manager = QueueManager(address = (HOST, PORT), authkey = AUTHKEY)
    manager.start() # This actually starts the server

    return manager

# Start three queue servers
qm0 = CreateQueueServer(HOST, PORT0, AUTHKEY, name0, description)
qm1 = CreateQueueServer(HOST, PORT1, AUTHKEY, name1, description)
qm2 = CreateQueueServer(HOST, PORT2, AUTHKEY, name2, description)

raw_input("return to end")

rawDescription: Python multiprocessing RemoteManager under a multiprocessing.Process


rawDescription: best way to make nested lists?

description: Make nested lists


code: UserSizer.Add( lowerSizer, 0, 0, 5 )

rawDescription: How to remove blank area between sizers in wxPython

description: Remove blank area between sizers in wxPython


rawDescription: How can I get the number of records that reference a particular foreign key in Django?

description: Get the number of records that reference a particular foreign key in Django


code:
x = func # note: no ()
x() # calls func()
y = x() # y is now 7

rawDescription: What does it mean when you assign int to a variable in Python?


code:
for folder in directories:
    citation = os.path.join(folder, "citation.txt")
    sys.stdout = open(citation, "w")

rawDescription: How to open multiple directories and read the files inside

description: Open multiple directories and read the files inside


code:
if e.type is KEYDOWN and e.key == K_w:
    pygame.display.set_mode(size)
if e.type is KEYDOWN and e.key == K_f:
    pygame.display.set_mode(size, FULLSCREEN)

rawDescription: How can I exit Fullscreen mode in Pygame?

description: Exit Fullscreen mode in Pygame


code:
import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def tearDown(self):
        self.widget.dispose()
        self.widget = None

    def test_default_size(self):
        self.assertEqual(self.widget.size(), (50,50),
                     'incorrect default size')

    def test_resize(self):
        self.widget.resize(100,150)
        self.assertEqual(self.widget.size(), (100,150),
                     'wrong size after resize')

rawDescription: call different methods in unittest according to input arguments

description: Call different methods in unittest according to input arguments


code:
df = pd.io.parsers.read_csv('temp.csv', header = [0,1], tupleize_cols = True)
df.columns = [c for _, c in df.columns[:3]] + [c for c in df.columns[3:]]
df = df.set_index(list(df.columns[:3]), append = True)
df.columns = pd.MultiIndex.from_tuples(df.columns, names = ['hour', 'field'])

rawDescription: Multiindex only some of columns in Pandas


code:
from collections import Counter
c=Counter(l)
[i for i in c if c[i]<(0.1*len(l))]

rawDescription: How do you tally the amount of times a item in appears from a randomly list?

description: Tally the amount of times a item in appears from a randomly list


code:
def blitSpecial(surf):
    surf.blit()

rawDescription: Python and Pygame: Avoiding creating display surface twice


code:
from django.shortcuts import render_to_response
from django.template import RequestContext

from models import Location

def view(request):
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        return render_to_response('object_list.html', {'object_list': locs}, context_instance=RequestContext(request))
    return render_to_response('base.html', {'object_list': locs}, context_instance=RequestContext(request))

rawDescription: How to return json dictionary in django ajax update

description: Return json dictionary in django ajax update


code: foo = None

rawDescription: Python: How to check if a variable has been already declared


code:
import sys
import math
import ctypes

bitness = 1 << round(math.log2(round(math.log2(sys.maxsize + 1))))
ctypes.WinDLL('ANSI{}.DLL'.format(bitness))

rawDescription: Ansicon doesn't install from python but only from cmd


code:
def get_selected_index(self):
    return self._treeView.get_cursor()[0][0]

rawDescription: Is it possible to unpack a tuple in Python without creating unwanted variables?


rawDescription: Encode and assemble multiple features in PySpark


code:
def routeapp(obj):
    for kw in dir(app):
        attr = getattr(app, kw)
        if hasattr(attr, 'route'):
            bottle.route(attr.route)(attr)

class App(object):
    def __init__(self, config):
        self.config = config

    def index(self):
        pass
    index.route = '/index/'

app = App({'config':1})
routeapp(app)

rawDescription: Bottle framework and OOP, using method instead of function


code:
class Foo(object):
    @property
    def age(self):
        return 11

class Bar(Foo):
    @property
    def age(self):
        return 44

rawDescription: python properties and inheritance

description: Python properties and inheritance


code:
folders = ['fepu', 'mpu', 'sbmu']

def mk_needle(folder_name):
    return "ls: cannot access %s/*.elf: No such file or directory" % folder_name

with open(logfilePath) as f:
    contents = f.read()
    if any(mk_nedele(fname) in contents for fname in folders):
        ...

rawDescription: How to cut short a long 'if' statement with multiple logical AND in Python?

description: Cut short a long 'if' statement with multiple logical AND in Python


rawDescription: Removing numbers.

description: Removing numbers.


code: dir(B)

rawDescription: pls help - error message "no attribute 'renderContents'"

description: Pls help - error message "no attribute 'renderContents'"


rawDescription: matplotlib PdfPages compounding images

description: Matplotlib PdfPages compounding images


code: [m for e in engine.engines for m in e.modules]

rawDescription: Python nested select on named property

description: Python nested select on named property


code: d["doChoice"]["exp"] = "return (dosomething if argE > 0 else dosomethingElse) + argF"

rawDescription: How to don't evaluate both functions in list choice if/else alternative?

description: Don't evaluate both functions in list choice if/else alternative


code:
def get_object_list(self, request):
     return super(FollowingPhoto, self).get_object_list(request).filter(photographer__user__in = request.user.relationships.following()).exclude(photographer__user__in=request.user.relationships.blocking())

rawDescription: How can I implement blocking using Django-relationships?

description: Implement blocking using Django-relationships


code: selected = fields.Boolean(search='_search_dummy', store=False)

rawDescription: Activate a field in a form, via boolean checkmarks - Odoo v8


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

x = np.linspace(0,9,10)
y = x ** 2
plt.plot(x,y,"b-")
plt.fill_between(x,y,color="red")
maxy = plt.ylim()[1]
plt.fill_between(x,y,maxy,color="green")
plt.show()

rawDescription: Plotting a curve with different background colors in python


code:
df2 = df.pivot_table(index='id', columns='order', aggfunc='size', fill_value=0)
df2

rawDescription: Pandas: How to groupby and get a count of uniques in a given column?


code:
import tornado.platform.asyncio as tasyncio
from tornado import testing
from tornado import web

class Handler(web.RequestHandler):
    async def post(self):
        await asyncio.sleep(0.1)
        self.write('spam')

    get = put = post

class HandlerTest(testing.AsyncHTTPTestCase):
    def get_app(self):
        return web.Application([('/', Handler)])

    def get_new_ioloop(self):
        return tasyncio.AsyncIOMainLoop()

    def test_get(self):
        response = self.fetch('/', method='GET')
        self.assertEqual(b'spam', response.body)

    def test_put(self):
        response = self.fetch('/', method='PUT', body=b'')
        self.assertEqual(b'spam', response.body)

    def test_post(self):
        response = self.fetch('/', method='POST', body=b'')
        self.assertEqual(b'spam', response.body)

import unittest
unittest.main()

rawDescription: Can only perform GET requests in Tornado test


code:
idx = np.where(variance > 0.5 * np.max(variance))

X_min = np.min(X[idx])
# -14.0
X_max = np.max(X[idx])
# 15.0

rawDescription: Filter an array based on density

description: Filter an array based on density


code:
with open(filename) as input_file:
    biography = input_file.readlines()[4:]

rawDescription: Python: How do you read a chunk of text from a file without knowing how long the file actually is?


code:
from __future__ import division, print_function
import math
import multiprocessing as mp
from scipy.spatial.distance import cosine
from operator import itemgetter
import itertools

def worker(enumerated_comps):
    return [(ind, cosine(artist_topic_probs[a], artist_topic_probs[b])) for ind, (a, b) in enumerated_comps]

def slice_iterable(iterable, chunk):
    """
    Slices an iterable into chunks of size n
    :param chunk: the number of items per slice
    :type chunk: int
    :type iterable: collections.Iterable
    :rtype: collections.Generator
    """
    _it = iter(iterable)
    return itertools.takewhile(
        bool, (tuple(itertools.islice(_it, chunk)) for _ in itertools.count(0))
    )

# Test data
artist_topic_probs = [range(10) for _ in xrange(10)]
comps = tuple(enumerate([(1, 2), (1, 3), (1, 4), (1, 5)]))

n_cores = 2
chunksize = int(math.ceil(len(comps)/n_cores))
jobs = tuple(slice_iterable(comps, chunksize))

pool = mp.Pool(processes=n_cores)
work_res = pool.map_async(worker, jobs)
c_dists = map(itemgetter(1), sorted(itertools.chain(*work_res.get())))
print(c_dists)

rawDescription: Parallelizing array row similarity calculations in python


code:
a = [4, 5]
next(element for element in a if element in b_set)

rawDescription: Finding if any element in a list is in another list and return the first element found


rawDescription: Django substring

description: Django substring


code: ['.'.join(j[0][:4])+"/"+str(j[1])+" "+j[0][4] for j in list(zip([[str(int(i, 2)) for i in  item.split()] for item in mylist], slashes))]

rawDescription: How to make a list of Binary numbers a list of Dotted Decimal Numbers?

description: Make a list of Binary numbers a list of Dotted Decimal Numbers


code:
def move_music(source_dir, destination, dirpath, a_file):
    check = check_names(dirpath, a_file)
    dir_name = os.path.split(dirpath)[-1]
    if dir_name != source_dir:
        check_folders(destination, dir_name)
        if os.path.join(source, dir_name) not in COPIED_DIRECTORIES:
              COPIED_DIRECTORIES.append(os.path.join(source, dir_name))
        shutil.move(os.path.join(dirpath, a_file if not check[0] else check[1]),
                    os.path.join(destination , dir_name))

    else:
        shutil.move(os.path.join(dirpath, a_file if not check[0] else check[1]), destination)

def check_move(source, destination, file_extension, sub_string):
    source_dir = os.path.split(source)[-1]
    for dirpath, dirnames, filenames in os.walk(source):
        for a_file in filenames:
            if (a_file.endswith(file_extension) and sub_string in a_file):
                move_music(source_dir, destination, dirpath, a_file)

rawDescription: Cleaner way to move renamed files when walking over directory


rawDescription: python: while statment with several boolean tests

description: Python: while statment with several boolean tests


code:
class Tag:
    published = BooleanField()
    (...)

rawDescription: Get labels from check boxes in form

description: Get labels from check boxes in form


rawDescription: Cannot convert ascii to utf-8 in python

description: Cannot convert ascii to utf-8 in python


rawDescription: Inspecting data descriptor attributes in python


code:
def userNum(iterations):
    myList = []
    for _ in range(iterations):
        value = int(input("Enter a number for sound: "))
        myList.append(value)
    return myList

rawDescription: Adding multiple elements to a list in Python


rawDescription: Convert float to string with cutting zero decimals afer point in Python


code:
import subprocess

def git_commit(message):
    return subprocess.check_output(['git', 'commit',  '-m', message])

rawDescription: Python: GIT commit programmatically

description: Python: GIT commit programmatically


code:
import sys

outfile = open(sys.argv[1], 'w')
# write to the outfile
x = raw_input("What's your name?")
outfile.write(x)

rawDescription: Interactive user input while using stdout


code:
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

rawDescription: POST requests to ASP site don't bring a good result


code:
try:
    r = time.strftime("%Y%m%d",t)
    return r
except:
    pass

rawDescription: Match and change multiple date formats into one with Python Regex


rawDescription: 2D Array - Select range of columns

description: 2D Array - Select range of columns


rawDescription: How to make one json file as output in a python?

description: Make one json file as output in a python


code:
xmin, ymin = min(xvals), min(yvals)
xmax, ymax = max(xvals), max(yvals)

rawDescription: Using Python with a set of not regular point X,Y,Z in order to create a regular grid where each pixel is the minimum value of the point


rawDescription: Python: Pandas, Dataframe, Convert 1column data into 2D data format


code:
def adjacent(array,x_orig, y_orig, possible_offsets = (-1,0,1)):
    """generates all elements in 2d array around given origin"""
    for x_off in possible_offsets:
        for y_off in possible_offsets:
            ...

rawDescription: Given the indices of a 2 dimensional list, how can I get the next item over?


rawDescription: Deleting consonants from a string in Python


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

class EmailBackend(object):
    """ Authenticates against the email field of django.contrib.auth.models.User
    """

    def authenticate(self, email=None, password=None):
        # Try using the email if it is given
        if email:
            for user in User.objects.filter(email=email):
                if user.check_password(password):
                    return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

rawDescription: how do I change 'username-password login' to 'email-password login' on django-registration

description: Change 'username-password login' to 'email-password login' on django-registration


code:
df.set_index('x').\
   groupby(lambda x: (k for k,v in row_groups.iteritems() if x in v).next()).sum()

rawDescription: Group pandas df according to set

description: Group pandas df according to set


code:
import pygame

# the functions for display
def disp(phrase,loc,screen):   # function to display phrase at loc on surface.
    s = font.render(phrase, True, (255,255,255))
    screen.blit(s, loc) #

def text_display(data,surface):
    '''display your data(list/tuple),containing strings on surface'''
    for x in range(6):         # your data is in 6 X 6 grid
        for y in range(6):
            disp( data[x+(y*6)], (64*x+10,64*y+10), surface)
            # 64 is the distance between 2 strings and 10 is the offset

pygame.init()
pygame.font.init()
font = pygame.font.SysFont("Courier",36) # font initialisation
screen = pygame.display.set_mode((400,400))

text = [str(i) for i in range(36)] # raw data!
text_display(text,screen) # text is displayed
pygame.display.update() # screen updated

# Main loop, does nothing! :)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            break
    if not running:
        break

rawDescription: Python - Display Excel database in a grid


code:
from operator import itemgetter
l = sorted(l, key=itemgetter('time'), reverse=True)

rawDescription: How to sort this list in Python?

description: Sort this list in Python


code:
from django.utils import simplejson

from models import *

def island_name_choices_for_island_group(request, qs=None):
    if qs is None:
        # Change the default QS to your needs
        # (you didn't specify it)
        qs = Island.objects.all()

    if request.GET.get('island_group'):
        # assuming your Island model has an FK named island_group to model IslandGroup
        qs = qs.filter(island_group__pk=request.GET.get('island_group'))

    results = []
    for choice in qs:
        results.append((choice.pk, choice.name))

    return http.HttpResponse(simplejson.dumps(results))

rawDescription: django dynamic filtered form

description: Django dynamic filtered form


code: [sum(z) for z in zip(*tups)]

rawDescription: Adding tuples to produce a tuple with a subtotal per 'column'


code:
higher_in_rank(card('spades', 8))
higher_in_rank(card('diamonds', 6))

rawDescription: Create a function that produces a list of all cards that have a rank higher than base_card?


code:
from datetime import timedelta,datetime
strs = "2012-05-12T13:04:35.347-07:00"
#replace the last ':' with an empty string, as python UTC offset format is +HHMM
strs = strs[::-1].replace(':','',1)[::-1]

rawDescription: Convert timestamps of "yyyy-MM-dd'T'HH:mm:ss.SSSZ" format in Python


code:
from array import array
a = array('B', [1, 2, 3])
with open(path, 'wb') as byte_file:
    byte_file.write(a.tostring())

rawDescription: Python string contains byte array

description: Python string contains byte array


code:
import turtle

colors = [
    "#880000",
    "#884400",
    "#888800",
    "#008800",
    "#008888",
    "#000088",
    "#440088",
    "#880088"
]

#--------------------

def filled_arc(radius, angle, color):

    turtle.color(color)

    turtle.begin_fill()
    turtle.forward(radius)
    turtle.left(90)
    turtle.circle(radius, angle)
    turtle.left(90)
    turtle.forward(radius)
    turtle.end_fill()

    turtle.left(180-angle)

#--------------------

angle = 360/len(colors)

for color in colors:
    filled_arc(100, angle, color)
    turtle.left(angle)

rawDescription: Python: Use Multiple Colors at once in turtle


code:
{
    'anmol': {'chemistrymarks': 3, 'physicsmarks': 2, 'mathmarks': 1},
    'uppal': {'chemistrymarks': 6, 'physicsmarks': 5, 'mathmarks': 4}
}

rawDescription: How to store multiple entries for each student using dictionaries

description: Store multiple entries for each student using dictionaries


code:
def int2hex(x):
    val = hex(x)[2:] # returns something like '0x15', so we remove the '0x'
    val = "0"+val if len(val)<2 else val # make sure 2 digits
    return val

rawDescription: Convert a float to a two-digit hex number in Python


code:
ba = bytearray(foo)
ba[0]

rawDescription: Python 2 and 3 compatible method to convert bytes to integer


code:
import os
dir = os.path.dirname(__file__)
filename = os.path.join(dir, '/relative/path/to/file/you/want')

rawDescription: Relative paths in Python

description: Relative paths in Python


code: cur2.execute("SELECT  * from obs where ujd=%s;",(float(time[j]),))

rawDescription: Psycopg2 not fetching all data that exists in database


code: f <- cut(Height, 5, ordered_result = TRUE)

rawDescription: Python's barchart equivalent in R

description: Python's barchart equivalent in R


rawDescription: Infinitely Nested Dictionary in Python

description: Infinitely Nested Dictionary in Python


code:
VAR=file1
file2
file3

rawDescription: how to make subprocess called with call/Popen inherit environment variables

description: Make subprocess called with call/Popen inherit environment variables


rawDescription: Python in vs iteration for nested list

description: Python in vs iteration for nested list


code:
{'E:\\GIS_DOCUMENT\\BCAS_Map\\BCAS_All.gdb\\BCAS_BD_Infrastructure': [u'BD_Health_Infrastructures_1',
                                                                      u'BD_Railway_Establishments_1',
                                                                      u'BGD_roads_1'],
 'E:\\GIS_DOCUMENT\\BCAS_Map\\BCAS_All.gdb\\BD_Admin': [u'BGD_4_new_district',
                                                        u'BGD_3_old_district',
                                                        u'BGD_2_division',
                                                        u'BGD_1_all',
                                                        u'BGD_5_Upazilla',
                                                        u'BGD_4_old_district',
                                                        u'BGD_6_Union_court',
                                                        u'BGD_6_Union',
                                                        u'BD_exposed_coastal_area',
                                                        u'BD_drought',
                                                        u'BGD_1_River',
                                                        u'BGD_1_River_detail',
                                                        u'BD_international_bnd',
                                                        u'BGD_1_River_1',
                                                        u'BGD_7_Mauza',
                                                        u'test',
                                                        u'BGD_5_UpazillaAnno',
                                                        u'BGD_4_new_districtAnno',
                                                        u'BGD_4_new_districtAnno2']}

rawDescription: How to make a list from several nested lists

description: Make a list from several nested lists


rawDescription: Numpy: Add rows from one matrix to another by index


rawDescription: Converting flat Python Dictionary to List of Dictionaries


code:
from subproject1 import script1_main

if __name__ == "__main__":
    script1_main.main()

rawDescription: Python: sharing common code among a family of scripts


code:
def get_list_id(self):  # added method
    import os
    print("get_list_id() running in process", os.getpid())
    return id(self.nl)

rawDescription: Python multiprocessing- sharing a complex object


rawDescription: fetchall for loop multiple list to one

description: Fetchall for loop multiple list to one


rawDescription: Changing the color of the offset in scientific notation in matplotlib


code:
def are_sinonims(a, b):
    return a in synonym.get(b,[]) or b in synonym.get(a,[]) or any(a in synonym[k] and b in synonym[k] for k in synonym)

rawDescription: Python: comparing two synonyms through a dictionary


rawDescription: How can I use the replace function to change the headers in a .txt file?

description: Use the replace function to change the headers in a .txt file


code:
with open('<filename>','r') as f:
    file_list = []
    numlines = int(f.readline())
    for i, line in enumerate(f, 1):
        file_list.append(line.strip())
        if i >= numlines:
            break

rawDescription: In Python, how can I read a yet-unknown number of lines from a txt file?


code: matches = list(dict_matcher(dict1, dict2 , 2, 6, 3, 8))

rawDescription: Help using *args in tuple matching Python function


code: next((dic[k] for k in dic if k[1]=='c'), None)

rawDescription: Referencing to elements of tuples when used as keys in a python dictionary


code:
name_dict = {}
for num,name in zip(num_list,name_list):
    name_dict[num] = name

rawDescription: Create a dictionary from two lists and then print the data in python


rawDescription: Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row


code:
import time
start_time = time.time()

rawDescription: Timer in Python(simultany)

description: Timer in Python(simultany)


code: length = struct.unpack('>I', received_msg[:4])[0]

rawDescription: Python String Prefix by 4 Byte Length

description: Python String Prefix by 4 Byte Length


code:
def func_(lis):
    ind = 0
    lst = []
    for h in lis:
        lst.append((h, ind))
        ind += 1
    return lst
lis=[1,2,3,4,5]
func_(lis)

rawDescription: creating a list of tuples using for loop

description: Creating a list of tuples using for loop


code:
print(Thing.foo)
# <__main__.Field object at 0xb76cedec>

rawDescription: Use class variables as instance vars?

description: Use class variables as instance vars


code:
print(Member.__bases__)
# (<class __main__.Child at 0xb74a141c>,)

rawDescription: change the superclass of object in Python

description: Change the superclass of object in Python


code:
xl = win32com.client.GetObjec(None, "Excel.Application") #instance one
xl = win32com.client.GetObject("Name_Of_Workbook") #instance two

rawDescription: Get name of active Excel workbook from Python


rawDescription: Fetching and evaluating a Python code from an HTTP response in Python 3.X


rawDescription: Get only time data out of date and time string.


code:
from datetime import datetime
from flask import g
from sqlalchemy import Column, DateTime, String
from sqlalchemy.orm import MapperExtension

class AuditColumns(object):

    created_dt = Column(DateTime,
                        default=datetime.utcnow(),
                        nullable=False)

    created_by = Column(String(64),
                        nullable=False)

    updated_dt = Column(DateTime,
                        default=datetime.utcnow(),
                        nullable=False,
                        onupdate=datetime.utcnow())

    updated_by = Column(String(64),
                        nullable=False)

class AuditExtension(MapperExtension):

    def before_insert(self, mapper, connection, instance):
        """ Make sure the audit fields are set correctly  """
        instance.created_dt = datetime.utcnow()
        instance.created_by = g.username

        instance.updated_dt = datetime.utcnow()
        instance.updated_by = g.username

    def before_update(self, mapper, connection, instance):
        """ Make sure when we update this record the created fields stay unchanged!  """
        instance.created_dt = instance.created_dt
        instance.created_by = instance.created_by

        instance.updated_dt = datetime.utcnow()
        instance.updated_by = g.username

rawDescription: SQLAlchemy - onupdate do not override current value


code:
import random
import re
import string

def find_random_pattern(theme):
    lines = open('poempatterns.txt','r').readlines()
    stripped_lines = map(string.strip, lines)
    found_lines = filter(lambda l: re.match(".*theme=%s.*" % theme, l), stripped_lines)
    return random.choice(found_lines)

rawDescription: re.findall() doesn't matches with it's finding

description: Re.findall() doesn't matches with it's finding


code:
for i in orientation:
    newCord = firstCord[0] + i[0], firstCord[1] + i[1]

rawDescription: List Value gets updated inside an if statement even though the condition is not true


code:
class Suite(object): pass

class Heart(Suite): pass
class Club(Suite): pass

rawDescription: Python's enum equivalent

description: Python's enum equivalent


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

rawDescription: How do I make a class in Python behave with Sets?

description: Make a class in Python behave with Sets


code:
for x in range(len(p)):
    print(formula(p[x],r[x],n[x]))

rawDescription: How can I pass multiple values in a function parameter?

description: Pass multiple values in a function parameter


code: myfile = open('Stats.txt','w')

rawDescription: Making A Statistics Text File (Python)

description: Making A Statistics Text File (Python)


code:
with open('ini.txt', encoding='utf8') as data:
    section = None  # current section
    name = None     # current name being stored
    result = {}
    for line in data:
        line = line.strip()

        if not line or line.startswith(';'):
            # skip comments and empty lines
            continue

        if line.startswith('[') and line.endswith(']'):
            # new section
            section_name = line.strip('[]')
            section = result[section_name] = {}
            continue

        # add entries to the existing section
        if '=' in line:
            name, _, value = line.partition('=')
            name = name.strip()
            section[name] = value.strip()
        else:
            # adding to last-used name
            section[name] += ' ' + line

rawDescription: Dictionary of ini file data

description: Dictionary of ini file data


code:
rng = pd.date_range('2013', freq='H', periods=1000)
df = pd.DataFrame(np.random.randn(len(rng)), index=rng, columns=['data'])

rawDescription: Plotting Weekly Tick Data From A Year Time Series


code:
import atexit
process = subprocess.Popen(args.server_file_path)
@atexit.register
def kill_process():
    try:
        process.terminate()
    except OSError:
        pass #ignore the error.  The OSError doesn't seem to be documented(?)
             #as such, it *might* be better to process.poll() and check for
             #`None` (meaning the process is still running), but that
             #introduces a race condition.  I'm not sure which is better,
             #hopefully someone that knows more about this than I do can
             #comment.

pid = process.pid

rawDescription: Killing child process when parent crashes in python


code: groupA[name].append([count])  # this appends a list to the list

rawDescription: When i add to the list in my dictionary, it doesn't actually add to the list? python


code: df['wa'] = df.value / g.value.transform("sum") * df.wt

rawDescription: Calculate weighted average using a pandas/dataframe


code:
from datetime import datetime, date, time

def float_to_datetime(myfloat):
    minutes, seconds = str(myfloat).split('.')
    return datetime.combine(date.today(), time(0, int(minutes), int(seconds)))

a = float_to_datetime(6.58)
b = float_to_datetime(7.12)

rawDescription: A way to convert numbers to seconds

description: A way to convert numbers to seconds


code:
from collections import Counter
from operator import or_

max_dict = reduce(or_, map(Counter, original_dict_list))

rawDescription: Merge multiple dictionaries conditionally


code:
import glob
import os

xlsx_files = glob.glob("*xlsx")
for xlsx_file in xlsx_files:
    os.system("unoconv -f xls {0}".format(xlsx_file) )

rawDescription: Convert a batch of xlsx to xls in programmatically using python in ubuntu


code:
A=np.delete(A, [2,3])
A

rawDescription: Python: list vs. np.array: switching to use certain attributes


rawDescription: Combine data from two different text files in just one line (Python)


code:
import inspect, opcode

def num_expected_results():
    """Return the number of items the caller is expecting in a tuple.

    Returns None if a single value is expected, rather than a tuple.
    """
    f = inspect.currentframe(2)
    code = map(ord, f.f_code.co_code)
    pos = f.f_lasti
    if code[pos] == opcode.opmap['GET_ITER']: pos += 1 # Skip this and the FOR_ITER
    if code[pos] > opcode.EXTENDED_ARG: pos +=5
    elif code[pos] > opcode.HAVE_ARGUMENT: pos +=3
    else: pos += 1
    if code[pos] == opcode.opmap['UNPACK_SEQUENCE']:
        return code[pos+1] + (code[pos+2] << 8)
    return None

rawDescription: how to program functions with alternative return value signatures in python? (next() for alternative iterators)

description: Program functions with alternative return value signatures in python? (next() for alternative iterators)


rawDescription: Remove rows from numpy array based on presence/absence in other arrays


code: regex = regex[1:-1]

rawDescription: Python/Regex splitting a specifically formatted return string


code:
for id in hotelIDs:
    hotels.append({
        'hotelName': hotelName,
        'standardRate': standardRate,
        'govtRate': govtRate,
        'standardAvailable': standardAvailable,
        'govtAvailable': govtAvailable,
        'arrive': dateToISO(arrive),
        'depart': dateToISO(depart),
        'location': Location(city='Atlanta')  # <- new location instance here
        })

rawDescription: Save relational sqlalchemy object from a dict


code:
class Client(Base):
    __tablename__ = "client"
    client_id = Column(Integer, primary_key=True)
    # ...

    addresses = relationship(Address, ...)

    primary_address = relationship(Address, uselist=False,
            primaryjoin = and_(Address.client_id == client_id, Address.type == 1),
            )
    secondary_address = relationship(Address, uselist=False,
            primaryjoin = and_(Address.client_id == client_id, Address.type == 2),
            )

rawDescription: How to create one-to-one accessor from one-to-many with extra join arguments with sqlalchemy?

description: Create one-to-one accessor from one-to-many with extra join arguments with sqlalchemy


code:
file_1 = open('file_1.txt', 'r')
text_1 = file_1.read().split(' ')
file_1.close()
file_2 = open('file_2.txt', 'r')
text_2 = file_2.read().split(' ')
file_2.close()

rawDescription: Delta words between two TXT files

description: Delta words between two TXT files


rawDescription: Error while I use math.atan in Python!

description: Error while I use math.atan in Python!


code:
PQRSTUVWXY
ZABCJRISKJ
JJSKWIOFJA

rawDescription: How to merge specific lines positioned between certain characters

description: Merge specific lines positioned between certain characters


code:
for item in os.listdir(dirpath):
    i = i + 1
    repo_name = name+str(i)
    path_to_repo = os.path.join(dirpath, item)

    repo_name = Repository(path_to_repo)
    repo_list[item] = repo_name

rawDescription: Using pygit2's discover_repository to locate multiple repositories in a directory


code:
#your original code

while not stop:
    #draw controls, boat and water
    #increment WaterLevel and Depth

    #event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    #get state of left mouse button
    isPressed = pygame.mouse.get_pressed()[0]

    #change location
    if ispressed and Left_Rect.collidepoint(pygame.mouse.get_pos()):
        Location -= 5
    elif ispressed and Right_Rect.collidepoint(pygame.mouse.get_pos()):
        Location += 5

    CLOCK.tick(FPS)

    pygame.display.update()

    CLOCK.tick(FPS)

    pygame.display.update()

rawDescription: How can I get continuous motion in pygame?

description: Get continuous motion in pygame


rawDescription: cluster points after KMeans clustering (scikit learn)

description: Cluster points after KMeans clustering (scikit learn)


code:
# settings.py

def init():
    global myList
    myList = []

rawDescription: Using global variables between files in Python?


code: print(text)

rawDescription: How can I count the length of the output of print in Python?

description: Count the length of the output of print in Python


code:
fields = {'foo': 'The Foo value', 'bar': 'A barren area', 'spam': 'The greatest canned meat!', 'eggs': 'scrambled or easy over?'}
template = 'Please provide me with eggs, {eggs}'
template.format(**fields)

rawDescription: Dynamic fields in a Python string

description: Dynamic fields in a Python string


code:
import glob, os, shutil
fnames = sorted(glob.glob('*asc.gz'))
for i, fnames in enumerate(grouper(fnames, 150)):
    dirname = 'batch%d' % i
    os.mkdir(dirname)
    for fname in fnames:
        shutil.move(fname, dirname)

rawDescription: For every x number of files; create new directory and move files -- using Python


code:
myprops = {}
with open('filename.properties', 'r') as f:
    for line in f:
        line = line.rstrip() #removes trailing whitespace and '\n' chars

        if "=" not in line: continue #skips blanks and comments w/o =
        if line.startswith("#"): continue #skips comments which contain =

        k, v = line.split("=", 1)
        myprops[k] = v

rawDescription: Python: How to create a dictionary from properties file while omitting comments


code:
def get_items(dict_object):
    for key in dict_object:
        yield key, dict_object[key]

rawDescription: Python 2 and 3 compatible way of iterating through dict with key and value


code:
import simplejson
json = response.read()
dict = simplejson.load(json)

rawDescription: Capture access_token from facebook's server-side authentication in Django


code:
DATABASES = {
             'default': {
                         'ENGINE': 'mysql',
                         'OPTIONS': {'init_command': 'SET storage_engine=INNODB'}
                        }
            }

rawDescription: In Django, how do I set the default so that every model is created with INNODB?


code: newlist = [ list(filter(None, x)) for x in oldlist ]

rawDescription: How do I create a new list with specific items from an old list in Python 2?

description: Create a new list with specific items from an old list in Python 2


code:
import math
from pyspark.sql.functions import udf
from pyspark.sql.types import DoubleType

my_pow = udf(lambda x, y: math.pow(x, y), DoubleType())

rawDescription: Spark withColumn() performing power functions


code:
def partition1(max_range, S):
    max_range = np.asarray(max_range, dtype = int)
    a = np.indices(max_range + 1)
    b = a.sum(axis = 0) <= S
    return (a[:,b].T)

rawDescription: Generating a numpy array with all combinations of numbers that sum to less than a given number


code:
umap = {ord(key):unicode(val) for key, val in umlautDictionary.items()}
umap
print(u'ÄÖ'.translate(umap))

rawDescription: Python - Transliterate German Umlauts to Diacritic


code:
urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^about/$', views.about, name='about'),
)

rawDescription: Page not found (404) Error in Django

description: Page not found (404) Error in Django


code:
from os import listdir
from MyImages import MyImages # auto-generated .py file

myimages = MyImages()
for imagePath in listdir('dirPath'):
    im = MyImages.image()
    im.src = imagePath
    myimages.append(im)

with open("output.xml", 'w') as f:
    f.write(myimages.toxml("utf-8"))

rawDescription: Simple Python xml image generator

description: Simple Python xml image generator


rawDescription: Transposing arrays in an array

description: Transposing arrays in an array


rawDescription: How to work with data from NBA.com?

description: Work with data from NBA.com


code:
a_list = [["Bob", 2], ["Bill", 1], ["Bob", 2]]
memory = {}
{name: memory[name] for name, count in a_list if not memory.__setitem__(name, count + memory.setdefault(name, 0))}
memory

rawDescription: Adding and combining values with dictionary comprehensions?


code:
# This statement doesn't reference 'users' at compile time
def bind_form(func):
    ...

# This statement doesn't reference 'users' at compile time
class Create_User(Forms.Form):

    # This statement declares a new scope
    def clean(self):

        # This statement references 'users' at runtime, but not at compile time
        if users.user_exists(user):
            ...

# Now import
import users

rawDescription: Modules that rely on each other

description: Modules that rely on each other


code:
import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (numpy.nan, numpy.nan),
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')

rawDescription: matplotlib: Plot numpy arrays with None as values

description: Matplotlib: Plot numpy arrays with None as values


rawDescription: Selecting only some values from dictionaries in list


code: np.nanmean(data, axis=0)

rawDescription: How to read columns of varying length from a text file in NumPy using genfromtxt()?

description: Read columns of varying length from a text file in NumPy using genfromtxt()


code:
def suite():
    suite = unittest.TestSuite()
    suite.addTest(WidgetTestCase('test_default_size'))
    suite.addTest(WidgetTestCase('test_resize'))
    return suite

rawDescription: call different methods in unittest according to input arguments

description: Call different methods in unittest according to input arguments


rawDescription: Python - Convert a matrix to edge list/long form


code:
result = pd.melt(df)
result[['variable', 'num']] = result['variable'].str.extract('(\D+)(\d+)', expand=True)
result = result.pivot(index='num', columns='variable', values='value')
print(result)

rawDescription: Difficult Dataframe Reshape in Python Pandas


code:
def main():
    n=int(input("how many no.s are we dealing with?"))
    result = 0
    for i in range(n):
        value = float(input('enter next number to add'))
        result += value
    print('the result is {0}'.format(result))

rawDescription: How to map all the values in a range upto n, range(n) in Python

description: Map all the values in a range upto n, range(n) in Python


code:
fig = plt.figure()
ax = fig.gca(projection='3d')
x = np.arange(11)
y = np.arange(11)
X, Y = np.meshgrid(x,y)
Z = np.zeros_like(X)
Z[5][5] = 5
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1)
plt.show()

rawDescription: Python 2d grid : Assigning values to coordinates in the grid


code:
import itertools
import operator

data=[(1, 'A', 'foo'),
    (2, 'A', 'bar'),
    (100, 'A', 'foo-bar'),

    ('xx', 'B', 'foobar'),
    ('yy', 'B', 'foo'),

    (1000, 'C', 'py'),
    (200, 'C', 'foo'),
    ]

for key,group in itertools.groupby(data,operator.itemgetter(1)):
    print(list(group))

rawDescription: Split a list of tuples into sub-lists of the same tuple field


code:
import re
re.findall(r'\S+', "defenders\t2\n")

rawDescription: Python regex parsing and putting into a multidimensional list