code:
import networkx as nx
G = nx.Graph()
G.add_edge(1,2,weight=1)
G.add_edge(2,3,weight=0.25)
H = nx.Graph([(u,v,d) for (u,v,d) in  G.edges(data=True) if d['weight']>0.5])
H.edges()
G.remove_edges_from([(u,v,d) for (u,v,d) in  G.edges(data=True) if d['weight']<0.5])
G.edges()

rawDescription: extracting connected nodes from weighted undirected graph based on the weight of the edges

description: Extracting connected nodes from weighted undirected graph based on the weight of the edges


code:
from gi.repository import Gtk, Gdk, GdkX11, Wnck
from subprocess import PIPE, Popen

class WindowError(Exception):
    pass

def getScreen():
    Gtk.main_iteration()

    screen = Wnck.Screen.get_default()
    screen.force_update()

    return screen

def getGDKWindow(aWindow):
    gdkdisplay = GdkX11.X11Display.get_default()
    gdkwindow  = GdkX11.X11Window.foreign_new_for_display(gdkdisplay, aWindow.get_xid())

    return gdkwindow

def getWindow(aTitle):
    screen = getScreen()
    active = screen.get_active_window()

    if active.get_name() == aTitle:
        return active

    for window in screen.get_windows():
        if window.get_name() == aTitle:
            return window

    return None

def adjust(aWindow):
    gdkwindow = getGDKWindow(aWindow)

    gdkwindow.set_decorations(Gdk.WMDecoration.BORDER)
    gdkwindow.move(0,0)

    aWindow.set_skip_pager(True)
    aWindow.set_skip_tasklist(True)

    aWindow.maximize_horizontally()

    aWindow.stick()
    aWindow.make_above()

def onWindowOpen(aScreen, aWindow, aData):
    if aWindow.get_name() == aData:
        adjust(aWindow)

        Gtk.main_quit()

def main():
    timestamp = Gtk.get_current_event_time()
    window      = getWindow('Dropdown Terminal')

    if window:
        if window.is_minimized():
            window.activate(timestamp)
            window.unminimize(timestamp)
        else:
            window.minimize()
    else:
        Popen(['roxterm', '--separate', '--profile=Dropdown', '--directory=.'])

        getScreen().connect('window-opened', onWindowOpen, 'Dropdown Terminal')

        Gtk.main()

if __name__ == "__main__":
    main()

rawDescription: window position a little off just after spawning and moving using python-wnck

description: Window position a little off just after spawning and moving using python-wnck


code:
def child(n, a):
    g_mutex = threading.Lock()
    g_mutex.acquire()
    random.seed(n)
    for i in xrange(100):
        a.append(random.randint(0, 1000))
    g_mutex.release()

rawDescription: how do I make randint threadsafe in python?

description: Make randint threadsafe in python


code:
import time
import win32con
import win32api
from win32api import keybd_event, mouse_event

time.sleep(3)
keybd_event(160, 0, 1, 0)
time.sleep(1)

keybd_event(160, 0, win32con.KEYEVENTF_EXTENDEDKEY  |
win32con.KEYEVENTF_KEYUP, 0)
time.sleep(1)

keybd_event(84, 0, 1, 0)
time.sleep(1)
keybd_event(84, 0, win32con.KEYEVENTF_EXTENDEDKEY  |
win32con.KEYEVENTF_KEYUP, 0)
time.sleep(1)

rawDescription: Python win32api event shift not releasing key when other text is added


code:
soup = bs4.BeautifulSoup(html)
q1=soup.find('li', class_="sense_list_item level_1",value='1').text

rawDescription: How can I extract data from a html tag using Python?

description: Extract data from a html tag using Python


code:
my_string = 'this is my complex description'
keywords = ['my', 'desc', 'complex']
set(my_string.split()) & set(keywords)

rawDescription: Get keywords in a string from a list of strings in Python


rawDescription: How to retrieve interesting fields from a complex list in order to insert them into an sqlite3 table

description: Retrieve interesting fields from a complex list in order to insert them into an sqlite3 table


code:
#Code originally posted by Alex Martelli
#Modified to use standard Python variable name conventions
import threading
threadlocal = threading.local()

def threadlocal_var(varname, factory, *args, **kwargs):
  v = getattr(threadlocal, varname, None)
  if v is None:
    v = factory(*args, **kwargs)
    setattr(threadlocal, varname, v)
  return v

rawDescription: Thread local storage in Python

description: Thread local storage in Python


code:
conn = sqlite3.connect(os.path.join("data", "db", "Kanji-story.db"))
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS current")

c.execute("ATTACH DATABASE ? AS db2", (os.path.join('data', 'db', 'Kanji-story_bak.db'),))

c.execute("SELECT sql FROM db2.sqlite_master WHERE type='table' AND name='current'")
c.execute(c.fetchone()[0]) # Contains: CREATE TABLE current (framenum INTEGER, nextKanji INTEGER)
c.execute("INSERT INTO main.current SELECT * FROM db2.current")

conn.commit()
conn.close()

rawDescription: sqlite3 python ATTACH DATABASE copy table .schema

description: Sqlite3 python ATTACH DATABASE copy table .schema


rawDescription: How can I sort a portion of a list in place?

description: Sort a portion of a list in place


code:
ILLEGAL_NTFS_CHARS = "[<>:/\\|?*\"]|[\0-\31]"
def __removeIllegalChars(name):
    # removes characters that are invalid for NTFS
    return re.sub(ILLEGAL_NTFS_CHARS, "", name)

rawDescription: how to check for platform incompatible folder (file) names in python

description: Check for platform incompatible folder (file) names in python


rawDescription: Plotting non-numeric x-axis away from the y-axis


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

import time

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0, 2 *np.pi])
ax.set_ylim([-1, 1])

th = linspace(0, 2 * np.pi, 1000)

line, = ax.plot([],[],'b-', animated=True)
line.set_xdata(th)
# getFrame() makes a call to the CCD frame buffer and retrieves the most recent frame

# animation function
def update(data):
    line.set_ydata(data)

    return line,

def data_gen():
    t = 0
    while True:
        t +=1
        yield np.sin(th + t * np.pi/100)

# call the animator
anim = animation.FuncAnimation(fig, update, data_gen, interval=10, blit=True)

rawDescription: Pyplot animation not updating continuously


rawDescription: python - how to display time as epoch?

description: Python - how to display time as epoch


rawDescription: Parsing in Python: what's the most efficient way to supress/normalize strings?


code:
countText = usefont.render( "%d" % secs_left, 1, (255, 0, 0))
countRect = countText.get_rect()
countRect.y, countRect.centerx = yPos, screen.get_rect().width/2
screen.set_clip(countRect)        # Allow updates only to area in countRect
screen.blit(bg_image, (0,0))      # bg_img will only be drawn within countRect
screen.blit(countText, countRect)
pygame.display.flip()

rawDescription: How to redraw text on gradient background in pygame?

description: Redraw text on gradient background in pygame


code:
right_now = datetime.datetime.now()
one_hour_before = right_now - datetime.timedelta(hours=1)

rawDescription: In Python, how would I do this Datetime?

description: In Python, how would I do this Datetime


code:
# Create the engine. This starts a fresh database
engine = create_engine('sqlite://')
# Fills the database with the tables needed.
# If you use declarative, then the metadata for your tables can be found using Base.metadata
metadata.create_all(engine)
# Create a session to this database
session = sessionmaker(bind=engine)()

# Create some posts using the session and commit them
...

# Test your repository object...
repo = PostRepository(session)
results = repo.find_latest()

# Run your assertions of results
...

rawDescription: Python SQLAlchemy - Mocking a model attribute's "desc" method


code:
file.write(fastaform)
file.close()

rawDescription: Send output of print to a new file in python?


code:
# Only accepts keyword attributes
def kw_only(**arguments):
    # defaults
    arguments['features1'] = arguments.get('features1', False)
    arguments['features2'] = arguments.get('features2', False)
    arguments['features3'] = arguments.get('features3', False)

    for k, v in arguments.items():
        print (k, v)

print(kw_only(one=1, two=2))

rawDescription: Iterate over function parameters

description: Iterate over function parameters


code:
from collections import defaultdict
import csv

reader = csv.reader(open('data.file', 'rb'), delimiter='\t')
data_of_category = defaultdict(list)
lines = [line for line in reader]
mask =  [i for i, n in enumerate(lines[1]) if gettype(n)!="float"]
for line in lines[1:]:
    category = ','.join([line[i] for i in mask])
    data_of_category[category].append(line)

rawDescription: Dynamically parsing research data in python


code:
class UserSerializer(serializers.ModelSerializer):
    included = SnippetSerializer(many=True, read_only=True)

    class Meta:
        model = User
        depth = 1
        fields = ('id','included')

rawDescription: Django Rest - Include serializer object in get_*** method


code:
if 'test' in sys.argv:
    CELERY_ALWAYS_EAGER = True

rawDescription: Testing Django coupled with Celery

description: Testing Django coupled with Celery


code:
def make_caching_prepare_input_source(old_prepare_input_source, proxy):
    def caching_prepare_input_source(source, base = None):
        if isinstance(source, xmlreader.InputSource):
            return source

        full_uri = urlparse.urljoin(base or "", source)

        if not full_uri.startswith('http:'):
            args = (source,) if base == None else (source, base)
            return old_prepare_input_source(*args)

        r = urllib2.Request(full_uri)
        r.set_proxy(proxy, 'http')
        f = urllib2.urlopen(r)

        i = xmlreader.InputSource()
        i.setSystemId(source)
        i.setByteStream(f)

        return i

    return caching_prepare_input_source

def enable_http_proxy(server):
    saxutils.prepare_input_source = make_caching_prepare_input_source(
        saxutils.prepare_input_source,
        server,
    )

rawDescription: How can I make xml.sax use a HTTP proxy for its DTD requests?

description: Make xml.sax use a HTTP proxy for its DTD requests


code:
def setUp(self):
    self.testbed = testbed.Testbed()
    self.testbed.activate()
    self.testbed.init_datastore_v3_stub(root_path="your-root-path")

rawDescription: Automatically generate indexes with app engine unit tests


code:
for doc in coll.find():      # .find() returns cursor which is meant for iteration
    print(doc["oxigeno"])    # doc is a python dictionary representing the returned BSON document

rawDescription: MongoDB object pointing

description: MongoDB object pointing


code:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

address_book = ['person1@company.com', 'person2@company.com', 'group3@company.com']
msg = MIMEMultipart()
sender = 'me@company.com'
subject = "My subject"
body = "This is my email body"

msg['From'] = sender
msg['To'] = ','.join(address_book)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
text=msg.as_string()
#print text
# Send the message via our SMTP server
s = smtplib.SMTP('our.exchangeserver.com')
s.sendmail(sender,address_book, text)
s.quit()

rawDescription: Sending Email to a Microsoft Exchange group using Python?


code:
import sys
import collections
import ruamel.yaml as yaml

yaml_str = """\
level0:
  stuff: string0
  level1:
    stuff: string1
    level2: ...
"""

from ruamel.yaml.reader import Reader
from ruamel.yaml.scanner import Scanner
from ruamel.yaml.parser import Parser
from ruamel.yaml.composer import Composer
from ruamel.yaml.constructor import SafeConstructor
from ruamel.yaml.resolver import Resolver
from ruamel.yaml.nodes import MappingNode

class FancyDict(collections.MutableMapping):
    def __init__(self, *args, **kwargs):
        for name in kwargs:
            setattr(self, name, kwargs[name])

    # provide the missing __getitem__, __setitem__, __delitem__, __iter__, and __len__.

class MyConstructor(SafeConstructor):
    def construct_mapping(self, node, deep=False):
        res = SafeConstructor.construct_mapping(self, node, deep)
        assert isinstance(res, dict)
        return FancyDict(**res)

class MyLoader(Reader, Scanner, Parser, Composer, MyConstructor, Resolver):
    def __init__(self, stream, version=None):
        Reader.__init__(self, stream)
        Scanner.__init__(self)
        Parser.__init__(self)
        Composer.__init__(self)
        MyConstructor.__init__(self)
        Resolver.__init__(self)

data = yaml.load(yaml_str, Loader=MyLoader)

rawDescription: How to use custom dictionary class while loading yaml?

description: Use custom dictionary class while loading yaml


code:
#   (generated by ArcGIS/ModelBuilder)
# Usage: DBF2SHAPEFILE <XY_Table> <Y_Field> <X_Field> <Output_Feature_Class>
# ---------------------------------------------------------------------------

# Import system modules
import sys, string, os, arcgisscripting, datetime

# Adds the creation date to all of the previous shapefiles in that folder
filename = 'D:/test.txt'
fileinfo = os.stat(filename)
creation_date = datetime.date.fromtimestamp(fileinfo.st_ctime)
os.rename(filename, filename + '-' + creation_date.strftime('%Y-%m-%d'))

# Create the Geoprocessor object
gp = arcgisscripting.create()

# Load required toolboxes...
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")

# Script arguments...
XY_Table = sys.argv[1]

Y_Field = sys.argv[2]

X_Field = sys.argv[3]

Output_Feature_Class = sys.argv[4]

# Local variables...
Layer_Name_or_Table_View = ""

# Process: Make XY Event Layer...
gp.MakeXYEventLayer_management(XY_Table, X_Field, Y_Field, Layer_Name_or_Table_View, "")

# Process: Copy Features...
gp.CopyFeatures_management(Layer_Name_or_Table_View, Output_Feature_Class, "", "0", "0", "0")

rawDescription: How to use python to turn a .dbf into a shapefile

description: Use python to turn a .dbf into a shapefile


code:
import pygame
screen = pygame.display.set_mode((800, 600))
line_start = None

while True:
  mouse_pos = pygame.mouse.get_pos()
  for e in pygame.event.get():
    if e.type == pygame.QUIT:
      break
    if e.type == pygame.MOUSEBUTTONUP:
      line_start = None if line_start else mouse_pos
  else:
    if line_start:
      pygame.draw.line(screen, pygame.color.Color('White'), line_start, mouse_pos, 1)
      line_start = mouse_pos
    pygame.display.flip()
    continue
  break

rawDescription: How do I make this pygame program to change from a drawing state to non drawing state when clicked and vice versa?

description: Make this pygame program to change from a drawing state to non drawing state when clicked and vice versa


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

#---------
# IMPORT
#---------
import sys, os

from PyQt4 import QtGui, QtCore

#---------
# DEFINE
#---------
class MyListWidget(QtGui.QListWidget):
    dropped = QtCore.pyqtSignal(list)

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

        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls:
            event.accept()

        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()

        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()

            filePaths = [
                str(url.toLocalFile())
                for url in event.mimeData().urls()
            ]

            self.dropped.emit(filePaths)

        else:
            event.ignore()

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.listWidgetFiles = MyListWidget(self)
        self.listWidgetFiles.dropped.connect(self.on_listWidgetFiles_dropped)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.listWidgetFiles)

    @QtCore.pyqtSlot(list)
    def on_listWidgetFiles_dropped(self, filePaths):
        for filePath in filePaths:
            if os.path.exists(filePath):
                QtGui.QListWidgetItem(filePath, self.listWidgetFiles)

#---------
# MAIN
#---------
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(333, 111)
    main.show()

    sys.exit(app.exec_())

rawDescription: QListView not accepting drops in QMainWindow with Python PyQt4


code:
height = int(input('input height: '))

for row in range(1,height+1):
    for pattern in range(1,row+1):
        if row % 2 != 0:
            if pattern % 2 == 1:
                print('AA', end = '')
            else:
                print('BB', end = '')
        else:
            if pattern % 2 == 1:
                print('BB', end = '')
            else:
                print('AA', end = '')
    print()

rawDescription: Python for loop with non desired results


code:
import numpy as np
my_array = np.zeros((int(sp)-i,5),dtype=int)
for ii in range(i,int(sp)):
    body=(np.bincount(un[i].ravel().astype('int'), weights=step_periods[i].ravel()))
    my_array[ii,:len(body)]=body

rawDescription: Combining rows numpy to one single array


code:
import matplotlib.pyplot as plt
from matplotlib import ticker

import numpy as np

N = 10

x = np.arange(N)
y = np.random.randn(N)

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

# Create your ticker object with M ticks
M = 3
yticks = ticker.MaxNLocator(M)

# Set the yaxis major locator using your ticker object. You can also choose the minor
# tick positions with set_minor_locator.
ax.yaxis.set_major_locator(yticks)

plt.show()

rawDescription: change ticks number on a subplot

description: Change ticks number on a subplot


code:
import boto
s3 = boto.connect_s3()
bucket = s3.lookup('mybucket')
key = bucket.lookup('mykey')
your_bytes = key.get_contents_as_string(headers={'Range' : 'bytes=73-1024'})

rawDescription: Reading part of a file in S3 using Boto

description: Reading part of a file in S3 using Boto


code:
class A(object):
  def __new__(cls):
    class C(cls, B):
      pass
    self = object.__new__(C)
    return self

rawDescription: Python multiple inheritance: Whats wrong doing it dynamically?


code:
import urllib2
from urlgrabber.keepalive import HTTPHandler
keepalive_handler = HTTPHandler()
opener = urllib2.build_opener(keepalive_handler)
urllib2.install_opener(opener)

fo = urllib2.urlopen('http://www.python.org')

rawDescription: Python urllib2 with keep alive

description: Python urllib2 with keep alive


code: A = np.squeeze(np.asarray(M))

rawDescription: Numpy matrix to array

description: Numpy matrix to array


code:
import matplotlib.pyplot as plt
import numpy as np
def plotStuff():
    lines = plt.plot(np.random.rand(20))
    color = lines[0].get_color()
    plt.plot(np.random.rand(20),color = color,label = "_nolegend_" )
plotStuff()

rawDescription: matplotlib retrieve color from plt.plot command

description: Matplotlib retrieve color from plt.plot command


code:
from matplotlib import pyplot as plt

data = []

with open('cat_data.dat') as f:
    for line in f:
        if line[1].isalpha():
            continue
        if line.startswith('%'):
            data.append([])
            continue
        data[-1].append([float(x) for x in line.split()])

# Now you have all values in data:
# [[[0.9, 0.9, 0.6, 0.5], [0.0, 0.1, 0.3, 0.2], [0.5, 0.2, 0.0, 0.1]], [[0.2, 0.6, 0.2, 0.3], [0.2, 0.1, 0.1, 0.2], [0.4, 0.2, 0.1, 0.1]]]

_set = 2
row = 1 # Corresponds to 0.2  0.1  0.1  0.2

plt.plot(range(1, 5), data[_set - 1][row])
plt.show()

rawDescription: how to plot a structured data file with Python?

description: Plot a structured data file with Python


code:
import base64

gpgFH = open(gpgFile, 'rb')
gpgStr = gpgFH.read()
gpgEncoded = base64.b64encode(gpgStr)
...

rawDescription: python imaplib gpg file contents into message

description: Python imaplib gpg file contents into message


code:
import re

dict = [('british','7'),('cuneate nucleus','Medulla oblongata'),('Motoneurons','anterior')]

filetext = """<s id="69-7">British Meanwhile is the studio 7 album by british pop band 10cc 7.</s>
<s id="5239778-2">Medulla oblongata,the name refers collectively to the cuneate nucleus and gracile nucleus, which are present at the junction between the spinal cord and the medulla oblongata.</s>
<s id="21120-99">Terior horn cells, motoneurons located in the spinal.</s>
"""

linelist = re.split(u'[\n|\r\n]+', filetext)

s_tag = re.compile(r"(<s[^>]+>)(.*?)(</s>)")

for i in range(3):
    left, right = dict[i]

    line_parts = re.search(s_tag, linelist[i])
    start = line_parts.group(1)
    content = line_parts.group(2)
    end = line_parts.group(3)

    left_match = "(?i)\\b(%s)\\b" % left
    right_match = "(?i)\\b(%s)\\b" % right
    if re.search(left_match, content) and re.search(right_match, content):
        line1 = re.sub(left_match, '<w1>\\1</w1>', content)
        line2 = re.sub(right_match, '<w2>\\1</w2>', line1)
        print(line_parts.group(1) + line2 + line_parts.group(3))

rawDescription: string matching in python

description: String matching in python


code:
progress = 0

@route("/")
def hello():
    global progress
    if progress == 0:
        GPIO.output(led1, False)
        GPIO.output(led2, False)
        GPIO.output(led3, False)
        GPIO.output(led4, False)
        GPIO.output(led5, False)

        progress = 1
        return template('index.html')

    if (not GPIO.input(switch1)) and progress == 1:
        GPIO.output(led1, True)
        progress = 2
        return template('video1.html')

    elif (not GPIO.input(switch2)) and progress == 2:
        GPIO.output(led1, False)
        GPIO.output(led2, True)
        progress = 3
        return template('video2.html')

    elif (not GPIO.input(switch3)) and progress == 3:
        GPIO.output(led2, False)
        GPIO.output(led3, True)
        progress = 4
        return template('video3.html')

    elif (not GPIO.input(switch4)) and progress == 4:
        GPIO.output(led3, False)
        GPIO.output(led4, True)
        progress = 5
        return template('video4.html')

    elif (not GPIO.input(switch5)) and progress == 5:
        GPIO.output(led4, False)
        GPIO.output(led5, True)
        progress = 6
        return template('video5.html')

    elif progress == 6:
        while True:
            GPIO.output(led1, True)
            GPIO.output(led2, True)
            GPIO.output(led3, True)
            GPIO.output(led4, True)
            GPIO.output(led5, True)
            time.sleep(0.5)
            GPIO.output(led1, False)
            GPIO.output(led2, False)
            GPIO.output(led3, False)
            GPIO.output(led4, False)
            GPIO.output(led5, False)
            time.sleep(0.5)

            return template('succes.html')

    elif GPIO.input(switch1) and GPIO.input(switch2) and GPIO.input(switch3) and GPIO.input(switch4) and GPIO.input(switch5):
         time.sleep(0.15)

    else:
        GPIO.output(led1, False)
        GPIO.output(led2, False)
        GPIO.output(led3, False)
        GPIO.output(led4, False)
        GPIO.output(led5, False)

        return template('false.html')

rawDescription: Use same Python variable in multiple if-statements


code:
class MyModel(models.Model):
    timezone1 = TimeZoneField(default='Europe/London') # defaults supported

rawDescription: Django detecting redundant migrations repetitively


code:
@property
def category(self):
    _category = getattr(self, '_category', None)
    if not _category:
        self.__class__._category = _category = Category.objects.get(code='EC')
    return _category

rawDescription: Hardcoding attributes in django models

description: Hardcoding attributes in django models


code:
i = pd.Series(['a', 'a', 'b', 'c', 'b'])
df.lookup(i.index, i.values)

rawDescription: How can I select a specific column from each row in a Pandas DataFrame?

description: Select a specific column from each row in a Pandas DataFrame


code:
import matplotlib.pyplot as plt
import numpy as np
x = y = np.arange(5)

fig,ax = plt.subplots(1)

ax.scatter(x,y,  s=100,marker='x',color='b',linewidths=1)
ax.scatter(x,y+1,s=100,marker='x',color='r',linewidths=2)
ax.scatter(x,y+2,s=100,marker='x',color='g',linewidths=3)

plt.show()

rawDescription: change scatter plot marker thickness

description: Change scatter plot marker thickness


rawDescription: Unable to remove NaN from panda Series

description: Unable to remove NaN from panda Series


code:
regex = re.compile(r"My big honking regex")
for datafile in files:
    content = datafile.read()
    result = regex.sub("Replacement", content)

rawDescription: Speed up a series of regex replacement in python


code:
query = 'name=Alan age=23, name=Jake age=24'
query_split = [x.strip() for x in query.split(",")]
names = [a.split(" ")[0][5:] for a in query_split]
print(names)

['Alan', 'Jake']

rawDescription: How to split string on second character match in python?

description: Split string on second character match in python


code:
s = "Rajasekar SP  def"
s.split(' ')
s.split()
s.partition(' ')

rawDescription: What is for Python what 'explode' is for PHP?


code:
parsed = parse_date(timestamp)
timetuple = parsed.timetuple()
return calendar.timegm(timetuple)

rawDescription: Python: Reliably convert a 8601 string to timestamp


code:
def bitCount(x):
    count = 0
    while x != 0:
       count += 1
       x &= (x-1)
    return count

rawDescription: Bitwise Programming in Python

description: Bitwise Programming in Python


code:
import os

known_extensions = ['.tar.gz', '.tar.bz2']
def splitext(file_name):
    file_name = file_name.strip()

    for ex in known_extensions:
        if file_name[-len(ex):] == ex:
            return file_name[:-len(ex)], ex

    return os.path.splitext(file_name)

rawDescription: How does google chrome auto-rename files when downloading files?


code:
# UPDATE mydb.test1 SET Cnt=5 WHERE Id=1
hs.update('mydb', 'test1', '=', ['Id', 'Cnt'], ['1'], ['1', '5'])

rawDescription: Python-handler-socket (pyhs) update function example


code:
def fs2ClientdataDoc(*args):
#get the doc from the scripting context which is made available to all scripts
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
#get the XText interface
    try:
        text = model.Text
    except AttributeError:
        raise Exception("This script is for Writer Documents only")

#create an XTextRange at the end of the document
    tRange = text.End
    cursor = Desktop.getCurrentComponent().getCurrentController().getViewCursor()
# your cannot insert simple text and text into a table with the same method
# so we have to know if we are in a table or not.
# oTable and oCurCell will be null if we are not in a table
    oTable = cursor.TextTable
    oCurCell = cursor.Cell
#and get the string from Footswitch2 via a TCP port
    import os, socket, time
    from configobj import ConfigObj
    configuration_dir = os.environ["HOME"]
    config_filename = configuration_dir + "/fs2.cfg"
    if os.access(config_filename, os.R_OK):
        pass
    else:
        return None
    cfg = ConfigObj(config_filename)
#define values to use from the configuration file
    tcp_port = int(cfg["control"]["TCP_PORT"])
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.5)
    try:
        sock.connect(("localhost", tcp_port))
    except:
        return None
    sock.settimeout(5)
    try:
        sock.send(bytes('client\n', 'UTF-8'))
    except:
        return None
    try:
        time.sleep(1.0)
        s_list = sock.recv(4096).decode('UTF-8')
        s_list = s_list.split("\n")
    except:
        return None
    lines_in_response = len(s_list)
    if lines_in_response is None:
        return None
    for x in range(0,lines_in_response):
        insert_text = s_list[x]+"\n"
        if oCurCell == None: # Are we inserting into a table or not?
            text.insertString(cursor, insert_text, 0)
        else:
            insert_table = s_list[x].split("\n")
            parts = len(insert_table)
            for y in range(0,parts):
                it = insert_table[y]
                cell = oTable.getCellByName(oCurCell.CellName)
                cellCursor = cell.createTextCursor() # use this cursor if you want the text inserted at the beginning of the cell
                cell.insertString(cellCursor, it, False)
        #        cell.insertString(cursor, insert_text, False) # use the standard cursor to insert at the current position
                cursor.goDown(1,False)
                cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
                oTable = cursor.TextTable
                oCurCell = cursor.Cell
    sock.close()
    return None

rawDescription: How do I write a python macro in libreoffice writer to send a receive data

description: Write a python macro in libreoffice writer to send a receive data


code:
if logger.isEnabledFor(logging.DEBUG):
    logger.debug("Message with %s, %s", expensive_func1(),
                                        expensive_func2())

rawDescription: python - Which is the better way to enable/disable logging?

description: Python - Which is the better way to enable/disable logging


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://jsfiddle.net/9pKMU/show/')
for a in driver.find_elements_by_xpath('.//span[contains(text(), "Author")]/a'):
    print(a.get_attribute('href'))

rawDescription: How to get link from elements with Selenium and Python

description: Get link from elements with Selenium and Python


code:
import praw

r = praw.Reddit(UNIQUE_AND_DESCRIPTIVE_USERAGENT_CONTAINING_YOUR_REDDIT_USERNAME)
subreddit = r.get_subreddit('python')
submissions = subreddit.get_top(limit=1)
for submission in submissions:
    submission.replace_more_comments(limit=None, threshold=0)
    flat_comments = praw.helpers.flatten_tree(submission.comments)
    for comment in flat_comments:
        print(comment.body)

rawDescription: Trouble parsing comments with praw

description: Trouble parsing comments with praw


rawDescription: Grab the aperture values in .chan camera


code:
import datetime
earliest = datetime.datetime.now() - datetime.timedelta(days=7)
Mjcode.query(Mjcode.date <= earliest).fetch(keys_only=True)

rawDescription: Delete entities having datetime older than N seconds from google-app-engine ndb


code:
from datetime import date, timedelta
# http://www.ianlewis.org/en/python-date-range-iterator
def datetimeRange(from_date, to_date=None):
    while to_date is None or from_date <= to_date:
        yield from_date
        from_date = from_date + timedelta(days = 1)

start = date(2009, 8, 20)
end = date(2009, 8, 23)
objects = Obj.objects.filter(date__gte=start)
objects = objects.filter(date__lte=end)

results = {}
for o in objects:
    results[o.date] = o.value

return [results.get(day, 0) for day in datetimeRange(start, end)]

rawDescription: query for values based on date w/ Django ORM

description: Query for values based on date w/ Django ORM


code:
class Animal(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def description(self):
        print (self.name)
        print (self.age)
    def testt(self):
        animo = Animal('johndoe', 5)
        animo.description()

horse = Animal('trevor', 4)
horse.testt()

rawDescription: Is it possible to create an object of class X in a member function of class X itself in python and operate on the object references


code:
a
from scipy.linalg import sqrtm
sq = sqrtm(a)
np.dot(sq, sq) - a

rawDescription: MATLAB matrix^-0.5 equivalent in Python

description: MATLAB matrix^-0.5 equivalent in Python


code: text.split(' ', 2)

rawDescription: Splitting a line into three parts using whitespaces in python


code:
if hasattr(sys, 'frozen'):
    basis = sys.executable
else:
    basis = sys.argv[0]

rawDescription: Python os.list_dir stopping one level short


code:
import os

with open('your_txt_file_name.txt') as names:
     for line in names:
         if line.strip(): #this strip makes you skip empty lines
             parts = line.split(",")
             oldname = parts[0] #you can use strip here depending on your txt
             newname = parts[1] #you can use strip here depending on your txt
             os.rename(oldname, newname)

rawDescription: How to rename the file names in a folder with new names of text file line by line in python

description: Rename the file names in a folder with new names of text file line by line in python


code:
def grouper(n, iterable, fillvalue=None):
  "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  args = [iter(iterable)] * n
  return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Python generator that groups another iterable into groups of N


code:
from subprocess import check_call
check_call(['dot','-Tpng','InputFile.dot','-o','OutputFile.png'])

rawDescription: Converting dot to png in python

description: Converting dot to png in python


code:
compiled = re.compile(r'\d(?:-\d)*$')
result = compiled.match(string_to_parse)

rawDescription: regexp matching slug

description: Regexp matching slug


rawDescription: Grouping Elements of Lists Within a List by Index


rawDescription: Use regular expressions to replace overlapping subpatterns


code:
def get_all_txts_on_dir(path):
    import os
    ret = []
    for root, dir, files in os.walk(path):
        for name in files:
            if name.endswith('.txt'):
                ret.append(name)
    return ret

rawDescription: How to find all text files with Regex?

description: Find all text files with Regex


code: f2.write(line.replace('12345', str(n)))

rawDescription: python: use a increasing variable to repalce

description: Python: use a increasing variable to repalce


code:
import turtle as t

def showTurtle():
    t.st()
    return

def getPos(x,y):
    print("(", x, "," ,y,")")
    return

def hideTurtle(x,y):
    t.ht()
    return

def main():
    t.speed(20)
    t.shapesize(1000,1000)
    t.up()
    t.goto(1000,0)
    t.ht()
    t.onkey(showTurtle,"a")
    t.listen()
    t.onclick(getPos)
    t.onrelease(hideTurtle)
    t.mainloop()
main()

rawDescription: Python 3.0 using turtle.onclick

description: Python 3.0 using turtle.onclick


code: l = [(x, v[x]) for x in i[0]]

rawDescription: python: creating numpy nonzero index, value pair

description: Python: creating numpy nonzero index, value pair


code:
import operator
coco = operator.attrgetter('co_code', 'co_consts')
coco((lambda x: x+2).__code__) == coco((lambda x: x+2).__code__)
coco((lambda x: x+2).__code__) == coco((lambda x: x+1).__code__)
def foo(y):
  return y + 2

coco((lambda x: x+2).__code__) == coco(foo.__code__)

rawDescription: Lambda-function comparison in python

description: Lambda-function comparison in python


code:
import openpyxl

avg = [10, 20, 25, 5, 32, 7]

wb = openpyxl.load_workbook('output/file_base.xlsx')
ws = wb.active

for row, entry in enumerate(avg, start=20):
    ws.cell(row=row, column=4, value=entry)

wb.save('out.xlsx')

rawDescription: Openpyxl: iterate on range of cell

description: Openpyxl: iterate on range of cell


code:
import matplotlib.pyplot as plt
for i, fig_data in enumerate(quadnumcounts):
    # Set current figure to the i'th subplot in the 2x2 grid
    plt.subplot(2, 2, i + 1)
    # Set axis labels for current figure
    plt.xlabel('Trials')
    plt.ylabel('Frequency')
    for line_data in fig_data:
        # Plot a single line
        xs = [i + 1 for i in range(len(line_data))]
        ys = line_data
        plt.plot(xs, ys)
# Now that we have created all plots, show the result
plt.show()

rawDescription: How to plot multiple lines in single graph python

description: Plot multiple lines in single graph python


code:
from django.db.models import Count

Expiration.objects.annotate(num_profiles=Count('profile')).order_by('num_profiles')[0]

rawDescription: How to find the object with smallest related_set in Django?

description: Find the object with smallest related_set in Django


code:
fig = matplotlib.pyplot.figure()

plt1 = fig.add_subplot(2,1,1)
plt2 = fig.add_subplot(2,1,2)

rawDescription: matplotlib. How do I switch between subplots, rather than replotting them from scratch?

description: Matplotlib. How do I switch between subplots, rather than replotting them from scratch


code:
import matplotlib.pyplot as plt
h = plt.plot([0, 0, 1, 1], [0, 1, 1, 0], 'bo')
h[0].set_clip_on(False)
plt.show()

rawDescription: matplotlib: how to show markers on canvas boundary

description: Matplotlib: how to show markers on canvas boundary


code:
ok_words = set(["a", "b", "c", "e"])

def filter_words(words):
    return [word for word in words if word in ok_words]

rawDescription: passing text through a dictionary in Python

description: Passing text through a dictionary in Python


code: np.choose(idx, a.T[:,:,np.newaxis])

rawDescription: Indexing a 2d array with a 3d array in numpy


code:
import re
next = 'user/Syntaf'
m = re.search(r'\/(.*)$', next)
m.group(1)
result = m.group(1)
result

rawDescription: Grab back of string until terminating character


code: {{ something|safe }}

rawDescription: Passing HTML to template using Flask/Jinja2


code:
class Foo:
  def setAllWithKwArgs(self, **kwargs):
    for key, value in kwargs.items():
      setattr(self, key, value)

rawDescription: How can you set class attributes from variable arguments (kwargs) in python

description: Set class attributes from variable arguments (kwargs) in python


code:
import csv
import itertools
import operator

filename = 'testing.csv'
outfile = 'outfile.csv'
ndups = 0

with open(filename, 'r') as fin, open(outfile, 'w') as fout:
    reader = csv.DictReader(fin)
    writer = csv.DictWriter(fout, lineterminator='\n', fieldnames=reader.fieldnames)
    for id_, grp in itertools.groupby(reader, key=operator.itemgetter('ID')):
        rows = list(grp)
        if len({row['Name'] for row in rows}) > 1:
            ndups += len(rows)
            continue
        writer.writerows(rows)

print('{} duplicates.'.format(ndups))

rawDescription: Read CSV and remove duplicate values based on the values in two (out of many) columns


code:
for idA,val in enumerate(items):
    for idB in range(0, idA):
        process_it(val,items[idB])

rawDescription: Effective ways to implement Every-to-Every interaction?


code: np.repeat(test, [4, 1, 1], axis=0)

rawDescription: replicating borders in 2d numpy arrays

description: Replicating borders in 2d numpy arrays


code:
MSILISTS = {}
MSILISTS['AC_LIST'] = [
        'somename.msi',
        'someothername.msi',
    ]
MSILISTS['AC_LIST']

rawDescription: Python: Is it possible to have a list of lists? and how do I call a particular list?


code:
import numpy as np
u_padded = np.random.randint(1,100,3024).reshape(1,3024) # random array of 1*3024 elements
u_padded.shape
index = np.random.randint(0,3024,100*2016).reshape(100,2016) # random array of 100*2016 indexes with index range = (0,3024)
index.shape
u_padded[0,index] # select elements from u_padded with index from index array
u_padded[0,index].shape

rawDescription: TypeError: 'numpy.ndarray' object is not callable while extracting index and elements are stored in different array in python


code:
import os
from PyQt4 import QtCore, QtGui, uic

# get the directory of this script
path = os.path.dirname(os.path.abspath(__file__))

MainWindowUI, MainWindowBase = uic.loadUiType(
    os.path.join(path, 'mainwindow.ui'))

LandingPageUI, LandingPageBase = uic.loadUiType(
    os.path.join(path, 'landing.ui'))

class MainWindow(MainWindowBase, MainWindowUI):
    def __init__(self, parent=None):
        MainWindowBase.__init__(self, parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.handleButton)

    def handleButton(self):
        # keep a reference to the landing page
        self.landing = LandingPage()
        self.landing.show()

class LandingPage(LandingPageBase, LandingPageUI):
    def __init__(self, parent=None):
        LandingPageBase.__init__(self, parent)
        self.setupUi(self)

rawDescription: Working with PyQt and Qt designer ui files


code:
payload = {'grant_type': 'authorization_code',
    'code': code,
    'client_id': 'xxxxxxxxxxxxxxxxxxxxxxx',
    'client_secret': 'xxxxxxxxxxxxxxxxxxxxxx',
    'redirect_uri': redirect_uri}
result = urlfetch.fetch(url=API_ACCESS_TOKEN_URL, payload = payload, method=urlfetch.POST)

rawDescription: how to make a POST request in python and webapp2

description: Make a POST request in python and webapp2


code:
with MySQLdb.connect(**kw) as db:
    while some_condition():
        do_stuff_with(db)

rawDescription: Should I keep a db connection open in MySQLdb?


code:
import traceback
try:
    d = json.loads(data[data.index('{'):-1])
except:
    traceback.print_exc()
else:
    print(d)

rawDescription: Problems loading JSON code in Python

description: Problems loading JSON code in Python


code:
xs = df.values
xs.T.dot(xs)

rawDescription: Elegant way to perform column-wise operations on two dataframe


code:
subprocess.Popen(['/bin/bash', '-c', 'rsem-calculate-expression -p 2 \
    --some-other-option --paired-end \
    <(zcat a_1.fastq.gz b_1.fastq.gz c_1.fastq.gz) \
    <(zcat b_2.fastq.gz b_2.fastq.gz c_2.fastq.gz) \
    ~/index/hg19 output_dir'])

rawDescription: how to use subprocess with multiple multiple stdin from zcat

description: Use subprocess with multiple multiple stdin from zcat


code:
import numpy as np
np.array(data_list).reshape(-1, 2)

rawDescription: How can I turn a list into an array in python?

description: Turn a list into an array in python


code:
print('Let\'s print "Happiness" out')
print("Let's print \"Happiness\" out")
print('''Let's print "Happiness" out''')
print("""Let's print "Happiness" out""")

rawDescription: Use single quote and double quote same time as string python


code:
import re
scores = ["Bob Foo - 10 / 10\n",
          "John Smith - 5 / 10\n",
          "Bob Foo - 7 / 10\n",
          "Jack T - 6 / 10\n",
          "Jack T - 4 / 10\n",
          "Bob Foo - 9 / 10\n"]

# First, split the names and scores up
scores = [re.match('(\S+ \S+) - (\d+)', score).groups() for score in scores]
#print (scores)

# Convert the number string into an integer
scores = [[score[0], int(score[1])] for score in scores]
#print (scores)

# Create a dictionary, keyed by the name
names = set(score[0] for score in scores)
scores = {
    name: [score[1] for score in scores if name == score[0]]
    for name in names
}
# print (scores)

# Compute the average for each name
scores = {
    name: sum(score)/len(score)
    for name, score in scores.items()
}
print (scores)

rawDescription: Finding averages from strings in a list in Python 3


code:
plt.Figure()
thismanager = get_current_fig_manager()
thismanager.window.wm_geometry("500x500+890+300") #sets original size and position
button = Tkinter.Button(self,command=self.Click)

def Click(self):
   thismanager = get_current_fig_manager()
   thismanager.set_window_title('Title')
   plt.clf()
   plt.xlabel('Xaxis',fontsize=16)
   im=imshow(variable, cmap='gray', origin='lower',vmin=0,vmax=255,interpolation='nearest')
   cb=colorbar()
   cb.set_label('Label',fontsize=16)
   show()

rawDescription: Get size of resized matplotlib plot window


code: LOGIN_URL = 'erp:index:login'

rawDescription: globally replace login_url of login_required in django

description: Globally replace login_url of login_required in django


rawDescription: Updating Kivy GUI using clock object?

description: Updating Kivy GUI using clock object


code:
import numpy
from scipy import misc, ndimage

lena = misc.lena()
image = numpy.vstack((lena, numpy.zeros(lena.shape[1])))
weights = numpy.array([[1, 1, 1],
                    [1, 8, 1],
                    [1, 1, 1]])/16.
convimage = ndimage.convolve(image, weights, mode='wrap')[0:lena.shape[1],]

rawDescription: scipy.ndimage.filters.convolve - different modes along different axes?

description: Scipy.ndimage.filters.convolve - different modes along different axes


code:
from bs4 import BeautifulSoup

html_text = 'This is
what
I want. WITH the
 tags.'
soup = BeautifulSoup(html_text)
text_wanted = soup.find('span', {'id': 'spamANDeggs'}).decode_contents(formatter="html")

rawDescription: Using BeautifulSoup to extract <span> WITH tags


code:
import csv
with open('file.txt', newline='') as csvfile, open("data.csv","w",newline='') as mycsv:
    reader = csv.reader(csvfile, delimiter=' ')
    wr=csv.writer(mycsv,delimiter=',', quotechar='"',quoting=csv.QUOTE_ALL)
    for row in reader:
        print(', '.join(row))
        wr.writerow(row)

rawDescription: text file of data to csv file in python

description: Text file of data to csv file in python


code:
import datetime
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# build up the data
df = []
start_date = datetime.datetime(2015, 7, 1)
for i in range(10):
    for j in [1,2]:
        unit = 'Ones' if j == 1 else 'Twos'
        date = start_date + datetime.timedelta(days=i)

        # I believe it makes more sense to directly convert the datetime to a
        # "matplotlib"-date (float), instead of creating strings and then let
        # pandas parse the string again
        df.append({
                'Date': mdates.date2num(date),
                'Value': i * j,
                'Unit': unit
            })
df = pd.DataFrame(df)

# build the figure
fig, ax = plt.subplots()
sns.tsplot(df, time='Date', value='Value', unit='Unit', ax=ax)

# assign locator and formatter for the xaxis ticks.
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y.%m.%d'))

# put the labels at 45deg since they tend to be too long
fig.autofmt_xdate()
plt.show()

rawDescription: Seaborn tsplot does not show datetimes on x axis well


code:
# set the locations and labels of the xticks
plt.xticks( arange(10), ('week1', 'week2', 'week3', 'week4', 'week5', 'week6', 'week7', 'week8', 'week9', 'week10') )

rawDescription: Python manually define matplotlib xlim()


code: q = q.with_entities(User.id)

rawDescription: SQLAlchemy ORM: modify the columns returned from a query


code:
import json
import logging

with open('myconfig.json') as f:
    config_dict = json.load(f)
    logging.config.dictConfig(config_dict)

rawDescription: Python logging: can dictConfig be read from a file?


code:
import struct
import hashlib
number_of_workers = 16
my_md5 = hashlib.md5('stackoverflow.com').hexdigest()
# my_md5 is 'd0cc85b26f2ceb8714b978e07def4f6e'

id = struct.unpack('>L', my_md5.decode('hex')[:4])[0]
# id is 3503064498L
# id % number_of_workers = 2
string_id = '%X' % (id % number_of_workers, )
# string_id = '2'

send_to_worker(string_id, task)

rawDescription: deterministic mapping of ids to arbitrary amount of workers

description: Deterministic mapping of ids to arbitrary amount of workers


code:
#!/usr/bin/env python3
import subprocess

try:
    file = subprocess.check_output(["zenity", "--file-selection"]).decode("utf-8").strip()
    print(file)
except subprocess.CalledProcessError:
    pass

rawDescription: Alternative for tkinter's askopenfilename


code:
import doctest
import unittest

# These are my modules that contain doctests:
from util import bitwise
from util import text
from util import urlutil
DOCTEST_MODULES = (
  bitwise,
  text,
  urlutil,
)

# unittest.TestLoader will call this when it finds this module:
def load_tests(*args, **kwargs):
  test_all_doctests = unittest.TestSuite()
  for m in DOCTEST_MODULES:
    test_all_doctests.addTest(doctest.DocTestSuite(m))
  return test_all_doctests

rawDescription: How to get django's unittest TestLoader to find and run my doctests?

description: Get django's unittest TestLoader to find and run my doctests


code:
hashable = (1,2,4)
not_hashable = ([1,2],[3,4])
hash_check = {}
hash_check[hashable] = True
hash_check
hash_check[not_hashable] = True

rawDescription: Immutable objects are not hashable in python?


code:
for root, dirs, files in os.walk('site_dump'):
  nested_levels = root.split('/')
  if len(nested_levels) == 5:
    del dirs[:]
    # Eventually do stuff with the file here

rawDescription: Limit the number of nested directories traversed by os.walk


code:
#!/usr/bin/env python
import wx
import wx.grid

class ExampleFrame ( wx.Frame ):

    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent)

        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )

        bSizer1 = wx.BoxSizer( wx.VERTICAL )

        self.Panel = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
        bSizer2 = wx.BoxSizer( wx.VERTICAL )

        self.nb = wx.Notebook( self.Panel, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )

        bSizer2.Add( self.nb, 1, wx.EXPAND |wx.ALL, 5 )

        self.Panel.SetSizer( bSizer2 )
        self.Panel.Layout()
        bSizer2.Fit( self.Panel )
        bSizer1.Add( self.Panel, 1, wx.EXPAND |wx.ALL, 0 )

        self.SetSizer( bSizer1 )
        self.Layout()
        self.menuBar = wx.MenuBar( 0 )
        self.filemenu = wx.Menu()
        self.menuAbout = wx.MenuItem( self.filemenu, wx.ID_ANY, u"&About", u" Information about this program", wx.ITEM_NORMAL )
        self.filemenu.AppendItem( self.menuAbout )

        self.menuExit = wx.MenuItem( self.filemenu, wx.ID_ANY, u"E&xit", u" Terminate the program", wx.ITEM_NORMAL )
        self.filemenu.AppendItem( self.menuExit )

        self.menuBar.Append( self.filemenu, u"&miP3" )

        self.SetMenuBar( self.menuBar )

        self.statusBar = self.CreateStatusBar( 1, wx.ST_SIZEGRIP, wx.ID_ANY )

        self.Centre( wx.BOTH )

        self.Bind( wx.EVT_MENU, self.OnAbout, id = self.menuAbout.GetId() )
        self.Bind( wx.EVT_MENU, self.OnExit, id = self.menuExit.GetId() )

    def __del__( self ):
            pass

    def OnAbout( self, event ):
        event.Skip()

    def OnExit( self, event ):
        event.Skip()

class ExamplePanel ( wx.Panel ):

    def __init__( self, parent ):
        wx.Panel.__init__ ( self, parent )

        # whatever you want on your panel goes here, for example a grid
        bSizer3 = wx.BoxSizer( wx.VERTICAL )
        self.m_grid1 = wx.grid.Grid( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_grid1.CreateGrid( 5, 3 )
        self.m_grid1.EnableEditing( True )
        self.m_grid1.EnableGridLines( True )
        self.m_grid1.EnableDragGridSize( False )
        self.m_grid1.SetMargins( 0, 0 )
        self.m_grid1.EnableDragColMove( False )
        self.m_grid1.EnableDragColSize( True )
        self.m_grid1.SetColLabelSize( 30 )
        self.m_grid1.SetColLabelAlignment( wx.ALIGN_CENTRE, wx.ALIGN_CENTRE )
        self.m_grid1.EnableDragRowSize( True )
        self.m_grid1.SetRowLabelSize( 80 )
        self.m_grid1.SetRowLabelAlignment( wx.ALIGN_CENTRE, wx.ALIGN_CENTRE )
        self.m_grid1.SetDefaultCellAlignment( wx.ALIGN_LEFT, wx.ALIGN_TOP )
        bSizer3.Add( self.m_grid1, 1, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( bSizer3 )
        self.Layout()

    def __del__( self ):
        pass

class MyFrame( ExampleFrame ):
    def __init__( self, parent ):
        ExampleFrame.__init__( self, parent )

        self.title = "Demo with Notebook"
        self.SetTitle(self.title)

        self.nb.AddPage(ExamplePanel(self.nb), "Absolute Positioning")
        self.nb.AddPage(ExamplePanel(self.nb), "Page Two")
        self.nb.AddPage(ExamplePanel(self.nb), "Page Three")

    def OnAbout(self, event):
        # A message dialoge box with an OK button. wx.OK is a sandard ID in wxWidgets
        dlg = wx.MessageDialog(self, "Author: Niek de Klein", "About miP3")
        dlg.ShowModal() # show it
        dlg.Destroy() # finally destroy it when finished

    def OnExit(self, eevent):
        self.Close(True) # close the frame

class testapp(wx.App):
    def OnInit(self):
        self.m_frame = MyFrame(None)
        self.m_frame.Show()
        self.SetTopWindow(self.m_frame)
        return True

app = testapp(0)
app.MainLoop()

rawDescription: How to get multiple panels on one frame when overwriting the standard frame?

description: Get multiple panels on one frame when overwriting the standard frame


rawDescription: How do I filter a Panda dataframe based on a simple criteria in Python?

description: Filter a Panda dataframe based on a simple criteria in Python


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

df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
axes = pd.tools.plotting.scatter_matrix(df, alpha=0.2)
plt.tight_layout()
plt.savefig('scatter_matrix.png')

rawDescription: matplotlib analog of R's `pairs`

description: Matplotlib analog of R's `pairs`


code:
with open('reference.pdf') as rf:
    reference_data = rf.read()
with open('pdf_from_website.pdf') as wf:
    website_data = wf.read()
self.assertEqual(reference_data[:11], website_data[:11])
self.assertEqual(reference_data[13:], website_data[13:])

rawDescription: Unittesting pdf generated from website

description: Unittesting pdf generated from website


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

Dictionary = {"A":3,"C":5,"B":2,"D":3,"E":4,
              "A very long key that will be truncated when it is graphed":1}
Dictionary_Length = len(Dictionary)
Max_Key_Length = 15
Sorted_Dict_Values = sorted(Dictionary.values(), reverse=True)
Sorted_Dict_Keys = sorted(Dictionary, key=Dictionary.get, reverse=True)
for i in range(0,Dictionary_Length):
    Key = Sorted_Dict_Keys[i]
    Key = Key[:Max_Key_Length]
    Sorted_Dict_Keys[i] = Key
X = np.arange(Dictionary_Length)
Colors = ('b','g','r','c')  # blue, green, red, cyan

Figure = plt.figure()
Axis = Figure.add_subplot(1,1,1)
for i in range(0,Dictionary_Length):
    Axis.bar(X[i], Sorted_Dict_Values[i], align='center',width=0.5, color=Colors[i%len(Colors)])

Axis.set_xticks(X)
xtickNames = Axis.set_xticklabels(Sorted_Dict_Keys)
plt.setp(Sorted_Dict_Keys)
plt.xticks(rotation=20)
ymax = max(Sorted_Dict_Values) + 1
plt.ylim(0,ymax)

plt.show()

rawDescription: Plotting histogram from dictionary Python


code:
def gym():
    y=int(input("How many items in your gym bag?"))
    gymbag=[]
    for x in range(y):
        f=input("Enter an item")
        gymbag.append(f)
    print(gymbag)
    return gymbag

def gyms(gymbag):
    total_length = 0
    for item in gymbag:
        print(len(item)) # LENGTH OF ITEM
        total_length += len(item)
    print(total_length) # LENGHT OF ALL ITEMS COMBINED IN GYMBAG

gymbag = gym()
gyms(gymbag)

rawDescription: Output from function 1 as input in function 2


code:
import wx

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")

        # Add a self.panel so it looks the correct on all platforms
        self.panel = wx.Panel(self, wx.ID_ANY)

        btn = wx.Button(self.panel, label="Change Cursor")
        btn.Bind(wx.EVT_BUTTON, self.changeCursor)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(btn)
        self.panel.SetSizer(sizer)

    #----------------------------------------------------------------------
    def changeCursor(self, event):
        """"""
        myCursor= wx.StockCursor(wx.CURSOR_WAIT)
        self.panel.SetCursor(myCursor)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyForm().Show()
    app.MainLoop()

rawDescription: wxPython change mouse cursor to notify a long running operation

description: WxPython change mouse cursor to notify a long running operation


rawDescription: Plotting Pandas Dataframe by Type

description: Plotting Pandas Dataframe by Type


code:
def P2R(radii, angles):
    return radii * exp(1j*angles)

def R2P(x):
    return abs(x), angle(x)

rawDescription: Python Numpy - Complex Numbers - Is there a function for Polar to Rectangular conversion?


code:
# assuming your input is in product_to_store
store_to_product = [[] for i in range(10)]
for product, store in enumerate(product_to_store):
  store_to_product[store].append(product)

rawDescription: Inverse mapping from a Python list-of-lists to an integer index


code:
the_string = "this is a very long string, here is a very long word, f" + ("o" * 50) + " good bye, string, "
filename_string = the_string
if len(the_string) > 100:
    # if the 100th character is not a space or a comma
    if the_string[99] != " " and the_string[99] != ",":
        # split the string by words, and rejoin all but the last
        # if it ends with a comma, remove it (it won't end in a space because of split())
        filename_string = " ".join(stripped_string[:99].split()[:-1]).rstrip(",")
    else:
        # just remove the last space (and if there is one, a comma)
        filename_string = stripped_string[:100].rstrip(", ")
with open(filename_string, 'w') as outfile:
    outfile.write(the_string)

rawDescription: Cutting the string if its too long an saving the original in Python 2.7.2


code:
# Response to StackOverflow post:
# Making a hollow box in Python

# The multiplication operator (*) is the same as repeated
# concatenation when applied to strings in Python.

# I solved the problem by creating an array with N elements
# and gluing them together (str.join(array)) with newline
# characters.

# I trust you're already familiar with string formatting and
# concatenation, but in case you're not, please feel free to
# ask for clarification.

def main():
    n = int (input("Enter an integer between 1 and 15"))
    box = "\n".join(["*"*(2*n)] + ["*%s*" % (" "*(2*n-2))]*(n-2) + ["*"*(int(n>1)*2*n)])
    print (box)

if __name__ == '__main__':
    main()
    input() # Prevents the console from closing immediately

rawDescription: Making a hollow box in Python to these specifications?


code: d[Foo(3).val] = 'bar'

rawDescription: Dictionary key from object field

description: Dictionary key from object field


code:
from pymongo import MongoClient
client = MongoClient(host="myhost.com")
db = client.mydb
current_ops = db.current_op(True)

rawDescription: How to run MongoDB commands with pymongo?

description: Run MongoDB commands with pymongo


code:
class ProjectModelView(ModelView):
    inline_models = (Task, )

rawDescription: Modify list template in flask admin

description: Modify list template in flask admin


code:
class Bill(models.Model):
    serial = models.IntegerField(default=lambda: Bill.objects.latest('id').serial + 1)
    # ...

rawDescription: How do I get a default Value for a Field that usually increments in Django?

description: Get a default Value for a Field that usually increments in Django


code:
userWantToContinue = True
while aqpool[0] and userWantToContinue:
    shuffle (aqpool)
    numRight = 0

    for question, rightAnswer in aqpool:
        answer = raw_input(question + " ")

        if answer == rightAnswer:
            print ("RÄTT SVAR!")

            numRight = numRight + 1

        else:
            print("FEL SVAR! Rätta svaret är: " + rightAnswer + "\n")

        print("Vill du försätta spela? (ja eller nej)")
        userWantToContinue = str(raw_input()) not in ('n', 'nej')
        if not userWantToContinue:
            break

    total = numRight / len(aqpool) * 100
    print ("Du hade %s%% rätt!" % total)

rawDescription: Python programing - exiting the loop and displaying score


code:
from scipy import stats
import numpy as np
stats.lognorm(0.5, scale=np.exp(2)).ppf(0.005)

rawDescription: How to calculate the inverse of the log normal cumulative distribution function in python?

description: Calculate the inverse of the log normal cumulative distribution function in python


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

# some data
a = np.sort(np.random.randn(10, 10))

# use the default 'jet' colour map for showing the difference later
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.imshow(a, cmap=cm.get_cmap('jet'))
fig.savefig('map1.png')

# let's use jet and modify the alpha channel
# you would use your own colour map specified by f
my_cmap = cm.get_cmap('jet')

# this is a hack to get at the _lut array, which stores RGBA vals
my_cmap._init()

# use some made-up alphas, you would use the ones specified by f
alphas = np.abs(np.linspace(-1.0, 1.0, my_cmap.N))

# overwrite the alpha channel of the jet colour map
my_cmap._lut[:-3,-1] = alphas

# plot data with our modified colour map
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.imshow(a, cmap=my_cmap)
fig.savefig('map2.png')

rawDescription: Create a colorbar from an RGBA function in matplotlib


code:
class Foo():
    def __init__(self, name):
         self.name = name
    def __str__(self):
         return '<Foo name=%s>' % self.name
    def __repr__(self):
         return str(self)

f = Foo('bar')
f

rawDescription: How do I control the title of instances of a class in Python?

description: Control the title of instances of a class in Python


code:
def is_data_objet_deleted(self, name):
    table = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.ID, 'data_configuration_data_objects_ct_fields_body')))
    rows = table_id.find_elements(By.TAG_NAME, "tr")

    result = all(row.find_elements(By.TAG_NAME, "td")[2].text != name
                 for row in rows)

    # save a screenshot if there was name found
    if not result:
        self.save_screenshot("data_objects_page_saved_details")
    return result

rawDescription: Selenium Python iterate over a table of rows it is stopping at the first row


code:
doc = minidom.parseString('<cart><items><item id="1" /></items><items><item id="2" /></items></cart>')

newItem = doc.createElement('item')
newItem.setAttribute('id', 'new item')

items = doc.getElementsByTagName('item')
for item in items:
    item.parentNode.appendChild(newItem.cloneNode(True))
    print(item.parentNode.toxml())
print(doc.toprettyxml())

rawDescription: xml document not updating in minidom

description: Xml document not updating in minidom


code:
def grades(alist):
    highest, average, lowest, sumvalues = alist[0]
    for i in alist[1:]:
        if i[0] > highest: highest = i[0]
        average += i[1]
        if i[2] < lowest: lowest = i[2]
        sumvalues += i[3]
    average = average / len(alist)
    return highest, average, lowest, sumvalues

rawDescription: Python Find max, average, min, and add up values in a tuple in a list


code:
df = DataFrame({'uid':uid,'misc':misc,'ts':rng})
df = df.sort(["uid", "ts"])
df["since_seen"] = df.groupby("uid")["ts"].apply(lambda x: x - x.iloc[0])
df

rawDescription: adding column with per-row computed time difference from group start?

description: Adding column with per-row computed time difference from group start


code:
from pylab import *
from scipy.integrate import odeint
from numpy import *
import math

#Parameters.
k = 2.0
m = 1.0
w0 = (k/m)**(1/2)
alpha = 0.2
l = alpha/(2*m)
f = 1.0
wd = w0 + 0.025
beta = 0.2
t_fixed = 2.0

#Arrays.
t = linspace(0.0, 200.0, 200.0)
wd_array = linspace(w0-1.0, w0+1, 200.0)
f_array = linspace(10.0, 200.0, 3.0)

#Time step.
init_x = 0.0
init_v = 0.0
dx = 15.0
dv = 0.0
init_cond = [init_x,init_v]
init_cond2 = [init_x + dx,init_v + dv]

def rhs6(c,t,wd,f):
    c0dot = c[1]
    c1dot = -2*l*c[1] - w0*w0*c[0] + (f/m)*cos((wd)*t)
    return [c0dot, c1dot]

full_array = zeros((len(f_array),len(wd_array)))
for index,force in enumerate(f_array):
    amp_list = []
    for wd in wd_array:
        res = odeint(rhs6, init_cond, t, args=(wd,force))
        amp = max(res[:,0])
        amp_list.append(amp)
        # print(res)
    amp_array = array(amp_list)
    full_array[index,:] = amp_array

for f in full_array:
    plot(wd_array, f)

show()

rawDescription: Do calculation for array of values - Python


code:
import numpy as np
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import animation

fig, ax = plt.subplots()

patches = []
# create circles with random sizes and locations
N = 10 # number of circles
x = np.random.rand(N)
y = np.random.rand(N)
radii  = 0.1*np.random.rand(N)
for x1,y1,r in zip(x, y, radii):
    circle = Circle((x1,y1), r)
    patches.append(circle)

# add these circles to a collection
p = PatchCollection(patches, cmap=cm.prism, alpha=0.4)
ax.add_collection(p)

def animate(i):
    colors = 100*np.random.rand(len(patches)) # random index to color map
    p.set_array(np.array(colors)) # set new color colors
    return p,

ani = animation.FuncAnimation(fig, animate, frames=50, interval=50)

plt.show()

rawDescription: How to efficiently alter the color in an animation of patches circles in matplotlib?

description: Efficiently alter the color in an animation of patches circles in matplotlib


code:
x = ['str4', 'str5']

if d.index(x[0]) + 1 == d.index(x[1]):
    return d.index(x[1])

rawDescription: Search a list in a list

description: Search a list in a list


code:
class User():
    def setup(self):
        self.listA = []                          # instance variable
        self.listB = []                          # instance variable
        for i in range(1):
            self.listA.append('a')
            self.listB.append('b')

rawDescription: Python Strange Behavior with List & Append


code:
from bottle import static_file
@route('/static/<filename>')
def server_static(filename):
    return static_file(filename, root='/path/to/your/static/files')

rawDescription: How to return an html file in bottle server?

description: Return an html file in bottle server


code:
def test(dynamic, filename):
    return dynamic[:3] in filename

rawDescription: Python non strict search text in string

description: Python non strict search text in string


code:
import wx
import wx.lib.newevent

import random

CpuEvent, EVT_CPU_EVENT = wx.lib.newevent.NewEvent()

class CPU(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id, size=(80, 110))

        self.value  = 100
        self.parent = parent

        self.SetBackgroundColour('#ffffff')

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(EVT_CPU_EVENT, self.do_value)

    def do_value(self, event):
        self.value = event.value
        self.Refresh()

    def OnPaint(self, event):

        dc = wx.PaintDC(self)

        dc.SetDeviceOrigin(0, 100)
        dc.SetAxisOrientation(True, True)

        pos = self.value
        rect = pos / 5

        for i in range(1, 21):
            if i > rect:
                dc.SetBrush(wx.Brush('#075100'))
                dc.DrawRectangle(10, i*4, 30, 5)
                dc.DrawRectangle(41, i*4, 30, 5)
            else:
                dc.SetBrush(wx.Brush('#36ff27'))
                dc.DrawRectangle(10, i*4, 30, 5)
                dc.DrawRectangle(41, i*4, 30, 5)

class CPUWidget(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        self.cpu = CPU(self, -1)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.do_CpuData)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(self.cpu, 1, wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)

        self.SetSizer(hbox)
        hbox.Fit(self)
        self.Centre()
        self.Show(True)
        self.timer.Start(1000)

    def do_CpuData(self, event = None):
        cData = random.randint(0, 100)
        event = CpuEvent(value = cData)
        wx.PostEvent(self.cpu, event)

app = wx.App(redirect = False)
CPUWidget(None, -1, 'cpu')
app.MainLoop()

rawDescription: wxPython: How to remove slider and in return populate custom gauge with function CpuData

description: WxPython: How to remove slider and in return populate custom gauge with function CpuData


code:
from tkinter import Tk, StringVar, ttk

class Application:

    def __init__(self, parent):
        self.parent = parent
        self.combo()

    def combo(self):
        self.box_value = StringVar()
        self.box = ttk.Combobox(self.parent, textvariable=self.box_value,
                                state='readonly')
        self.box['values'] = ('A', 'B', 'C')
        self.box.current(0)
        self.box.grid(column=0, row=0)

if __name__ == '__main__':
    root = Tk()
    app = Application(root)
    root.mainloop()

rawDescription: Set a default value for a ttk Combobox

description: Set a default value for a ttk Combobox


code:
for txt in legend.get_texts():
    txt.set_ha("center") # horizontal alignment of text item
    txt.set_x(-5) # x-position
    txt.set_y(10) # y-position

rawDescription: Matplotlib legend: labels above markers

description: Matplotlib legend: labels above markers


code:
...

self.ser = serial.Serial(comDev, 115200, timeout=10)

...

#Function that continue to read from Serial port until 'readUntil'
#sequence of symbols appears
def CheckReadUntil(self, readUntil):
    outputCharacters = []
    while 1:
        ch = self.ser.read()
        if len(ch) == 0:
            break
        outputCharacters += ch
        if outputCharacters[-len(readUntil):]==readUntil:
            break
    outputLines = ''.join(outputCharacters)
    return outputLines

rawDescription: PySerial: how to understand that the timeout occured while reading from serial port?


code:
import numpy as np

s1 = 5
s2 = 3
s3 = 13

A = ['s1', 's2', 's3', 's1']
B = [1, 2, 13, 4]

def fun1(s, arg2):
 return s * np.random.normal(0, 1, (200, arg2))

C = [fun1(locals()[A_item], B_item) for A_item, B_item in zip(A, B)]

rawDescription: Python evaluating a function based on contents of a list


rawDescription: How do I get the name from a named tuple in python?

description: Get the name from a named tuple in python


code:
for device in root.iter("device"):
    dicto[device.get("id")] = [0, 0, 0, 0]
    completes = 0
    for child in device:
         ...
    dicto[device.get("id")][3] = completes

rawDescription: Strange Python Counter issue

description: Strange Python Counter issue


code:
def foo(a, b):
    if b is not None:
        return a, b
    else:
        return None, None

value1, value2 = foo(a, b)
if value1 is None:   # Alt: value1 is None or value2 is None
    return get_something(a)

rawDescription: PyLint: Attempting to unpack a non-sequence


code:
from itertools import tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

# Convert input line into list of line segments
Line1_segs = [LineString(p) for p in pairwise(Line1_string.coords[:])]

# Find the intersections
intersect_segs = [i for i, s in enumerate(Line1_segs) if line2_string.intersects(s)]
print(intersect_segs)  # [2]

rawDescription: calculate the intersection point of a line to a Linestring and define the Linestring segment using shapely

description: Calculate the intersection point of a line to a Linestring and define the Linestring segment using shapely


code:
def onClose(self, event):
   frame = self.GetParent()
   frame.Close()

rawDescription: Exit frame and panel from panel method

description: Exit frame and panel from panel method


code:
import math
math.acos(0)
_ * 2 - math.pi

rawDescription: Inverse Cosine in Python

description: Inverse Cosine in Python


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

labels = ["Something really long here", "normal"]
values = [10, 5]
plt.barh(range(len(labels)), values)
plt.yticks(np.arange(len(labels)) + .5, labels, rotation='horizontal')
plt.tight_layout()
plt.show()

rawDescription: Completely display labels on barchart with matplotlib


code: db.createCollection( "myCollection", { capped: true, max: 1000, size: 5242880 } )

rawDescription: Stack db with mongoDB

description: Stack db with mongoDB


code:
class InternForm(ModelForm):

    # ...

    class Meta:
        model = Intern

class ApplyInternForm(InternForm):

    class Meta:
        model = Intern
        exclude = ('is_active',)

rawDescription: In Django, can I exclude a field in ModelForm sub-subclass?


code:
powers = [10 ** x for x in (3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 100)]
human_powers = (N_('thousand'), N_('million'), N_('billion'), N_('trillion'), N_('quadrillion'),
                N_('quintillion'), N_('sextillion'), N_('septillion'),
                N_('octillion'), N_('nonillion'), N_('decillion'), N_('googol'))

rawDescription: Humanize numbers with python

description: Humanize numbers with python


rawDescription: How do I give additional arguments when using Python to open on application on Mac?

description: Give additional arguments when using Python to open on application on Mac


rawDescription: GAE Python - get_by_key_name no result - maybe Parent issue?


code: dx, dy = -dy, dx

rawDescription: Is there a way to write these ifs nicer?

description: Is there a way to write these ifs nicer


code: b[np.in1d(a, my_list)]

rawDescription: Slice numpy array based on values of other array using more than 2 arguments


code:
constraints = []
if 'column1' in data:
    try:
        value = int(data['column1'])
    except (TypeError, ValueError):
        pass
    else:
        constraints.append(MyModel.column1 == value)

if 'column2' in data:
    try:
        value = datetime.utcfromtimestamp(int(data['column2']))
    except (TypeError, ValueError):
        pass
    else:
        constraints.append(MyModel.column2 >= value)

if constraints:
    query = query.filter(or_(*constraints))

rawDescription: OR multiple filters for SQL Alchemy query


code:
from StringIO import StringIO
from PIL import Image
im = Image.open(StringIO(image_string))
im.size, im.bits

rawDescription: How do I get the color depth and/or the resolution from a byte string in Python?

description: Get the color depth and/or the resolution from a byte string in Python


rawDescription: Pandas Dataframe String Column to Concatenated Int


code:
import pygame
import time
import random

pygame.init()

pygame.mixer.music.load('song.mp3')
pygame.mixer.music.play(0)
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)

display_width = 800
display_height  = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('KALM Creation')

#Score
score=0

#img=pygame.image.load("1.png")
#intro=pygame.image.load("intro.png")
foodimg=pygame.image.load("food.png")

#Our Icon For The Game
icon=pygame.image.load('icon1.jpg')
pygame.display.set_icon(icon)

clock = pygame.time.Clock()

AppleThickness=30
block_size = 10
FPS = 30

smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)

#The score function

def scoredisplay(scoredef=0):
    text=smallfont.render("Score :%s" %(scoredef) ,True ,black)
    gameDisplay.blit(text,[0,0])
#The random function of apple
def randAppleGen():
    randAppleX = round(random.randrange(0, display_width-AppleThickness))
    randAppleY = round(random.randrange(0, display_height-AppleThickness))

    return randAppleX,randAppleY
randAppleX,randAppleY=randAppleGen()

#Starting Of the game
def game_intro():

    intro = True
    while intro:
      for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key ==pygame.K_c:
                intro = False
            if event.key ==pygame.K_q:
                pygame.quit()
                quit()
        gameDisplay.fill(white)
        message_to_screen("Welcome To  Eat it Game",
                          green,
                          -200,
                          size="medium")
        message_to_screen("This Game is created by KALM Creations",
                          black,
                          -30,
                          size="small")
        message_to_screen("Eat the food to gain a score!",
                          black,
                          10,
                          size="small")
        message_to_screen("Avoid the rock , if you hit them you lose!",
                          black,
                          50,
                          size="small")
        message_to_screen("Press 'C' to play the game or 'Q' to quit.",
                          black,
                          150,
                          size="small")
        pygame.display.update()
        clock.tick(15)
#Snake aka the object which is moving (in green colour)
def snake(lead_x,lead_y,block_size):
    pygame.draw.rect(gameDisplay, green, [lead_x,lead_y,block_size,block_size])

#Text Size
def text_objects(text,color, size):
    if size=="small":
        textSurface=smallfont.render(text, True ,color)
    elif size=="medium":
        textSurface=medfont.render(text, True ,color)
    elif size=="large":
        textSurface=largefont.render(text, True ,color)

    return textSurface,textSurface.get_rect()

#Message to screen
def message_to_screen(msg,color,y_displace=0,size="small"):
    textSurf,textRect=text_objects(msg,color,size)
    textRect.center = (display_width / 2),(display_height / 2)+y_displace
    gameDisplay.blit(textSurf,textRect)

#   The game run up
def gameLoop():
    score=0
    gameExit = False
    gameOver = False

    lead_x = display_width/2
    lead_y = display_height/2

    lead_x_change = 0
    lead_y_change = 0

    randAppleX,randAppleY=randAppleGen()

    while not gameExit:

        while gameOver == True:

            gameDisplay.fill(white)
            message_to_screen("Game over",
                              red,
                              y_displace=-50,
                              size="large")
            message_to_screen("Press C to play again or Q to quit",
                              black,
                              y_displace=50,
                              size="medium")

            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    lead_x_change = -block_size
                    lead_y_change = 0
                elif event.key == pygame.K_RIGHT:
                    lead_x_change = block_size
                    lead_y_change = 0
                elif event.key == pygame.K_UP:
                    lead_y_change = -block_size
                    lead_x_change = 0
                elif event.key == pygame.K_DOWN:
                    lead_y_change = block_size
                    lead_x_change = 0

        if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
            gameOver = True

        gameDisplay.blit(foodimg,(randAppleX,randAppleY))

        lead_x += lead_x_change
        lead_y += lead_y_change

        gameDisplay.fill(white)
        gameDisplay.blit(foodimg,(randAppleX,randAppleY))

        snake(lead_x,lead_y,block_size)
        pygame.display.update()

        if lead_x > randAppleX and lead_x < randAppleY + AppleThickness or lead_x + block_size>randAppleX and lead_x + block_size< randAppleX + AppleThickness:
             if lead_y > randAppleY and lead_y< randAppleY + AppleThickness or lead_y + block_size>randAppleY and lead_y + block_size< randAppleY + AppleThickness:
                 randAppleX,randAppleY=randAppleGen()
                 score+=1
             elif lead_y +block_size >randAppleY and lead_y +block_size < randAppleY:
                 randAppleX,randAppleY=randAppleGen()
                 score+=1

        scoredisplay(score)
        pygame.display.update()

        clock.tick(FPS)

    pygame.quit()
    quit()

game_intro()
gameLoop()
#Episode 36

rawDescription: How to fix the auto update of score in pygame?

description: Fix the auto update of score in pygame


code: getattr(model, fieldtoget)

rawDescription: Django model field by variable

description: Django model field by variable


rawDescription: How to calculate group by cumulative sum for multiple columns in python

description: Calculate group by cumulative sum for multiple columns in python


code:
d = {}

for _ in range(TotalLists):   # The same loop you have now
    ListName = input("whatever...")
    d[ListName] = []

rawDescription: Convert User Input into a List name

description: Convert User Input into a List name


code:
class Person(Document):
    name = StringField()
    name_index = Index().ascending('name').unique()

rawDescription: Validating for uniqueness in MongoAlchemy?


code:
from itertools import chain
a = dict(a='b', c='d')
','.join(chain(*a.items()))

rawDescription: python join equivalent

description: Python join equivalent


code:
class SaneTextIOWrapper(io.TextIOWrapper):
    def __init__(self, *args, **kwargs):
        self._should_close_buffer = True
        super(SaneTextIOWrapper, self).__init__(*args, **kwargs)

    def __del__(self):
        # Accept the inevitability of the buffer being closed by the destructor
        # because of this line in Python 2.7:
        # https://github.com/python/cpython/blob/2.7/Modules/_io/iobase.c#L221
        self._should_close_buffer = False
        self.close()  # Actually close for Python 3 because it is an override.
                      # We can't call super because Python 2 doesn't actually
                      # have a `__del__` method for IOBase (hence this
                      # workaround). Close is idempotent so it won't matter
                      # that Python 2 will end up calling this twice

    def close(self):
        # We can't stop Python 2.7 from calling close in the deconstructor
        # so instead we can prevent the buffer from being closed with a flag.

        # Based on:
        # https://github.com/python/cpython/blob/2.7/Lib/_pyio.py#L1586
        # https://github.com/python/cpython/blob/3.4/Lib/_pyio.py#L1615
        if self.buffer is not None and not self.closed:
            try:
                self.flush()
            finally:
                if self._should_close_buffer:
                    self.buffer.close()

rawDescription: Prevent TextIOWrapper from closing on GC in a Py2/Py3 compatible way


code: writer.writerows([line[1:] for line in results])

rawDescription: Python export only parts of list to CSV

description: Python export only parts of list to CSV


code:
key = int(hashlib.md5(word).hexdigest(), 16)
assert word == self.id_to_word.setdefault(key, word)

rawDescription: Performance comparison of using `in` vs try except in python


code:
import itertools
def derangement(x):
    p = itertools.permutations(x)
    return (i for i in p if not any(i[k] == x[k] for k in range(len(x))))

rawDescription: Python - generate derangements of string.ascii_lowercase


code:
import heapq

elements = heapq.nsmallest(4, my_list, key=f)
foo = choice(elements)

rawDescription: Fast way to get N Min or Max elements from a list in Python


code:
import pytz
from pytz import timezone
utc=pytz.utc
newdate=datetime.strptime(createDate, "%Y-%m-%dT%H:%M:%S-05:00")
servertz = timezone("UTC")
myJson={}
myJson['date'] = servertz.localize(newdate).isoformat
json.dumps(myJson)

rawDescription: Setting datetime object in a json using python


code:
# when instantiating your authentication
api_auth = UserAuth(auth, protected_methods=['GET', 'POST', 'PUT', 'DELETE'])
read_only_auth = UserAuth(auth) # default protected methods are POST/PUT/DELETE

rawDescription: flask peewee REST api authentication to limit GET

description: Flask peewee REST api authentication to limit GET


code:
for i in range(s):
    for j in range(s):
        if j < i:
            t[i][j] = 0

rawDescription: How to make output into list within list format?

description: Make output into list within list format


code:
# Assuming same lines from your example
cols_to_norm = ['Age','Height']
survey_data[cols_to_norm] = survey_data[cols_to_norm].apply(lambda x: (x - x.mean()) / (x.max() - x.min()))

rawDescription: How can I normalize the data in a range of columns in my pandas dataframe

description: Normalize the data in a range of columns in my pandas dataframe


code:
m = hashlib.md5()
m.update('test')
m.hexdigest()

rawDescription: SWF file loads a new url, how to grab it using Python?


code:
#!/usr/bin/python

if __name__ != '__lib__':
    def outputSchema(dont_care):
        def wrapper(func):
            def inner(*args, **kwargs):
                return func(*args, **kwargs)
            return inner
        return wrapper

# Your UDFs go here

rawDescription: In a python script how can I ignore Apache Pig's Python Decorators for standalone unit testing


code:
import re

pattern = 'Delivered to Mr.Smith at Seattle'

re.match(r'Delivered to (.*) at (.*)', pattern).groups()
('Mr.Smith', 'Seattle')

re.findall(r'Delivered to (.*) at (.*)', pattern)
[('Mr.Smith', 'Seattle')]

rawDescription: Find string match pattern

description: Find string match pattern


code:
timeit.timeit('"xyz" in "abcxyz"', number=10000000)
timeit.timeit('re.search(p,"abcxyz")', number=10000000, setup='import re; p=re.compile("xyz")')
timeit.timeit('p.search("abcxyz")', number=10000000, setup='import re; p=re.compile("xyz")')

rawDescription: Python efficient pattern finding: regex v/s pattern in text?


rawDescription: convert string to 2d numpy array

description: Convert string to 2d numpy array


code:
crop = input("Which crop? ")
quantity = input("How many? ")
def crop(crop, quantity):
        file =  open('cropdatabase.txt',"r+")
        lines = file.readlines()
        linenumber = 0
        for i in range(len(lines)):
            if crop == lines[i].split()[0]:
                linenumber = i
                break
        lines[linenumber] = lines[linenumber][:-1]
        lines[linenumber]+= " " + str(quantity)+'\n'
        text = "".join(lines)
        file.close()
        file2  = open('cropdatabase.txt',"w")
        file2.write(text)
        file2.close()

crop(crop, quantity)

rawDescription: How do I add this variable onto the same line as a specific variable in a .txt file?

description: Add this variable onto the same line as a specific variable in a .txt file


rawDescription: SQLAlchemy: Override relationship-defined "order_by" in a query


code:
import unittest
import collections
import itertools

class TestCase(unittest.TestCase):
    def assertRecursiveEq(self, first, second, *args, **kwargs):
        """
        http://stackoverflow.com/a/3124155/190597 (KennyTM)
        """
        if (isinstance(first, collections.Iterable)
            and isinstance(second, collections.Iterable)):
            for first_, second_ in itertools.izip_longest(
                    first, second, fillvalue = object()):
                self.assertRecursiveEq(first_, second_, *args, **kwargs)
        else:
            # If first = np.nan and second = np.nan, I want them to
            # compare equal. np.isnan raises TypeErrors on some inputs,
            # so I use `first != first` as a proxy. I avoid dependency on numpy
            # as a bonus.
            if not (first != first and second != second):
                self.assertAlmostEqual(first, second, *args, **kwargs)

def perm3():
    return itertools.permutations([1,2,3])

class Test(TestCase):
    def test_perm3(self):
        self.assertRecursiveEq(perm3(),
            [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)])

if __name__ == '__main__':
    import sys
    sys.argv.insert(1, '--verbose')
    unittest.main(argv = sys.argv)

rawDescription: Testing functions returning iterable in python


code:
reader = csv.DictReader(open('/Users/myuser/Downloads/SalesData.csv', 'rU'), dialect='excel')

sortedreader = sorted(reader, key=lambda d: (d['Country'], d['State']))

groups = groupby(sortedreader, key=lambda d: (d['Country'], d['State']))

result = [(k, max(g, key=lambda d: d['Price'])) for k, g in groups]

rawDescription: Python - Grouping by multiple columns and getting max or sum


code:
url(r'blog/(?P<slug>[-\w]+)/$', 'blog.views.blog', name="blog"),
url(r'blog/', 'blog.views.blog_index', name="blog_index"),

rawDescription: Django views / URLS page now loading

description: Django views / URLS page now loading


code:
def AbbreviateAuthors(names):
    return ''.join(i.split()[-1][:3] for i in names.split(' and '))
AbbreviateAuthors('John Smith and Paul Anthony Doe and Chris Burns')
AbbreviateAuthors('John Smith and Paul Anthony Doe')
AbbreviateAuthors('John Smith')
AbbreviateAuthors('Smith')
AbbreviateAuthors('Sm')

rawDescription: Regex to obtain last digits in years and first three letters of surnames


code:
f = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
f.write(request.files.data.file.read())
f.close()

rawDescription: Upload and Save an excel file with BottlePy


code: new_data = data.filter(lambda x: x[1][0] == "ABC")

rawDescription: How access individual element in a tuple on a RDD in pyspark?


code:
import numpy as np
from scipy.spatial import cKDTree
A = np.loadtxt('A.txt')
B = np.loadtxt('B.txt')
tree = cKDTree( B[:,[1,2,3]] )
d, inds = tree.query( A[:,[1,2,3]], k=1, p=2)
B_new = B[inds]
xyz_near = np.hstack(( B_new[:,0:4], A[:,0:4] ))

for j, a in enumerate(A):
    # compute 2-norms from each point in B to a
    dd = np.sqrt(((a[1:] - B[:,1:])**2).sum(axis=1))
    # find closest point
    jx = np.argmin(dd)
    # check solution
    assert inds[j] == jx
    assert np.allclose(d[j], dd.min())
    # check it is unique
    assert (dd[jx+1:] > d[j]).all()
    assert (dd[:jx] > d[j]).all()

print("All OK")

rawDescription: cKDTree vs dsearchn

description: CKDTree vs dsearchn


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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Scatter graph
N = 100
X = np.random.uniform(-1, 1, N)
Y = np.random.uniform(-1, 1, N)
Z = np.random.uniform(-2, 2, N)
ax.scatter(X, Y, Z)

# Cylinder
x=np.linspace(-1, 1, 100)
z=np.linspace(-2, 2, 100)
Xc, Zc=np.meshgrid(x, z)
Yc = np.sqrt(1-Xc**2)

# Draw parameters
rstride = 20
cstride = 10
ax.plot_surface(Xc, Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)
ax.plot_surface(Xc, -Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)

ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()

rawDescription: Add cylinder to plot

description: Add cylinder to plot


code:
import matplotlib.pyplot as plt
from numpy import genfromtxt
data=genfromtxt("test",names=['x','y'])
x=data['x']
y=data['y']
columnsize = int(len(x)/6)
ax=plt.subplot(111)
for i in range(columnsize):
    ax.plot(x[i*6:(i+1)*6],y[i*6:(i+1)*6])
plt.show()

rawDescription: Plotting data from CSV files using matplotlib


code:
#!/usr/bin/python

from skimage import morphology
import cv2
import math
import numpy as np

im = cv2.imread("objects.png")
dst = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

dst = 1 - dst / 255
dst = morphology.skeletonize(dst).astype(np.uint8)

objs = 255 * dst

#cv2.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]])
rho = 1
theta = math.pi / 180
threshold = 1
minLineLength = 3
maxLineGap = 5

lines = np.ndarray([1, 1, 4, 4])
lines = cv2.HoughLinesP(dst, rho, theta, threshold, lines, minLineLength, maxLineGap)

lineColor = (0, 255, 0)  # red

for line in lines[0]:
        #print line
        cv2.line(im, (line[0], line[1]), (line[2], line[3]), lineColor, 1, 8)

#
#   Now you need to go through lines and find those that intersect
#   You will notice that some lines have small gaps where they should
#   join to a perpendicular line. Before find intersections you would
#   need to make each line longer (just by adjusting the numbers in lines)
#   to get around this problem.
#

cv2.imshow('Objects', objs)
cv2.imshow('Lines', im)
cv2.imwrite('lines.png', im)

cv2.waitKey()
cv2.destroyAllWindows()

rawDescription: OpenCV, divide object into parts

description: OpenCV, divide object into parts


rawDescription: how to remove plot elements in python

description: Remove plot elements in python


code:
def __iter__(self):
    for start in self.start_nodes:
        for end in self.end_nodes:
            for path in self.find_path(self._graph, start, end):
                yield path

rawDescription: DFS on a graph using a python generator

description: DFS on a graph using a python generator


rawDescription: Transfer layout from networkx to cytoscape


code: addpath(PATH_TO_BCT); savepath;

rawDescription: change matlab path from python

description: Change matlab path from python


code:
import numpy as np
import numpy.linalg as linalg

A = np.random.random((3,3))
eigenValues,eigenVectors = linalg.eig(A)

idx = eigenValues.argsort()[::-1]
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]

rawDescription: sort eigenvalues and associated eigenvectors after using numpy.linalg.eig in python

description: Sort eigenvalues and associated eigenvectors after using numpy.linalg.eig in python


code:
import tempfile
import subprocess
import os

def edit(data):
    fdes = -1
    path = None
    fp = None
    try:
        fdes, path = tempfile.mkstemp(suffix='.txt', text=True)
        fp = os.fdopen(fdes, 'w+')
        fdes = -1
        fp.write(data)
        fp.close()
        fp = None

        editor = (os.environ.get('VISUAL') or
                  os.environ.get('EDITOR') or
                  'nano')
        subprocess.check_call([editor, path])

        fp = open(path, 'r')
        return fp.read()
    finally:
        if fp is not None:
            fp.close()
        elif fdes >= 0:
            os.close(fdes)
        if path is not None:
            try:
                os.unlink(path)
            except OSError:
                pass

text = edit('Hello, World!')
print(text)

rawDescription: Python raw_input() replacement that uses a configurable text editor


code:
def mousePressEvent(self, event):
    self.offset = event.pos()

def mouseMoveEvent(self, event):
    x=event.globalX()
    y=event.globalY()
    x_w = self.offset.x()
    y_w = self.offset.y()
    self.move(x-x_w, y-y_w)

rawDescription: Draggable window with pyqt4

description: Draggable window with pyqt4


code:
import xml.etree.ElementTree as ET
tree = ET.parse(XML_FILE)
root = tree.getroot()

for p in root.iter('p'):
   sentences = p.text.split('.')
   p.text = ".".join([("<sup>%i<sup>" % count) + sentence for count, sentence in enumerate(sentences)])

tree.write(XML_FILE)

rawDescription: Numbering the sentences inside a <P> in a .xml file?


code:
def get_data(self, table_name):
    try:
        self._cursor.execute("select Name from {}".format(table_name))
        row = self._cursor.fetchall()
        return row
    except:
        raise DbException("An error occured...")

rawDescription: Selecting Table Name Runtime

description: Selecting Table Name Runtime


code:
from itertools import groupby

values = Value.objects.filter(type_id__in=t).values_list('type_id', 'item_id')
values = sorted(values, key=lambda x: x[1])

items = []
for key, group in groupby(values, lambda x: x[1]):
    types = [x[0] for x in group]
    if set(t).issubset(set(types)):
        items.append(key)

rawDescription: Django - Get the list of items with a filter


code:
import random
from factory.fuzzy import BaseFuzzyAttribute

class FuzzyPoint(BaseFuzzyAttribute):
    def fuzz(self):
        return Point(random.uniform(-180.0, 180.0),
                     random.uniform(-90.0, 90.0))

class PlaceFactory(FakerFactory):
    name = factory.LazyAttribute(lambda x: faker.name())
    location = FuzzyPoint()
    class Meta:
        model = models.Place

rawDescription: Using Factory Boy with GeoDjango PointFields


code:
def doit(nam, filters):
    alldims = []
    for dimname in getDimNames(nam):
      filt = filters.get(dimname, ())
      howmany = len(filt)
      if howmany == 0:
        sliciflt = slice()
      elif howmany == 1:
        sliciflt = filt[0]
      elif howmany in (2, 3):
        sliciflt = slice(*filt)
      else:
        raise RuntimeError("%d items in slice for dim %r (%r)!"
                           % (howmany, dimname, nam))
      alldims.append(sliciflt)

return readFrom.variables[nam][tuple(alldims)]

rawDescription: Dynamic list slicing

description: Dynamic list slicing


rawDescription: python: expanding a numpy array inside function

description: Python: expanding a numpy array inside function


code:
class OneFruit(object):
    def add_color(self, color):
        self.color = color
    def add_taste(self, taste):
        self.taste = taste

class Fruit(object):
    def add_item(self, name):
        setattr(self, name, OneFruit())

rawDescription: Create a Subclass from a String

description: Create a Subclass from a String


rawDescription: Matrices in Python

description: Matrices in Python


code:
import sys
import os

import java.lang.ClassLoader
import java.io.InputStreamReader
import java.io.BufferedReader

loader = java.lang.ClassLoader.getSystemClassLoader()
stream = loader.getResourceAsStream("com/example/action/myAction.py")
reader = java.io.BufferedReader(java.io.InputStreamReader(stream))

script = ""
line = reader.readLine()
while (line != None) :
    script += line + "\n"
    line = reader.readLine()

exec(script)

rawDescription: How do you invoke a python script inside a jar file using python?

description: Invoke a python script inside a jar file using python


code:
from itertools import chain

list(chain.from_iterable(list_of_lists))

rawDescription: how to extract nested lists?

description: Extract nested lists


code:
class Clazz1:
    def __init__(self, key, value):
        self.key = key
        self.value = value

class Clazz:
    EMPTY = Clazz1(None, None)

    def __init__(self):
        self.item = Clazz1("a", "b")

if __name__ == '__main__':
   h = Clazz()

rawDescription: How assign to a class attribute an instance from another class residing on the same module


code:
s="A:01 What is the date of the election ?"
" ".join(s.split()[1:-1])
s="BK:02 How long is the river Nile ?"
" ".join(s.split()[1:-1])
s="Date:30/4/2013"
s.split(":")[1:][0]
s="Day:Tuesday"
s.split(":")[1:][0]

rawDescription: Extracting sub-string after the first space in Python


code:
import scipy as sc
myone = sc.ones(100)
ind = sc.random.permutation(100)[:10]
myone[ind] = 0

rawDescription: scipy -- how to put randomly one array into another?

description: Scipy -- how to put randomly one array into another


code:
import re
groups = re.findall(r'(\w+)="(.*?)"', s)
line = dict(groups)
from pprint import pprint
pprint(line)

rawDescription: Python parse string with regex for constitute a dictionary


code: min(filter(lambda t: not math.isnan(t[1]), l), key=itemgetter(1))

rawDescription: List of Tuples (string, float)with NaN How to get the min value?