code:
start_month = 12
start_day = 31
end_month = 1
end_day = 1
query = (models.MyModel.objects.filter(Q(month=start_month, day=start_day) |
                                       Q(month=end_month, day=end_day))
                       .extra(select={'order_me': '''CASE WHEN month*31+day < %s*31+%s
                                                          THEN (12+month)*31+day
                                                          ELSE (month)*31+day
                                                   END''' % (start_month, start_day)})
                       .extra(order_by=['order_me']))

rawDescription: Applying an arbitrary sort to Django ORM querysets


code:
from operator import add

reduce(add, myList[0])

rawDescription: How to print list of list into one single list in python without using any for or while loop?

description: Print list of list into one single list in python without using any for or while loop


code:
import lxml.etree as PARSER
root = PARSER.fromstring(data)
root.xpath("//hosts/host[@name='server1']")
a = root.xpath("//hosts/host[@name='server1']")
for i in a:
   pp = i.getparent()
   pp.remove(i)

PARSER.tostring(root, method="xml")

rawDescription: etree xml parsing and deletion

description: Etree xml parsing and deletion


rawDescription: How to execute two loop simultaneously in python?

description: Execute two loop simultaneously in python


code:
plt.plot([0, len(data)], [centroids[0]]*2, lw=1.)
plt.plot([0, len(data)], [centroids[1]]*2, lw=1.)
plt.plot([0, len(data)], [centroids[2]]*2, lw=1.)

rawDescription: plot the centroid values over the existing plot using matplotlib

description: Plot the centroid values over the existing plot using matplotlib


code:
search_string
no_space_in_string = sum(c.isprintable() for c in search_string)
no_space_in_string

rawDescription: python - pandas dataframe string search - problems with ";" ?

description: Python - pandas dataframe string search - problems with ";"


code: my_true_numbers = {0, 2323, 23452} # just the True ones

rawDescription: Reducing memory used by a large dict

description: Reducing memory used by a large dict


rawDescription: How can I analyze or improve my niece's simple compression algorithm that is based on Morse code?

description: Analyze or improve my niece's simple compression algorithm that is based on Morse code


code:
import re
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 850 152 nisi ut aliquip ex ea commodo consequat. Duis aute irure 360 458 000 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."
re.sub(r'(?<=\d)\s(?=\d)', r'', s)

rawDescription: Python: How to remove whitespace from number in a string


code:
import sys
from PyQt4 import QtGui, QtCore

class QCustomTableWidget (QtGui.QTableWidget):
    def __init__ (self, parent = None):
        super(QCustomTableWidget, self).__init__(parent)
        self.focusKeyboardOn = False
        # Setup row & column data
        listsVerticalHeaderItem = ['Device 1', 'Device 2', 'Device 3', 'Device 4', 'Device 5']
        self.setRowCount(len(listsVerticalHeaderItem))
        for index in range(self.rowCount()):
            self.setVerticalHeaderItem(index, QtGui.QTableWidgetItem(listsVerticalHeaderItem[index]))
        listsVerticalHeaderItem = ['Device 1', 'Device 2', 'Device 3', 'Device 4']
        self.setColumnCount(5)
        listsHorizontalHeaderItem = ['Option 1', 'Option 2']
        self.setColumnCount(len(listsHorizontalHeaderItem))
        for index in range(self.columnCount()):
            self.setHorizontalHeaderItem(index, QtGui.QTableWidgetItem(listsHorizontalHeaderItem[index]))

    def dataChanged (self, topLeftQModelIndex, bottomRightQModelIndex):
        row                  = topLeftQModelIndex.row()
        column               = topLeftQModelIndex.column()
        dataQTableWidgetItem = self.item(row, column)
        if (self.currentItem() == dataQTableWidgetItem) and (self.focusKeyboardOn == True):
            self.emit(QtCore.SIGNAL('currentKeyboardDataChanged'), row, column, dataQTableWidgetItem)
        self.emit(QtCore.SIGNAL('dataChanged'), row, column, dataQTableWidgetItem)
        QtGui.QTableWidget.dataChanged(self, topLeftQModelIndex, bottomRightQModelIndex)

    def focusInEvent (self, eventQFocusEvent):
        self.focusKeyboardOn = False
        QtGui.QTableWidget.focusInEvent(self, eventQFocusEvent)

    def focusOutEvent (self, eventQFocusEvent):
        self.focusKeyboardOn = True
        QtGui.QTableWidget.focusOutEvent(self, eventQFocusEvent)

class QCustomWidget (QtGui.QWidget):
    def __init__(self, parent = None):
        super(QCustomWidget, self).__init__(parent)
        self.myQCustomTableWidget = QCustomTableWidget(self)
        self.myQLabel = QtGui.QLabel('Track edited data', self)
        myQVBoxLayout = QtGui.QVBoxLayout()
        myQVBoxLayout.addWidget(self.myQLabel)
        myQVBoxLayout.addWidget(self.myQCustomTableWidget)
        self.setLayout(myQVBoxLayout)
        self.connect(self.myQCustomTableWidget, QtCore.SIGNAL('currentKeyboardDataChanged'), self.setTrackData)
        self.myQCustomTableWidget.setItem(0, 0, QtGui.QTableWidgetItem('Test'))
        self.myQCustomTableWidget.setItem(1, 1, QtGui.QTableWidgetItem('Work'))

    def setTrackData (self, row, column, dataQTableWidgetItem):
        self.myQLabel.setText('Last updated\nRow : %d, Column : %d, Data : %s' % (row + 1, column + 1, str(dataQTableWidgetItem.text())))

if __name__ == '__main__':
    myQApplication = QtGui.QApplication(sys.argv)
    myQCustomWidget = QCustomWidget()
    myQCustomWidget.show()
    sys.exit(myQApplication.exec_())

rawDescription: PyQt QTableWidget retrieve edited field

description: PyQt QTableWidget retrieve edited field


code:
def forward():
    global current_image
    current_image += 1
    if current_image >= n_images:
        current_image = 0
    change_image()

def back():
    global current_image
    current_image -= 1
    if current_image < 0:
        current_image = n_images-1
    change_image()

def stop():
    if callback is not None:
        root.after_cancel(callback)

rawDescription: Tkinter Image Viewer Method

description: Tkinter Image Viewer Method


rawDescription: Python regex: How to match an empty string?


rawDescription: View row values in openpyxl

description: View row values in openpyxl


code:
count_a = Counter(a)
count_master = Counter(master)
count_both = count_a + count_master
dups = Counter({e : min((count_a[e], count_master[e])) for e in count_a if count_both[e] > count_a[e]})

rawDescription: using FOR statement on 2 elements at once python

description: Using FOR statement on 2 elements at once python


code:
if (sign) == 2:
    if (answer) == number1+number2:
        score += 1
    else:
        pass

rawDescription: Python v3.3.5 maths questions program

description: Python v3.3.5 maths questions program


code:
class Foo(object): pass

a = Foo()
a.foo = Foo()
a.foo.bar = Foo()
a.foo.bar.baz = Foo()
a.foo.bar.baz.qux = Foo()

reduce(lambda x,y:getattr(x,y,''),['foo','bar','baz','qux'],a)
reduce(lambda x,y:getattr(x,y,''),['foo','bar','baz','qux','quince'],a)

rawDescription: How to chain attribute lookups that might return None in Python?

description: Chain attribute lookups that might return None in Python


code:
if not "\x00" in network:
    aps["row" + str(i)] = self.APStore.append([network, "", "", ""])

rawDescription: Python ignore \x00\x00\x00\x00

description: Python ignore \x00\x00\x00\x00


code:
def __init__(self, **flags):
    for flag, value in flags.iteritems():
        setattr(self, flag, value)

rawDescription: Is there a shorthand to create member variables from function arguments in python?


code:
def load(myFile):
            spamReader = csv.reader(open(myFile))
            for row in spamReader:
                    a = list(row)

            ttk.Label(loadProject, text=(a[0])).grid(column=4, row=0, sticky=W)
            ttk.Label(loadProject, text=("\n"+a[1])).grid(column=4, row=1, sticky=W)
            ttk.Label(loadProject, text=("\n"+a[2])).grid(column=4, row=2, sticky=W)
            ttk.Label(loadProject, text=(a[3])).grid(column=4, row=3, sticky=W)
            ttk.Label(loadProject, text=(a[4])).grid(column=4, row=4, sticky=W)
            ttk.Label(loadProject, text=("\n"+a[5])).grid(column=4, row=5, sticky=W)
            ttk.Label(loadProject, text=("\n"+a[6])).grid(column=4, row=6, sticky=W)
            ttk.Label(loadProject, text=("\n\n"+a[7])).grid(column=4, row=7, sticky=W)

rawDescription: How to make a button open a specific .csv file using Python Tkinter?

description: Make a button open a specific .csv file using Python Tkinter


rawDescription: How to find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay?

description: Find all neighbors of a given point in a delaunay triangulation using scipy.spatial.Delaunay


code:
if request.urlparts.path == '/login':
    continue

rawDescription: bottle hooks with beaker session middleware and checking logins

description: Bottle hooks with beaker session middleware and checking logins


code:
#------ file views.py -------------

@web.asynchronous
@gen.coroutine
class Contact_handler(Main_handler):

    def get(self, other_id):

        event = events.Event_send_contact_request(self.user_id)
        result = yield model.push_event_to_user(other_id, event)

        self.finish("ok")

rawDescription: How to move db request (which uses yield) in an other function?

description: Move db request (which uses yield) in an other function


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


code:
yt_service = gdata.youtube.service.YouTubeService()
yt_service.ssl = True

yt_service.developer_key = 'xxx'
yt_service.client_id = 'xxx'

yt_service.email = 'xxx@dd.com'
yt_service.password = 'xxx'
yt_service.source = 'youtube'
yt_service.ProgrammaticLogin()
videos = yt_service.GetYouTubeVideoFeed("https://gdata.youtube.com/feeds/api/users/default/uploads")

rawDescription: How do i get the list of all videos from youtube using gdata python library

description: Get the list of all videos from youtube using gdata python library


rawDescription: Tkinter ScrolledFrame initial dimensions


code:
def dist(X,Y):
    return math.sqrt(
                     sum( (X[i] - Y[i])**2 for i in len(range(X)) )
                    )

sum( dist(x[i],x[i+1]) for i in range(len(points)-1) )

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

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


rawDescription: Hiding shell output from subprocess.check_output()


rawDescription: Python - regex to match url with mongo object id


rawDescription: How to combine the data from many data frames into a single data frame with an array as the data values

description: Combine the data from many data frames into a single data frame with an array as the data values


code:
import re

text ='''
[AA] abcd 1234 !@#$ _+{}[]:"
blah blah
[abc-def] this is also value.
[BB]abcd defg
[CC]
'''
pattern = re.compile(r'(?sm)^\[(?P<key>AA|BB|CC)\]\s*(?P<value>(?:(?!\n\[(?:AA|BB|CC)]).)*)')
result = {m.group('key'):m.group('value') for m in pattern.finditer(text)}
print(result)
# => {'AA': 'abcd 1234 !@#$ _+{}[]:"\nblah blah\n[abc-def] this is also value.', 'CC': '', 'BB': 'abcd defg'}

rawDescription: Solved - python - regex to extract key value by brackets


code: twitter_url = 'twitter.com/%(username)s/' % {'username': 'dir01'}

rawDescription: How to make string from regex and value of group

description: Make string from regex and value of group


rawDescription: Cumulative addition/multiplication in NumPy


code:
import json
import make_json_serializable  # apply monkey-patch

class Foo(object):
    def __init__(self, name):
        self.name = name
    def to_json(self):  # New special method.
        return "{u'name': %r}" % self.name.decode('utf-8')

foo = Foo('sazpaz')
print(json.dumps(foo))  # "{u'name': u'sazpaz'}"

rawDescription: Making object JSON serializable with regular encoder


code:
for elem in soup:
    if getattr(elem, 'name', None) == u'html':
        soup = elem
        break

soup.find_all('meta')

rawDescription: Beautifulsoup functionality not working properly in specific senario


rawDescription: Python Regex sub on single character

description: Python Regex sub on single character


code:
def sumTest3(xs):
    if len(xs) == 0:
        return 0

    midpoint = len(xs) / 2
    total    = xs[midpoint] if xs[midpoint] % 2 == 0 else 0

    return sumTest3(xs[:midpoint]) + total + sumTest3(xs[midpoint + 1:])

rawDescription: sum even integer in a list of integer (without loop)

description: Sum even integer in a list of integer (without loop)


code:
import lxml.html as LH
import requests
import pandas as pd
def text(elt):
    return elt.text_content().replace(u'\xa0', u' ')

url = 'http://www.fdmbenzinpriser.dk/searchprices/5/'
r = requests.get(url)
root = LH.fromstring(r.content)

for table in root.xpath('//table[@id="sortabletable"]'):
    header = [text(th) for th in table.xpath('//th')]        # 1
    data = [[text(td) for td in tr.xpath('td')]
            for tr in table.xpath('//tr')]                   # 2
    data = [row for row in data if len(row)==len(header)]    # 3
    data = pd.DataFrame(data, columns=header)                # 4
    print(data)

rawDescription: Python: Get html table data by xpath

description: Python: Get html table data by xpath


rawDescription: Select a specific column in a DF and a random column (python3, pandas)


code:
sc = StandardScaler()
sc.fit(data)
# Now, sc.mean_ and sc.std_ are the mean and standard deviation of the data
# Replace the sc.std_ value using std calculated using numpy
sc.std_ = numpy.std(data, axis=0, ddof=1)

rawDescription: Difference between R.scale() and sklearn.preprocessing.scale()


code:
from tkinter import *
import random
from tkinter.messagebox import showinfo

class BubbleFrame:
    ##############################################
    def __init__(self, root, name):
        self.name = name
    ###############################################
        root.title("Math Bubbles")
        self.bubbles = {}
        self.score = 0
        Button(root, text="Start", width=8, command=self.initialize_bubbles).pack()
        Button(root, text="Quit", width=8, command=quit).pack()
        self.canvas = Canvas(root, width=800, height=650, bg='#afeeee')
        self.canvas.create_text(400, 30, fill="darkblue", font="Times 20 italic bold", text="Click the bubbles that are multiples of two.")
        self.current_score = self.canvas.create_text(200, 60, fill="darkblue", font="Times 15 italic bold", text="Your score is: 0")
        self.canvas.pack()

    def initialize_bubbles(self):
        for each_no in range(1, 21):
            xval = random.randint(5, 765)
            yval = random.randint(5, 615)
            oval_id = self.canvas.create_oval(xval, yval, xval + 30, yval + 30,fill="#00ffff", outline="#00bfff", width=5, tags="bubble")
            text_id = self.canvas.create_text(xval + 15, yval + 15, text=each_no, tags="bubble")
            self.canvas.tag_bind("bubble", "<Button-1>", lambda x: self.click(x))
            self.bubbles[oval_id] = (xval, yval, 0, 0, each_no, text_id)

    def click(self, event):
        if self.canvas.find_withtag(CURRENT):
            item_uid = event.widget.find_closest(event.x, event.y)[0]
            is_even = False
            try:
                self.bubbles[item_uid]
            except KeyError:
                for key, value in self.bubbles.iteritems():
                    if item_uid == value[5]:
                        if value[4] % 2 == 0:
                            is_even = True
                        self.canvas.delete(key)
                        self.canvas.delete(item_uid)
            else:
                if self.bubbles[item_uid][4] % 2 == 0:
                    is_even = True
                self.canvas.delete(item_uid)
                self.canvas.delete(self.bubbles[item_uid][5])
            if is_even:
                self.score += 1
            else:
                self.score -= 1

            if self.score == 10:
                #########################################
                showinfo("Winner", "You won %s!" % self.name)
                #########################################

        self.canvas.delete(self.current_score)
        self.current_score = self.canvas.create_text(200, 60, fill="darkblue", font="Times 15 italic bold", text="Your score is: %s"%self.score)

    def loop(self, root):
        for oval_id, (x, y, dx, dy, each_no, text_id) in self.bubbles.items():
            dx += random.randint(-1, 1)
            dy += random.randint(-1, 1)
            dx, dy = max(-5, min(dx, 5)), max(-5, min(dy, 5))
            if not 0 < x < 770:
                dx = -dx
            if not 0 < y < 620:
                dy = -dy
            self.canvas.move(oval_id, dx, dy)
            self.canvas.move(text_id, dx, dy)
            self.bubbles[oval_id] = (x + dx, y + dy, dx, dy, each_no, text_id)
        root.after(100, self.loop, root)

if __name__ == "__main__":

    root = Tk()
    ###############################################################
    Label(root, text="Welcome to Math bubbles, what is your name?").pack()
    name = Entry(root)
    name.pack()
    def submit(name, root):
        root.destroy()
        root = Tk()
        Label(root, text="Hello %s, press the Start button to begin.\n" % name).pack()
        BubbleFrame(root, name).loop(root)
    Button(root, text="Ok", command=lambda: submit(name.get(), root)).pack()
    ######################################################################
    root.mainloop()

rawDescription: Python: How to get an entry box within a message box?


code:
from Queue import Queue
from threading import Thread

def is_ssh_up(result_queue, hostname, port=22):
    # try to connect here
    # ...
    # write results
    result_queue.put((hostname, True)) # Up

def main():
    q = Queue()
    hosts = ["host1", "host2", "google.com", "host3"]

    for hostname in hosts: # start worker threads
        t = Thread(target=is_ssh_up, args=[q, hostname])
        t.daemon = True
        t.start()

    for _ in hosts: # collect results
        hostname, is_up = q.get()
        print("%s is %s" % (hostname, "Up" if is_up else "Down"))

rawDescription: python : threads do not work properly in daemon

description: Python : threads do not work properly in daemon


code: sort_map = {c: i for i, c in enumerate(card_order)}

rawDescription: sorting list of cards

description: Sorting list of cards


code: line = line.strip()

rawDescription: Python, match the first letter of the word and the last one


rawDescription: Numpy indexing multidimensional arrays with array and slice


code: {k: sum(d[k] for d in my_dict) for k in reduce(set.intersection, map(set, my_dict))}

rawDescription: Python: find common keys and sort by value


code:
# setup.py
from packageTest import __version__
...

rawDescription: How do I assign a version number for a Python package using SVN and distutils?

description: Assign a version number for a Python package using SVN and distutils


code:
import re
from collections import OrderedDict as _OrderedDict

def Markdown_list_to_dictionary(Markdown_list):
    line = re.compile(r"( *)- ([^:\n]+)(?:: ([^\n]*))?\n?")
    depth = 0
    stack = [_OrderedDict()]
    for indent, name, value in line.findall(Markdown_list):
        indent = len(indent)
        if indent > depth:
            assert not stack[-1], "unexpected indent"
        elif indent < depth:
            stack.pop()
        stack[-1][name] = value or _OrderedDict()
        if not value:
            # new branch
            stack.append(stack[-1][name])
        depth = indent
    return(stack[0])

Markdown_list =\
"""
- launchers
   - say hello
      - command: echo "hello" | festival --tts
      - icon: shebang.svg
   - say world
      - command: echo "world" | festival --tts
      - icon: shebang.svg
   - say date
      - command: date | festival --tts
"""

print(Markdown_list_to_dictionary(Markdown_list))

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


code: fit(X, y=None, sample_weight=None)

rawDescription: How to assign sample_weights in sklearn.cluster DBSCAN?

description: Assign sample_weights in sklearn.cluster DBSCAN


code:
xml = """<DOCUMENT>
<PAGE width="544.252" height="634.961" number="1" id="p1">
<MEDIABOX x1="0" y1="0" x2="544.252" y2="634.961"/>

<BLOCK id="p1_b1">

<TEXT width="37.7" height="74.124" id="p1_t1" x="51.1" y="20.8652">
<TOKEN sid="p1_s11" id="p1_w1" font-name="Verdanae" bold="yes" italic="no">111</TOKEN>
</TEXT>
</BLOCK>

<BLOCK id="p1_b3">

<TEXT width="151.267" height="10.725" id="p1_t6" x="24.099" y="572.096">
<TOKEN sid="p1_s35" id="p1_w22" font-name="Verdanae" bold="yes"     italic="yes">AAA</TOKEN>
<TOKEN sid="p1_s36" id="p1_w23" font-name="verdanae" bold="yes" italic="no">BBB</TOKEN>
<TOKEN sid="p1_s37" id="p1_w24" font-name="verdanae" bold="yes" italic="no">CCC</TOKEN>
</TEXT>
</BLOCK>

<BLOCK id="p1_b4">

<TEXT width="82.72" height="26" id="p1_t7" x="55.426" y="138.026">
<TOKEN sid="p1_s42" id="p1_w29" font-name="verdanae" bold="yes" italic="no">DDD</TOKEN>
<TOKEN sid="p1_s43" id="p1_w30" font-name="verdanae" bold="yes" italic="no">EEE</TOKEN>
</TEXT>

<TEXT width="101.74" height="26" id="p1_t8" x="55.406" y="162.026">
<TOKEN sid="p1_s45" id="p1_w31" font-name="verdanae" bold="yes" italic="no">FFF</TOKEN>
</TEXT>

<TEXT width="152.96" height="26" id="p1_t9" x="55.406" y="186.026">
<TOKEN sid="p1_s47" id="p1_w32" font-name="verdanae" bold="yes" italic="no">GGG</TOKEN>
<TOKEN sid="p1_s48" id="p1_w33" font-name="verdanae" bold="yes" italic="no">HHH</TOKEN>
</TEXT>
</BLOCK>
</PAGE>
</DOCUMENT>"""
from lxml import etree
parsed = etree.fromstring(xml)
tokens = parsed.xpath('//TOKEN/text()')
tokens

rawDescription: Parsing Data in XML and Storing to DB in Python


rawDescription: 2D numpy array- check to see if all adjacent terms are equal


rawDescription: what is the Python equivalent of Ruby's yield?

description: What is the Python equivalent of Ruby's yield


rawDescription: list with numbers and strings to single string python

description: List with numbers and strings to single string python


code: np.all(a == 0, axis=-1).astype(int)

rawDescription: How to modify specific field in ndarray matrix

description: Modify specific field in ndarray matrix


code:
if yy<-.00001:
    y=0
    yy=sh   # <- add this line
    y+= 1
    pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)

rawDescription: animation in pygame

description: Animation in pygame


code:
data1 = [ data["info"][idx] for idx, x in enumerate(data["id"]) if x == 1 ]
#data1 = ['info1', 'info2', 'info5', 'info7']

rawDescription: Splitting dict by value of one of the keys


rawDescription: Shift elements in a numpy array

description: Shift elements in a numpy array


code:
iterable = iter(xrange(100))
for i in iterable:
    if i % 10 == 0:
        [iterable.next() for x in range(10)]

rawDescription: What's the best way of skip N values of the iteration variable in Python?


code:
import logging
log = logging.getLogger(__name__)
log.info("Whatever your info message.")

rawDescription: logger chain in python

description: Logger chain in python


code:
import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

rawDescription: How to save and load cookies using python selenium webdriver

description: Save and load cookies using python selenium webdriver


code:
a = int(input())
setx = set() #initializing empty sets
sety = set()
for _ in range(a):  #underscore often used when you don't care about what you're iterating over, just that you iterate a certain amount of times.
    setx.add(input()) #Previously, you'd just get the last input
    sety.add(input()) #I doubt that's what you wanted
if setx.intersection(sety): #no need to compare to empty set. if set() will evaluate as false
    print("NO")
else:
    print("YES")

rawDescription: What is a set? And what does "a for a in i" do?


code:
# writing data to a file
favorite_colors = {'tim':'yellow','mary':'blue'}

newsave_file = open(filename,'w')
for key, val in favorite_colors.items():
    newsave_file.write(str(key)+'|'+str(val)+'\n')

newsave_file.close()

# reading data from a file
favorite_colors = {}
open_file = open(filename,'r')
for line in open_file:
    pair = line.split('|')
    favorite_colors[pair[0]] = pair[1]
open_file.close()

rawDescription: How to load file and create infinite save files?

description: Load file and create infinite save files


rawDescription: How to convert utf-8 string to big5 with python?

description: Convert utf-8 string to big5 with python


rawDescription: How to style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)

description: Style (rich text) in QListWidgetItem and QCombobox items? (PyQt/PySide)


code:
d = hf.create_dataset('data', data=intdata)
d_new = get_dataset_as_type(d, dtype='float32')

print(d[:])
# array([81, 65, 33, 22, 67, 57, 94, 63, 89, 68], dtype=uint16)
print(d_new[:])
# array([ 81.,  65.,  33.,  22.,  67.,  57.,  94.,  63.,  89.,  68.], dtype=float32)

print(d.dtype, d_new.dtype)
# uint16, uint16

rawDescription: Creating reference to HDF dataset in H5py using astype


code: "({:d} goals, ${:d})".format(self.goals, self.penalties)

rawDescription: String Formatting in Python 3

description: String Formatting in Python 3


code:
"""
>> from packagename import module
>> module.show_real_world_usage()
'Hello world!'
"""

rawDescription: Python doctest: Skip entire block?

description: Python doctest: Skip entire block


rawDescription: Eliminate dups and sum corresponding terms in lists


code:
def product(*args, **kwds):
        '''
        Source: http://docs.python.org/library/itertools.html#itertools.product
        '''
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x+[y] for x in result for y in pool]
        for prod in result:
            yield tuple(prod)

rawDescription: Is there an algorithm to find unique combinations of 2 lists? 5 lists?


code:
total_days = 3
days = [0 for _ in range(total_days)]

rawDescription: Simple Python loop counter issue

description: Simple Python loop counter issue


code:
from Bio import AlignIO

align = AlignIO.read("Clustalw/opuntia.aln", "clustal")
indices = [12, 52, 68, 45]
columns_as_strings = []

for column in indices:
    columns_as_strings.append(align[:, column])

rawDescription: How to filter alignment columns based on list of position in biopython?

description: Filter alignment columns based on list of position in biopython


code: for dic in l: dic["order"] = tr[dic["name"]]

rawDescription: Adding a key value pair to a list of dicts based on another list Python


code:
def myMethod(request):
    par1 = request.GET.get('par1')
    par1 = request.GET.get('par2')
    list = request.GET.get('list').split('-and-')

    result = DO_SOMETHING(par1,par2,list)
    return result

rawDescription: Send a list to django within an ajax GET request


code:
from itertools import product

def extend_kmer(n, kmer="", alphabet="ATGC"):
    """
    >>> list(extend_kmer(2))[:4]
    ['AA', 'AT', 'AG', 'AC']
    """
    tails = product(alphabet, repeat=n)
    for tail in tails:
        yield kmer + "".join(tail)

def generate_kmers(k, seed_size,  alphabet="ATGC"):
    """
    >>> kmers = generate_kmers(6, 3, "ATGC").collect()
    >>> len(kmers)
    4096
    >>> sorted(kmers)[0]
    'AAAAAA'
    """
    seed = sc.parallelize([x for x in extend_kmer(seed_size, "", alphabet)])
    return seed.flatMap(lambda kmer: extend_kmer(k - seed_size, kmer, alphabet))

k = ... # Integer
seed_size = ... # Integer <= k
kmers = generate_kmers(k, seed_size) # RDD kmers

rawDescription: Spark: Generate Map Word to List of Similar Words - Need Better Performance


code:
pylab.plot(x, y)

ax = pylab.gca() # Gets the current axis object

text = ax.yaxis.get_offset_text() # Get the text object

text.set_size(30) # # Set the size.

pylab.show()

rawDescription: Python Pylab, how to alter the size of the label specifying the magnitude of the axes


code:
from collections import namedtuple
ll2D = namedtuple('Labeled_line2D',['line2D_obj','labels'])

rawDescription: What is a simple, yet proper, way to add a container to a pre-exisiting object in python?


code:
head = tail = Element(0, None)
tail.next = tail = Element(1, None)
head.value
head.next
head.next.value
tail is head.next
tail.next = tail = Element(2, None)
tail is head.next.next

rawDescription: Issue with Python implementation of assignment chaining


code:
class MockServices:
    def user_exists(id):
        return True

rawDescription: How to mock the service layer in a python (flask) webapp for unit testing?

description: Mock the service layer in a python (flask) webapp for unit testing


code:
import collections

def map_nested_dicts(ob, func):
    if isinstance(ob, collections.Mapping):
        return {k: map_nested_dicts(v, func) for k, v in ob.iteritems()}
    else:
        return func(ob)

map_nested_dicts(x, lambda v: v + 7)
# Creates a new dict object:
#    {'a': 8, 'b': {'c': 13, 'g': {'h': 10, 'i': 16}, 'd': 14}, 'e': {'f': 10}}

rawDescription: Python: Apply function to values in nested dictionary


code:
import re
from collections import defaultdict
regex = re.compile('([a-z]+\-)\d(\-[a-z]+)')

t = ["asdf-1-bhd","uuu-2-ggg","asdf-2-bhd","uuu-1-ggg","asdf-3-bhd"]

maps = defaultdict(list)

for x in t:
    parts = regex.match(x).groups()
    maps[parts[0]+parts[1]].append(x)

rawDescription: Split list into chunks by condition

description: Split list into chunks by condition


code:
def antilog(x):
    return 10 ** x

rawDescription: How to find every integer that is the closest to the antilogarithm (10base) for a series of n*0.1 (in Python)

description: Find every integer that is the closest to the antilogarithm (10base) for a series of n*0.1 (in Python)


code:
with open(localFileTT, 'rb', 0) as f:
    while True:
        chunk = f.read(1000)
        if not chunk:
            # EOF reached, end loop
            break
        # chunk is up to 1000 characters long

rawDescription: python read 1000 at a time until end of file?

description: Python read 1000 at a time until end of file


code:
counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])

rawDescription: Sort list by frequency in python

description: Sort list by frequency in python


code:
input = 'FFFF'
val = int(input,16) # is 65535

rawDescription: How can I convert a hex ASCII string to a signed integer

description: Convert a hex ASCII string to a signed integer


rawDescription: Use of SQL - IN in python

description: Use of SQL - IN in python


code:
from itertools import product

def flatten(lst):
    return [ x for it in list for x in it ]

def multi_product(lists, repeats):
    producted = [ product(lst, repeat) for lst, repeat in zip(lists, repeats) ]
    return ( flatten(x) for x in product(*producted) )

rawDescription: Can itertools allow for list to be created from multiple lists where I set a limit to how many selections per list?


code:
from collections import OrderedDict

tmp = OrderedDict()
for point in zip(x, y, z):
    tmp.setdefault(point[:2], point)

mypoints = tmp.values()

rawDescription: Python: method to remove all duplicate points from a X,Y,Z file that have identical x and y coordinates


code:
zm1 = clipped_zoom(img, 0.5)
zm2 = clipped_zoom(img, 1.5)

fig, ax = plt.subplots(1, 3)
ax[0].imshow(img, cmap='gray')
ax[1].imshow(zm1, cmap='gray')
ax[2].imshow(zm2, cmap='gray')

rawDescription: Scipy rotate and zoom an image without changing its dimensions


code: t = map(lambda s: s.strip(), t)

rawDescription: How to remove \n from a list element?

description: Remove \n from a list element


rawDescription: Stuck with Number Float format in Python Decimal


code:
import urllib2
req = urllib2.Request('http://www.facebook.com/')
req.add_header('Referer', 'http://www.lastpage.com/')
r = urllib2.urlopen(req)

rawDescription: Accessing Facebook from Python

description: Accessing Facebook from Python


code:
import re
string_test = "this.day"
re.sub(r"^(.)[^.]*\.(.*)", r"\1.\2", string_test)

rawDescription: How can I index group elements in re.sub?

description: Index group elements in re.sub


rawDescription: Reading binary data (image data type) from SQL database and inflate it, Matlab vs. Python


code:
loc2reg = {}
def populate_loc2reg():
    for region in regionList:
        for location_name in region:
            loc2reg[location_name] = [region[0], location_name]

rawDescription: Set player's main region depending on location - Python


rawDescription: Python 2.7.8 string slicing by letter?

description: Python 2.7.8 string slicing by letter


code:
from urlparse import urlparse
from functools import wraps
from flask import (
    Flask,
    redirect,
    request,
    render_template_string,
    url_for)
app = Flask(__name__)

def confirm_referrer(path, redirect_func):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            ref = urlparse(request.referrer or '')
            if (request.host, path) == (ref.netloc, ref.path):
                return f(*args, **kw)
            return redirect(url_for(redirect_func))
        return wrapper
    return decorator

@app.route('/map')
def map():
    return render_template_string('''

Demonstrate

        ''')

@app.route('/demo')
@confirm_referrer('/map', 'map')
def demo():
    return '''
This is a demonstration
'''

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: User Must Take Action for Page Redirection to Work in Flask


code:
def make_3sg_form():
    Word = input('Enter a word: ')
    if Word.endswith('y'):
        New_word=Word[:-1]+'ies'

    elif Word.endswith(('o', 'ch', 's', 'sh', 'x' ,'z')):
        New_word=Word+'es'

    else:
        New_word=Word+'s'
    print(New_word)
make_3sg_form()

rawDescription: Python 3.4 endswith()

description: Python 3.4 endswith()


code: #print('foo')  --> logging.debug(('foo'))

rawDescription: Convert commented out print statements to logging calls - Python


code:
x=np.zeros((0,4),float)
x
x==[]
0 in x.shape  # check if there's a 0 in the shape

rawDescription: remove empty numpy array

description: Remove empty numpy array


code: line = line.rstrip()

rawDescription: extracting data from multiple text files using python

description: Extracting data from multiple text files using python


code:
def check_answer(number1, number2, answer, operator):
    if operator == "+":
        test = number1 + number2
        return test == answer
    if operator == "-":
        test2 = number1 - number2
        return test2 == answer

answer1 = check_answer(1, 2, 3, "+")
print (answer1)
answer2 = check_answer(1, 2, -1, "-")
print (answer2)
answer3 = check_answer(9, 5, 3, "+")
print (answer3)
answer4 = check_answer(8, 2, 4, "-")
print (answer4)

rawDescription: Python "none" printing

description: Python "none" printing


code:
cv.ConvertScale(frameImg, frameImg, scale=0.5)
cv.ShowImage( "My Video Window",  frameImg )

rawDescription: What's the fastest way to iterate over a CvMat in Python using OpenCV?


rawDescription: NumPy: counting sizes of row-wise intersections between two arrays


rawDescription: Python : go backwards through a string, then remove everything after a specific character


code:
a = A(['foo', 'bar'])     #pass a list
b = A(('spam', 'eggs'))   #pass a tuple
a.idx
a.idx = ('python', 'org')  #works
b.idx = ('python',)         #fails

rawDescription: Property setter with multiple values

description: Property setter with multiple values


rawDescription: python - matplotlib - How to specify the scale for x axis

description: Python - matplotlib - How to specify the scale for x axis


code:
import urllib2
from bs4 import BeautifulSoup

url = 'http://www.millercenter.org/president/speeches'

date_soup = BeautifulSoup(urllib2.urlopen(url), "lxml")
speeches = date_soup.select('div#listing div.title a[href*=speeches]')

for speech in speeches:
    text = speech.get_text(strip=True)
    print(text)

rawDescription: Removing items from list if is not in '<a href'?


code: x = new_object

rawDescription: Python Assignment or Variable binding?

description: Python Assignment or Variable binding


rawDescription: Finding a string in a string in a list python


code:
import re
s = "(891 1783 1)"
pattern = re.compile('\d+')
pattern.sub(lambda m: str(int(m.group(0)) + 1), s)

rawDescription: Increment all numbers in a file

description: Increment all numbers in a file


code: getch()

rawDescription: Python key binding/capture

description: Python key binding/capture


code:
utf8_key = u'å'.encode('utf8')  # manually encoded for demo purposes
utf8_key
utf8_d = {utf8_key: 'bar'}
utf8_d
new_utf8_d = json.loads(json.dumps(utf8_d))
new_utf8_d
new_utf8_d[u'å']

rawDescription: How do you save a complex dictionary in JSON file, and then load it back as dictionary?

description: Save a complex dictionary in JSON file, and then load it back as dictionary


code:
from itertools import product
for x, y in product(range(n), repeat=2):
    ...

rawDescription: How to handle a variable number of nested for loops?

description: Handle a variable number of nested for loops


code: l_grouped = groupby(l_sorted, key=itemgetter(0))

rawDescription: How to add items in a list of tuples if the item is the same

description: Add items in a list of tuples if the item is the same


code:
def buttons_clicked(self):
  text = color_dialog_get_some_text() # customize this
  self.button_map[self.sender].setText(text)

rawDescription: Associate many QButtons with many QLineEdits


code:
import subprocess
import time
import datetime
from _winreg import *
from dateutil.parser import parse

def runProcess(exe):
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
      retcode = p.poll() #returns None while subprocess is running
      line = p.stdout.readline()
      yield line
      if(retcode is not None):
        break

def nasTime():
    for line in runProcess(r"net time \\nas".split()):
        timeLine = line
        break
    timeLine = timeLine.split("is ")[1].replace("\r\n", "")
    hKey = OpenKey (HKEY_CURRENT_USER, r"Control Panel\International")
    value, type = QueryValueEx (hKey, "sShortDate")
    dayFirst = str(value).lower().startswith("d") # tells if day first format was being used
    return time.mktime(parse(timeLine, dayfirst = dayFirst).timetuple())

rawDescription: How to determine what date time format the system is using?

description: Determine what date time format the system is using


rawDescription: Sort a list of dictionaries while consolidating duplicates in Python?


code:
class ButtonGroupBox(QtGui.QWidget):

    def __init__(self, parent=None):
        super(ButtonGroupBox, self).__init__(parent=parent)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.setContentsMargins(0,24,0,0)
        self.groupBox = QtGui.QGroupBox(self)
        self.button = QtGui.QPushButton("FOO", parent=self)
        self.layout.addWidget(self.groupBox)

        self.button.move(0, -4)

rawDescription: How to build a QGroupBox with a button in the title?

description: Build a QGroupBox with a button in the title


code:
def findFood(food, data):
    foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
    for line in data:
        ...

rawDescription: finding item in text file during 2nd read

description: Finding item in text file during 2nd read


code:
text=[]
with open('read_file.txt','r') as f:
    for line in f:
        for word in line.split(": "):
            text.append(word)

rawDescription: Transpose multiple txt data files and import into excel or database


rawDescription: Find span where condition is True using NumPy


rawDescription: What is the easiest way to detect a cross-over in values of 1d list?


code:
PARSERS = (
    (re.compile(r'([0-9]+)\(([-+0-9.]+)[mM]\)'), 1000000),
    (re.compile(r'([0-9]+)\(([-+0-9.]+)[kK]\)'), 1000),
    (re.compile(r'([0-9]+)\(([-+0-9.]+)\)'), 1),
)

def parse(num):
    for pattern, multiplier in PARSERS:
        match = pattern.match(num)
        if match is not None:
            return float(match.group(1)), float(match.group(2)) * multiplier
    raise ValueError("Failed to parse")

rawDescription: Regular Expression for Financial Numbers


rawDescription: Python: Why this tuple is printing the result and "None"? Also: Is there a better way to achieve the result?


code:
class Foo(object):
    pass

rawDescription: Python new-style classes and __subclasses__ function


code: df_cuts.sum() == df['agrpreg'].sum()

rawDescription: python & pandas: How do I split a dataframe into groups

description: Python & pandas: How do I split a dataframe into groups


code:
df.index = df.dt
time1=datetime.strptime("20150101 11:00", "%Y%m%d %H:%M")
time2=datetime.strptime("20150102 12:00", "%Y%m%d %H:%M")
df.ix[time1:time2]['count'].cumsum()

rawDescription: Python Pandas cumulative column between datetime ranges


code: yield [dict1[item1][i] for i in other1_poss], [dict2[item2][i] for i in other2_poss]

rawDescription: Help using *args in tuple matching Python function


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

rawDescription: Pandas count the number of different items within a column of data


code: res = thingy(res) # instead of thingy(res)

rawDescription: How can I save a variable inside a definition in python?

description: Save a variable inside a definition in python


rawDescription: order of parameters of function call of python

description: Order of parameters of function call of python


code:
{
    ' numbers': [' 1', ' 2', ' 3', ' 4'],
    ' colors ': [' blue', ' red', ' green', ' yellow'],
    'strings': ['string1', 'string2', 'string3', 'string4']
}

rawDescription: python csv to dictionary columnwise

description: Python csv to dictionary columnwise


code: name = r'Br\"{u}derle'

rawDescription: latexcodec stripping slashes but not translating characters (Python)

description: Latexcodec stripping slashes but not translating characters (Python)


rawDescription: Making nonzero elements in grayscale array equal to 1 in 'G' column in an RGB array in Python


code:
maxloop = len(protein)
n = 0
while n < maxloop:
    met = protein.find("M", n)
    if met == -1:
        break
    #etc
    n = nextmet + 1

rawDescription: Printing all occurrences in a string starting with x and ending with y


rawDescription: Negative power in modular pow()

description: Negative power in modular pow()


code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

groups = df.groupby('label')

# Plot
fig, ax = plt.subplots()
ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling
for name, group in groups:
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name)
ax.legend()

plt.show()

rawDescription: Scatter plots in Pandas/Pyplot: How to plot by category


rawDescription: Transformations with DataFrame exporting series


code:
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/searchQuery', methods=['POST'])
def search_query():
    sq_ = request.form.get('searchQuery')
    print(sq_)

    return render_template('simplesearch.html', search_query=sq_)

rawDescription: Creating variable numbers of text boxes using Python Flask?


code:
aba
aa
bbb

rawDescription: python list elements start with and end with same character

description: Python list elements start with and end with same character


code:
def __init__(self, *args, **kwargs):
  super(TreasureHuntGrid, self).__init__(*args, **kwargs)
  status = ListProperty(Finish.board) #Return a random lists of lists with 1 and -1
  calculations = status

rawDescription: How to copy a class variable - Python

description: Copy a class variable - Python


code:
from lxml import html

doc = html.fromstring("""
3 Detroit
""")
stop_nodes = doc.cssselect('li a')
stop_names = []
for start in stop_list:
    node_text = start.itertext()
    node_text.next() # Skip '3'
    stop_names.append(node_text.next().lstrip())
    continue

rawDescription: lxml classic: Get text content except for that of nested tags?

description: Lxml classic: Get text content except for that of nested tags


rawDescription: Find string within a string and save it to file on BioPython


code:
ROUTES = (webapp2.Route('/extraction', ExtractionWorker),
          webapp2.Route('/indexer', IndexingWorker))

rawDescription: App engine tasks are not executed in defined target


code: list(filter(lambda d: d['type'] in keyValList, exampleSet))

rawDescription: python filter list of dictionaries based on key value

description: Python filter list of dictionaries based on key value


rawDescription: Merge multiple dataframes with non-unique indices


rawDescription: how to (simply) build a integer and float mixed numpy array


code: ["|".join([p, q, r]) for p, q, r in product(*lst)]

rawDescription: Python 3.3: All possible combinations of list


code:
if keyword0 in list and keyword1 in list:
    # do your work
    pass

rawDescription: Checking for a string/keyword in a list

description: Checking for a string/keyword in a list


rawDescription: how to create a mask from time points for a numpy array?

description: Create a mask from time points for a numpy array


code:
from django.shortcuts import redirect

def login_success(request):
    """
    Redirects users based on whether they are in the admins group
    """
    if request.user.groups.filter(name="admins").exists():
        # user is an admin
        return redirect("admin_list")
    else:
        return redirect("other_view")

rawDescription: Django -- Conditional Login Redirect

description: Django -- Conditional Login Redirect


code:
def get_subdicts(i):
    body = i.find_all("div", id=lambda x: x and x.startswith('game-wrapper-s-'))
    for bet in body:
        yield {get_bets_pav(bet): get_cof(bet)}

pavdict = {get_main_pav(i): tuple(get_subdicts(i)) for i in kofai}

rawDescription: dictionary of dictionaries(nested dicts)

description: Dictionary of dictionaries(nested dicts)


code:
import re
sentence = input("Give me a sentence ")
word = input("What word would you like to find ")
for match in re.finditer(word, sentence):
    print (match.start(), match.end())

rawDescription: How to find all the indexes of all the occurrences of a word in a string

description: Find all the indexes of all the occurrences of a word in a string


code: [n == int(n) for n in x]

rawDescription: Finding round figure

description: Finding round figure


code: map(''.join, zip(*(s[i:] for i in range(4))))

rawDescription: Most efficient way to take sequential substrings python


rawDescription: Redimension numpy array dynamically

description: Redimension numpy array dynamically


code:
name, params = s.split('(')
name = name.split()[1]
params = params[:-1].split(',')
d = {'module_name':name,
     'module_params':params[:-1],
     'module_last_param':params[-1]}

rawDescription: Save matches on array

description: Save matches on array


rawDescription: Converting 3D matrix to cascaded 2D Matrices


code:
s = Series([True])
s.append(Series([nan], index=[1], dtype=object))

rawDescription: Preserving the distinctions between bools and floats when adding NaN to a pandas Series?


code:
with open("your_file.txt") as file:
     for line in file:
          do_something(line)

rawDescription: How to read a line from a text file and use it as an input

description: Read a line from a text file and use it as an input


rawDescription: Most pythonic way to convert a list of tuples


rawDescription: How to parse a zcat output

description: Parse a zcat output


code:
from google.appengine.ext import deferred

def do_something_expensive(a, b, c=None):
  logging.info("Doing something expensive!")
  # Do your work here

# Somewhere else
deferred.defer(do_something_expensive, "Hello, world!", 42, c=True)

rawDescription: Processing data after returning content - GAE Python


code:
class LazyWrapper(object):
    def __init__(self, func):
        self.func = func
    def __call__(self):
        try:
            return self.value
        except AttributeError:
            self.value = self.func()
            return self.value

rawDescription: python lazy variables?  or, delayed expensive computation

description: Python lazy variables?  or, delayed expensive computation


code:
numbers = [sum(v.isnumeric() for v in part) for part in partition2d]

numbers
#>>> [2, 3, 4]

rawDescription: Count number of elements in each row in 2D list


code: data = np.loadtxt('data.txt', dtype=float, delimiter=',')

rawDescription: Converting coordinate tuple information to numpy arrays


rawDescription: mongodb: query for values (not objects) in list

description: Mongodb: query for values (not objects) in list


code:
sequence = "GAGCCATCTATTGCTTACATTTGCTTCTGACACAACTGTGTTCACTAGCAACCTCAAACAGACACCATGGTGCACCTGACTCCTGTGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGTTGGTATCAAGGTTACAAGACAGGTTTAAGGAGACCAATAGAAACTGGGCATGTGGAGACAGAGAAGACTCTTGGGTTTCT"
codon_list = ["ATG", "TAA", "TAG", "TGA"]

# store the starting positions of the codons
found_codon_positions = []

# note that we can use len() and [] with strings as well, no need to
# convert to list first
n = len(sequence)
k = 0
while k < n-2:
    # extract a three-nucleotide subsequence
    possible_codon = sequence[k:k+3]
    if possible_codon in codon_list:
        found_codon_positions.append(k)
    k += 1

print('found codons at indices {}'.format(found_codon_positions))

print('extracted sequence:')
print(sequence[found_codon_positions[0]:found_codon_positions[-1]+3])

rawDescription: Python code to find coding DNA with start and stop codons


code:
# file: foo.py
import singleton

def foo():
    # ... do complex computations ...
    singleton.element_list.append('baz')

rawDescription: Define a constructor in full classmethod class


rawDescription: Collecting like term of an expression in Sympy


code:
class TestBottleServer(object):
    """
    Starts a local instance of bottle container to run the tests against.
    """
    is_running = False

    def __init__(self, app=None, host="localhost", port=3534, debug=False, reloader=False, server="tornado"):
        self.app = app
        self.host = host
        self.port = port
        self.debug = debug
        self.reloader = reloader
        self.server = server

    def ensured_bottle_started(self):
        if TestBottleServer.is_running is False:
            start_new_thread(self.__start_bottle__, (), {})
            #Sleep is required for forked thread to initialise the app
            TestBottleServer.is_running = True
            time.sleep(1)

    def __start_bottle__(self):
        run(
            app=self.app,
            host=self.host,
            port=self.port,
            debug=self.debug,
            reloader=self.reloader,
            server=self.server)

    @staticmethod
    def restart():
        TestBottleServer.is_running = False
        TestBottleServer.ensured_bottle_started()

TEST_BOTTLE_SERVER = TestBottleServer()

rawDescription: python bottle integration tests

description: Python bottle integration tests


code:
import bottle

app = bottle.app()

def redirect_http_to_https(callback):
    '''Bottle plugin that redirects all http requests to https'''

    def wrapper(*args, **kwargs):
        scheme = bottle.request.urlparts[0]
        if scheme == 'http':
            # request is http; redirect to https
            bottle.redirect(bottle.request.url.replace('http', 'https', 1))
        else:
            # request is already https; okay to proceed
            return callback(*args, **kwargs)
    return wrapper

bottle.install(redirect_http_to_https)

@bottle.route('/hello')
def hello():
    return 'hello\n'

bottle.run(host='127.0.0.1', port=8080)

rawDescription: How to set wsgi.url_scheme to https in bottle?

description: Set wsgi.url_scheme to https in bottle


code:
with open(file_name) as fid:
    for line in fifo(fid, n_skip):
        do_something_with(line)

rawDescription: Simple Way of NOT reading last N lines of a file in Python


rawDescription: matplotlib animation FuncAnimation frames argument

description: Matplotlib animation FuncAnimation frames argument


code: max(c, key=c.get)

rawDescription: How to find the 2nd max of a Counter - Python

description: Find the 2nd max of a Counter - Python


code: result = '%d%d%d' % (one, two, three)

rawDescription: Showing numbers one after the other instead of them adding up


code: df

rawDescription: Pandas: Combining values in multiple columns to create a new column


code:
# urls.py
from django.conf.urls import patterns, url, include
from myproject.admin import admin_site

urlpatterns = patterns('',
    (r'^myadmin/', include(admin_site.urls)),
)

rawDescription: Why isn't admin.autodiscover() called automatically in Django when using the admin, why was it designed to be called explicitly?


rawDescription: How to ignore '\n' while comparing two lists

description: Ignore '\n' while comparing two lists


code:
in_use = []
for server in nc.servers.list():
    in_use.append(server.image['id'])

rawDescription: Openstack - Selectively deleting images based on some criteria?


code: for row in A: print(np.amax(row))

rawDescription: Whats the best way to iterate over multidimensional array and tracking/doing operations on iteration index


code:
revised( step2 )
revised( step2_alternative )

rawDescription: What is an elegant way to abstract functions - not objects?


code:
class Base:
    __count = 0
    @classmethod
    def _count(cls):
        Base.__count += 1
        return Base.__count
    def __init__(self):
        self.__id = self._count()
    @property
    def id(self):
        return self.__id

class SubBase1(Base): pass

class SubBase2(Base): pass

SubBase1().id
SubBase1().id
SubBase2().id
SubBase2().id

rawDescription: How to count the number of instance of a custom class?

description: Count the number of instance of a custom class


rawDescription: Python sort CSV File

description: Python sort CSV File


code:
def show_items():
    T = len(data) # not sure where your data comes from, or if you have to process a query first...
    P = request.vars.page # e.g. http://blah.com/show_items?page=0
    I = request.vars.ipp # e.g. http://blah.com/show_items?page=0&ipp=50

    #now the code from before...
    num_pages = Math.Ceil( T / I ) # ceil(100/10) = 10 pages
    cur_page = P # 0

    start = I*P # 10 * 0 = 0
    end = start + ipp # 0 + 10 = 10
    if end > total: # false
      end = total

    items = allitems[start:end] # this page's items

    return dict(
      data=items,
      start=start,
      end=end,
      total=total,
      prev=page-1 if page > 0 else None, # set to None if page =0
      next=page+1 if page < num_pages else None, # set to None if page == num_pages
    )

rawDescription: Pagination in web2py with no database

description: Pagination in web2py with no database


code: [item.strip() for item in my_string.split(',')]

rawDescription: Splitting string and removing whitespace Python


rawDescription: Access a hidden library function in Python?


code:
image = self.request.POST.get("imageurl")
image_read = image.file.read()
b64 = base64.b64encode(image_read)

rawDescription: Getting file location from an html form

description: Getting file location from an html form


code:
def static(**kwargs):
    def wrap_f(function):
        def probeFunc(frame, event, arg):
            if event == 'call':
                frame.f_locals.update(kwargs)
                frame.f_globals.update(kwargs)
            elif event == 'return':
                for key in kwargs:
                    kwargs[key] = frame.f_locals[key]
                sys.settrace(None)
            return probeFunc
        def traced():
            sys.settrace(probeFunc)
            function()
        return traced
    return wrap_f

rawDescription: Python: static variable decorator

description: Python: static variable decorator


code:
#!/usr/bin/python
import os, sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'PROJECTNAME.settings'
sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi',
    'PROJECTNAME'))

virtenv = os.environ['APPDIR'] + '/virtenv/'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')

try:
    execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
    pass

#
# IMPORTANT: Put any additional includes below this line.  If placed above this
# line, it's possible required libraries won't be in your searchable path
#
from django.core.handlers import wsgi
application = wsgi.WSGIHandler()

rawDescription: How to configure Django on OpenShift?

description: Configure Django on OpenShift


rawDescription: Python - Printing/Reading first Element generally any element of bytes object


code:
import os
from gps import *
from time import *
import time
import threading
import Queue

gpsd = None #seting the global variable

os.system('clear') #clear the terminal (optional)

class GpsPoller(threading.Thread):

    QUEUE_MAX_SIZE = 50

    def __init__(self):
        threading.Thread.__init__(self)
        global gpsd #bring it in scope
        gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
        self.current_value = None
        self.running = True #setting the thread running to true
        self.queue = Queue.Queue(maxsize=self.QUEUE_MAX_SIZE)

    def run(self):
        global gpsd
        while self.running:
            gpsinfo = gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
            # Here I'm just populating the queue with the return of gpsd.next(),
            # you can choose what you specifically want to populate it with.
            # like gpsinfo = [gpsd.fix.latitude, gpsd.fix.longitude]
            self.queue.put_nowait(gpsinfo) #add the gpsinfo to the queue for others to read

rawDescription: How to make the result from continous script a callable object for another

description: Make the result from continous script a callable object for another


code:
post = db.session.query(Post).get(1)
post.tags = []
db.session.commit()

rawDescription: Flask and SqlAlchemy how to delete records from ManyToMany Table?


code:
from collections import defaultdict
output = defaultdict(list)
for x, y in tuple_data:
    output[x].append(y)
output

rawDescription: creating dictionaries in python

description: Creating dictionaries in python


code: lista = z.read().splitlines()

rawDescription: readlines() without EOL at the of the lines

description: Readlines() without EOL at the of the lines


code:
from myapp.main import testing

if testing:
    ...

rawDescription: Can I determine if an application is being run normally vs via a unittest in Python?

description: Determine if an application is being run normally vs via a unittest in Python


code: pm.ls( type = 'dagPose')

rawDescription: Selecting bindpose nodes

description: Selecting bindpose nodes


code:
data = []
with open('text.txt', 'r') as fp:
  for line in (l.split() for l in fp):
    line[1:] = [float(x) for x in line[1:]]
    data.append(line)

rawDescription: How does one parse a file to a 2d array whilst maintaining data types in Python?

description: Parse a file to a 2d array whilst maintaining data types in Python


code:
from struct import pack, unpack
signed = unpack('B', pack('b', unsigned))[0]

rawDescription: convert ascii character to signed 8-bit integer python

description: Convert ascii character to signed 8-bit integer python


rawDescription: Python pandas: Getting the locations of a value in dataframe


code:
arr = np.array([(k,)+v for k,v in data_dict.iteritems()], \
         dtype=[('date', '|O4'), ('high', '<f8'), ('low', '<f8')])

rawDescription: How to convert Python dictionary object to numpy array

description: Convert Python dictionary object to numpy array


code:
def _copy_immutable(x):
    return x

for t in (type(None), int, long, float, bool, str, tuple,
          frozenset, type, xrange, types.ClassType,
          types.BuiltinFunctionType, type(Ellipsis),
          types.FunctionType, weakref.ref):
    d[t] = _copy_immutable

rawDescription: Why there is no difference between shallow copy and deep copy for a list of immutables


code:
mmlinput = "<math> <mrow> <mfrac> <mrow> <mn>3</mn> </mrow> <mrow> <mn>5</mn> </mrow> </mfrac> </mrow> </math>"

def parseMML(mmlinput):
    from lxml import etree
    from StringIO import *
    from lxml import objectify
    exppy=[]
    events = ("start", "end")
    level = 0
    context = etree.iterparse(StringIO(mmlinput),events=events)
    for action, elem in context:
        if (action=='start') and (elem.tag=='mfrac'):
            level += 1
            mmlaux=etree.tostring(elem[0])
            exppy+=parseMML(mmlaux)
            exppy+='/'
            mmlaux=etree.tostring(elem[1])
            exppy+=parseMML(mmlaux)
        if (action=='end') and (elem.tag=='mfrac'):
            level -= 1
        if level:
            continue
        if (action=='start') and (elem.tag=='mrow'):
            exppy+='('
        if (action=='end') and (elem.tag=='mrow'):
            exppy+=')'
        if action=='start' and elem.tag=='mn': #this is a number
            exppy+=elem.text
    return (exppy)

rawDescription: How to recursive iterparse an LXML tree avoiding to enter twice a node?

description: Recursive iterparse an LXML tree avoiding to enter twice a node


rawDescription: Python space+time efficient Data Structure to store 2D Bit Arrays


code:
for i in a:
    b.extend(i.split(','))

rawDescription: Splitting a String Python within a list

description: Splitting a String Python within a list


rawDescription: How to temporarily remove ( not delete and replace ) Tkinter widget without using just .place?

description: Temporarily remove ( not delete and replace ) Tkinter widget without using just .place


$regex: one

$regex: two

$regex: three

rawDescription: MongoDB: Transform PHP code to Python code


code:
from gi.repository import Nautilus, GObject
from urllib import unquote
import pyexiv2

class MyExtension(Nautilus.ColumnProvider, Nautilus.InfoProvider, GObject.GObject):
    def __init__(self):
        pass

    def get_columns(self):
        return (
            Nautilus.Column(name='MyExif::DateTime',
                            attribute='Exif:Image:DateTime',
                            label='Date Original',
                            description='Data time original'
            ),
        )

    def update_file_info_full(self, provider, handle, closure, file_info):
        if file_info.get_uri_scheme() != 'file':
            return

        filename = unquote(file_info.get_uri()[7:])
        attr = ''

        if file_info.get_mime_type() in ('image/jpeg', 'image/png'):
            metadata = pyexiv2.ImageMetadata(filename)
            metadata.read()

            try:
                tag = metadata['Exif.Image.DateTime'].value
                attr = tag.strftime('%Y-%m-%d %H:%M')
            except:
                attr = ''

        file_info.add_string_attribute('Exif:Image:DateTime', attr)

        return Nautilus.OperationResult.COMPLETE

rawDescription: Speed up nautilus python-extensions for reading image's Exif


code: strided = strided[:-N+1]

rawDescription: Reasoning about consecutive data points without using iteration


code:
timeout = 1000
last_true = -timeout

if (p.rect.left < self.rect.centerx < p.rect.right and self.rect.bottom >= 560):
    last_true = pygame.time.get_ticks()

if pygame.time.get_ticks() < last_true + timeout:
    self.kill()
    p.image.fill(red)

rawDescription: Pygame time control

description: Pygame time control


code:
class ClockInForm(forms.Form):
    driver_number = forms.IntegerField(required=True, max_length=8)

rawDescription: ModelForm returning field is required, not saving to sqliteDB


code: theta_degrees = [i % 360 for i in theta_degrees]

rawDescription: Simple loop for making sure angle is less than 360 [Python]


code:
import itertools

def object_list(request):
    ...
    iterator = iter(objects)
    pairs = itertools.izip_longest(*(iterator, iterator))
    return render(request, 'objects/object_list.html', {'objects': objects, 'pairs': pairs})

rawDescription: Displaying data in Django

description: Displaying data in Django


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
fieldnames = [...]
writer = DictWriter(worksheet, fieldnames)
writer.writeheader()

# below comes your code
for d in data:
  real_profit = str(float(d['Stat']['profit']) - (float(d['Stat']['clicks']) * 0.0004))
  writer.writerow({"Date": d['Stat']['date'], "Advertiser": d['Advertiser']['company'], "Offer": d['Offer']['name'], "Affiliate": d['Affiliate']['company'], "Affiliate Source": d['Stat']['source'], "Impressions": d['Stat']['impressions'], "Clicks": d['Stat']['clicks'], "Cost click": str(int(d['Stat']['clicks']) * 0.0004), "Conversions": d['Stat']['conversions'], "Cost": d['Stat']['payout'], "Revenue": d['Stat']['revenue'], "Profit": d['Stat']['profit'], "Real profit": real_profit})

rawDescription: How to write data with xlsxwriter iteratively with no precise row:column coordinate?

description: Write data with xlsxwriter iteratively with no precise row:column coordinate


code:
query = db.session.query(Tag, db.func.count(Post.id))
# This works but the preferred way is what's below it
#query = query.join(tags_to_posts_association_table, Post)
query = query.join(Post.tags)
query = query.group_by(Tag.id)

rawDescription: Flask how to calculate tags count

description: Flask how to calculate tags count


code:
tst = {'taste': ('sweet', 'sour', 'juicy', 'melon-like', 'yuck!', 'tasty', 'smoothie')}
taste = tst.get('taste')
taste
'sour' in taste
'sour1' in taste

rawDescription: Python: Append a list to an existing list assigned to a key in a dictionary?


code:
mask = im == 0
mask

rawDescription: Remove empty 'rows' and 'columns' from 3D numpy pixel array


code: ' '.join(w for w in re.split(r"\W", s) if w)

rawDescription: Python removing delimiters from strings

description: Python removing delimiters from strings


rawDescription: Python pandas dataframe max in a group based on conditions on other columns


code:
codeobj = compile(open('test.py').read(), 'read.py', 'exec')
exec(codeobj)

rawDescription: Python Compilation in Terminal

description: Python Compilation in Terminal


code: MySecondList = MyList

rawDescription: List being identified with another, using new items in the loop


code:
def expand_sparse_array(inp):
    length = (inp[-1][0]+1) # index of last element + 1
    out = [0]*length

    for (idx, val) in inp:
        out[idx] = val

    return out

rawDescription: Python: turn tuples into array

description: Python: turn tuples into array


code: func( API(arg1='foo', arg2='bar'), POST(arg1='foo1'), POST(arg2='bar1'))

rawDescription: Magic assign for custom parameters

description: Magic assign for custom parameters


code:
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
print(df)

rawDescription: how to display pandas DataFrame using a format string for columns?

description: Display pandas DataFrame using a format string for columns


code:
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def gcd(a, b):
    while a != b:
        if a > b:
            a -= b
        else:
            b -= a
    return a

rawDescription: I can not make my code iterate x -= 1

description: I can not make my code iterate x -= 1


code: [dict(list(i.items())+list(j.items())+list(k.items())) for i,j,k in zip(list1, list2, list3)]

rawDescription: Merge dictionaries from multiple lists in Python


code:
map(sum, zip(*j))
list(map(sum, zip(*j))) # In Python 3.x

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


code:
data ="\n random stuff\na,1\nb,2\nc,3\n ... "
[line for line in csv.reader(data.split('\n')) if len(line) > 1]

rawDescription: shortest Python solution for creating list from csv string

description: Shortest Python solution for creating list from csv string


code:
def user_input():
    user_in = input('\nplease give your input (Ctrl+C to break): ') # pop_up_and_ask_for_input
    if user_in:
         inputs.append(user_in)

rawDescription: User Defined Interrupt

description: User Defined Interrupt


code:
from flask import session
session['my_key'] = my_value  # add value
del session['my_key']  # remove value
session.clear()  # remove everything

rawDescription: Copy user session when anonymous user logs in with Flask-Login


code: x = y = None

rawDescription: Python initialize multiple variables to the same initial value


code:
target_list.sort(key=lambda x: abs(4-x))
target_list

rawDescription: sorting a list with respect to the closest number in the list python

description: Sorting a list with respect to the closest number in the list python


code:
import random
stats = {'strength' : 0, 'dexterity' : 0, 'intelligence' : 0}

for key, value in stats.items():
    value = random.randint(1,18)
    stats[key] = value # assign the value to dictionary
    print (value)

for key, value in stats.items():
    print (key, value)

rawDescription: How to store a random integers in a dictionary?

description: Store a random integers in a dictionary


code:
[(0, 'Planet', 'Mercury'),
 (1, 'Planet', 'Venus'),
 (2, 'Planet', 'Mars'),
 (3, 'Planet', 'Jupiter'),
 (4, 'Planet', 'Saturn'),
 (5, 'Planet', 'Uranus'),
 (6, 'Planet', 'Neptune'),
 (7, 'Planet', 'Pluto'),
 (8, 'Planet', 'Sun'),
 (9, 'Planet', 'Moon'),
 (10, 'PlanetMoon', 'Phobos'),
 (11, 'PlanetMoon', 'Deimos'),
 (12, 'PlanetMoon', 'Io'),
 (13, 'PlanetMoon', 'Europa'),
 (14, 'PlanetMoon', 'Ganymede'),
 (15, 'PlanetMoon', 'Callisto'),
 (16, 'PlanetMoon', 'Mimas'),
 (17, 'PlanetMoon', 'Enceladus'),
 (18, 'PlanetMoon', 'Tethys'),
 (19, 'PlanetMoon', 'Dione'),
 (20, 'PlanetMoon', 'Rhea'),
 (21, 'PlanetMoon', 'Titan'),
 (22, 'PlanetMoon', 'Hyperion'),
 (23, 'PlanetMoon', 'Iapetus'),
 (24, 'PlanetMoon', 'Ariel'),
 (25, 'PlanetMoon', 'Umbriel'),
 (26, 'PlanetMoon', 'Titania'),
 (27, 'PlanetMoon', 'Oberon'),
 (28, 'PlanetMoon', 'Miranda')]

rawDescription: look up planet or moon by name in pyephem?

description: Look up planet or moon by name in pyephem


rawDescription: Extract ip addres and other stuff from a bind log string using python


code:
import re
a = re.compile('a')
a
type(a)
repr(a)

rawDescription: Adding re.compile to list

description: Adding re.compile to list


rawDescription: How do I get the private IP address of the computer that I am using in python?

description: Get the private IP address of the computer that I am using in python


rawDescription: tornado maps GET and POST arguments to lists. How can I disable this "feature"?

description: Tornado maps GET and POST arguments to lists. How can I disable this "feature"


code:
for price in driver.find_elements_by_css_selector(".totalPrice"):
    print(price.text.strip())

rawDescription: BeautifulSoup not finding elements

description: BeautifulSoup not finding elements


rawDescription: Python: Checking a list with regex, filling in blanks


code:
S = {1}
min(S)
S
max(S)
S

rawDescription: Python | Access the sole element of a set


code:
parameters = []
for i in range(1, 51):
    parameter = getattr(root, 'OM%02d' % i)
    parameters.append(parameter)

# now all of your parameters are in the parameter array

rawDescription: Loop a python script

description: Loop a python script


code:
import sys
import functools

print_hello = functools.partial(sys.stdout.write, "Hello world\n")

print_hello()

rawDescription: Python Argument Binders

description: Python Argument Binders


rawDescription: Python Pandas: Find index based on value in DataFrame


code:
class Window(QtGui.QDialog):

    def __init__(self):
        super(Window, self).__init__()
        self.resize(600,400)

        self.mainLayout = QtGui.QVBoxLayout(self)
        self.mainLayout.setMargin(10)

        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.mainLayout.addWidget(self.scroll)

        scrollContents = QtGui.QWidget()
        self.scroll.setWidget(scrollContents)

        self.textLayout = QtGui.QVBoxLayout(scrollContents)
        self.textLayout.setMargin(10)

        for _ in xrange(5):
            text = GrowingTextEdit()
            text.setMinimumHeight(50)
            self.textLayout.addWidget(text)

class GrowingTextEdit(QtGui.QTextEdit):

    def __init__(self, *args, **kwargs):
        super(GrowingTextEdit, self).__init__(*args, **kwargs)
        self.document().contentsChanged.connect(self.sizeChange)

        self.heightMin = 0
        self.heightMax = 65000

    def sizeChange(self):
        docHeight = self.document().size().height()
        if self.heightMin <= docHeight <= self.heightMax:
            self.setMinimumHeight(docHeight)

rawDescription: PySide Qt: Auto vertical growth for TextEdit Widget, and spacing between widgets in a vertical layout


rawDescription: Regex not working in python script

description: Regex not working in python script


code: indexes[:3, :]

rawDescription: List of indices of every value

description: List of indices of every value


code: bcrypt.check_password_hash(users_doc["password"], request.form["password"]) # Just an example of how you could use it.

rawDescription: save password as salted hash in mongodb in users collection using python - bcrypt

description: Save password as salted hash in mongodb in users collection using python - bcrypt


code:
def move():
    print("Test.")

func_dict = {'move':move}
if __name__ == "__main__":
    input("Press enter to begin.")
    currentEnvironment = "room" #getNewEnvironment(environments)
    currentTimeOfDay = "1 A.M." #getTime(timeTicks, timeOfDay)
    print("You are standing in the {0}. It is {1}.".format(currentEnvironment, currentTimeOfDay))
    command = input("> ")
    func_dict[command]()

rawDescription: Using user input to call functions

description: Using user input to call functions


code:
def optfloat(intcoef, xs, ys):
    from scipy.optimize import curve_fit
    def poly(xs, floatcoef):
        return np.dot(xs, [intcoef, floatcoef])
    popt, pcov = curve_fit(poly, xs, ys)
    errsqr = np.linalg.norm(poly(xs, popt) - ys)
    return dict(errsqr=errsqr, floatcoef=popt)

rawDescription: curve fitting with integer inputs Python 3.3

description: Curve fitting with integer inputs Python 3.3


code:
cur = connection.cursor()

# Query IDs.
cur.execute("SELECT id FROM history WHERE category = %s;", ['DATA'])
rows = cur.fetchall()
num_rows = int(cur.rowcount)

# Create a generator yielding the 0-th column (id) from each row.
x = (row[0] for row in rows)

D = np.fromiter(iter=x, dtype=float, count=-1)

rawDescription: python3 work with values of fetchall and DictCursor

description: Python3 work with values of fetchall and DictCursor


code: phrases("A Day in the Life")

rawDescription: Python: Finding unknown repeated word(s) in a list of strings


code: cimg = detect_circles("circles.png")

rawDescription: Find all circles in image

description: Find all circles in image


code:
def normalize_groups(in_list):
    groups = {}
    output = []
    for value in in_list:
        if value not in groups:
            groups[value] = len(groups)
        output.append(groups[value])
    return output

rawDescription: Ordering a list of items in place to compare clustering solutions


code: val = x.values()[0]

rawDescription: access value of a python dict() without knowing the keys

description: Access value of a python dict() without knowing the keys


code: sorted(sav, key=lambda x: int(x[3]))

rawDescription: Sorting an array by a number string (Python 3.4.2)


code:
dictonary = dict(((i,[]) for i in drug_list))

dictonary = {drug: [] for drug in drug_list}  # As @J.F. Sebastian suggested.

for file in file_list:
    k = file.split('.')[-2]
    if k in dictonary:
        dictonary[k].append(file)

rawDescription: combine two lists into a dictionary if a pattern matches

description: Combine two lists into a dictionary if a pattern matches


code:
from lxml import etree
from docx import nsprefixes

page_br_elements = document.xpath(
    "//w:p/w:r/w:br[@w:type='page']", namespaces={'w': nsprefixes['w']}
)
for br in page_br_elements:
    t = etree.Element('w:t', nsmap={'w': nsprefixes['w']})
    t.text = '{{foobar}}'
    br.addprevious(t)
    parent = br.getparent()
    parent.remove(br)

rawDescription: How to identify page breaks using python-docx from docx

description: Identify page breaks using python-docx from docx


code:
ar.dtype.type
ar.dtype.type == numpy.string_

rawDescription: How to get type of multidimensional Numpy array elements in Python

description: Get type of multidimensional Numpy array elements in Python


code:
for i in B:
    if i == -1:
        # prints a new line character
        # print("\n") if you need a blank line between entries
        print()
    else:
        # end specifies how your elements will be seperated
        print(i, end=" ")

rawDescription: Python "Arrays and Restrictions"

description: Python "Arrays and Restrictions"


rawDescription: copying functions located in instances

description: Copying functions located in instances


code:
def unique_combos(digits, total, smallest=0):
    if digits*9 < total or digits*smallest > total:
        return
    if digits==1:
        yield [total]
        return

    for i in range(smallest, 10):
        for combo in unique_combos(digits-1, total-i, i):
            yield [i]+combo

rawDescription: Speeding Up a Python While Loop

description: Speeding Up a Python While Loop


rawDescription: Finding a circle in an undirected graph

description: Finding a circle in an undirected graph


code:
#!/usr/bin/env python
import os
import time
from subprocess import Popen, STDOUT

DEVNULL = open(os.devnull, 'wb', 0)

start = time.time()
p = Popen(['sleep', '1'], stdout=DEVNULL, stderr=STDOUT)
ru = os.wait4(p.pid, 0)[2]
elapsed = time.time() - start
print(" {:.3f}real {:.3f}user {:.3f}system".format(
       elapsed, ru.ru_utime, ru.ru_stime))

rawDescription: Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?


rawDescription: Python Qt: How to catch "return" in qtablewidget


code:
"This is an example.A particular case.Made up of more than once sentence?Yes, it is.But no blank !!!That'sa problem ????Yes.I think so!"
':)'

'This is an example.'
'A particular case.'
'Made up of more than once sentence?'
'Yes, it is.'
'But no blank !'
'!'
'!'
"That's a problem ?"
'?'
'?'
'?'
'Yes.'
'I think so!'
' :)'

rawDescription: Non-consuming regular expression split in Python


code:
# Here you remove all the cells in your array which are not a day of the week
# or a time (not the call to "list" before filter object are not indexable in Python 3+)
data = list(filter(lambda x: x in days_of_the_week or x[0].isdigit(), input_array))
while data:
    # Get the first item available and remove it
    curday = days_of_the_week[data.pop(0)]
    # For each couple (start, end), add an item to business_hours
    while data and data[0][0].isdigit():
        business_hours.append({
            'weekday_name':  curday,
            'starting_time': data[0],
            'ending_time':   data[1]
        })
        data = data[2:]

rawDescription: python algorithm to be done in a pythonic fashion?

description: Python algorithm to be done in a pythonic fashion


code: crosscut = [entry[0] for entry in L]

rawDescription: Python list index splitting and manipulation


code: pattern = re.escape('apple.fruit[0]')+ '|' + re.escape('vegi[0]')

rawDescription: Python re.search regx using or condition


code:
"""
Django migrations

This package does not contain South migrations.  South migrations can be found
in the ``south_migrations`` package.
"""

SOUTH_ERROR_MESSAGE = """\n
For South support, customize the SOUTH_MIGRATION_MODULES setting like so:

SOUTH_MIGRATION_MODULES = {
    'wfp_auth': 'wfp_auth.south_migrations',
}
"""

# Ensure the user is not using Django 1.6 or below with South
try:
    from django.db import migrations  # noqa
except ImportError:
    from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured(SOUTH_ERROR_MESSAGE)

rawDescription: Best way to add Django migrations to a django project

description: Add Django migrations to a django project


code:
fp=open('Input.txt')
data={}
def strmin(a,b):
    return str(min(int(a),int(b)));
def strmax(a,b):
    return str(max(int(a),int(b)));
for line in fp:
    ID,chrom,txStart,txEnd,score,strand=line.split()
    if ID=="ID":
        print(line.strip()) # header
        continue
    if not data.has_key(ID):
        data[ID]=[ID,chrom,txStart,txEnd,score,strand]
        continue
    i,c,ts,te,sc,st=data[ID]
    data[ID] = [i,c,strmin(txStart,ts),strmax(txEnd,te),sc,st]

# maybe you want to sort it here...
for ID in data.keys():
    print('\t'.join(data[ID]))

rawDescription: Algorithm to parse file where redundant index values are selected by maximum and minimum values


code: csv = open('inlog.csv', 'r').read().split('\n')[1].split(';')

rawDescription: Find password by username

description: Find password by username


code: any([acceptable_stem in filename for acceptable_stem in acceptable_stems])

rawDescription: One-liner for partial string match in list lookup


code: soup.find("td", class_="pizza", text=lambda text: text and text.strip() != "cheese")

rawDescription: BeautifulSoup4 Python 3.4 Scraping Issue


rawDescription: Packing 4 Integers as ONE INTEGER?

description: Packing 4 Integers as ONE INTEGER


code:
def inverse_circular_crosscorelation(y):
    """
    Input:
        symbol for y[1, m]

    Returns:
        symbol for y_inv s.t.
        cc( y, y_inv ) = (1, 0 ... 0)
    """

    A = circulant_t(y.reshape((-1, )))
    b = T.concatenate([T.zeros((y.shape[1] - 1, )), T.ones((1, ))]).reshape((-1, 1))
    return T.nlinalg.matrix_inverse(A).dot(b).reshape((1, -1))[:, ::-1]

rawDescription: Circular Correlation in Theano

description: Circular Correlation in Theano


code:
import unittest
import re

# Extract numbers improved
def extract_numbers_improved(x):

    numbers = re.findall(r"[-+]?\d*\.\d+|\d+", x)

    return numbers

# Unit Test
class Test(unittest.TestCase):
    def testcase(self):

        teststr = "12asdasdsa 33asdsad 44 aidsasdd 2231%#@ qqq55 2222ww ww qq 1asdasd 33##$11 42.09 12$"
        self.assertEqual(extract_numbers_improved(\
            teststr), ['12', '33', '44', '2231', '55', '2222', '1', '33', '11', '42.09', '12'])

unittest.main()

rawDescription: How to extract only numbers from input file. Numbers can be float/int

description: Extract only numbers from input file. Numbers can be float/int


rawDescription: Python 3.4.3 and PySqlite3 not Inserting content on Table


rawDescription: Stripping links returned by beautfulsoup


rawDescription: Can python regex negate a list of words?

description: Can python regex negate a list of words


code:
for item in YourArray:
    TheResult = YourTreeName.query(item, k=1, distance_upper_bound=6)

rawDescription: Nearest Neighbor Search: Python

description: Nearest Neighbor Search: Python


code:
for media in tweet.entities.get("media",[{}]):
    #checks if there is any media-entity
    if media.get("type",None) == "photo":
        # checks if the entity is of the type "photo"
        image_content=requests.get(media["media_url"])
        # save to file etc.

rawDescription: Filter images from tweets

description: Filter images from tweets


code:
name,email,rank
Joe,joe@example.com,7
Jim,jim@example.com,12
Jen,jane@example.com,2

rawDescription: manipulating TSV file

description: Manipulating TSV file


code:
def is_backspace(c):
    return c in ('\x08','\x7F')

def is_interrupt(c):
    return c == '\x04'

rawDescription: Python, "filtered" line editing, read stdin by char with no echo


code:
rc = call([sys.executable, '-c', '''import sys
print(sys.argv)
'''])

rawDescription: Python losing control of subprocess?

description: Python losing control of subprocess


code:
from django import forms
from .models import Country, RUSSIA

class CountryForm(forms.ModelForm):

    class Meta:
        model = Country

    def clean(self):
        cleaned_data = self.cleaned_data

        country = cleaned_data.get('country')
        name_of_team = cleaned_data.get('name_of_team')

        if country == RUSSIA and not name_of_team:
            self.add_error('name_of_team', 'You must supply a team name')

        return cleaned_data

rawDescription: How to check field in django model?

description: Check field in django model


code:
df1 = pd.read_csv("fish1.csv")
df2 = pd.read_csv("fish2.csv")
df1
df2

rawDescription: Merge two CSV's with unique columns in python


code:
nrow = 1; ncol = 2;
fig, axs = plt.subplots(nrows=nrow, ncols=nrow)

for ax in axs.reshape(-1):
  ax.set_ylabel(str(i))

rawDescription: matplotlib iterate subplot axis array through single list

description: Matplotlib iterate subplot axis array through single list


rawDescription: pulling min and max values from list of list

description: Pulling min and max values from list of list


code:
a=open("file","r") # if they're in a file and written newline-separated
for x in a:
    the_list.append(int(x)) # add a value to list
a.close() # close file
for x in the_list:
    print(x) # print value line by line
the_list=list() # empty list

rawDescription: Store a list (ArrayList?) of integers in python


code:
keywords = ['nike', 'adidas', 'reebok']
items = ['sneakers', 'sneaker shoes', 'adidas shoes', 'nike', 'any shoe', 'all nikes', 'a nike shoe']
bits = [any(keyword in item for keyword in keywords) for item in items]

rawDescription: Comparing the items of two lists in Python


rawDescription: Filter a string for valid MySQL Column name


code: from myapp.data import something_large

rawDescription: How to load an object into memory for entire django project to see?

description: Load an object into memory for entire django project to see


code: result = ''.join(string for (string, _) in ordered)

rawDescription: Extract information from defaultdict

description: Extract information from defaultdict


code:
from django.forms import ModelForm, PasswordInput

class TwitterUserForm(ModelForm):
    password = forms.CharField(widget=PasswordInput())
    class Meta:
        model = TwitterUser

rawDescription: Making a CharField use a PasswordInput in the admin


code:
class DirectorySubmitHandler(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        merchandise_type = self.request.get("dir_type", "")
        dir_type = merchandise_type
        if user:
            item = Item()
            item.title = self.request.get("title")
            item.url = self.request.get("url")
            item.type = self.request.get("dir_type")
            item.user_who_liked_this_item = user
            item.put()
            self.redirect("/dir?type=%s" %
self.request.get("dir_type"))
        else:
            self.redirect(users.create_login_url(self.request.uri))

rawDescription: How do I pass url parameter to form value?

description: Pass url parameter to form value


code: event = events.get()

rawDescription: Calling While loop Function in __main__?

description: Calling While loop Function in __main__


code:
import struct
from functools import partial

# (c) 2010 Eric L. Frederich
#
# Python implementation of algorithms detailed here...
# from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

def c_mem_cast(x, f=None, t=None):
    '''
    do a c-style memory cast

    In Python...

    x = 12.34
    y = c_mem_cast(x, 'd', 'l')

    ... should be equivilent to the following in c...

    double x = 12.34;
    long   y = *(long*)&x;
    '''
    return struct.unpack(t, struct.pack(f, x))[0]

dbl_to_lng = partial(c_mem_cast, f='d', t='l')
lng_to_dbl = partial(c_mem_cast, f='l', t='d')
flt_to_int = partial(c_mem_cast, f='f', t='i')
int_to_flt = partial(c_mem_cast, f='i', t='f')

def ulp_diff_maker(converter, negative_zero):
    '''
    Getting the ulp difference of floats and doubles is similar.
    Only difference if the offset and converter.
    '''
    def the_diff(a, b):

        # Make a integer lexicographically ordered as a twos-complement int
        ai = converter(a)
        if ai < 0:
            ai = negative_zero - ai

        # Make b integer lexicographically ordered as a twos-complement int
        bi = converter(b)
        if bi < 0:
            bi = negative_zero - bi

        return abs(ai - bi)

    return the_diff

# double ULP difference
dulpdiff = ulp_diff_maker(dbl_to_lng, 0x8000000000000000)
# float  ULP difference
fulpdiff = ulp_diff_maker(flt_to_int, 0x80000000        )

# default to double ULP difference
ulpdiff = dulpdiff
ulpdiff.__doc__ = '''
Get the number of doubles between two doubles.
'''

rawDescription: floating point equality in Python and in general

description: Floating point equality in Python and in general


code:
all_users = User.objects.all()
values = {}
for this_user in all_users:
    values[this_user.id] = Lead.objects.filter(assign_to=this_user).exclude(lead_status='converted').aggregate(Sum('annual_spend'))['annual_spend__sum']

rawDescription: return all objects associated with a user

description: Return all objects associated with a user


code: next(x for x in lst if matchCondition(x))

rawDescription: Return the first item in a list matching a condition


rawDescription: How to return a number as a binary string with a set number of bits in python

description: Return a number as a binary string with a set number of bits in python


code:
oauth = OAuth1Session(CONSUMER_KEY, client_secret=CONSUMER_SECRET,
                          signature_method=SIGNATURE_HMAC,
                          signature_type=SIGNATURE_TYPE_AUTH_HEADER, client_class=CustomClient)

rawDescription: Setting HTTP User-Agent header with requests-oauthlib


code:
src = getSourceFromMaster()
obj = compile(src, "master.py", "exec")
exec(obj)

rawDescription: How can I send python code to another machine to be executed?

description: Send python code to another machine to be executed


code:
@app.route('/protected')
@role_required('admin')
def admin_view():
    " this view is for admins only "

rawDescription: What is the best way to protect a flask endpoint?


rawDescription: Convert Long to String Python

description: Convert Long to String Python


code:
data = list()
for i in arange(num):
    data.append(np.loadtxt("datafromafile%d.txt" % i))

rawDescription: creating numpy arrays in a for loop

description: Creating numpy arrays in a for loop


code:
stmt_ab = """
stmt_mg = """
import timeit
t1_ab = timeit.Timer(stmt=stmt_ab, setup = "from __main__ import sample")
t1_mg = timeit.Timer(stmt=stmt_mg, setup = "from __main__ import sample, textwrap")
t1_ab.timeit(10000)
t1_mg.timeit(10000)

rawDescription: How to optimize matching a substring of n length, but only whole words?

description: Optimize matching a substring of n length, but only whole words


code:
Alice, Bob = re_splitters.split(user_input)
# YOU MUST CHECK HERE THAT ALICE AND BOB ARE BOTH IN net_dict
action = re_splitters.search(user_input).group(0)
if action:
    result = eval("net_dict[{}] {} net_dict[{}]".format(Alice, action, Bob))
    # strong warning about an injection vulnerability!

rawDescription: Python- Key from dict on user input eval. Send to overloaded operator function


code:
def is_subtuple(tup1, tup2):
    '''Return True if all the elements of tup1 are consecutively in tup2.'''
    if len(tup2) < len(tup1): return False
    try:
        offset = tup2.index(tup1[0])
    except ValueError:
        return False
    # This could be wrong if tup1[0] is in tup2, but doesn't start the subtuple.
    # You could solve this by recurring on the rest of tup2 if this is false, but
    # it doesn't apply to your input data.
    return tup1 == tup2[offset:offset+len(tup1)]

rawDescription: Recursively reduce list of tuples

description: Recursively reduce list of tuples


code:
[pytest]
norecursedirs=tests/helpers

rawDescription: Create and import helper functions in tests without creating packages in test directory using py.test


rawDescription: Komodo - watch variables and execute code while on pause in the program


code:
grid = [['O' for i in range(10)] for j in range(10)] # use generators to create list

def print_grid():
    print("  " + " ".join(str(i) for i in range(10))) # " ".join() puts the " " between each string in the list
    for y in range(10):
        print(str(y) + " " + " ".join(grid[y]))

print_grid()

# OUTPUT:
#   0 1 2 3 4 5 6 7 8 9
# 0 O O O O O O O O O O
# 1 O O O O O O O O O O
# 2 O O O O O O O O O O
# 3 O O O O O O O O O O
# 4 O O O O O O O O O O
# 5 O O O O O O O O O O
# 6 O O O O O O O O O O
# 7 O O O O O O O O O O
# 8 O O O O O O O O O O
# 9 O O O O O O O O O O

grid[0][3] = 'X'
grid[1][3] = 'X'
grid[2][3] = 'X'
grid[3][3] = 'X'

print_grid()

# OUTPUT:
#   0 1 2 3 4 5 6 7 8 9
# 0 O O O X O O O O O O
# 1 O O O X O O O O O O
# 2 O O O X O O O O O O
# 3 O O O X O O O O O O
# 4 O O O O O O O O O O
# 5 O O O O O O O O O O
# 6 O O O O O O O O O O
# 7 O O O O O O O O O O
# 8 O O O O O O O O O O
# 9 O O O O O O O O O O

rawDescription: Generating random X,Y coordinates in a grid


rawDescription: How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python?

description: Obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python


code:
from django.utils.safestring import mark_safe
from django import template
register = template.Library()

@register.simple_tag
def spanme(fld):
    return mark_safe("<span>%s</span>" % fld)

rawDescription: Implement html output for a model field in Django


code: [7 if val > 3046 else 10 for val in df.HIGH.at_time("09:30:00")]

rawDescription: How do I get each answer for each row with this conditional

description: Get each answer for each row with this conditional


code:
from itertools import chain
list1 = [['a', 'b', 'c', 'd'], ['w', 'x', 'y', 'z']]
list(chain.from_iterable(list1))

rawDescription: List in list convert to one list?

description: List in list convert to one list


rawDescription: BeautifulSoup Python script no longer working for mining a simple field


code: return any(val in x for x in lst)

rawDescription: How do I check existence of a string in a list of strings, including substrings?

description: Check existence of a string in a list of strings, including substrings


code:
class Level1():
    level_name = CharField()

rawDescription: How can I change the strings as variables in python django?

description: Change the strings as variables in python django


code:
pd.DataFrame({'BeginDate' : df.groupby('value_grp').Date.first(),
              'EndDate' : df.groupby('value_grp').Date.last(),
              'Consecutive' : df.groupby('value_grp').size(),
              'No' : df.groupby('value_grp').No.first()}).reset_index(drop=True)

rawDescription: How to use pandas to find consecutive same data in time series

description: Use pandas to find consecutive same data in time series


rawDescription: Iterating over list of namedtuples, selecting restaurants


rawDescription: python timestamp : Find all timestamps as string before 5 mins

description: Python timestamp : Find all timestamps as string before 5 mins


code:
a_non_empty = [s for s in a if s]
a_non_empty

rawDescription: Split string by multiple separators?

description: Split string by multiple separators


code:
import re
s = 'abc-abc- abc -abc - abc'
r = re.compile('\s*-\s*')
r.split(s)

rawDescription: Splitting by character using regular expressions


code:
from tkinter import filedialog as fd

filename = fd.askopenfilename()
print(len(filename))

rawDescription: Get file path from askopenfilename function in Tkinter


code: poll = models.ForeignKey(Poll, related_name="votes", unique=False, blank=False, db_index=True)

rawDescription: Extra "row-level" data in ListView django


code: q = [x for x in random.sample(a_q, len(a_q))]

rawDescription: Delete a string in a dictionary after it's shown


code:
class Test(object):
    def __init__(self, smile):
            print(smile)
help(Test)

rawDescription: Is there a Python function or method that displays object specifications?


code:
zip(bins, count)
import json
json.dumps(_)

rawDescription: Missed values when creating a dictionary with two values


code:
centerFilter = vtk.vtkCenterOfMass()
centerFilter.SetInputData(polydata)
centerFilter.SetUseScalarsAsWeights(False)
centerFilter.Update()
center = centerFilter.GetCenter()

rawDescription: centering the axis/pivot of a polydata model in python-vtk/three.js

description: Centering the axis/pivot of a polydata model in python-vtk/three.js


code: test:         "|/usr/local/bin/your-app"

rawDescription: Send AND receive email in an python application (no IMAP or POP3)


code: chisquare(observed)

rawDescription: Chi-Squared test in Python

description: Chi-Squared test in Python


code:
#FinalGrade
Student = str(input("Student Name: "))
Grade1 = int(input("Enter Student's First Grade: "))
Grade2 = int(input("Enter Student's Second Grade: "))
Grade3 = int(input("Enter Student's Third Grade: "))
Grade4 = int(input("Enter Student's Fourth Grade: "))

average =  (Grade1+Grade2+Grade3+Grade4 )/4
print ("Total Grade Average: %G" % (average))

print ("%s has:" % (Student))

if average < 40:
    print ("Failed!")
if average > 40:
    print ("Passed!")

#what if average == 40 ?

rawDescription: Dividing in Python

description: Dividing in Python


code:
import nltk
nltk.download()

rawDescription: How to tag an article with NLTK?

description: Tag an article with NLTK


rawDescription: How do I convert a python string to ucs2 hex?

description: Convert a python string to ucs2 hex