code:
#!/usr/bin/env python

import sys
from select import select

def main(argv):
    timeout = 3
    prompt = '> '
    max_chars = 3

    # set raw input mode if relevant
    # it is necessary to make stdin not wait for enter
    try:
        import tty, termios

        prev_flags = termios.tcgetattr(sys.stdin.fileno())
        tty.setraw(sys.stdin.fileno())
    except ImportError:
        prev_flags = None

    buf = ''
    sys.stderr.write(prompt)

    while True: # main loop
        rl, wl, xl = select([sys.stdin], [], [], timeout)
        if rl: # some input
            c = sys.stdin.read(1)
            # you will probably want to add some special key support
            # for example stop on enter:
            if c == '\n':
                break

            buf += c
            # auto-output is disabled as well, so you need to print it
            sys.stderr.write(c)

            # stop if N characters
            if len(buf) >= max_chars:
                break
        else:
            # timeout
            break

    # restore non-raw input
    if prev_flags is not None:
        termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, prev_flags)
    # and print newline
    sys.stderr.write('\n')

    # now buf contains your input
    # ...

if __name__ == "__main__":
    main(sys.argv[1:])

rawDescription: How to Read Keyboard Input One Char at a time with a timer with Python


code:
options = [dict() for i in range(number_of_options_you_need)]
#use options[0] instead of options0

#to set new key-value to all options
for opt in options:
    opt['Risk_rate'] = some_new_value

rawDescription: Adding colums to a list of variables

description: Adding colums to a list of variables


code:
def smallIntToRoman(integer):
    rlist = romanList = [(1000, "M"),(900, "CM"),(500, "D"),(400, "CD"),(100, "C"),(90, "XC"),(50, "L"),(40, "XL"),(10, "X"),(9, "IX"),(5, "V"),(4, "IV"),(1, "I")]
    romanResult = ""
    for wholeNumber in rlist:
            while integer >= wholeNumber[0]:
                    integer -= wholeNumber[0]
                    romanResult += wholeNumber[1]
    return romanResult

def bigIntToRoman(integer):
    thousands, rest = divmod(integer, 1000)
    return "({}){}".format(smallIntToRoman(thousands), smallIntToRoman(rest))

def intToRoman(integer):
    if integer >= 4000:
        return bigIntToRoman(integer)
    else:
        return smallIntToRoman(integer)

def smallRomanToInt(numeral):
    rlist = romanList = [(1000, "M"),(900, "CM"),(500, "D"),(400, "CD"),(100, "C"),(90, "XC"),(50, "L"),(40, "XL"),(10, "X"),(9, "IX"),(5, "V"),(4, "IV"),(1, "I")]
    if checkIfRomanNumeral(numeral) is False:
        pass
    elif checkIfRomanNumeral(numeral) is True:
        index = 0
        intResult = 0
        for integer, romanNumeral in rlist:
            while numeral[index : index + len(romanNumeral)] == romanNumeral:
                intResult += integer
                index += len(romanNumeral)

def romainToInt(numeral):
    if len(numeral) == 0:
        return None
    int_parts = numeral[1:].split(')') # Better done with regex
    if len(int_parts) == 1:
        return smallRomainToInt(numeral)
    elif len(int_parts) == 2:
        big = smallRomainToInt(int_parts[1])
        small = smallRomainToInt(int_parts[0])
        if big is None or small is None:
            return None
        else:
            return big * 1000 + small
    else:
        return None

rawDescription: Converting roman/arabic numerals higher than 4000


code:
import os
os.path.basename('channel/subchannel1')
os.path.basename('channel/subchannel2')

rawDescription: Storing Folder+Files inside dict, optimization


code: y = list(x)

rawDescription: python: Assigning a list to a variable from a named list. How to avoid dependency?

description: Python: Assigning a list to a variable from a named list. How to avoid dependency


code:
class Button(QPushButton):
    def __init__(self, text, parent, TextObject):
        super().__init__(text, parent=parent or None)
        self.setSizePolicy ( QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.clicked.connect(TextObject.SLOT_TextInsert('%s' %(text)))

rawDescription: Why PyQt QGridLayout does not resize?

description: Why PyQt QGridLayout does not resize


code:
def initialize_one(seq, n):
    if not seq:
        seq[:] = [1] * n

rawDescription: Mutating list in python

description: Mutating list in python


code: foobar = imp.load_source('foobar', '/path/to/foobar')

rawDescription: Import a python module without the .py extension


code:
def mergeandsort(src1, src2, dst):
    # Use `with` statements to close file automatically
    with open(src1, 'r') as s1, open(src2, 'r') as s2, open(dst, 'w') as d:
        l = list(s1) + list(s2)
        l.sort(reverse=true)  # Since you seem to want them in reverse order...
        c = ''.join(l)
        d.write(c)

rawDescription: Merge two files in Python and sort

description: Merge two files in Python and sort


code:
if __name__ == "__main__":
    MLL = LinkedList()

    LL1 = LinkedList()
    LL2 = LinkedList()

    array_list1 = [2, 4, 5, 7, 11, 12, 15, 20]
    array_list2 = [3, 6, 9, 10]

    for p in array_list1:
        LL1.addElement(p)

    for q in array_list2:
        LL2.addElement(q)

    cur_node_l1 = LL1.Head
    cur_node_l2 = LL2.Head
    cur_node = MLL.Head;
    while(cur_node_l1 and cur_node_l2):
        e1 = cur_node_l1.element
        e2 = cur_node_l2.element
        if e1 < e2:
            if not cur_node:
                cur_node =  cur_node_l1;
                MLL.Head = cur_node
            else:
                cur_node.Next = cur_node_l1;
                cur_node = cur_node_l1
            cur_node_l1 = cur_node_l1.Next
#            MLL.TAIL = cur_node_l1;

        else:
            if not cur_node:
                cur_node =  cur_node_l2;
                MLL.Head = cur_node
            else:
                cur_node.Next = cur_node_l2;
                cur_node = cur_node_l2;
            cur_node_l2 = cur_node_l2.Next
#        MLL.TAIL = cur_node_l2;
    if (cur_node_l1):
        cur_node.Next = cur_node_l1
        cur_node = LL1.Tail;
    if (cur_node_l2):
        cur_node.Next = cur_node_l2
        cur_node = LL2.Tail;
    MLL.Tail = cur_node
    MLL.size = LL1.size + LL2.size
    MLL.displayLinkedList()

rawDescription: Merging Linked List in Python

description: Merging Linked List in Python


code: df_joined = df1.join(df2)

rawDescription: How do I join columns from diferent Pandas DataFrames?

description: Join columns from diferent Pandas DataFrames


code:
from datetime import datetime
...
source.date = datetime.now()

rawDescription: Insert MySQL timestamp column value with SqlAlchemy


code:
sections = db.relationship("NoteSection",
            secondary=NoteTypeToSectionMap.__table__,
            order_by=NoteTypeToSectionMap.__table__.c.position)

rawDescription: SQLAlchemy. How to order on many to many relationship?


code:
s = requests.session()
rs = [grequests.get(url, session=s) for url in urls]
grequests.map(rs)

rawDescription: HTTP SSL pipelining in Python

description: HTTP SSL pipelining in Python


code:
item_list_json = get_paramw(kw, 'my_list', unicode)
item_list = json.loads(item_list_json)

rawDescription: How to pass an array of integers as a parameter from javascript to python?

description: Pass an array of integers as a parameter from javascript to python


code:
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
np.vstack((a, b))

rawDescription: How to combine arrays which are contained in a list in python

description: Combine arrays which are contained in a list in python


code:
df2 = pd.DataFrame({'VAR_1' : [1,2,3,4,5], 'GROUP': [1,1,1,2,2]})
df2["GROUP_MEAN"] = df2.groupby('GROUP')['VAR_1'].transform('mean')
df2

rawDescription: Filling cells with conditional column means


code:
while y != 100:
    dice = random.randint(1,6)
    z = y
    y = y + dice
    if y > 100:
        print('Roll '+str(dice)+' ... '+str(z)+' + '+str(dice)+' is over 100. Therefore it remains at '+str(z)+'\n')
        y = z
        input('Press <Enter> to roll again...\n')
    else:
        print('Roll '+str(dice)+' ... '+str(y)+' + '+str(dice)+' is '+str(y+dice))

rawDescription: Python looping (skip some part)

description: Python looping (skip some part)


code:
import getpass
password = getpass.getpass('Enter your password: ')

rawDescription: how to prevent printing output of raw_input()?

description: Prevent printing output of raw_input()


code:
kfold = cross_validation.StratifiedKFold(y)
[svc.fit(X[train], y[train]).score(X[test], y[test])
 for train, test in kfold]
cross_validation.cross_val_score(svc, X, y)

rawDescription: Difference between cross_val_score and estimator score?


code:
fileTexts = []
for document in allFiles:
    fileTexts.append(getFileText(basePath + document))

rawDescription: Iteratively populate array in Python

description: Iteratively populate array in Python


code:
id = None
title_set = True
f = open("test.txt",'r')
while True:
    text = f.readline()
    if text.startswith("ID: "):
        id = text[4:].strip() # The strip() is to remove the newline
    if text == "End":
        title_set = False
    if text == "Title":
        title_set = True
    if title_set and id is not None:
        print(id + " " + text.strip())

rawDescription: Parsing Text Files

description: Parsing Text Files


code:
from dateutil import parser

# map time zones to seconds from GMT
zones = {
    'EST': -5 * 3600,
    'PST': -8 * 3600
}

parser.parse('8 PM on Sunday PST', tzinfos=zones)
# datetime.datetime(2016, 4, 24, 20, 0, tzinfo=tzoffset('PST', -28800))

rawDescription: Parse timezone from a human time input

description: Parse timezone from a human time input


code:
file_lists = [('file1.data', 1), ('file1.data', 3), ('file2.data',3)]

temp_data = []

for a_file in file_lists:
    file_h = open(a_file[0])
    a_list = []
    csv_reader = csv.reader(file_h, delimiter='\t')
    for row in csv_reader:
       a_list.append(row[a_file[1]])
    temp_data.append((n for n in a_list))
    file_h.close()

with open('output.data', 'w') as output_file:
    csv_writer = csv.writer(output_file, delimiter='\t')
    for row in list(zip(*temp_data)):
        csv_writer.writerow(row)

rawDescription: Merging selected colums from multiple text file to one text file using Python


code:
fruit = ['A', 'banana', 'Watermelon', 'mango']
' + '.join(sorted(fruit, key=str.lower))

rawDescription: Skip linebreak, lowercase and uppercase in sorted() function in Python?


code:
img = Image.open(filename)
print(img.format)  # 'JPEG'

rawDescription: How to get the format of image with PIL?

description: Get the format of image with PIL


code: df['id'] =df['id'].astype(int)

rawDescription: pandas.to_csv outputs a column of floats instead of integers

description: Pandas.to_csv outputs a column of floats instead of integers


code:
import pandas as pd
import StringIO
from boto.s3.connection import S3Connection

AWS_KEY = 'XXXXXXDDDDDD'
AWS_SECRET = 'pweqory83743rywiuedq'
aws_connection = S3Connection(AWS_KEY, AWS_SECRET)
bucket = aws_connection.get_bucket('YOUR_BUCKET')

fileName = "test.csv"

content = bucket.get_key(fileName).get_contents_as_string()
reader = pd.read_csv(StringIO.StringIO(content))

rawDescription: Retrive S3 file as Object instead of downloading to absolute system path


code:
def current_speed():
    # uses the fact that true = 1 and false = 0
    currently_pressed = pygame.key.get_pressed()
    hdir = currently_pressed[pygame.K_RIGHT] - currently_pressed[pygame.K_LEFT]
    vdir = currently_pressed[pygame.K_DOWN] - currently_pressed[pygame.K_UP]
    return hdir * 4, vdir * 4

while running:

    clock.tick(60)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False

        player.hspd, player.vspd = current_speed()

    #Clear the screen
    display.fill(white)

    #Move objects
    player.move()
    #Draw objects
    player.draw()

    #Update the screen
    pygame.display.flip()

rawDescription: Player movement stops when direction reverses in Pygame


code:
l = ['aaa 0', 'bbb 1', 'ccc 2', 'ddd 3', 'abc 1']
wanted = {'aaa', 'abc'}
{key: value for key, value in (x.split() for x in l) if key in wanted}

rawDescription: Assigning intermediate variable in python list comprehension


code:
def balanced_subsample(x,y,subsample_size=1.0):

    class_xs = []
    min_elems = None

    for yi in np.unique(y):
        elems = x[(y == yi)]
        class_xs.append((yi, elems))
        if min_elems == None or elems.shape[0] < min_elems:
            min_elems = elems.shape[0]

    use_elems = min_elems
    if subsample_size < 1:
        use_elems = int(min_elems*subsample_size)

    xs = []
    ys = []

    for ci,this_xs in class_xs:
        if len(this_xs) > use_elems:
            np.random.shuffle(this_xs)

        x_ = this_xs[:use_elems]
        y_ = np.empty(use_elems)
        y_.fill(ci)

        xs.append(x_)
        ys.append(y_)

    xs = np.concatenate(xs)
    ys = np.concatenate(ys)

    return xs,ys

rawDescription: Scikit-learn balanced subsampling

description: Scikit-learn balanced subsampling


code: wx.FutureCall(0, foo.bar)

rawDescription: wxPython - run function after GUI is fully drawn

description: WxPython - run function after GUI is fully drawn


code:
url(controller='rpc/sessions', action='index')
url(controller='rpc/sessions', action='index', qualified=True)

rawDescription: How can I generate an absolute url for a Pylons controller?

description: Generate an absolute url for a Pylons controller


code:
mask = "ffff:fff0::"
bitCount = [0, 0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00, 0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff]

count = 0
try:
  for w in mask.split(':'):
    if not w or int(w, 16) == 0: break
    count += bitCount.index(int(w, 16))
except:
  raise SyntaxError('Bad NetMask')

rawDescription: python ipaddr library netmask IPv6

description: Python ipaddr library netmask IPv6


code:
os.chdir(os.path.expanduser('~/Documents/XDF_Thumbnails_Sci'))
for file in os.listdir('.'):
    if os.path.splitext(file)[1] == ".feedme":
        os.system("~/galfit %s" % file)

rawDescription: Ubuntu/Python- How to call ubuntu commands and 3rd party applications through Python


code: self.gui.bind_all("<Command-n>", lambda event: self.New())

rawDescription: In Tkinter how to pass a called function as argument?


code:
class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (
        # Extract links matching 'category.php' (but not matching 'subsection.php')
        # and follow links from them (since no callback means follow=True by default).
        Rule(SgmlLinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),

        # Extract links matching 'item.php' and parse them with the spider's method parse_item
        Rule(SgmlLinkExtractor(allow=('item\.php', )), callback='parse_item'),
    )

    def parse(self, response): # When writing crawl spider rules, avoid using parse as callback, since the CrawlSpider uses the parse method itself to implement its logic. So if you override the parse method, the crawl spider will no longer work.
        for request_or_item in CrawlSpider.parse(self, response):
            if isinstance(request_or_item, Request):
                request_or_item = request_or_item.replace(meta = {'start_url': response.meta['start_url']})
            yield request_or_item

    def make_requests_from_url(self, url):
        """A method that receives a URL and returns a Request object (or a list of Request objects) to scrape.
        This method is used to construct the initial requests in the start_requests() method,
        and is typically used to convert urls to requests.
        """
        return Request(url, dont_filter=True, meta = {'start_url': url})

    def parse_item(self, response):
        self.log('Hi, this is an item page! %s' % response.url)

        hxs = HtmlXPathSelector(response)
        item = Item()
        item['id'] = hxs.select('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
        item['name'] = hxs.select('//td[@id="item_name"]/text()').extract()
        item['description'] = hxs.select('//td[@id="item_description"]/text()').extract()
        item['start_url'] = response.meta['start_url']
        return item

rawDescription: How to access a specific start_url in a Scrapy CrawlSpider?

description: Access a specific start_url in a Scrapy CrawlSpider


code:
from sqlalchemy.engine import Engine
from sqlalchemy import event

@event.listens_for(Engine, "before_cursor_execute", retval=True)
def comment_sql_calls(conn, cursor, statement, parameters,
                                    context, executemany):
    statement = statement + " -- some comment"
    return statement, parameters

rawDescription: SQLAlchemy add comment to every query

description: SQLAlchemy add comment to every query


code:
from random import shuffle
import sys
from time import sleep

# version compatibility shim
if sys.hexversion <= 0x3000000:  # Python 2.x
    inp = raw_input
else:                            # Python 3.x
    inp = input

def get_word(prompt):
    return inp(prompt).strip().lower()

def shuffled(words):
    words_copy = list(words)
    shuffle(words_copy)
    return words_copy

class MadLib:
    BLANK = "___"
    DELAY = 1

    def __init__(self, intros, prompt, words):
        self.intros = intros
        self.prompt = prompt
        self.words = words
        self.num_words = len(words)
        assert prompt.count(self.BLANK) == self.num_words, "Number of blanks must match number of words!"

    def play(self):
        # show introduction
        for s in self.intros:
            sleep(self.DELAY)
            print(s, flush=True)
        # display madlib with blanks
        sleep(self.DELAY)
        print(self.prompt)
        # get words from user
        print("Words available: " + ", ".join(shuffled(self.words)))
        gotten = [
            get_word("Word {}: ".format(i))
            for i in range(1, self.num_words + 1)
        ]
        # evaluate results
        num_right = sum(g == w for g,w in zip(gotten, self.words))
        if num_right == self.num_words:
            print("You did it!")
            return True
        else:
            print("You got {} out of {} words right.".format(num_right, self.num_words))
            return False

madlibs = {
    "easy":
        MadLib(
            [
                "Here we go...",
                "Here's your text. Should be an easy one.",
                "Just fill in the blanks!"
            ],
            (
                "Python is a ___ language that provides constructs intended to "
                "enable clear programs on both small and large scale. "
                "Python implementation was started in December ___ by "
                "Guido von Rossum. The most basic ___ in Python is ___, "
                "often used by beginners to tell Python to display 'Hello "
                "World' on the screen."
            ),
            ['programming', '1989', 'command', 'print']
        ),
    "medium":
        MadLib(
            [
                "Good choice. Lets see how much you know about Python",
                "Here's your text. It's a tricky one that requires some more knowledge about Python.",
                "Just fill in the blanks!"
            ],
            (
                "A string object is ___, i.e. it cannot be modified after it "
                "has been created. An important concept in Python and other "
                "programming languages is the ___, used to store a value. "
                "To assign a value to you use the ___ operator. A more "
                "versatile data type in Python is ___, containing items "
                "separated by commas and within square brackets and to "
                "some extent they are similar to arrays in C."
            ),
            ['immutable', 'variable', 'equals', 'list']
        ),
    "hard":
        MadLib(
            [
                "Bold move! Here we go. Check out this text. It's a tough one!",
                "Here's your text.  This one requires quite some Python knowledge.",
                "Just fill in the blanks!",
                "Here's your text:"
            ],
            (
                "Similar to other programming languages, Python has flow "
                "control commands. The most common is ___ which lets you branch "
                "based on a condition. Looping commands like ___ execute "
                "statements a given number of times, or ___ repeats statements "
                "so long as a condition is True."
            ),
            ['if', 'for', 'while']
        )
}

def main():
    print(
        "Welcome to my first quiz with user input!\n"
        "Lets get cracking straight away."
    )
    while True:
        choice = get_word("Which difficulty level would you like? [easy, medium, hard] (or just hit Enter to exit) ")
        if not choice:
            break
        elif choice in madlibs:
            madlibs[choice].play()
        else:
            print("Sorry, that was not a recognized option.")

if __name__=="__main__":
    main()

rawDescription: Validating user input in a "fill in the blanks" program using Python


code:
def compare(A,B):
    Awins = 0
    Aties = 0
    Alosses = 0
    for i in range(0, whatever):
        random.shuffle(listA)
        random.shuffle(listB)
        for a,b in zip(A,B):
            if a > b:
                Awins += 1
            elif a == b:
                Aties += 1
            else:
                Alosses += 1

rawDescription: Comparing Values in List in For Loop; Python


rawDescription: How to do math in a Django template?

description: Do math in a Django template


code:
# coding: utf-8

text = u'résumé'

rawDescription: What's the preferred way to include unicode in python source files?


code:
def generateInsult(word=allWords):
    ...

def generateInsults(word=allWords):
    ...
    insults.append(generateInsult(word))

rawDescription: Insult Generator Gone Wrong

description: Insult Generator Gone Wrong


code:
import re

pattern = re.compile(r'^cfn(\d+)e(\d+)')
a, b = pattern.match('cfn99e1195_1.lp').groups()

rawDescription: In python, how to extract some char from each item of a list ?


code:
import unittest
class Wordnet():

    def __init__(self):
        # self.graph = Graph()
        self.before_at = ''
        self.after_at = ''
        self.word_part = ''
        self.gloss_part = ''
        self.lex_filenum = ''

    def process_file(self):
        self.file = open("testing_line.txt", "r")
        return self.file

    def line_for_loop(self, file):
        for line in file:
            self.split_pointer_part(line)
            self.split_word_part(line)
            self.split_gloss_part(line)
            self.process_lex_filenum(self.word_part)

    def split_pointer_part(self, line):
        self.before_at, self.after_at = line.split('@', 1)
        return self.before_at, self.after_at

    def split_word_part(self, line):
        self.word_part = line.split()
        return self.word_part

    def split_gloss_part(self, line):
        self.gloss_part = line.strip().split('|')
        return self.gloss_part

    def process_lex_filenum(self, word_part):
        self.lex_filenum = word_part[1]
        return self.lex_filenum

class WordnetTestCase(unittest.TestCase):
    def setUp(self):
        self.wn = Wordnet()

    def test_split_pointer_part(self):
        line = 'foo@bar'
        result = self.wn.split_pointer_part(line)
        answer = ('foo', 'bar')
        self.assertEqual(len(result), 2)
        for r, a in zip(result, answer):
            self.assertEqual(r, a)

if __name__ == '__main__':
    unittest.main()

rawDescription: Creating Unit tests for methods with global variables


code: col.insert(f, manipulate=False)

rawDescription: pymongo adds the _id field to my dictionary on insertion

description: Pymongo adds the _id field to my dictionary on insertion


code:
try:
    import win32file
except ImportError:
    win32file = None
    import glob

if win32file:
    def findfile(wildcard):
        """Returns path of the first matched file. Using win32file."""
        ...
        return filepath
else:
    def findfile(wildcard):
        """Returns path of the first matched file. Using glob."""
        ...
        return filepath

rawDescription: Import statement after function definition -- How can I make it more pythonic?


code:
import os

for dirpath, _, filenames in os.walk(finaldest):
    os.utime(dirpath, None)
    for file in filenames:
        os.utime(os.path.join(dirpath, file), None)

rawDescription: using shutil.copytree without copystat

description: Using shutil.copytree without copystat


code:
def parse(self, response):
    urls = response.meta.get('urls')
    if urls is None:
        urls = set()

    # do some logic of collecting urls from response into urls set
    # ...

    if is_still_has_data(response):
        # continue collecting urls in other page
        return scrapy.FormRequest(response.url, formdata={'dummy':'dummy1'},
            meta={'urls': urls}, callback=self.parse)
    else:
        return self.do_loop_urls(urls)

def do_loop_urls(self, urls):
    # parse urls found
    for url in urls:
        yield self.parse_url(url) # will yield Item inside

rawDescription: Is it possible to do this code pattern in scrapy?


rawDescription: how to step through a list and accumulate a integer value telling how many times an element based on it's position in list was seen

description: Step through a list and accumulate a integer value telling how many times an element based on it's position in list was seen


code:
# Define the list of values to group
values = [1, 2, 3, 10, 11, 12]

# Sort the values
values.sort()

# Split the values down into an even number of `n` groups
no_groups = 3
group_size = len(values) / no_groups
groups = []

for i in range(0, no_groups):
    groups.append(values[0:(group_size)])
    values = values[group_size:]

# Calculate the average minimum value of the groups
average_min = float(sum([g[0] for g in groups])) / no_groups

print(average_min)

rawDescription: Algorithm - Group/sort list to maximize minimum average group value


code:
def test_functions():
    assert f()
    assert g()
    assert h()

rawDescription: Python - Unit testing functions that are dependant on previous functions outcome (Chained functions)


rawDescription: Unescape Python Strings From HTTP

description: Unescape Python Strings From HTTP


code:
import scrapy
from selenium import webdriver

class product_spiderItem(scrapy.Item):
    title = scrapy.Field()
    price=scrapy.Field()
    pass

class ProductSpider(scrapy.Spider):
    name = "product_spider"
    allowed_domains = ['ebay.com']
    start_urls = ['http://www.ebay.com/sch/i.html?_odkw=books&_osacat=0&_trksid=p2045573.m570.l1313.TR0.TRC0.Xpython&_nkw=python&_sacat=0&_from=R40']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)

        while True:

            sel = scrapy.Selector(text=self.driver.page_source)

            for prod in sel.xpath('//ul[@id="GalleryViewInner"]/li/div/div'):
                item = product_spiderItem()
                item['title'] = prod.xpath('.//div[@class="gvtitle"]/h3/a/text()').extract()
                item['price'] = prod.xpath('.//div[@class="prices"]//span[@class=" bold"]/text()').extract()
                yield item

            next = self.driver.find_element_by_xpath('//td[@class="pagn-next"]/a')

            try:
                next.click()

            except:
                break

    def closed(self, reason):
        self.driver.close()

rawDescription: Scraper implemented with python, using scrapy and selenium launches but shuts down


code:
from django.db.models import Count
Tag.objects.annotate(img_count=Count('image')).order_by('img_count')

rawDescription: Sorting based on the count in a related field in Django


code:
encoded_name = ''.join([chr((ord(c)>>4) + ord('A'))
                        + chr((ord(c)&0xF) + ord('A')) for c in original_name])

rawDescription: encode Netbios name python

description: Encode Netbios name python


code:
data = 'S\x00e\x00r\x00i\x00e\x00s\x00'
data.decode('utf-16')

rawDescription: Python - converting wide-char strings from a binary file to Python unicode strings


code:
db = SQLAlchemy()

#models here

def create_app():
    app = Flask(__name__)
    #db configuration
    db.init_app(app)
    return db

rawDescription: How to define flask-sqlalchemy objects on demand?

description: Define flask-sqlalchemy objects on demand


code:
import time

import toro
import tornado.ioloop
import tornado.gen
import tornado.web

class Client():

    def __init__(self):
        self.queued_items = toro.Queue()

    @tornado.gen.coroutine
    def watch_queue(self):
        while True:
            items = yield self.queued_items.get()
            # go_do_something_with_items(items)

class IndexHandler(tornado.web.RequestHandler):

    @tornado.gen.coroutine
    def get(self):
        yield client.queued_items.put("%f" % time.time())
        self.write("Queued a new item")

if __name__ == "__main__":

    client = Client()

    # Watch the queue for when new items show up
    tornado.ioloop.IOLoop.instance().add_callback(client.watch_queue)

    # Create the web server
    application = tornado.web.Application([
        (r'/', IndexHandler),
    ], debug=True)

    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Creating a processing queue in Tornado

description: Creating a processing queue in Tornado


code:
listener = threading.Thread(target=kbdListener)
listener.start()

rawDescription: Trouble getting variable read out of a thread in python


rawDescription: Python - Get the coordinates of densest point


code:
with open("results.txt", "w") as results:
    p1 = subprocess.Popen(["command1"], stdout=results)
    p2 = subprocess.Popen(["command2"], stdout=results)
    p1.wait()
    p2.wait()

rawDescription: Multi-thread Linux tool commands?

description: Multi-thread Linux tool commands


code:
from concurrent.futures import ProcessPoolExecutor, Future, wait
from itertools import combinations
from functools import partial

similarity_matrix = [[0]*word_count for _ in range(word_count)]

def callback(i, j, future):
    similarity_matrix[i][j] = future.result()
    similarity_matrix[j][i] = future.result()

with ProcessPoolExecutor(max_workers=4) as executer:
    fs = []
    for i, j in combinations(range(wordcount), 2):
        future = excuter.submit(
                    calculate_similarity,
                    t_matrix[i],
                    t_matrix[j])

        future.add_done_callback(partial(callback, i, j))
        fs.append(future)

    wait(fs)

rawDescription: Parallelize this nested for loop in python


code:
@csrf_exempt
def save(request):
    if request.method == 'POST':
        rawdata1 = request.body
        rawdata2 = json.loads(rawdata1)
        length = len(rawdata2)
        for i in range(0,length,1):
            x = meterdata(time_elapsed=rawdata2[i]['time_elapsed'], volts=rawdata2[i]['volts'], amps=rawdata2[i]['amps'], kW=rawdata2[i]['kW'], kWh=rawdata2[i]['kWh'], session=rawdata2[i]['session'])
            x.save()
    return HttpResponse("Success!")

rawDescription: Storing JSON into sqlite database using Python


code:
Column(u'int_part', Integer, primary_key=True, nullable=False,
       autoincrement=False)

rawDescription: Is it possible to get sqlalchemy to create a composite primary key with an integer part without making it an IDENTITY type?


code:
days = ['mon','tues','weds','thurs','fri','sat','sun']
for day in days:
    setattr(form, day + '_start', start_value)
    setattr(form, day + '_end', end_value)

rawDescription: Getting an attribute of an instance by string in python?


code:
import matplotlib.pyplot as plt
handles, labels = plt.gca().get_legend_handles_labels()
my_artist = plt.Line2D((0,1),(0,0), color = "blue", linestyle = "-", linewidth = 1)
p = plt.Rectangle((0, 0), 1, 1, fc="b")
plt.legend([handle for i,handle in enumerate(handles) if i in display]+[my_artist, p],
           [label for i,label in enumerate(labels) if i in display]+["Line2D", "Rectangle"],
           handlelength=0.8, handleheight=0.8)
plt.show()

rawDescription: Small square instead of line in legend?

description: Small square instead of line in legend


code:
from __future__ import division as _division
import numpy as _np
import pandas as _pd

rawDescription: Hide external modules when importing a module (e.g. regarding code-completion)


code:
X, Y = np.meshgrid(np.linspace(0, 10, 100), np.linspace(0, 2*np.pi, 150),)
h = np.sin(Y)
Y *= np.linspace(.5, 1, 100)

fig, ax = plt.subplots(1, 1)
ax.pcolormesh(X, Y, h)

rawDescription: Matplotlib heatmap with changing y-values


code:
def reimport_class(self, cls):
    """
    Reload and reimport class "cls".  Return the new definition of the class.
    """

    # Get the fully qualified name of the class.
    from twisted.python import reflect
    full_path = reflect.qual(cls)

    # Naively parse the module name and class name.
    # Can be done much better...
    match = re.match(r'(.*)\.([^\.]+)', full_path)
    module_name = match.group(1)
    class_name = match.group(2)

    # This is where the good stuff happens.
    mod = __import__(module_name, fromlist=[class_name])
    reload(mod)

    # The (reloaded definition of the) class itself is returned.
    return getattr(mod, class_name)

rawDescription: Dynamically reload a class definition in Python


code:
from collections import Counter

def counter_is_subset(x, y):
    # If subtracting y from x doesn't return an empty Counter,
    # x is NOT a subset of y.
    return not (x - y)

def find_buildable_words(words, letters):
    letters = Counter(letters)

    for word in words:
        if counter_is_subset(Counter(word), letters):
            yield word

words = ['BLAH', 'FIZZ', 'FEZ', 'FOO', 'FAZE', 'ZEE']
letters = 'ZZAFIEA'

buildable_words = find_buildable_words(words, letters)

for word in buildable_words:
    print(word)

rawDescription: Matching a string (any order) to strings in an array of a huge size


code: return render_to_response('base.html', {'has_sidebar': has_sidebar})

rawDescription: Django - A Variable to Check in Base Template That Is Modified By View Functions


code: a, b, c = [ [] for i in range(3) ]

rawDescription: assign empty pointer to multiple variables

description: Assign empty pointer to multiple variables


code:
frames = [df1, df2, df3]
result = pd.concat(frames)

rawDescription: Append more than 2 data frames in pandas


code:
url(r'^(?P<pk>\d+)/$', YourDetailView.as_view(), name='cars-advertisment-detail'),

class YourDetailView(DetailView):
    context_object_name = "advertisment"
    model = Advertisement

    def get_context_data(self, **kwargs):
        """
        This has been overridden to add `car` to the templates context,
        so you can use {{ car }} etc. within the template
        """
        context = super(YourDetailView, self).get_context_data(**kwargs)
        context["car"] = Car.objects.get(registration="DK52 WLG")
        return context

rawDescription: django - DetailView how to display two models at same time

description: Django - DetailView how to display two models at same time


code:
sTestDataPath = "/path/to/data/test_data.p"
import pickle

with open(sTestDataPath, 'w') as f:
    pickle.dump(dInputData, f)

with open(sTestDataPath, 'r') as f:
    dInputData = pickle.load(f)

rawDescription: save/load dictionary while conserving keys' datatype

description: Save/load dictionary while conserving keys' datatype


code:
def attach_listener(window, event_name, function):
    def wrapper(*args, **kwargs):
        if window.exists():
            return function(*args, **kwargs)
        else:
            remove_listener(wrapper.id_number)
    wrapper.id_number = add_listener(event_name, wrapper)

rawDescription: Circular argument requirement for wrapper


code:
required_url = ""
while True:
    current_url = driver.current_url
    if "example_id=" in current_url:
        required_url = current_url
        print('\n'+required_url)
        break
    else: print(current_url)

rawDescription: WebDriver, Python: How to catch dynamically updating url with the appropriate value and save it to the variable


code:
class a(object):
    def __init__(self, x):
            self.x = x
    @property
    def xval(self):
            return self.x

b = a(5)
b.xval
b.xval = 6

rawDescription: What is the easiest, most concise way to make selected attributes in an instance be readonly?


code: ' '.join(''.join(x) for x in itertools.product('abcd', repeat = 2))

rawDescription: Which itertools generator doesn't skip any combinations?


code:
print ('How old are you? ')
user_value = info(input()) # store it is a variable
if user_value == '12':
    print ('some example text')
elif user_value == '13':
    print ('more example text') # it works!

rawDescription: Python - creating "if" statement with function and getting return without repetition


code:
try:
    limit_default_value = 10
    limit = int(self.request.get('limit', limit_default_value))
except ValueError: #catch a string that does not like decimal
    limit = limit_default_value

rawDescription: Setting a default variable value if param is not defined


rawDescription: Return a list of race positions without the values


code:
def do_update():
    ser.write(flagCharacter)
    allitems=ser.readline(6)
    x, y, z = allitems.split()
    sensores(x, y, z)
    root.after(1000, do_update)

rawDescription: Update value all the time in python interface (Arduino)


code:
import importlib
import sys

def import_class(class_name, module_name = "girvi.models"):
    module = importlib.import_module(module_name)
    class_object = getattr(module, class_name) # does not work for nested classes
    return class_object

rawDescription: Import Class from a python package at runtime


code:
neg_sample = df['Sample'] == 'neg'
neg_means = df[neg_sample].groupby(['SujectID', 'Experiment']).mean()
neg_means.columns = ['Adj']

df = df.merge(neg_means, how='left', left_on=['SujectID','Experiment'], right_index=True)
df['Adjusted'] = df['Results'] - df['Adj']

rawDescription: Performing calculations on specific rows in dataframe and using the results to perform additonal calculations


code:
from PySide import QtGui, QtCore

app = QtGui.QApplication([])
window = QtGui.QWidget()
layout = QtGui.QVBoxLayout(window)
edit = QtGui.QTextEdit('jfdh afdhgfkjg fdnvfh vklkfjvkflj lddkl ljklfjkl jvkldjfkvljfgvjldf ll dl dljvklj ljljlbl  llkb jbgl')
edit.setLineWrapColumnOrWidth(200)
edit.setLineWrapMode(QtGui.QTextEdit.FixedPixelWidth)
layout.addWidget(edit)
window.show()
app.exec_()

rawDescription: QTextEdit doesn't show horizontal scrollbar upon resizing


code:
import json
stuff = '[["hiya"]]'
js = json.loads(stuff)
str(js[0][0])

rawDescription: How can I remove the Unicode u from a JSON item?

description: Remove the Unicode u from a JSON item


code:
for row in act:
    row = row.strip()
    if row:
        curr.append(row)

rawDescription: How do I append to a file without adding '\n'?

description: Append to a file without adding '\n'


code:
from collections import defaultdict
result = defaultdict(tuple)
for key, value in zip(list1, list2):
   result[key] += (value,)

rawDescription: Python: from lists, build dict with key:value ratio not 1:1


code:
def my_func(a=None,b=None):
    kwargs = locals()
    print (kwargs["a"] * kwargs["b"])

In [5]: my_func(10,2)
20

rawDescription: is there a way to access kwargs dict without explicitly using it with def(**kwargs)?

description: Is there a way to access kwargs dict without explicitly using it with def(**kwargs)


code:
import wx

class ViewApp(wx.App):
    def OnInit(self):
        self.frame = ToolFrame(None, -1, "Test App")
        self.frame.Show(True)
        return True

class MyPopupMenu(wx.Menu):
    def __init__(self, parent):
        wx.Menu.__init__(self)

        self.parent = parent

        minimize = wx.MenuItem(self, wx.NewId(), 'Minimize')
        self.AppendItem(minimize)
        self.Bind(wx.EVT_MENU, self.OnMinimize, id=minimize.GetId())

    def OnMinimize(self, event):
        self.parent.Iconize()

class ToolFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(350, 250))

        self.toolbar = self.CreateToolBar()
        self.tool_id = wx.NewId()
        for i in range(3):
            tool_id = wx.NewId()
            self.toolbar.AddCheckLabelTool(tool_id, 'Tool', wx.EmptyBitmap(10,10))
            self.toolbar.Bind(wx.EVT_MENU, self.OnTool, id=tool_id)
        self.toolbar.Realize()
        self.Centre()
        self.Show()

    def OnTool(self, event):
        if event.IsChecked():
            # Get the position of the toolbar relative to
            # the frame. This will be the upper left corner of the first tool
            bar_pos = self.toolbar.GetScreenPosition()-self.GetScreenPosition()

            # This is the position of the tool along the tool bar (1st, 2nd, 3rd, etc...)
            tool_index = self.toolbar.GetToolPos(event.GetId())

            # Get the size of the tool
            tool_size = self.toolbar.GetToolSize()

            # This is the upper left corner of the clicked tool
            upper_left_pos = (bar_pos[0]+tool_size[0]*tool_index, bar_pos[1])

            # Menu position will be in the lower right corner
            lower_right_pos = (bar_pos[0]+tool_size[0]*(tool_index+1), bar_pos[1]+tool_size[1])

            # Show upper left corner of first tool in black
            dc = wx.WindowDC(self)
            dc.SetPen(wx.Pen("BLACK", 4))
            dc.DrawCircle(bar_pos[0], bar_pos[1], 4)

            # Show upper left corner of this tool in blue
            dc.SetPen(wx.Pen("BLUE", 4))
            dc.DrawCircle(upper_left_pos[0], upper_left_pos[1], 4)

            # Show lower right corner of this tool in green
            dc.SetPen(wx.Pen("GREEN", 4))
            dc.DrawCircle(lower_right_pos[0], lower_right_pos[1], 4)

            # Correct for the position of the tool bar
            menu_pos = (lower_right_pos[0]-bar_pos[0],lower_right_pos[1]-bar_pos[1])

            # Pop up the menu
            self.PopupMenu(MyPopupMenu(self), menu_pos)

if __name__ == "__main__":
    app = ViewApp(0)
    app.MainLoop()

rawDescription: Wxpython: Positioning a menu under a toolbar button


code:
from itertools import permutations
map(' '.join, permutations("python generate combinations".split()))

rawDescription: itertools: Python Module help creating combinations/permutations

description: Itertools: Python Module help creating combinations/permutations


code:
from twython import Twython, TwythonError

app_key = 'your_key'
app_secret = 'your_secret'
oauth_key = 'your_oauth_key'
oauth_secret = 'your_oauth_secret'

twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
mfriends = twitter.get_followers_ids(screen_name='myscreenname', count=50)

try:
    for unfollo in mfriends['ids']:
        twitter.destroy_friendship(user_id=unfollo)
except TwythonError as e:
    print(e)

rawDescription: Twython Unfollow Script

description: Twython Unfollow Script


code:
def replacer(original, looking_for, replace_with):
   ''' A straightforward way... '''
   return original.replace(looking_for, replace_with, 1)
   #return regex.sub(replace_with, looking_for, 1)

rawDescription: Python translator, how to replace just one word


code:
df.loc[rows, columns] = 99
df

rawDescription: Edit pandas DataFrame using indexes

description: Edit pandas DataFrame using indexes


code:
choices = [(obj.id, obj.profile.display_name()) for obj in User.objects.all()]

participants = UserMultipleChoiceField(
    queryset=User.objects.none(),
    label="",
    widget=forms.SelectMultiple(
        attrs={
            "data-placeholder": "Choose members.. "
        }
    ),
    choices=choices
)

rawDescription: Django ModelChoiceField displaying values in django.contrib.auth and a Profile table


code:
import  wx
import  wx.grid as  gridlib

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

class NewEnterHandlingGrid(gridlib.Grid):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)
        self.log = log

        self.CreateGrid(20, 6)

        self.SetCellValue(0, 0, "Enter moves to the right")
        self.SetCellValue(0, 5, "Enter wraps to next row")
        self.SetColSize(0, 150)
        self.SetColSize(5, 150)

        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

    def OnKeyDown(self, evt):
        if evt.GetKeyCode() != wx.WXK_RETURN:
            evt.Skip()
            return

        if evt.ControlDown():   # the edit control needs this key
            evt.Skip()
            return

        self.DisableCellEditControl()
        success = self.MoveCursorRight(evt.ShiftDown())

        if not success:
            newRow = self.GetGridCursorRow() + 1

            if newRow < self.GetTable().GetNumberRows():
                self.SetGridCursor(newRow, 0)
                self.MakeCellVisible(newRow, 0)
            else:
                # this would be a good place to add a new row if your app
                # needs to do that
                pass

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

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480))
        grid = NewEnterHandlingGrid(self, log)

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

if __name__ == '__main__':
    import sys
    app = wx.App()
    frame = TestFrame(None, sys.stdout)
    frame.Show(True)
    app.MainLoop()

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

rawDescription: Setting focus to cell wxGrid

description: Setting focus to cell wxGrid


code:
# change variable name and values to what you need
connection.execute("SET SESSION query_cache_type = OFF")

rawDescription: SQLAlchemy: How to change a MySQL server system variable using SQLAlchemy?


code:
def float_to_binary(num):
    exponent=0
    shifted_num=num
    while shifted_num != int(shifted_num):
        shifted_num*=2
        exponent+=1
    if exponent==0:
        return '{0:0b}'.format(int(shifted_num))
    binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)
    integer_part=binary[:-exponent]
    fractional_part=binary[-exponent:].rstrip('0')
    return '{0}.{1}'.format(integer_part,fractional_part)

def floathex_to_binary(floathex):
    num = float.fromhex(floathex)
    return float_to_binary(num)

print(floathex_to_binary('0x1.a000000000000p+2'))
# 110.1

print(floathex_to_binary('0x1.b5c2000000000p+1'))
# 11.01101011100001

rawDescription: Converting float.hex() value to binary in Python


code:
class MainPanel(wx.Panel):
    def __init__(self, parent):
        super(MainPanel, self).__init__(parent)

        #Atributos
        bmp = wx.Bitmap('./img.png',wx.BITMAP_TYPE_PNG)
        self.boton = wx.BitmapButton(self,bitmap=bmp)

        # Layout
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(self.boton)
        self.SetSizer(self.sizer)

        self.Bind(wx.EVT_BUTTON,self.add,self.boton)

    def add(self,event):
        self.sizer.Add(wx.StaticText(self,label='Testing'))
        self.Layout()

rawDescription: Learning wxPython, basic thing

description: Learning wxPython, basic thing


code:
cmds.window(title='Test Window')
cmds.columnLayout()
cmds.textFieldGrp('obj1', label='Name', text ="Please enter your name")
cmds.textFieldGrp('obj2', label='Address', text = "Please enter your address")
cmds.rowLayout(nc=3)
cmds.button(label="Lock", width=100, c=disable_texts)
cmds.button(label="Edit", width=100)
cmds.button(label="Reset", width=100)
cmds.showWindow()

def disable_texts(*args):
    #The e=True is for edit, so I'm 'editing' 'obj1' which is the name of the textFieldGrp
    cmds.textFieldGrp('obj1', e=True, enable=False)

rawDescription: Simple custom UI in Maya using Python

description: Simple custom UI in Maya using Python


code:
do_avg = np.vectorize(np.average)
data_2d = do_avg(data)

rawDescription: Numpy: average over one dimension in "jagged" 3D array


code:
import wx
import opencv.cv as cv
import opencv.highgui as gui

class CvMovieFrame(wx.Frame):
    TIMER_PLAY_ID = 101
    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1,)

        sizer = wx.BoxSizer(wx.VERTICAL)

        self.capture = gui.cvCreateCameraCapture(0)
        frame = gui.cvQueryFrame(self.capture)
        cv.cvCvtColor(frame, frame, cv.CV_BGR2RGB)

        self.SetSize((frame.width + 300, frame.height + 100))

        self.bmp = wx.BitmapFromBuffer(frame.width, frame.height, frame.imageData)
        self.displayPanel= wx.StaticBitmap(self, -1, bitmap=self.bmp)
        sizer.Add(self.displayPanel, 0, wx.ALL, 10)

        self.shotbutton = wx.Button(self,-1, "Shot")
        sizer.Add(self.shotbutton,-1, wx.GROW)

        self.retrybutton = wx.Button(self,-1, "Retry")
        sizer.Add(self.retrybutton,-1, wx.GROW)
        self.retrybutton.Hide()

        #events
        self.Bind(wx.EVT_BUTTON, self.onShot, self.shotbutton)
        self.Bind(wx.EVT_BUTTON, self.onRetry, self.retrybutton)
        self.Bind(wx.EVT_PAINT, self.onPaint)
        self.Bind(wx.EVT_CLOSE, self.onClose)

        self.playTimer = wx.Timer(self, self.TIMER_PLAY_ID)
        wx.EVT_TIMER(self, self.TIMER_PLAY_ID, self.onNextFrame)

        self.fps = 8;
        self.SetSizer(sizer)
        sizer.Layout()
        self.startTimer()

    def startTimer(self):
        if self.fps!=0: self.playTimer.Start(1000/self.fps)#every X ms
        else: self.playTimer.Start(1000/15)#assuming 15 fps

    def onRetry(self, event):
        frame = gui.cvQueryFrame(self.capture)
        cv.cvCvtColor(frame, frame, cv.CV_BGR2RGB)
        self.bmp = wx.BitmapFromBuffer(frame.width, frame.height, frame.imageData)
        self.startTimer()
        self.shotbutton.Show()
        self.retrybutton.Hide()
        self.hasPicture = False
        self.Layout()
        event.Skip()

    def onShot(self, event):
        frame = gui.cvQueryFrame(self.capture)
        self.playTimer.Stop()
        gui.cvSaveImage("foo.png", frame)

        self.hasPicture = True
        self.shotbutton.Hide()
        self.retrybutton.Show()
        self.Layout()
        event.Skip()

    def onClose(self, event):
        try:
            self.playTimer.Stop()
        except:
            pass

        self.Show(False)
        self.Destroy()

    def onPaint(self, evt):
        if self.bmp:
            self.displayPanel.SetBitmap(self.bmp)
        evt.Skip()

    def onNextFrame(self, evt):

        frame = gui.cvQueryFrame(self.capture)
        if frame:
            cv.cvCvtColor(frame, frame, cv.CV_BGR2RGB)
            self.bmp = wx.BitmapFromBuffer(frame.width, frame.height, frame.imageData)
            self.Refresh()
        evt.Skip()

if __name__=="__main__":
    app = wx.App()
    f = CvMovieFrame(None)
    f.Centre()
    f.Show(True)
    app.MainLoop()

rawDescription: Python GStreamer webcam viewer

description: Python GStreamer webcam viewer


code:
import dbus

bus = dbus.SessionBus()
vlc_media_player_obj = bus.get_object("org.mpris.MediaPlayer2.vlc", "/org/mpris/MediaPlayer2")
props_iface = dbus.Interface(vlc_media_player_obj, 'org.freedesktop.DBus.Properties')
pb_stat = props_iface.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')

rawDescription: using org.mpris.mediaplayer2.player PlaybackStatus property in python

description: Using org.mpris.mediaplayer2.player PlaybackStatus property in python


code: filtered_clue = filter(lambda x: len(x['number']), clue)

rawDescription: Remove empty sets from a dict inside a list (python 2.7)


code:
#get the sheet you want to work with, I'm just going to grab the first sheet
sheets = document.getSheets().createEnumeration()
sheet = sheets.nextElement()

#start with a range on the first cell
range = sheet.getCellRangeByPosition( 0, 0, 0, 0 )

#expand to full extend of the used area
range.gotoEndOfUsedArea( True ) #true for expand selection

#no do whatever formatting things you want to do

rawDescription: OpenOffice pyuno "select all"

description: OpenOffice pyuno "select all"


code:
cwt = commonWordTweets()   # Replace with code to get the item from your datastore
d = {"commonWords":cwt.commonWords, "venue": cwt.venue.name}
jsonout = simplejson.dumps(d)

rawDescription: Serializing ReferenceProperty in Appengine Datastore to JSON


code:
import numpy as np

# Made up parameters
N_random_variables = 500
n_vals = np.random.random_integers(100, 200, N_random_variables)
p_vals = np.random.random_sample(N_random_variables)

# Can this portion be vectorized? Yes
results = np.empty(N_random_variables)
results = np.random.binomial(n_vals, p_vals)

rawDescription: Vectorized sampling of multiple binomial random variables


code:
def stripped(strings):
    return [s.strip() for s in strings]

rawDescription: C# like extension functions in python?

description: C# like extension functions in python


rawDescription: How to access last column field with Python and increase by 1 in .csv

description: Access last column field with Python and increase by 1 in .csv


rawDescription: Python click Js link with selenium

description: Python click Js link with selenium


code:
from pylab import *
ion()
figure(facecolor='white') # Or any other color
axes(frameon = 0, aspect = 1, polar = 1)
grid(True)

rawDescription: change background *without* a frame with matplotlib

description: Change background *without* a frame with matplotlib


code:
import ctypes
MB_OK = 0x0
MB_OKCXL = 0x01
MB_YESNOCXL = 0x03
MB_YESNO = 0x04
MB_HELP = 0x4000
ICON_EXLAIM=0x30
ICON_INFO = 0x40
ICON_STOP = 0x10

result = ctypes.windll.user32.MessageBoxA(0, "Your text?", "Your title", MB_HELP| MB_YESNO | ICON_STOP)

rawDescription: Python MessageBox with Icons using ctypes and windll


rawDescription: Slice syntax for python 2.7, reverse a part of a list


code:
dicts = {}
# dict_list = []
for i in xrange(10):
    dictionary_key = ('d{0}'.format(i))
    dict_item = {"Fruit":"Apple","Book":"Oliver Twist","Building":"White House"}
    dicts[dictionary_key] = dict_item
    # dict_list.append(dict_item)

rawDescription: Python: use a string as a variable?

description: Python: use a string as a variable


code:
import numpy as np
from scipy.io import wavfile
from scipy import interpolate

NEW_SAMPLERATE = 48000

old_samplerate, old_audio = wavfile.read("test.wav")

if old_samplerate != NEW_SAMPLERATE:
    duration = old_audio.shape[0] / old_samplerate

    time_old  = np.linspace(0, duration, old_audio.shape[0])
    time_new  = np.linspace(0, duration, int(old_audio.shape[0] * NEW_SAMPLERATE / old_samplerate))

    interpolator = interpolate.interp1d(time_old, old_audio.T)
    new_audio = interpolator(time_new).T

    wavfile.write("out.wav", NEW_SAMPLERATE, np.round(new_audio).astype(old_audio.dtype))

rawDescription: How to read a .wav file using SciPy at a different sampling rate?

description: Read a .wav file using SciPy at a different sampling rate


rawDescription: a = b || c in Python

description: A = b || c in Python


code:
class A(object):
    def __init__(self):
        pass

    def method1(self):
        "This is method1 of class A"
        pass

a = A()
help(a)

def method2(self):
    """ Method 2 still not associated"""
    pass

A.method2 = method2
# if you did a.method2 = method2
# Then it won't show up in the help() statement below

help(a)

rawDescription: Display dynamically added methods and attributes in python help


code:
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select * FROM spam")
cursor2.execute("select * FROM eggs")
cursor1.fetchone() #first result from query 1
cursor2.fetchone() #first result from query 2

rawDescription: Can i store a cursor.fetchone() in a variable

description: Store a cursor.fetchone() in a variable


code:
#!/usr/bin/env python
import boto.ec2
from boto.ec2 import EC2Connection

csv_file = open('/home/sbasnet/Scripts/Instances/instances_east.csv','w+')

def process_instance_list(connection):
    map(build_instance_list,connection.get_all_instances())

def build_instance_list(reservation):
    map(write_instances,reservation.instances)

def get_tag(tags, tag_name):
    if tag_name in tags.keys():
        return tags[tag_name]
    else:
        return "N/A"

def write_instances(instance):
    if instance.platform == 'windows':
        platform = 'Windows'
    else:
        platform = 'Linux'
    csv_file.write("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"%(instance.id,
                                                         instance.private_ip_address,
                                                         get_tag(instance.tags, "Classification"),
                                                         get_tag(instance.tags, "FQDN"),
                                                         get_tag(instance.tags, "Owner"),
                                                         get_tag(instance.tags, "RunType"),
                                                         instance.instance_type,
                                                         instance.subnet_id,
                                                         instance.key_name,
                                                         platform,
                                                         instance.placement))
    csv_file.flush()

if __name__=="__main__":
    connection = EC2Connection(aws_access_key_id='ACCESS',aws_secret_access_key='SECRET')
    process_instance_list(connection)
    csv_file.close()

rawDescription: Boto issues listing AWS instances with no-tags


code:
a=np.zeros((982,5))
b=np.random.randint(0,100,(491,5)) # your 491 row matrix
a[::2] = b

rawDescription: Numpy array, insert alternate rows of zeros


code:
import numpy
import matplotlib.pyplot as plt

mean = 0
std = 1
num_samples = 1000
samples = numpy.random.normal(mean, std, size=num_samples)

plt.plot(samples)
plt.show()

rawDescription: Defining a white noise process in Python


code:
class Example(list):
    def sum(self):
        return sum(self)

x = Example((1,2,3))
print(x.sum())

rawDescription: whiat is different between function conj(x) and method x.conj() python

description: Whiat is different between function conj(x) and method x.conj() python


code:
while True:
    Fibonacci1 = Fibonacci1 + Fibonacci2
    if Fibonacci1 % 2 == 0:
        if a + Fibonacci1 > 4000000:
            break
        a = a + Fibonacci1
    Fibonacci2 = Fibonacci1 + Fibonacci2
    if Fibonacci2 % 2 == 0:
        if a + Fibonacci2 > 4000000:
            break
        a = a + Fibonacci2

rawDescription: Fibonacci under 4 millions

description: Fibonacci under 4 millions


code:
# For a public key "ssh-rsa AAblablabla...":
key = paramiko.RSAKey(data=base64.b64decode('AAblablabla...'))
key.verify_ssh_sig(..., ...)

rawDescription: Paramiko: Creating a PKey from a public key string


code:
import math

def perfect_squares(min, max):
    lowest = int(math.ceil(math.sqrt(min)))
    highest = int(math.sqrt(max))
    return (n**2 for n in range(lowest, highest + 1))

rawDescription: Python - Fastest way to find all perfect squares in a given large number range


code:
class Base(object):
    static_types_mapping = {
          "params" : "namespace",
            "data" : "data",
            "type" : "blob",
          }

    def algo(self, data):
        do_some_magic(data, self.static_types_mapping)

class Derived(Base):
    static_types_mapping = Base.static_types_mapping.copy()
    static_types_mapping.update( {"extra_field" : "fancy_type"} )

rawDescription: Extending contents of static list or dict in a derived making base method work on the derived version


code:
import csv
from collections import OrderedDict

with open('file1.csv') as f:
    reader = csv.reader(f)
    reader.next()
    rows = OrderedDict((tuple(row[:2]), None) for row in reader)

with open('file2.csv') as f:
    reader = csv.reader(f)
    reader.next()

    # Skip row if matching row wasn't present in file1.csv
    rows.update({tuple(row[:2]): row[2] for row in reader if tuple(row[:2]) in rows})

with open('network_python.csv', 'wb') as csvfile:
    fieldnames = ['From', 'To', 'Mode']
    writer = csv.writer(csvfile)
    writer.writerow(fieldnames)

    # Skip row if it wasn't present in file2.csv
    writer.writerows((k[0], k[1], v) for k, v in rows.iteritems() if v is not None)

rawDescription: Match 2 csv files and write the third cell of the second file


code:
import Tkinter as Tk

class App(Tk.Frame):
    def __init__(self, master, *args, **kwargs):
        Tk.Frame.__init__(self, *args, **kwargs)

        self.existing_lines = 2
        self.entry_lines = Tk.IntVar()

        Tk.Label(self, text="Number Of Lines").grid(row=0, column=0)
        Tk.Entry(self, textvariable=self.entry_lines).grid(row=0, column=1)
        Tk.Button(self, text="Apply Number", command=self.add_rows).grid(row=1, column=1)

    def add_rows(self):
        for row in xrange(self.existing_lines, self.existing_lines+self.entry_lines.get()):
            Tk.Label(self, text="Line %i" % (row-1)).grid(row=row, column=0)
            Tk.Entry(self, textvariable=self.entry_lines).grid(row=row, column=1)
            self.existing_lines+= 1

if __name__ == "__main__":
    root = Tk.Tk()
    App(root).pack()
    root.mainloop()

rawDescription: Python Tkinter, Number of Label/Entry based on IntVar


code:
import nmap
nm = nmap.PortScanner()
nm.scan('127.0.0.1', '22-443', arguments='-P0')  # <----
nm.command_line()

rawDescription: How to enable "no ping" when using nmap from python

description: Enable "no ping" when using nmap from python


code:
def create_closure_and_function(*args):
    func = None
    def create_function_closure():
         return func

    closure = create_function_closure.__closure__
    func = types.FunctionType(*args[:-1] + [closure])
    return func

rawDescription: How can I serialise a recursive function?

description: Serialise a recursive function


code:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.base import TemplateView, View

class LoginTemplateView(TemplateView):
    template_name = 'login.html'

class HomeTemplateView(TemplateView):
    template_name = 'home.html'

    @method_decorator(login_required(login_url='/'))
    def dispatch(self, request, *args, **kwargs):
        return super(HomeTemplateView, self).dispatch(request, *args, **kwargs)

class LogoutView(View):
    def get(self, request, *args, **kwargs):
        auth_logout(request)
        return redirect('/')

rawDescription: Function views to Class based-views

description: Function views to Class based-views


code:
o = object()
repr(o)
id(o)
hex(id(o))

rawDescription: Python: how can I get an object's address in the __repr__ method?


code: znew = np.vstack((z[0],z[1]))

rawDescription: Python concatenate arrays in a list

description: Python concatenate arrays in a list


rawDescription: Encode East Asian languages using Python


code:
import timeit
from itertools import tee, izip, islice

def isplit(source, sep):
    sepsize = len(sep)
    start = 0
    while True:
        idx = source.find(sep, start)
        if idx == -1:
            yield source[start:]
            return
        yield source[start:idx]
        start = idx + sepsize

def pairwise(iterable, n=2):
    return izip(*(islice(it, pos, None) for pos, it in enumerate(tee(iterable, n))))

def zipngram(text, n=2):
    return zip(*[text.split()[i:] for i in range(n)])

def zipngram2(text, n=2):
    words = text.split()
    return pairwise(words, n)

def zipngram3(text, n=2):
    words = text.split()
    return zip(*[words[i:] for i in range(n)])

def zipngram4(text, n=2):
    words = isplit(text, ' ')
    return pairwise(words, n)

s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
s = s * 10 ** 3

res = []
for n in range(15):

    a = timeit.timeit('zipngram(s, n)', 'from __main__ import zipngram, s, n', number=100)
    b = timeit.timeit('list(zipngram2(s, n))', 'from __main__ import zipngram2, s, n', number=100)
    c = timeit.timeit('zipngram3(s, n)', 'from __main__ import zipngram3, s, n', number=100)
    d = timeit.timeit('list(zipngram4(s, n))', 'from __main__ import zipngram4, s, n', number=100)

    res.append((a, b, c, d))

a, b, c, d = zip(*res)

import matplotlib.pyplot as plt

plt.plot(a, label="zipngram")
plt.plot(b, label="zipngram2")
plt.plot(c, label="zipngram3")
plt.plot(d, label="zipngram4")
plt.legend(loc=0)
plt.show()

rawDescription: Fast/Optimize N-gram implementations in python


code:
class Sample_stats:
    def __init__(self):
        self.ts = datetime.now()
        self.total = randint(10,10000)
        self.seed = randint(5,5000)
        self.post_id = randint(0,100)
        self.site_id = 1
        self.twitter = randint(5,5000)
        self.facebook = randint(5,5000)
        self.gplus = randint(5,5000)
        self.pinterest = randint(5,5000)
        self.clicks = randint(5,5000)
        self.subpage_id = 1
        self.mouse_overs = randint(5,5000)
        self.impressions = randint(5,5000)

rawDescription: Python how to create a new Object with new instance values


code:
a = 0b11111111
b = 0b11011111

diff = a^b  # 0b100000
diff.bit_length()-1 # 5 (the first position (backwards) which differs, 0 if a==b )

rawDescription: Get the bit number that differs between two (binary) numbers


code:
cmd = (
    'xgettext -d %s -L Python %s %s --keyword=gettext_noop '
    '--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 '
    '--keyword=ugettext_noop --keyword=ugettext_lazy '
    '--keyword=ungettext_lazy:1,2 --keyword=pgettext:1c,2 '
    '--keyword=npgettext:1c,2,3 --keyword=pgettext_lazy:1c,2 '
    '--keyword=npgettext_lazy:1c,2,3 --from-code UTF-8 '
    '--add-comments=Translators -o - "%s"' %
    (domain, wrap, location, work_file))

rawDescription: ugettext and ugettext_lazy functions not recognized by makemessages in Python Django

description: Ugettext and ugettext_lazy functions not recognized by makemessages in Python Django


code:
img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

rawDescription: apply mask to color image

description: Apply mask to color image


code:
import dis
def x(a,b):
    return a+b

dis.dis(x)

rawDescription: Measuring bytecode usage

description: Measuring bytecode usage


code:
#Connect to aws
conn = S3Connection(aws_access_key_id=key, aws_secret_access_key=secret)
bucket = conn.get_bucket('mybucket')

#Build path
path = 'prefix'
key_name = 'this_is_any.file'
full_key_name = os.path.join(path, key_name)

#Set and save in S3
k = bucket.new_key(full_key_name)
k.set_contents_from_filename(...)

rawDescription: Python boto upload with prefix

description: Python boto upload with prefix


code:
import sys
data = [line.strip() for line in open(sys.argv[1],  "rb")]

rawDescription: replace loading a file to a list with command line/shell version in python

description: Replace loading a file to a list with command line/shell version in python


code:
import struct
struct.unpack("<h", "\x00\x05")
struct.unpack("<h", "\x00\x06")
struct.unpack("<h", "\x01\x06")

rawDescription: Convert little endian string to integer

description: Convert little endian string to integer


code:
values = results_array[:, 3]
row_idx = results_array[:, 2]
col_idx = results_array[:, 1]

sparse_array = csc_matrix((values, (row_idx, col_idx)), shape=(14, 14))

rawDescription: Copying values of a numpy array into specific location of sparse matrix


code:
import pylab as pl
pl.gca().set_aspect("equal")

rawDescription: Matplotlib similar axis scales

description: Matplotlib similar axis scales


code:
def write_dict(out_dict, filename):
    with open(filename, 'w') as f:
        for key, value in out_dict.items():
            f.write('{} {}\n'.format(key, value))

rawDescription: Writing a dict to a file with a certain format


code:
import os
import IPython
ip = IPython.ipapi.get()

def runMyFile(self):
    ip.magic('%run myFile.py')
    raise IPython.ipapi.TryNext()

ip.set_hook('pre_runcode_hook', runMyFile)

rawDescription: How can I get a file to autorun before I run any command in ipython?

description: Get a file to autorun before I run any command in ipython


code: df1.values[spots, [0, 1]]

rawDescription: Slicing Pandas DataFrame with an array of integers specifying location


code:
intervals = [(0.2, 0.3),
             (0.8, 1.0),
             (0.4, 0.6),
             (0.32, 0.38)]

intervals = sorted(intervals)
disjoint = all(intervals[i+1][0] > intervals[i][1] for i in range(len(intervals) - 1))

rawDescription: Checking whether a bunch of intervals are overlapping


code: items = raw_input("Enter your data items separated by commas: ").split(",")

rawDescription: Python: raw_input a list

description: Python: raw_input a list


code:
import os.path as _osp

def is_inside(file_path, folder_path):
    full_file_path = _osp.realpath(file_path)
    full_folder_path = _osp.realpath(folder_path)
    return _osp.commonprefix([full_file_path, full_folder_path]) == \
           full_folder_path

rawDescription: How to determine whether specified file is placed inside of the specified folder?

description: Determine whether specified file is placed inside of the specified folder


rawDescription: How to display a quote in django template

description: Display a quote in django template


code:
class MyModelAdmin(admin.ModelAdmin):

    # A template for a very customized change view:
    change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'

    def get_osm_info(self):
        # ...
        pass

    def change_view(self, request, object_id, extra_context=None):
        extra_context = extra_context or {}
        extra_context['osm_data'] = self.get_osm_info()
        return super(MyModelAdmin, self).change_view(request, object_id,
            extra_context=extra_context)

rawDescription: methods in django admin

description: Methods in django admin


rawDescription: creating a boolean indexing in for loop in pandas

description: Creating a boolean indexing in for loop in pandas


code:
for i in a.winfo_children():
    if i.winfo_class() == "TRadiobutton" and i.instate(['selected']) is True:
        return i.cget('value')

rawDescription: python tkinter radiobutton state

description: Python tkinter radiobutton state


code:
def complicated_dot(v, w):
    dot = 0
    for (v_i, w_i) in zip(v, w):
        for x in v_i.iterkeys():
            if x in w_i:
                dot += v_i[x] * w_i[x]
    return dot

rawDescription: What's the best way to find the similarity among these vectors?


rawDescription: Find all links within a div using lxml

description: Find all links within a div using lxml


code:
input = [2,6,4,2,7,98,32,5,15,4,2,6,43,23,95,10,31,5,1,73]
brk = [6,43,23,95]
brk_len = len(brk)
brk_idx = 0
brk_offset = brk_idx + brk_len

try:
    while input[brk_idx:brk_offset] != brk:
        brk_idx = input.index(brk[0], brk_idx + 1)
        brk_offset = brk_idx + brk_len
except ValueError:
    print("Not found")
else:
    print(input[:brk_idx])

rawDescription: Python split list if sequence of numbers is found


code:
a = 1
while a > 0:
    a = a - 0.1
    print(repr(a))

rawDescription: why is my if statement showing to be false? code not not quitting when a==0. the time is supposed to be in min/sec

description: Why is my if statement showing to be false? code not not quitting when a==0. the time is supposed to be in min/sec


code:
def Timer(*args, **kwargs):
    """Factory function to create a Timer object.

    Timers call a function after a specified number of seconds:

        t = Timer(30.0, f, args=[], kwargs={})
        t.start()
        t.cancel()     # stop the timer's action if it's still waiting

    """
    return _Timer(*args, **kwargs)

class _Timer(Thread):
    """Call a function after a specified number of seconds:

            t = Timer(30.0, f, args=[], kwargs={})
            t.start()
            t.cancel()     # stop the timer's action if it's still waiting

    """

    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

rawDescription: Does threading.Timer open a function in a separate thread?


code:
np.where(
    np.array([frame.index.isin(['Utah', 'Texas']) for _ in frame.columns]).T,
    frame.apply(f1, axis=1),
    frame.apply(f2, axis=1))

rawDescription: Pandas Data Frame function application to a specific row


code:
seq = [100, 2, 400, 500, 400]
heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])

rawDescription: heapq.nlargest index of returned result in original sequence

description: Heapq.nlargest index of returned result in original sequence


code: int(not(x))

rawDescription: Binary negation in python

description: Binary negation in python


code:
all_data = pd.DataFrame()
for f in glob.glob("path/*.xlsx"):
    df = pd.read_excel(f, skiprows=4,index_col=None, na_values=['NA'])
    df['filename'] = f
    all_data = all_data.append(df,ignore_index=True)

task_output = all_data.groupby(['filename', "Task","Subtask"])["Hours"].agg([np.sum,np.mean])

rawDescription: Create new sheet with sums of specific column for each file in directory of multiple xlsx files


code:
def nearestDate(dates, pivot):
  return min(dates, key=lambda x: abs(x - pivot))

rawDescription: Find the closest date to a given date

description: Find the closest date to a given date


code: lastRow = houseRows[-1]

rawDescription: Indexing of TD/TR with BeautifulSoup

description: Indexing of TD/TR with BeautifulSoup


code:
from bottle import run
run(reloader=True)

rawDescription: How can I get Bottle to restart on file change?

description: Get Bottle to restart on file change


code:
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

x = np.random.rand(200)*16 - 8
y = np.random.rand(200)*16 - 8
r = np.sqrt(x**2 + y**2)
z = np.sin(r)/r

xi = np.linspace(min(x),max(x), 100)
yi = np.linspace(min(y),max(y), 200)

X,Y = np.meshgrid(xi,yi)

Z = griddata(x, y, z, X, Y, interp='linear')

fig = plt.figure()
ax = fig.gca(projection='3d')

surf = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap=cm.jet, vmin=np.nanmin(Z), vmax=np.nanmax(Z), shade=False)
scat = ax.scatter(x, y, z)

rawDescription: How to produce MATLAB plot (interpolation) in Matplotlib (Numpy)?

description: Produce MATLAB plot (interpolation) in Matplotlib (Numpy)


code:
import matplotlib.pyplot
from numpy import arange
from numpy import meshgrid

delta = 0.025
xrange = arange(-5.0, 20.0, delta)
yrange = arange(-5.0, 20.0, delta)
X, Y = meshgrid(xrange,yrange)

# F is one side of the equation, G is the other
F = Y**X
G = X**Y

matplotlib.pyplot.contour(X, Y, (F - G), [0])
matplotlib.pyplot.show()

rawDescription: Is it possible to plot implicit equations using Matplotlib?


code:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("foo", ..., required=True)
parser.parse_args()

rawDescription: How to check if an argument from commandline has been set?

description: Check if an argument from commandline has been set


code:
def the_list():
    try:
        with open('data.txt', 'r') as f:
            data = [line.strip() for line in f]
    except:
        data = []

    for i in data:
        print(i)

    print (' would you like to add')
    a = raw_input()

    if a == 'yes':
        b = input()

        data.append(b)
        print (data)

    with open('data.txt', 'r') as nf:
        nf.write('\n'.join(data))
the_list()

rawDescription: Python, How to save user input to list

description: Python, How to save user input to list


code:
import json, urllib

for i in range(1,301): # loop from 1 to 300
    page_data = urllib.urlopen("http://example.com/wp-content/themes/example/html5system/request/example-8/get/%d/" % i).read()
    js = json.loads(page_data)

    with open('page%d.svg' % i, 'wb') as f_out: # save each page in a separate svg
        f_out.write(js['page'].encode('utf-8'))
        f_out.close()

rawDescription: How to make a page loop script

description: Make a page loop script


code:
def all_keys(dictlist):
    return set().union(*dictlist)

rawDescription: Union of all keys from a list of dictionaries


code:
def retrieve(self, curs, condition=None):
    query_ = "SELECT * FROM rows"
    if condition is not None:
        query_ += " %s" %condition
    curs.execute(query_)

    for row in curs.fetchall(): # iterate over the retrieved results
        yield row               # and yield each row in turn

rawDescription: python generator

description: Python generator


rawDescription: How to refresh Scapy configuration after importing it?

description: Refresh Scapy configuration after importing it


code:
import Pandas
pd.options.display.float_format = '{:20,.2f}'.format

rawDescription: Python: pd.read_csv - import all numbers after the decimal


code:
def registering(self, username, email, password, passwordCheck, phone):
    with open('static/test.jpg') as test:
        imgStringIO = StringIO(test.read())

    return self.app.post('/registering',
        content_type='multipart/form-data',
        data=dict(
            {'file': (imgStringIO, 'test.jpg')},
            username=username,
            email=email,
            password=password,
            passwordCheck=passwordCheck,
            phone=phone
        ), follow_redirects=True
    )

def test_03_registering(self):
    rv = self.registering('TestUser', 'test@test.com', 'passwordTest', 'passwordTest', '900102030')
    assert 'Registered Successfully' in rv.data

rawDescription: How to Define request.files['file'] from test function?


code: t1 = threading.Thread(target = func1, args = (arg1, arg2))

rawDescription: Python : Running function in thread does not modify current_thread()


code:
from pandas.tseries.frequencies import to_offset
to_offset('59s') < to_offset('1T')
to_offset('13T') > to_offset('59s')
to_offset('13T') < to_offset('59s')
to_offset('13T') > to_offset('2H')
to_offset('13T') < to_offset('2H')

rawDescription: How to compare frequencies/sampling rates in pandas?

description: Compare frequencies/sampling rates in pandas


code:
def getNodeDepsTree(self, node, back_path=None):
    """Return whole dependency tree for given node"""
    # List of current node dependencies
    node_deps = []

    if not back_path:
        back_path = []

    # Push current node into return path list
    back_path.append(node)

    # Get current node dependencies list
    deps = getNodeDeps(node)

    for dep in deps:
        # If dependency persist in list of visited nodes - it's a recursion
        if dep in back_path:
            pos = back_path.index(dep)
            self.log.error("Recursive link detected. '" + node
                    + "', contains a recursive link to '" + dep
                    + "'. Removing dependency. Recursive loop is:\n\t"
                    + '\n\t'.join(back_path[pos:]))
            continue
        # Recursively call self for child nodes
        node_deps.extend(self.getNodeDepsTree(dep, back_path))

    # Finally add current node as dependency
    node_deps.append(node)

    # Remove current node from list of visited nodes and return
    back_path.pop()

    return node_deps

rawDescription: Configuration inheritance mechanism

description: Configuration inheritance mechanism


code:
# build rows for each date and add to a list of rows we'll use to insert as a batch
rows = []
numberOfYears = endYear - startYear + 1
for i in range(numberOfYears):
    for j in range(12):
        # make a date for the first day of the month
        dateValue = datetime.date(startYear + i, j + 1, 1)
        index = (i * 12) + j
        row = (stationId, dateValue, temps[index], precips[index])
        rows.append(row)

# insert all of the rows as a batch and commit
ip = '192.1.2.3'
port = 1521
SID = 'my_sid'
dsn = cx_Oracle.makedsn(ip, port, SID)
connection = cx_Oracle.connect('username', 'password', dsn)
cursor = cx_Oracle.Cursor(connection)
cursor.prepare('insert into ' + database_table_name + ' (id, record_date, temp, precip) values (:1, :2, :3, :4)')
cursor.executemany(None, rows)
connection.commit()
cursor.close()
connection.close()

rawDescription: How can I do a batch insert into an Oracle database using Python?

description: Do a batch insert into an Oracle database using Python


code:
N=4
image = Image.new("RGBA", (256*N, 128*N), "#DDD")
draw = ImageDraw.Draw(image, image.mode)
draw.pieslice((0, 0 , 64*N, 64*N), 180, 270, fill="white")
del draw
image = image.resize((256,128)) # using user3479125's correction
image.save("file2.png", "PNG")

rawDescription: Python3 PIL (Pillow) draw.pieslice bad arc


code:
def f1():
  if a:
    b = 1
  elif aa:
    b = 2

def f2():
  if a:
    b = 1
  else:
    if aa:
      b = 2

dis.dis(f1)
dis.dis(f2)

rawDescription: Is the python "elif" compiled differently from else: if?


code:
links = self.browser.find_elements_by_xpath('//ol[@class="listing"]/li/h4/a')
for link in links:
    link = link.get_attribute('href')
    self.browser.get(link)
    # crawl

rawDescription: Iterating over links in selenium with scrapy


code:
def sumtuple(A,B):
    ret = []
    for a, b in zip(A, B):
        ret.append((a[0] + b[0], a[1] + b[1]))

    return ret

rawDescription: Function that returns a list of tuples.

description: Function that returns a list of tuples.


code:
import gtk

window = gtk.Dialog()
button = gtk.Button('Click Me')

style = button.get_style().copy()
style.bg[gtk.STATE_PRELIGHT] = style.bg[gtk.STATE_NORMAL]
button.set_style(style)

window.vbox.pack_start(button)
window.show_all()
window.run()

rawDescription: disable glow effect of gtkbutton

description: Disable glow effect of gtkbutton


code:
admin.site.unregister(User)

class AProfileInline(admin.StackedInline):
    model = UserProfileA

class BProfileInline(admin.StackedInline):
    model = UserProfileB

class UserProfileAdmin(UserAdmin):
    inlines = [AProfileInline, BProfileInline, ]

    def get_object(self, *args, **kwargs):
        obj = super(UserProfileAdmin, self).get_object(*args, **kwargs)
        if obj:
            self.inline_instances = []
            if AProfileInline.model.objects.filter(user=obj):
                inline_instance = AProfileInline(self.model, self.admin_site)
                self.inline_instances.append(inline_instance)
            if BProfileInline.model.objects.filter(user=obj):
                inline_instance = BProfileInline(self.model, self.admin_site)
                self.inline_instances.append(inline_instance)
        return obj

admin.site.register(User, UserProfileAdmin)

rawDescription: Django - subclassing UserAdmin to create dynamic templates?


code:
suits = ["h","c", "d", "s"]
aces = ["a" + suit for suit in suits]
aces

rawDescription: python: add a character to each item in a list

description: Python: add a character to each item in a list


code:
def __init__(self, master):
    super().__init__(master)
    self.parent = master
    self.parent.title("tic tac toe")
    self.logo = tk.PhotoImage(file="X.png")  # <----
    for i in range(3):
        for j in range(3):
            w = tk.Label(self, image=self.logo)  # <---
            w.grid(row=i, column=j)

    self.pack()

rawDescription: tkinter tic tac toe program

description: Tkinter tic tac toe program


code:
follower_user_ids = UserFollowUser.objects.filter(follower__user_id = request.user.id)\
                                          .values_list('follower__user_id', flat=True)\
                                          .distinct()
posts = Post.objects.filter(user_id__in=follower_user_ids)

rawDescription: Making a complicated query in Django all my follows posts


code: x, y, z = (v + 2 for v in l)

rawDescription: How do you apply the same action to multiple variables efficiently in Python?

description: Apply the same action to multiple variables efficiently in Python


code:
while True:
    input = input("What do you do")
    if input == "Choice1":
        print("Consequence1")
        break
    if input == "Choice2":
        print("Consequence2")
        break
    if input == "Choice3":
        print("Consequence3")
        break

rawDescription: Text Game - If statement based of input text - Python


code:
import re

file_to_write = open('tokens.txt','wb')
attribute = ['P_10490','P_9912,P_9916','P_9914,P_9915,P_9918']

for item in attribute:
    tokens = re.findall('(P_[0-9]+)', item)
    for t in tokens:
        file_to_write.write(t + '\n')

file_to_write.close()

rawDescription: split arcgis string field with mutiple delimiters into new text file in Python

description: Split arcgis string field with mutiple delimiters into new text file in Python


code:
split_data = file_object.split('\n')
result = {}
for line in split_data:
    if '=' in line:
        key, value = line.split('=', 1)
        result[key.strip()] = value.strip()
return result

rawDescription: Using Python to split a Unicode file object into dictionary Keys and values


code:
def sort_by_list(dict_, list_):
    for key in list_:
        dict_.move_to_end(key)

sort_by_list(ordereddict, key_list)

rawDescription: How to sort OrderedDict using a sorted list of keys?

description: Sort OrderedDict using a sorted list of keys


code:
import networkx as nx

# Create a graph
G = nx.florentine_families_graph()

# Save to a file
filename = 'florentine_families_graph.graphml'
G = nx.write_graphml(G, filename)

# Load from a file
filename = 'florentine_families_graph.graphml'
G = nx.read_graphml(filename)

rawDescription: Loading and saving graphs in python

description: Loading and saving graphs in python


code:
with open('inp') as inp: inp_words = set(line.strip() for line in inp)

with open('example') as example, open('result', 'w') as result:
    for line in example:
        if line.split()[0] in inp_words:
            result.write(line)

rawDescription: efficient way of string search in a file

description: Efficient way of string search in a file


code:
def p_things(p):
    '''
    things : things thing
    things : thing
    '''
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1]
        p[0].append(p[2])

rawDescription: PLY: quickly parsing long lists of items?


rawDescription: How can I indicate a specific TextCtrl within a window frame and print to it, based on program result, on wxPython?

description: Indicate a specific TextCtrl within a window frame and print to it, based on program result, on wxPython


code:
import numpy as np
import seaborn as sns
from scipy import stats
import pandas as pd
import pylab as plt

def refineLocus(Colorx,Colory, ratio):
    """
    Remove objects whose density is below 1/ratio of the mean density.
    The point density is estimated by Gaussian kernel convolution,
    with automatic bandwidth determination.
    Inputs: the color pair Colorx and Colory (the x- and y-color)
            the threshold ratio for the cut
    Output: object index array
    """
    for j in range(Colorx.shape[1]):
        X=np.array([[Colorx[i,j],Colory[i,j]] for i in range(Colorx.shape[0])])
        data = pd.DataFrame(X, columns=["X", "Y"])
        kernel = stats.gaussian_kde(X.T)
        kernel.set_bandwidth(bw_method='scott')
        KdeEval=np.zeros(Colorx.shape[0],float)
        for i in range(Colorx.shape[0]):
            KdeEval[i]=kernel.evaluate(X[i,:])
        ex=np.where(KdeEval<KdeEval.mean()/ratio)
        if (j==0):
           exarr=ex[0]
        else:
           if len(ex[0])!=0:
              exarr=np.unique(np.concatenate((exarr,ex[0])))
    for j in range(Colorx.shape[1]):
        X=np.array([[Colorx[i,j],Colory[i,j]] for i in range(Colorx.shape[0])])
        data = pd.DataFrame(X, columns=["X", "Y"])
        sns.kdeplot(data.X,data.Y,bw='scott',shade=True, cmap="Purples")
        plt.scatter(Colorx[:,j],Colory[:,j],marker='.',s=2,color='red')
        plt.scatter(Colorx[exarr,j],Colory[exarr,j],s=10,facecolors='none', edgecolors='k')
        figname = 'refineLocus.kde.%d.pdf' % (j, )
        plt.savefig(figname)
        plt.close()
    return exarr

if __name__ == "__main__":
    Cy=np.loadtxt('Colory.asc')
    Cx=np.loadtxt('Colorx.asc')
    arr=refineLocus(Cx,Cy, ratio=25)
    r=arange(Cx.shape[0])
    new_r=setxor1d(r,arr)
    nCX=Cx[new_r]
    nCY=Cy[new_r]

rawDescription: excluding the scatter points from a feature

description: Excluding the scatter points from a feature


code:
class Location_exit_state(models.Model):
    location_exit = models.ForeignKey(Location_exit, related_name='user_states')
    ...

class Location_exit(models.Model):
    ...
    default_exit_type = models.SmallPositiveIntegerField(...)

    def exit_type(self, user):
        try:
            return self.user_states.get(user=user).exit_type
        except:
            self.user_states.create(user=user, exit_type=default_exit_type)
            return default_exit_type
    exit_type.alters_data = True

    def set_new_exit_type(self, user, new_type):
        user_exit_state = self.user_states.get(user=user)
        user_exit_state.exit_type = new_type
        user_exit_state.save()
    set_new_exit_type.alters_data = True

rawDescription: Django, select queryset overriding values


code: letter = im[y:y+h,x:x+w]

rawDescription: Extract bounding box and save it as an image


code:
def test_mytest(input1):
    func(input1)
    assert input1 == result

rawDescription: How do you test a mutable, implied result?

description: Test a mutable, implied result


rawDescription: Regex to find links in one row

description: Regex to find links in one row


rawDescription: How to find an element by href value using selenium python?

description: Find an element by href value using selenium python


code: assert isinstance(something,dict)

rawDescription: Understanding json response types in Python, and IDE autocomplete


code:
from django.db.models import Count
Usage.objects.filter(no_of_people_house='4', city='HYDERABAD', nursing_cnt='2ND TIME MOTHER', bucket='BRAND PENETRATION').values('final_category').annotate(responders=Count('responders'))

rawDescription: Group by, distinct, count in django

description: Group by, distinct, count in django


code:
from xml.etree import ElementTree as ET
data = '<article n="1" translation="Year_1973_fr.xml:1"/>'
element = ET.fromstring(data)
element.attrib
element.attrib['translation']

rawDescription: Python: Get attributes

description: Python: Get attributes


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

numlines = np.random.randint(1, 15)
x = np.linspace(0, 1, 10)

fig, ax = plt.subplots()
for i in range(1, numlines + 1):
    ax.plot(x, i * x, label='$y={}x$'.format(i))

numitems = len(list(ax._get_legend_handles()))
nrows = 5
ncols = int(np.ceil(numitems / float(nrows)))

ax.legend(ncol=ncols, loc='best')

plt.show()

rawDescription: Creating matplotlib legend with dynamic number of columns


code:
import tkinter

def rgb(r, g, b):
    return "#%s%s%s" % tuple([hex(c)[2:].rjust(2, "0") for c in (r, g, b)])

root = tkinter.Tk()
root.title("Gradient")

gradient1 = tkinter.Canvas(root, width=255*2, height=50)
gradient1.pack()

gradient2 = tkinter.Canvas(root, width=255*2, height=50)
gradient2.pack()

for x in range(0, 256):
    r = x
    g = 255-x
    gradient1.create_rectangle(x*2, 0, x*2 + 2, 50, fill=rgb(r, g, 0),
        outline=rgb(r, g, 0))

for x in range(0, 256):
    r = x*2 if x < 128 else 255
    g = 255 if x < 128 else 255 - (x-128)*2
    gradient2.create_rectangle(x*2, 0, x*2 + 2, 50, fill=rgb(r, g, 0),
        outline=rgb(r, g, 0))

rawDescription: Draw a scale which ranges from red to green in Tkinter


code: plt.errorbar(x, y, yerr=err, fmt='-o',  markersize=2, color='k', label = 'size 2')

rawDescription: How to make markers on lines smaller in matplotlib?

description: Make markers on lines smaller in matplotlib


code:
firstset = set(firstlist)
[(v in firstset) for v in otherlist]

rawDescription: Python any item from a list in another list


code:
import re

instidre = re.compile(r'NEW\((\d+)\)')

class Afile(object):

  def __init__(self, filename):
    self.filename = filename
    self.geninput = dict()
    self.instances = dict()

  def feed_data(self, listoftuples):
    it = iter(listoftuples)
    assert next(it) == ('$$$$', 'General Inputs')
    for name, value in it:
      if name == '$$$$': break
      self.geninput[name] = value
    else:  # no instances at all!
      return
    currinst = dict()
    for name, value in it:
      if name == '$$$$':
        self.finish_inst(currinst)
        currinst = dict()
        continue
      mo = instidre.match(name)
      if mo:
        assert value == '.TRUE.'
        name = '$$$INSTID$$$'
        value = mo.group(1)
      currinst[name] = value
    self.finish_inst(currinst)

  def finish_inst(self, adict):
    instid = dict.pop('$$$INSTID$$$')
    assert instid not in self.instances
    self.instances[instid] = adict

rawDescription: Selective merge of two or more data files


code:
a = [(1,2),(3,5)]
all(isinstance(item, tuple) for item in a)
b = [(1,2),(3,5), "string"]
all(isinstance(item, tuple) for item in b)

rawDescription: Test if variable has type "list of tuples"


code:
import scipy, numpy, math
scipy.math.factorial, numpy.math.factorial, math.factorial

rawDescription: Factorial in numpy and scipy

description: Factorial in numpy and scipy


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

ts = pd.Series(np.random.randn(1000),
               index=pd.date_range('1/1/2000',
               periods=1000))

ts = ts.cumsum()
ts.plot()

label_list = [
    (pd.to_datetime("2001-05-01"), 'My\nbirthday', 'r'),
    (pd.to_datetime("2001-10-16"), "Dad's\nbirthday", 'b')
]

ax = plt.gca()

for date_point, label, clr in label_list:
    plt.axvline(x=date_point, color=clr)
    plt.text(date_point, ax.get_ylim()[1]-4, label,
             horizontalalignment='center',
             verticalalignment='center',
             color=clr,
             bbox=dict(facecolor='white', alpha=0.9))

plt.show()

rawDescription: Marking specific dates when visualizing a time series


code:
from rest_framework.response import Response
from rest_framework import serializers, views

class IncredibleInputSerializer(serializers.Serializer):
    model_input = serializers.CharField()

class IncredibleView(views.APIView):

    def get(self, request):
        # Validate the incoming input (provided through query parameters)
        serializer = IncredibleInputSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # Get the model input
        data = serializer.validated_data
        model_input = data["model_input"]

        # Perform the complex calculations
        complex_result = model_input + "xyz"

        # Return it in your custom format
        return Response({
            "complex_result": complex_result,
        })

rawDescription: Django and REST API to serve calculation-based requests


code:
result = sm.Logit(outcomes, values).fit()
result.predict([82,45,2])

rawDescription: Beginner stats: Predict binary outcome of set of numbers given history (Logistic regression)


code:
def somefunction(lst, position):
   count=0
   for i in range(position,len(lst)):
       if lst[i] < lst[position]:
          count += 1
   return count

somefunction([21, 4, 5, 66, 4, 3,555], 2)

rawDescription: How to tell python to use a specific value from a lst by inputing an integer of a postion (of the lst)

description: Tell python to use a specific value from a lst by inputing an integer of a postion (of the lst)


code:
import wx
class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title = title, size = (200, -1))
        self.state = 'Yes'
        self.panel = wx.Panel(self)
        self.status = wx.StaticText(self.panel, label = self.state,
                               pos = (95, 5), size = (50, 20))
        self.button = wx.Button(self.panel, label = 'Change',
                                pos = (115, 45), size = (50, 20))
        self.Bind(wx.EVT_BUTTON, self.changed, self.button)
    def changed(self, event):
        self.state = 'Yes' if self.state == 'No' else 'No'
        self.status.SetLabel(self.state)

app = wx.App(False)
frame = MyFrame(None, "Hello")
frame.Show()
app.MainLoop()

rawDescription: wxPython button changes text on panel

description: WxPython button changes text on panel


code:
import csv
import sqlite3

conn = sqlite3.connect('navjod.db')
c = conn.cursor()
# Create table name | size | hash | downloads_count | category_id* | seeders | leechers
c.execute("DROP TABLE IF EXISTS torrents")
c.execute('''CREATE TABLE torrents
             (name TEXT, size TEXT, hash TEXT UNIQUE, downloads_count TEXT,
                category TEXT, seeders INTEGER, leechers INTEGER)''')

with open('sample.csv') as csvfile:
    spamreader = csv.reader(csvfile, delimiter='|')
    for i in spamreader:
        c.execute("INSERT INTO torrents VALUES (?,?,?,?,?,?,?)", i)

conn.commit()

rawDescription: creating a database table using very large csv in python

description: Creating a database table using very large csv in python


code:
import numpy as np
a = np.fromfile("file A", dtype="uint8")
b = np.fromfile("file B", dtype="uint8")

# Compute the number of bytes that are different
different_bytes = np.sum(a != b)

# Compute the sum of the differences
difference = np.sum(a - b)

# Compute the sum of the absolute value of the differences
absolute_difference = np.sum(np.abs(a - b))

# In some cases, the number of bits that have changed is a better
# measurement of change. To compute it we make a lookup array where
# bitcount_lookup[byte] == number_of_1_bits_in_byte (so
# bitcount_lookup[0:16] == [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4])
bitcount_lookup = np.array(
    [bin(i).count("1") for i in range(256)], dtype="uint8")

# Numpy allows using an array as an index. ^ computes the XOR of
# each pair of bytes. The result is a byte with a 1 bit where the
# bits of the input differed, and a 0 bit otherwise.
bit_diff_count = np.sum(bitcount_lookup[a ^ b])

rawDescription: What information depicts the quantitative difference between two large given files of the same size?