code:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import wx
import wx.lib.sized_controls as sc

class AFrame(sc.SizedFrame):
    def __init__(self, *args, **kwds):
        super(AFrame, self).__init__(*args, **kwds)

        pane = self.GetContentsPane()

        self.tc1 = wx.TextCtrl(pane, style=wx.TE_PROCESS_ENTER)
        self.tc2 = wx.TextCtrl(pane)

        self.tc1.Bind(wx.EVT_TEXT_ENTER, self.onTc1Enter)

    def onTc1Enter(self, Evt):
        self.tc2.ChangeValue(self.tc1.GetValue())

if __name__ == "__main__":
    import wx.lib.mixins.inspection as WIT

    app = WIT.InspectableApp()
    f = AFrame(None)
    f.Show()
    app.MainLoop()

rawDescription: wxPython - Process input from one TextCtrl and send output to another TextCtrl?

description: WxPython - Process input from one TextCtrl and send output to another TextCtrl


code:
import select, sys
r, w, x = select.select([sys.stdin], [], [], 3)

rawDescription: make python raw_input() or input() not waiting

description: Make python raw_input() or input() not waiting


code:
links = [link.get_attribute('href') for link in browser.find_elements_by_xpath('//span[@class="jcn"]/a')]
for link in links:
    browser.get(link)

rawDescription: Make selenium click Consecutive Elements with same class for n times


code:
my_dict = {1:5, 2:4, 3:5, 26:3, 5:2, 6:4, 8:3}
sorted(my_dict, key=lambda x: (my_dict[x], -x))
sorted(sorted(my_dict)[::-1], key=my_dict.get)
sorted(sorted(my_dict, reverse=True), key=my_dict.get)

rawDescription: sorting a dictionary python values descending, but keys ascending

description: Sorting a dictionary python values descending, but keys ascending


code:
import matplotlib.pyplot as plt

for i, group in df.groupby('ModelID'):
    plt.figure()
    group.plot(x='saleDate', y='MeanToDate', title=str(i))

rawDescription: Plotting a Pandas DataSeries.GroupBy

description: Plotting a Pandas DataSeries.GroupBy


code:
import scipy, pylab
fig = pylab.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(scipy.randn(8))
ax.set_yticks(scipy.arange(-1.5,1.5,0.25))
fig.show()

rawDescription: How to change the amount of increments in pyplot axis

description: Change the amount of increments in pyplot axis


rawDescription: Python - Non-matching regex

description: Python - Non-matching regex


code:
from collections import deque

class PriorityQueue:
    def __init__(self, priorities=10):
        self.subqueues = [deque() for _ in range(levels)]

    def enqueue(self, priorty, value):
        self.subqueues[priority].append(value)

    def dequeue(self):
        for queue in self.subqueues:
            try:
                return queue.popleft()
            except IndexError:
                continue

rawDescription: python Priority Queue implementation

description: Python Priority Queue implementation


code:
from urlparse import urlparse
def extract_hostname(url):
    components = urlparse(url)
    if not components.scheme:
        components = urlparse('http://' + url)
    return components.netloc
extract_hostname('http://stackoverflow.com/questions/22143342')
extract_hostname('www.apple.com/itune')
extract_hostname('file:///usr/bin/python')

rawDescription: How else can I strip a domain name from webpage with no additional library - python?


code:
from openerp.tools import html2plaintext
# ...
if 'description' in fields and not data.get('description'):
    data['description'] = html2plaintext(msg.get('body')) if msg.get('body') else ''
# ...

rawDescription: In odoo how can I match content of the email body to the description field in leads


code:
s = 'Person One (Something inside here) Second Thing (another thing) OK (something else)'
import re
re.sub('(.*?) \((.*?)\)( ?)', r'\2 (\1)\3', s)

rawDescription: Python string -- swap positions in and out of parentheses


code: numpy.ndarray.det = numpy.linalg.det

rawDescription: Adding `numpy.linalg.det` as method to `numpy.matrix`


code:
import pytz

tznames = pytz.country_timezones['us']

rawDescription: How to get the list of US time zones only?

description: Get the list of US time zones only


code:
class PrimeTester:
    def __init__(self):
        x = int(raw_input('Input a number to test if prime:'))
        result = self.primeTest(x)
        print("The number " + str(x) + " is " + result)

    def primeTest(self, number):
        if number == 2:
            result = "prime"

        if number % 2 == 0:
            result = "not prime"

        highesttestnum = number ** 0.5 + 1
        count = 3
        while count <= highesttestnum:
            if number % count == 0:
                result = "not prime"
            count += 2

            result= "prime"

        return result

if __name__ == '__main__':
    obj = PrimeTester()

rawDescription: Python program not asking for input

description: Python program not asking for input


rawDescription: Convert vtkPoints to numpy array?

description: Convert vtkPoints to numpy array


code:
def paste_keys(self, xpath, text):
    os.system("echo %s| clip" % text.strip())
    el = self.driver.find_element_by_xpath(xpath)
    el.send_keys(Keys.CONTROL, 'v')

rawDescription: Paste command using Selenium

description: Paste command using Selenium


code:
class Event(Base):
    __tablename__ = "events"
    id = Column(Integer, primary_key = True)
    ...

class Notification(Base):
    __tablename__ = "notifications"
    id = Column(Integer, primary_key = True)
    event_id = Column(Integer, ForeignKey("events.id"))
    event = relationship("Event")
    ...
    def __init__(self, event):
        self.event = event

notification = Notification(Event())
session.add(notification)
session.commit()

rawDescription: SQLAlchemy primary key assignement

description: SQLAlchemy primary key assignement


code:
import logging
from logging.handlers import TimedRotatingFileHandler

my_logger = logging.getLogger('my_logger')
my_handler = TimedRotatingFileHandler('logfile.log')
my_logger.addHandler(my_handler)

def get_filename(some_logger):
    return [some_handler.baseFilename
            for some_handler in some_logger.handlers
            if isinstance(some_handler, TimedRotatingFileHandler)]

print(get_filename(my_logger))  # ['/home/finwood/temp/so/logfile.log']

rawDescription: retrieve output logfile value from logger

description: Retrieve output logfile value from logger


code:
results = {}
start = 0
startColumn = ""
while True:
    # Fetch blocks of size 500

   buffer = get(key, column_start=startColumn, column_finish="", column_count=100)
   # iterate returned values.
   # set startColumn == previous column_finish.

rawDescription: Cassandra buffered read of millions of columns


rawDescription: Setting Custom axis values pyplot

description: Setting Custom axis values pyplot


code:
from Crypto.PublicKey import RSA
from Crypto.Util import randpool
from Crypto.Cipher import PKCS1_OAEP as PKCS

s = "\x00\x00\x00\x00\x03\x00\x00\x00id\x00\x00"
key = RSA.generate(1024, randpool.RandomPool().get_bytes)

cipher = PKCS.new(key)
encr = cipher.encrypt(s)
decr = cipher.decrypt(encr)

rawDescription: RSA decryption strips leading null-bytes


code:
from elasticsearch import Elasticsearch
es = Elasticsearch()
es.info()

rawDescription: Elasticsearch python client: Getting the ES version through API call


code:
import xml.etree.ElementTree as ET
tree = ET.parse('interface_range_test.xml')
root = tree.getroot()
# note the explicit namespaces
commands = root.findall('{http://clish.sourceforge.net/XMLSchema}'
                        'VIEW/{http://clish.sourceforge.net/XMLSchema}COMMAND')
for command in commands:
  if 'shutdown' in command.get('name'):
    ET.dump(command) # modify to taste

rawDescription: write part of xml file to new file, elementree

description: Write part of xml file to new file, elementree


code:
def method2(a,b):
    tmpdict = dict(zip(a,range(len(a))))
    idx = numpy.array([tmpdict[bi] for bi in b])

rawDescription: Finding a list of indices from master array using secondary array with non-unique entries


code:
def generalized_taylor_expansion_exponents( order, n_variables ):
    """
    Find the exponents of a multivariate polynomial expression of order
    `order` and `n_variable` number of variables.
    """
    pattern = [0] * n_variables
    for current_sum in range(1, order+1):
        pattern[0] = current_sum
        yield tuple(pattern)
        while pattern[-1] < current_sum:
            for i in range(2, n_variables + 1):
                if 0 < pattern[n_variables - i]:
                    pattern[n_variables - i] -= 1
                    if 2 < i:
                        pattern[n_variables - i + 1] = 1 + pattern[-1]
                        pattern[-1] = 0
                    else:
                        pattern[-1] += 1
                    break
            yield tuple(pattern)
        pattern[-1] = 0

rawDescription: Optimize generator for multivariate polynomial exponents


code:
def my_round(x):
 return round(x*4)/4

assert my_round(10.38) == 10.50
assert my_round(11.12) == 11.00
assert my_round(5.24) == 5.25
assert my_round(9.76) == 9.75

rawDescription: Python - Rounding by quarter-intervals

description: Python - Rounding by quarter-intervals


code:
from django.db import transaction
a=Friends.objects.filter(user_me=self.user_id, user_he = friend_id, permission_he =True, permission_me = True).update(permission_me=False)
transaction.enter_transaction_management()
transaction.commit()

rawDescription: Bug in Django querySet?

description: Bug in Django querySet


code:
def find_root(docu):
    for token in docu:
        if token.head is token:
            return token

rawDescription: How to get the dependency tree with SpaCy?

description: Get the dependency tree with SpaCy


code:
from operator import itemgetter
a = range(100)
itemgetter(5,13,25)(a)

rawDescription: Python List Slicing with Arbitrary Indices


code: ftp = ftplib.FTP(timeout=100)

rawDescription: Is it in Python possible to set the last parameter of several in a function call?


code:
def snap_to_pixels(ctx, x, y):
    x, y = ctx.user_to_device(x, y)
    # No idea how to round an integer in python,
    # this would be round() in C
    # (Oh and perhaps you don't want this rounding, but
    # instead want to round the top-left corner of your
    # rectangle towards negative infinity and the bottom-right
    # corner towards positive infinity. That way the rectangle
    # would never become smaller to the rounding. But hopefully
    # this example is enough to get the idea.
    x = int(x + 0.5)
    y = int(x + 0.5)
    return ctx.device_to_user(x, y)

# Calculate the top-left and bottom-right corners of our rectangle
x1, y1 = 0.2, 0.2
x2, y2 = x1 + 0.2, y1 + 0.2
x1, y1 = snap_to_pixels(ctx, x1, y1)
x2, y2 = snap_to_pixels(ctx, x2, y2)
# Clip for this rectangle
ctx.rectangle(x1, y1, x2 - x1, y2 - y1)
ctx.clip()

rawDescription: Cairo clip creates unwanted edges

description: Cairo clip creates unwanted edges


code:
import gtk.gdk
import pynotify

n = pynotify.Notification("This is my title", "This is my description")
n.set_hint('x', gtk.gdk.screen_width()/2.)
n.set_hint('y', gtk.gdk.screen_height()/2.)
n.show()

rawDescription: How to center a GNOME pop-up notification?

description: Center a GNOME pop-up notification


code: new_list = [''.join(i) for i in zip(*old_list)] # KMY, LPY, GDL, ...

rawDescription: Split list items into columns and append to new list


code: max_value = max(set(firstArray) - set(secondArray))

rawDescription: python expression for this: max_value = max(firstArray) that is not in secondArray

description: Python expression for this: max_value = max(firstArray) that is not in secondArray


code:
pat=[1,2,3,4,5,6,7]
count=[5,6,7,8,9,10,11]
newarray = list(map(list,zip(pat,count)))
newarray

rawDescription: Python Mapping Arrays

description: Python Mapping Arrays


rawDescription: Create array in Python with two different spacing values


code:
from matplotlib.collections import LineCollection
x=linspace(0,4*pi,10000)
y=cos(x)
lwidths=1+x[:-1]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, linewidths=lwidths,color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,4*pi)
a.set_ylim(-1.1,1.1)
fig.show()

rawDescription: Matplotlib plot with variable line width


code: np.any(np.absolute(my_array) < eps)

rawDescription: Check array for values equal or very close to zero


code:
class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        # your intended modification
        do_something()
        super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
        do_something_else()

rawDescription: Is Django has something like "database middleware"?


code: df.groupby('ItemID')['Feedback'].apply(lambda x: ', '.join(x))

rawDescription: Row Values to Column Array in Pandas DataFrame


code:
import datetime
my_date = datetime.datetime.strptime("2014-01-01T05:00:00.000Z", "%Y-%m-%dT%H:%M:%S.%fZ")
my_date.strftime('%d.%m.%Y')
date.strftime('%H:%M:%S %d.%m.%Y')

rawDescription: Convert a particular timestamp with Python 2.7.x


code:
import operator
from scipy import stats
l = [(1, 6), (2, 3), (2, 5), (2, 2), (1, 7), (3, 2), (2, 2)]
uniq = list(set(t for t in l))
s = sorted(uniq)
r = [s.index(i) for i in l]
rank = stats.rankdata(r, method='min')
rank

rawDescription: Python -- rank tuples by first item, resolve ties by second item


code:
urls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']

import gevent
from gevent import monkey

# patches stdlib (including socket and ssl modules) to cooperate with other greenlets
monkey.patch_all()

import urllib2

def print_head(url):
    print ('Starting %s' % url)
    data = urllib2.urlopen(url).read()
    print ('%s: %s bytes: %r' % (url, len(data), data[:50]))

jobs = [gevent.spawn(print_head, url) for url in urls]

rawDescription: Threading HTTP requests (with proxies)

description: Threading HTTP requests (with proxies)


code:
from tkinter import *

class Game:
    def __init__(self):
        self.__window = Tk()

        self.gifdir = "./"

        self.imgs = [PhotoImage(file=self.gifdir+"empty.gif"),
                     PhotoImage(file=self.gifdir+"empty.gif")]
        self.btns = []

        btn1 = Button(self.__window, image=self.imgs[0],
                           command = lambda: self.change_picture(0))
        btn1.grid(row=1, column=2, sticky=E)

        self.btns.append(btn1)

        btn2 = Button(self.__window, image=self.imgs[1],
                            command = lambda: self.change_picture(1))
        btn2.grid(row=1, column=1, sticky=E)

        self.btns.append(btn2)

        self.__window.mainloop()

    def change_picture(self, btn_no):
        self.imgs[btn_no] = PhotoImage(file=self.gifdir+"new.gif")
        self.btns[btn_no].configure(image = self.imgs[btn_no])

def main():
    Game()

main()

rawDescription: Python tkinter: Replacing an image button with an image label by pressing the button


code:
def rem(a):
    copy = a[:]
    for value in set(copy):
        copy.remove(value)
    return copy

rawDescription: Return a list with every duplicate value in Python?


code:
class TypedWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which uses "fieldformats" to format fields.
    """

    def __init__(self, f, fieldnames, fieldformats, **kwds):
        self.writer = csv.DictWriter(f, fieldnames, **kwds)
        self.formats = fieldformats

    def writerow(self, row):
        self.writer.writerow(dict((k, self.formats[k] % v)
                                  for k, v in row.iteritems()))

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

rawDescription: Specifying formatting for csv.writer in Python


code:
for tile in tiles:
  if camera.viewport.contains(tile.rect):
    tile.draw()

rawDescription: Blitting a Pygame Tile-map Efficiently

description: Blitting a Pygame Tile-map Efficiently


code:
def saveVarsAsDict(lpProblem):
    varsNameValue = {}
    for v in lpProblem._variables:
        if v.varValue != 0:
            varsNameValue[v.name] = v.varValue
    return varsNameValue

def restoreVarsValues(lpProblem, varsNameValue):
    for v in lpProblem._variables:
        if v.name in varsNameValue:
            v.varValue = varsNameValue[v.name]
        else:
            v.varValue = 0

rawDescription: How to deepcopy LpVariables

description: Deepcopy LpVariables


code:
with open(csvfilename, 'rb') as fileobj:
    reader = csv.reader(fileobj)

rawDescription: How to disable universal newlines in Python 2.7 when using open()

description: Disable universal newlines in Python 2.7 when using open()


code:
def funz1(dates,k):
    result=[dates[0]]
    for date in dates:
        if (date-result[-1]).days >= k:
            result.append(date)
    return result

rawDescription: keeping only elements in a list at a certain distance at least - changing iterator while looping - Python

description: Keeping only elements in a list at a certain distance at least - changing iterator while looping - Python


code:
f = open('mycsv.csv','rb')
fo = open('out.csv','wb')

# go through each line of the file
for line in f:
    bits = line.split(',')
    # change second column
    bits[1] = '"input"'
    # join it back together and write it out
    fo.write( ','.join(bits) )

f.close()
fo.close()

rawDescription: Replace data in csv file using python

description: Replace data in csv file using python


code:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager,\
    PermissionsMixin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.utils.http import urlquote

class CustomUserManager(BaseUserManager):

    def create_user(self, email, password=None, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = CustomUserManager.normalize_email(email)
        user = self.model(email=email,
                          is_staff=False, is_active=True, is_superuser=False,
                          last_login=now, date_joined=now, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, **extra_fields):
        u = self.create_user(email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save(using=self._db)
        return u

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.pk)

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.first_name

    # define here other needed methods
    # Look at django.contrib.auth.models.AbstractUser

rawDescription: Set email as username in Django 1.5

description: Set email as username in Django 1.5


code:
def save(self, *args, **kwargs):
    # New objects have no `pk`
    if self.pk is None and self.is_it_question:
        self.number = TypeFourChoice.objects.filter(is_it_question=True) \
                                            .count() + 1
    super(TypeFourChoice, self).save(*args, **kwargs)

rawDescription: How to change record of object in Django's model instantly?

description: Change record of object in Django's model instantly


code:
from pprint import pprint

def getCurrentVariableState():
    pprint(locals())
    pprint(globals())

rawDescription: Python, print names and values of all bound variables


code: 'yes' if eval(str(x) + op) else 'no'

rawDescription: Convert string ">0" to python > 0

description: Convert string ">0" to python > 0


code:
from glob import glob
import subprocess

for filename in glob("./*.xml"):
    subprocess.call(["myprogram.exe", filename])

rawDescription: Use one file on another - Python - Windows


code:
import datetime
date_str = '2014-06-15 19:51:37'
datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')

rawDescription: how do i store a return value in the format 2014-06-15 19:51:37 to a datetime variable in python?

description: Store a return value in the format 2014-06-15 19:51:37 to a datetime variable in python


code:
wb = pd.ExcelWriter(file)
tab = wb.sheets["My Tab"]
row, column = 9, 1
df1.to_excel(wb, tab, header=False, startrow=row, startcol=column, index=False)
row += 4
column = 1
df2.to_excel(wb, tab, header=False, startrow=row, startcol=column, index=False)

rawDescription: Is there a way to write two (or more) dataframes to one excel spreadsheet?


rawDescription: How can I avoid multiple loops to get the sorting I require in this sqlalchemy query?

description: Avoid multiple loops to get the sorting I require in this sqlalchemy query


code:
timeout = 10
target = time.time() + 370800

while True:
    diff = target - time.time()
    if diff < timeout:
        if diff > 0:  # highly unlikely that diff will go below 0 but just in case
            time.sleep(diff)
        break
    else:
        time.sleep(timeout)

winsound.Beep(1000,10000)

rawDescription: Python, writing a very basic alarm clock


code:
if re.search('^>[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]', line):
  try:
    seqFile.close()
  except NameError: # Assuming you haven't set seqFile else where before the first time through the loop
    pass
  seqFile = open('%s.fasta' % line, 'a+')
  # Do everything else you were going to do

rawDescription: Closing a file when looping creates that file


code:
root = Tk()

#notebook
nb = notebook(root )

# Admin Tab
admin = Frame( nb() , name='admin')
admin.grid( sticky=N+S+W+E)

# Every row and column have a wieght of one when resizing (linear transformation)
admin.grid_rowconfigure(0, weight=1)
admin.grid_rowconfigure(1, weight=1)
admin.grid_rowconfigure(2, weight=1)

admin.grid_columnconfigure(1, weight=1)
admin.grid_columnconfigure(2, weight=1)
admin.grid_columnconfigure(3, weight=1)

new_customer = Frame( admin , relief = RIDGE )

# Labels init
Label(admin, text="Name").grid(row=0, column = 0, sticky=N+S+W+E)
Label(admin, text="Type").grid(row=1, column = 0, sticky=N+S+W+E)
Label(admin, text="Date").grid(row=1, column = 2, sticky=N+S+W+E)

 # Elements Init
first_name  = Entry(admin)
middle_name = Entry(admin)
family_name     = Entry(admin)
date        = Entry(admin)

type_box = OptionMenu( admin , "one", "two", "three")

reset_button = Button( admin, text = "Reset Value" )
submit_button = Button( admin, text = "Submit"  )

# Place elements
first_name.     grid(row=0  , column  =1, sticky=N+S+W+E)
middle_name.    grid(row=0  , column  =2, sticky=N+S+W+E)
family_name.    grid(row=0  , column  =3, sticky=N+S+W+E)
date.       grid(row =1 , column  =3,  sticky=N+S+W+E)
type_box.   grid(row =1  , column  =1, sticky=N+S+W+E)
reset_button.   grid(row =2 , column  = 1 ,sticky=N+S+W+E)
submit_button.  grid(row =2 , column  = 3 , sticky=N+S+W+E)

# Add Tabls
nb.add_screen( admin , "Admin" )
nb.add_screen( Frame(nb()) , "Others" )

if __name__ == "__main__":
        root.mainloop()

rawDescription: Centering Items within a LabelFrame

description: Centering Items within a LabelFrame


code:
from pysnmp.entity.rfc3413.oneliner import cmdgen

def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBindTable, cbCtx):
    if errorIndication:
        print(errorIndication)
        return 1
    if errorStatus:
        print(errorStatus.prettyPrint())
        return 1
    for varBindRow in varBindTable:
        for oid, val in varBindRow:
            print('%s = %s' % (oid.prettyPrint(),
                               val and val.prettyPrint() or '?'))

cmdGen  = cmdgen.AsynCommandGenerator()

cmdGen.nextCmd(
    cmdgen.CommunityData('test-agent', 'public'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    ((1,3,6,1,2,1,1),),
    (cbFun, None)
)

cmdGen.snmpEngine.transportDispatcher.runDispatcher()

rawDescription: How to make a single GETNEXT query in PySNMP

description: Make a single GETNEXT query in PySNMP


code:
integers_list = [int(i) for i in raw_input().split()]
integers_list

rawDescription: how to insert integers in list/array separated by space in python

description: Insert integers in list/array separated by space in python


code:
from PyQt4.QtCore import QBuffer, QByteArray, QIODevice
from PyQt4.QtGui import QPixmap, QApplication

import cStringIO as StringIO

if __name__ == '__main__':
    # Create a QApplication so that QPixmaps will work.
    app = QApplication([])

    # Load a PNG into a QPixmap.
    pixmap = QPixmap('c:/in.png')

    # Save QPixmap to QByteArray via QBuffer.
    byte_array = QByteArray()
    buffer = QBuffer(byte_array)
    buffer.open(QIODevice.WriteOnly)
    pixmap.save(buffer, 'PNG')

    # Read QByteArray containing PNG into a StringIO.
    string_io = StringIO.StringIO(byte_array)
    string_io.seek(0)

    # Write the StringIO back to a file to test all is ok.
    with open('c:/out.png', 'wb') as out_file:
        out_file.write(string_io.read())

rawDescription: pyqt : QPixmap save to StringIO?

description: Pyqt : QPixmap save to StringIO


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

X_MAX = 50
Y_MAX = 50
Z_MAX = 50
fig = plt.figure(1)
ax = fig.add_subplot(111, projection='3d')
ax.set_title("My Title")
ax.set_xlim3d([0, X_MAX])
ax.set_ylim3d([0, Y_MAX])
ax.set_zlim3d([0, Z_MAX])
ax.set_autoscale_on(False)
plt.ion()
plt.show()

a = 0
sct = None
while a < 50:
  a += 1
  if sct is not None:
      sct.remove()
  sct = ax.scatter( a, a/2+1, 3, s=1 )
  fig.canvas.draw()
  plt.pause(0.001)

rawDescription: matplotlib - How do you keep the axes constant while adding new data?

description: Matplotlib - How do you keep the axes constant while adding new data


code:
import os
import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.img_fold = r"C:\Users\abhishek.garg\Desktop\New folder"

        self.widget_layout = QtGui.QVBoxLayout(self)
        self.scrollarea = QtGui.QScrollArea()
        self.scrollarea.setWidgetResizable(True)
        self.widget_layout.addWidget(self.scrollarea)
        self.widget = QtGui.QWidget()
        self.layout = QtGui.QVBoxLayout(self.widget)
        self.scrollarea.setWidget(self.widget)

        self.layout.setAlignment(QtCore.Qt.AlignHCenter)

        for img in os.listdir(self.img_fold):
            img_path = os.path.join(self.img_fold, img)

            pixmap = QtGui.QPixmap(img_path)
            lbl = QtGui.QLabel(self)
            lbl.setPixmap(pixmap)

            self.layout.addWidget(lbl)

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Image viewer')
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: How to load a contact sheet of images with PySide?

description: Load a contact sheet of images with PySide


code:
f = open("a.txt", "r")
sf = f.read()
f.close()

sf += "some more text"
f = open("a.txt", "w")
f.write(sf)
f.close()

rawDescription: How to convert datatype string to file?

description: Convert datatype string to file


code:
def nfak(n):
    if n < 0 :
        raise ValueError('Input has to be positive')
    elif n == 0:
        return 1
    else:
        return n * nfak(n - 1)

rawDescription: the return statement is not working

description: The return statement is not working


code:
import itertools
import multiprocessing

def worker(filename):
    pass   # do something here!

def main():
    with multiprocessing.Pool(48) as Pool: # pool of 48 processes

        walk = os.walk("some/path")
        fn_gen = itertools.chain.from_iterable((os.path.join(root, file)
                                                for file in files)
                                               for root, dirs, files in walk)

        results_of_work = pool.map(worker, fn_gen) # this does the parallel processing

rawDescription: parallel directory walk python

description: Parallel directory walk python


code:
import Tkinter

def EntryFocusedIn(params):
    params.widget.delete(0, Tkinter.END)

def EntryFocusedOut(params):
    # restore default value
    params.widget.delete(0, Tkinter.END)
    params.widget.insert(0, params.widget.default_value)

root = Tkinter.Tk()

entry1 = Tkinter.Entry()
entry1.default_value = 'hello'
entry1.pack()
entry1.insert(0, entry1.default_value)
entry1.bind("<FocusIn>", EntryFocusedIn)
entry1.bind("<FocusOut>", EntryFocusedOut)

entry2 = Tkinter.Entry()
entry2.default_value = 'again'
entry2.pack()
entry2.insert(0, entry2.default_value)
entry2.bind("<FocusIn>", EntryFocusedIn)
entry2.bind("<FocusOut>", EntryFocusedOut)

root.mainloop()

rawDescription: Reset Tkinter Widget to its default value


code:
import pyproj
sat = pyproj.Proj('+proj=geos +lon_0 +h=035785831.0 +x_0=0 +y_0=0')
x,y =  sat( 81.299, 0, radians = False, errcheck = True)
print (x * 2.0 / 3712.0 ) / 1000.0

rawDescription: How to get latitude and longitute for a pixel of a eumetsat image using python?

description: Get latitude and longitute for a pixel of a eumetsat image using python


code:
left = np.searchsorted(b, a - dx, 'left')
right = np.searchsorted(b, a + dx, 'right')
a[left != right]

rawDescription: What's the most efficient way to find which elements of one array are close to any element in another?


code:
''.join(BeautifulSoup(content).findAll(text=lambda text:
text.parent.name != "script" and
text.parent.name != "style"))

rawDescription: does BeautifulSoup strips inline CSS and javascript content

description: Does BeautifulSoup strips inline CSS and javascript content


code:
p = pexpect.spawn('ssh  %s@%s ls'%(un,ip), timeout)
print(p.read())

rawDescription: How can I send single ssh command to get result string with pexpect?

description: Send single ssh command to get result string with pexpect


code:
import networkx as nx
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap
m = Basemap(
        projection='merc',
        llcrnrlon=-130,
        llcrnrlat=25,
        urcrnrlon=-60,
        urcrnrlat=50,
        lat_ts=0,
        resolution='i',
        suppress_ticks=True)

# position in decimal lat/lon
lats=[37.96,42.82]
lons=[-121.29,-73.95]
# convert lat and lon to map projection
mx,my=m(lons,lats)

# The NetworkX part
# put map projection coordinates in pos dictionary
G=nx.Graph()
G.add_edge('a','b')
pos={}
pos['a']=(mx[0],my[0])
pos['b']=(mx[1],my[1])
# draw
nx.draw_networkx(G,pos,node_size=200,node_color='blue')

# Now draw the map
m.drawcountries()
m.drawstates()
m.bluemarble()
plt.title('How to get from point a to point b')
plt.show()

rawDescription: Drawing a graph with NetworkX on a Basemap


code:
from scipy.stats import truncnorm
import numpy as np

N = 1000
L = 5.0
mu = 4.0
sigma = 0.8

lower, upper = 0, L

X = truncnorm(
    (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)

points = np.reshape(X.rvs(2*N), (N, 2))

rawDescription: From Matlab to Python: N point with Gaussian Distribution inside a rectangle


code:
import itertools
l = [11, 22, 33, 44, 55, 66, 77]
sum(itertools.islice(l, 0, 4))

rawDescription: How to add a range of integer elements from a list? Python 3.3

description: Add a range of integer elements from a list? Python 3.3


code:
import pandas as pd
df = pd.to_datetime(pd.Series(['28Dec2013 19:23:15']),format="%d%b%Y %H:%M:%S",dayfirst=True)
df

rawDescription: In python pandas, how can I convert this formatted date string to datetime


code:
import xlwt as xlwt
wb = xlwt.Workbook()
names = ['a', 'b', 'c', 'd']
dataset = ['100', '200', '300', '400']
for name in names:
    wb.add_sheet(name)
for n, data in enumerate(dataset):
    ws = wb.get_sheet(n)
    ws.write(1, 1, data)
    # now do more things with ws if you like

rawDescription: xlwt create dynamic number of worksheets based on input

description: Xlwt create dynamic number of worksheets based on input


code:
win=GraphWin("game of life", 600, 600)
win.setCoords(-1,-3,s+1,s+1)

q = True

while q:

       board = iterate(board)

       x = 0

       while(x<s):
             y = 0
             while(y<s):
                      update_color(x ,y ,board ,rec)
                      y = y+1
             x = x+1
       if(win.checkMouse() is not None): #Checks if the user clicked yet
              q = False #Better to use the break statement here

rawDescription: PYTHON, how to exit a while true?

description: PYTHON, how to exit a while true


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

x = np.random.random(100)
normed_value = 2

hist, bins = np.histogram(x, bins=20, density=True)
widths = np.diff(bins)
hist *= normed_value

plt.bar(bins[:-1], hist, widths)
plt.show()

rawDescription: Python: Histogram with area normalized to something other than 1


code:
root = etree.Element('root')

for i in range(3):
    child = etree.Element('child')
    root.append(child)

rawDescription: python etree insert, append and SubElement

description: Python etree insert, append and SubElement


rawDescription: how to extract token from string in python?

description: Extract token from string in python


code:
from tkinter import *
import sqlite3

top_list = [] # holds the player labels currently shown

def getlist():
    global top_list

    conn = sqlite3.connect('C:\sqlite\crapsdatabase.db')
    c = conn.cursor()
    c.execute("SELECT playerName, playerBank FROM player ORDER BY playerBank desc limit 10")
    temp = c.fetchall()

    for player in top_list:
        player.pack_forget() # remove label from window
    top_list = [] # remove references to free memory

    for row in temp:
        texthold = str(row[0]) + ' ' + str(row[1])
        print(texthold)
        player = Label(root, text=texthold)
        player.pack()
        top_list.append(player)

    conn.commit() #confirms changes to the databae
    c.close() #closes the connection to the database
    conn.close()

root = Tk()

theLabel = Label(root, text="Top Ten Players")
buttonUpdate = Button(root, text="Update", fg="green", command=getlist)
buttonUpdate.pack()

theLabel.pack()
root.mainloop()

rawDescription: How do you refresh a label in tkinter and python

description: Refresh a label in tkinter and python


code:
@cp.expose
def qrcode(self, ticketnumber = 'unknown'):
    img = qrcode.make(ticketnumber)
    cp.response.headers['Content-Type'] = "image/png"
    buffer = StringIO.StringIO()
    img.save(buffer, 'PNG')
    return buffer.getvalue()

rawDescription: How to return a qrcode (pillow image) from cherrypy as PNG without saving it as a static file?

description: Return a qrcode (pillow image) from cherrypy as PNG without saving it as a static file


code: myList = [Test() for _ in range(5)]

rawDescription: Python List generation: Force new Object


code:
class ProjectSerializer(...):
    client = serializers.PrimaryKeyRelatedField(queryset=Client.objects.all)

    class Meta:
        model = Project
        fields = ('url', 'id', 'name', 'client', )

rawDescription: Adding field from joined model in Django rest


code: def cmp(v1, v2): return tuple(v1) < tuple(v2)

rawDescription: Vector pair ordering in numpy

description: Vector pair ordering in numpy


code:
# In the future, having the protocol version be a parameter to this
# method would probably be good.  It would be nice if this method
# weren't limited to issueing HTTP/1.1 requests.
requestLines = []
requestLines.append(
    '%s %s HTTP/1.1\r\n' % (self.method, self.uri))

rawDescription: Twisted Web Client HTTP Version

description: Twisted Web Client HTTP Version


code:
previous_month = datetime.now().month - 1
if previous_month == 0:
    previous_month = 12

rawDescription: Finding the previous month

description: Finding the previous month


code:
def process_list(mylist):
    return mylist[:1] + [my_method(item) for item in mylist[1:]]

mylist  = ['or', ['and','A','B','C'], 'B']
print(process_list(mylist))

rawDescription: Python : check length of list and run method for each item or sublist after first element


code:
def show_jar_classes(jar_file):
    """prints out .class files from jar_file"""
    zf = zipfile.ZipFile(jar_file, 'r')
    try:
        lst = zf.infolist()
        for zi in lst:
            fn = zi.filename
            if fn.endswith('.class'):
                print(fn)
    finally:
        zf.close()

rawDescription: Opening a java JAR file from python

description: Opening a java JAR file from python


code:
def balancedq(input):
    stack = []

    for char in input:
        #implement your logic here.
        if sometest:
           stack.append(char) #push
        elif someothertest:
           val = stack.pop()
           #maybe some test here?

rawDescription: How to check for a language of balanced delimiters

description: Check for a language of balanced delimiters


code:
from collections import OrderedDict
listA = ["Name", "Address", "Phone Number"]
listB = [1, 2, 3]
dictA = OrderedDict(zip(listA, listB))
dictA

rawDescription: Have Unexpected Result when Using Dict function to join lists into Dict file


code:
while True: # loop 'forever' until break
    grade = raw_input("enter grade ->")
    grade = int(grade)
    if grade == -1:
        break # we're done
    # rest of processing...

rawDescription: while loop, computing averages

description: While loop, computing averages


code:
side1 = raw_input('Enter the length of the first side,'
                  ' of the triangle: ')

rawDescription: How to separate the print command on multiple lines

description: Separate the print command on multiple lines


code:
config = {
         "name":{
                  'DBName':'blah'
                }
         }

rawDescription: Approaching a dictionary using parameters in Python


code:
from datetime import date
d = '1/8/1986'
date(*reversed([int(x) for x in d.split('/')])).strftime('%Y-%m-%d')

rawDescription: Using python, how do I convert dates that are stored as m(m)/dd/yyyy in a csv file to yyyy-mm-dd for use in sqlite?


rawDescription: Skipping Same Values when Reading csv into Python


code:
def __init__(self):
    self._previous_index = -1

def handleCurrentIndexChanged(self, index):
    # do stuff with previous_index (if valid)
    ...
    self._previous_index = index

rawDescription: PyQt4 : Can I intercept the currentIndexChanged signal of QComboBox?


code:
mylist = [1, 4, 0, 3, 2]
mylist.remove(max(mylist))
mylist.remove(min(mylist))

rawDescription: Remove Max and Min values from python list of integers


code:
class Risk(models.Model):
    drug_link = models.ForeignKey(Drug, on_delete=models.CASCADE)
    dosage = models.IntegerField(default=0)
    independent_risk = models.DecimalField("Individual Risk", max_digits=4, decimal_places=2)

    @property
    def name_dosage(self):
         return "%s - %s" % ( self.drug_link.drug_name, self.dosage )

rawDescription: Make model field equal concatenation of two fields in Django


code:
for lineno, line in enumerate(open(...)):
  if lineno > 2:
    break
  # Remaining code here.

rawDescription: iterate over first elements of a txt in python

description: Iterate over first elements of a txt in python


code: filename, filter = QtGui.QFileDialog.getSaveFileNameAndFilter(self, 'Save file', '', files_types)

rawDescription: How to know the file's type to save, using QFileDialog

description: Know the file's type to save, using QFileDialog


code:
def func(df, date_list):
    lb, ub = df.RPT_Date.min(), df.RPT_Date.max()
    pred = lambda x: lb <= x <= ub
    df = df.set_index('RPT_Date').reindex_axis(filter(pred, date_list))
    df.index.name = 'RPT_Date'
    return df

grb = df.reset_index().groupby('STK_ID')
grb.apply(func, date_list=RPT_DATE_LIST).drop('STK_ID', axis=1)

rawDescription: How to quickly fill the miss quarterly end record for Pandas dataframe?

description: Quickly fill the miss quarterly end record for Pandas dataframe


code: b = {v: k for k, v in a.iteritems()}

rawDescription: Python bidirectional mapping

description: Python bidirectional mapping


code:
psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                             '-ExecutionPolicy',
                             'Unrestricted',
                             './buildxml.ps1',
                             arg1, arg2, arg3], cwd=os.getcwd())
result = psxmlgen.wait()

rawDescription: Invoking a PowerShell script from Python


code:
wrapped = child.__of__(parent2)
assert wrapped.aq_parent is parent2

rawDescription: What is the best way to customize a Zope object's acquisition chain?


code:
m = re.match('Season ([0-9]+), Episode ([0-9]+): .*', s)
(season, episode) = (int(m.group(1)), int(m.group(2)))

rawDescription: Python sorting problem

description: Python sorting problem


code:
header = struct.Struct('>BBBH')
data = b'\xE0\x01\x00\x00\xD2\x59\x80...'  # read this from input file
view = memoryview(data)
offset = 0
while offset < len(data):
    channel, _, _, length = header.unpack(view[offset:offset + header.size])
    write_output(channel, view[header.size:header.size + length])
    offset += length

rawDescription: Parse raw binary file for multiple sets of video frames


rawDescription: Add rows in array with nested loop

description: Add rows in array with nested loop


code: {{ variable|stringformat:".3f" }}

rawDescription: Using python string formatting in a django template


code:
# cols to select
c = rpy2.robjects.IntVector((1,3))
# selection from df
mydf.rx(True, c)

rawDescription: how to select columns from R dataframe in rpy2 in python?

description: Select columns from R dataframe in rpy2 in python


code:
def xor2(a,b):
    f = mux41(0,1,1,0)
    return f(a,b)

rawDescription: 2 inputs to a function?

description: 2 inputs to a function


code:
with open(myfile) as f:
    for index, line in enumerate(f, 1):
        if s in line:
            print("'{0}' found on line {1}".format(s, index))

rawDescription: Python: Find string in a file and print which line it was found on


code:
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
segments = [Segment(start=9, end=1), Segment(start=1, end=3), Segment(start=2, end=5), Segment(start=3, end=6)]
sorted(segments, key=lambda s: (s.end < s.start, -s.end))

rawDescription: How to sort a list containing namedtuples based on the difference between attributes?

description: Sort a list containing namedtuples based on the difference between attributes


code:
import sys
from PySide import QtCore, QtGui, QtWebKit

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        # Create an exit action
        exitAction = QtGui.QAction('Load Yahoo', self)
        # Optionally you can assign an icon to the action
        # exitAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q') # set the shortcut
        # Connect the action with a custom function
        exitAction.triggered.connect(self.load_yahoo)
        # Create the toolbar and add the action
        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAction)

        # Setup the size and title of the main window
        self.resize(650, 750)
        self.setWindowTitle('Browser')

        # Create the web widget and set it as the central widget.
        self.web = QtWebKit.QWebView(self)
        self.web.load(QtCore.QUrl('http://google.com'))
        self.setCentralWidget(self.web)

    def load_yahoo(self):
        self.web.load(QtCore.QUrl('http://yahoo.com'))

app = QtGui.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())

rawDescription: How do add a toolbar on the browser example of PySide?


code:
legend.SetHorizontalAlignment(vtk.vtkChartLegend.CUSTOM)
legend.SetVerticalAlignment(vtk.vtkChartLegend.CUSTOM)
legend.SetPoint(200, 200) # position in window coordinates

rawDescription: Position vtkChartLegend in Python

description: Position vtkChartLegend in Python


rawDescription: How to substract 2 columns of unaligned data with Python/Pandas?

description: Substract 2 columns of unaligned data with Python/Pandas


code:
import os
from PIL import Image
import numpy as np
import scipy.stats.mstats as mstats

f = os.path.expanduser('~/tmp/image.png')
name, ext = os.path.splitext(f)
out = name+"_adjusted.png"

oldImage = Image.open(f).convert('L')
imageArray = np.array(oldImage)

vmin, vmax = mstats.mquantiles(imageArray.flatten(), prob=[0.01,0.99])

np.clip(imageArray, vmin, vmax, out=imageArray)
imageArray = (imageArray-vmin)*255/(vmax-vmin)
img = Image.fromarray(imageArray.astype('uint8'), 'L')
img.save(out)

rawDescription: Remove whitespace from matplotlib savefig


code:
import csv, os
with open('in.csv', 'r') as csvfile:
    a = []
    for row in csv.reader(csvfile, delimiter=',', quotechar='|'):
        a += [ row ]

f = open('out.csv', 'w')
i = 0
for i in range(len(a[0])):
    i += 1
    for j in range(i):
        f.write(str(i) + "," + str(j+1) + "," + str(a[i][j+1]) + os.linesep)
f.close()

rawDescription: How could I select particular data and reform my data structure? csv python


code:
def i64str(obj):
    if isinstance(obj, list):
        return [i64str(x) for x in obj]
    if isinstance(obj, dict):
        return {k:i64str(v) for k, v in obj.items()}
    if isinstance(obj, (int, long)) and obj >= 2**32:
        return str(obj)
    return obj

json.dumps(i64str(my_page_obj))

rawDescription: Best practice to convert 64 bit integers into string in an object for json encoding?


code:
def CarQueue(list):
    def __len__(self):
        return something_dubious()
    # if you're going to override len, make sure to overide `__iter__`
    # and `__getitem__`

class CarWash(object):
    def __init__(self):
        self._queue = CarQueue([1, 2, 3])

    @property
    def queue(self):
        return self._queue

rawDescription: How can I replace a class @property's len(..) return with a custom __len__() procedure?

description: Replace a class @property's len(..) return with a custom __len__() procedure


code:
import sys
import wx
import wx.lib.newevent

(MyCustomEvent, EVT_CUSTOM) = wx.lib.newevent.NewEvent()

class CustomEventTracker(wx.EvtHandler):
 def __init__(self, log, processingCodeFunctionHandle):
  wx.EvtHandler.__init__(self)
  self.processingCodeFunctionHandle = processingCodeFunctionHandle
  self.log = log
  EVT_CUSTOM(self, self.MyCustomEventHandler)

 def MyCustomEventHandler(self, evt):
  self.log.write(evt.resultOfDialog + '\n')
  self.processingCodeFunctionHandle(evt.resultOfDialog)
  evt.Skip()

class MyPanel2(wx.Panel):
 def __init__(self, parent, log):
  wx.Panel.__init__(self, parent)
  self.log = log

 def OnResults(self, resultData):
  self.log.write("Result data gathered: %s" % resultData)

class MyFrame(wx.Frame):
 def __init__(self, parent, ID = -1, title = "", pos = wx.DefaultPosition,
     size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE):
  wx.Frame.__init__(self, parent, ID, title, pos, size, style)
  self.panel = panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL
       | wx.CLIP_CHILDREN
       | wx.FULL_REPAINT_ON_RESIZE)
  sizer = wx.BoxSizer(wx.VERTICAL)
  sizer.Add((25, 25))

  row = wx.BoxSizer(wx.HORIZONTAL)
  row.Add((25,1))
  m_close = wx.Button(self.panel, wx.ID_CLOSE, "Close")
  m_close.Bind(wx.EVT_BUTTON, self.OnClose)
  row.Add(m_close, 0, wx.ALL, 10)
  sizer.Add(row)
  self.panel.SetSizer(sizer)

 def OnClose(self, evt):
  dlg = wx.MessageDialog(self,
   "Do you really want to close this frame?",
   "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
  result = dlg.ShowModal()
  dlg.Destroy()
  if result == wx.ID_CANCEL:
   event = MyCustomEvent(resultOfDialog = "User Clicked CANCEL")
   self.GetEventHandler().ProcessEvent(event)
  else: # result == wx.ID_OK
   event = MyCustomEvent(resultOfDialog = "User Clicked OK")
   self.GetEventHandler().ProcessEvent(event)
   self.Destroy()

app = wx.App(False)
f2 = wx.Frame(None, title="Frame 1 (for feedback)", size=(400, 350))
p2 = MyPanel2(f2, sys.stdout)
f2.Show()
eventTrackerHandle = CustomEventTracker(sys.stdout, p2.OnResults)
f1 = MyFrame(None, title="PushEventHandler Tester (deals with on close event)", size=(400, 350))
f1.PushEventHandler(eventTrackerHandle)
f1.Show()
app.MainLoop()

rawDescription: Return value from wxPython Frame

description: Return value from wxPython Frame


rawDescription: how can I get current value to qcombobox in pyqt?

description: Get current value to qcombobox in pyqt


code:
fig, ax = plt.subplots(1,1) # your only call to plt

ax.bar(r,v,width=0.9,color='red',edgecolor='black', lw=0.5, align='center')
ax.bar(r,j,width=0.6,color='green',edgecolor='black', lw=0.5, align='center')
ax.bar(r,n,width=0.3,color='blue',edgecolor='black', lw=0.5, align='center')
ax.set_xticks(r)
ax.set_xticklabels(x)
ax.axhline(y=0,linewidth=1,color='black')

fig.savefig('fig',dpi=300,format='png',orientation='landscape')
# or use plt.show() to see the figure interactively or inline, depending on backend
# (see Joe Kington's comment below)

rawDescription: Preserving the xticks in multiple bar plots in matplotlib


code: p = multiprocessing.Process(target=run, args=(vitems.pop(), arg2, ...))

rawDescription: Spawn parallel processes for function and pass several different arguments to function


code:
import sys
from PySide import QtCore, QtGui, QtWebKit

html = '''

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

'''

class WebPage(QtWebKit.QWebPage):
    def javaScriptConsoleMessage(self, message, line, source):
        if source:
            print('line(%s) source(%s): %s' % (line, source, message))
        else:
            print(message)

class Proxy(QtCore.QObject):
    @QtCore.Slot(float, float)
    def showLocation(self, latitude, longitude):
        self.parent().edit.setText('%s, %s' % (latitude, longitude))

class MainWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.view = QtWebKit.QWebView(self)
        self.view.setPage(WebPage(self))
        self.edit = QtGui.QLineEdit(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.view)
        layout.addWidget(self.edit)
        self.map = self.view.page().mainFrame()
        self.map.loadFinished.connect(self.handleLoadFinished)
        self.view.setHtml(html)
        self._proxy = Proxy(self)

    def handleLoadFinished(self, ok):
        self.map.addToJavaScriptWindowObject('qt', self._proxy)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.setGeometry(500, 300, 800, 600)
    window.show()
    sys.exit(app.exec_())

rawDescription: Getting javascript variable value into python from QWebView


code:
def append_doc_of(fun):
    def decorator(f):
        f.__doc__ += fun.__doc__
        return f

    return decorator

def A():
    '''
    I am doctring for function A
    '''
    pass

@append_doc_of(A)
def B1():
    '''
    I am doctring for function B1,

    followed by the same docstring as function A, which is:

    '''
    pass

rawDescription: how to make function docstring automatically updated according to another function in python?

description: Make function docstring automatically updated according to another function in python


code:
INSTALLED_APPS = (
    # ...
    'django.contrib.admin.apps.SimpleAdminConfig',  # instead of 'django.contrib.admin'
    # ...
)

rawDescription: Does Django v1.8 support `register_view` method of django-adminplus v0.3?


code:
import numpy
import theano
import theano.tensor as tt

def compile(input_size, hidden_size, output_size, learning_rate):
    w_h = theano.shared(numpy.random.standard_normal((input_size, hidden_size))
                        .astype(theano.config.floatX), name='w_h')
    b_h = theano.shared(numpy.random.standard_normal((hidden_size,))
                        .astype(theano.config.floatX), name='b_h')
    w_y = theano.shared(numpy.random.standard_normal((hidden_size, output_size))
                        .astype(theano.config.floatX), name='w_y')
    b_y = theano.shared(numpy.random.standard_normal((output_size,))
                        .astype(theano.config.floatX), name='b_y')
    x = tt.matrix()
    z = tt.vector()
    h = tt.tanh(theano.dot(x, w_h) + b_h)
    y = theano.dot(h, w_y) + b_y
    c = tt.sum(y - z)
    updates = [(p, p - tt.switch(tt.gt(c, 0), learning_rate * tt.grad(cost=c, wrt=p), 0))
               for p in (w_h, b_h, w_y, b_y)]
    return theano.function([x, z], outputs=c, updates=updates)

def main():
    f = compile(input_size=3, hidden_size=2, output_size=4, learning_rate=0.01)

main()

rawDescription: How to perform conditional updates on shared variables in Theano?

description: Perform conditional updates on shared variables in Theano


code:
from django.core.files.storage import FileSystemStorage

fss = FileSystemStorage()
filepath = fss.get_available_name(filepath)

rawDescription: Django unique filename method

description: Django unique filename method


code:
from sympy import Symbol, ground_roots
x = Symbol('x')
f = x**5 + 7*x + 1
p = 13
ground_roots(f, modulus=p)

rawDescription: How to check if complex number is a whole number

description: Check if complex number is a whole number


code:
import requests
requests.head("https://flic.kr/p/qf3mGd", allow_redirects=True, verify=False).url

rawDescription: Unshorten Flic.kr URLs

description: Unshorten Flic.kr URLs


code:
from Tkinter import *
import os
from PIL import Image

root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill=Y )
mylist = Listbox(root, font = "verdana 15", yscrollcommand = scrollbar.set,  height= 5, width = 10 )

pathToImages = ['D://images/biscuit.jpeg',
'D://images/chocolate.jpeg','D://images/sandwich.jpeg',
'D://images/cake.jpeg']

def buttonHandler(self):
    bi = Image.open(pathToImages[int(mylist.curselection()[0])])
    bi.show()

a = mylist.insert(END,str('Biscuit'))
b = mylist.insert(END,str('Chocolate'))
c = mylist.insert(END,str('Sandwich'))
d = mylist.insert(END,str('Cake'))

mylist.bind('<<ListboxSelect>>', buttonHandler)

mylist.pack( )
scrollbar.config( command = mylist.yview )
mainloop()

rawDescription: Binding the contents of list to display an image when clicked


code:
import sys
from pyspark.sql.window import Window
from pyspark.sql.functions import sum

df = data.toDF(["customer_id", "contract_id", "timestamp", "value"])
w = (Window()
    .partitionBy("customer_id", "contract_id")
    .orderBy("timestamp")
    # Current row and future values
    .rangeBetween(0, sys.maxsize)) # or .rowsBetween(0, sys.maxsize)

result = df.withColumn("future_value", sum("value").over(w))
result.show()

## +-----------+-----------+---------+-----+------------+
## |customer_id|contract_id|timestamp|value|future_value|
## +-----------+-----------+---------+-----+------------+
## | customer_1| contract_1|     7500|  500|         800|
## | customer_1| contract_1|    15000|  100|         300|
## | customer_1| contract_1|    20000|  200|         200|
## | customer_2| contract_2|    30000|  100|         100|
## +-----------+-----------+---------+-----+------------+

rawDescription: Spark - Reducing number of combinations using a groupBy


code:
form = StepOne(request.POST)
if form.is_valid():
    content = form.cleaned_data['content']
    difficulty = form.cleaned_data['difficulty']

rawDescription: How to access a ModelForm's fields in Django view

description: Access a ModelForm's fields in Django view


code:
from boto.s3.key import Key
k = Key(bucket)
k.key = 'yourkey'
k.set_contents_from_string(request.POST['data'])

rawDescription: Python Django : Creating file object in memory without actually creating a file


code:
class Participation(models.Model):
    user = models.ForeignKey(User)
    event = models.ForeignKey(Event)

class Event(models.Model):
    users = models.ManyToManyField(User, through='Participation')

rawDescription: Django manytomany signals?

description: Django manytomany signals


code:
from tkinter import *

root = Tk()

def yourFunction(event):
    print('left')

frame = Frame(root, width=100, height=100)

frame.bind("<Left>",yourFunction)   #Binds the "left" key to the frame and exexutes yourFunction if "left" key was pressed
frame.pack()

root.mainloop()

rawDescription: How to bind a keypress to a button in Tkinter

description: Bind a keypress to a button in Tkinter


code:
def initWidget(self, items):
    listBox = QVBoxLayout(self)
    self.setLayout(listBox)

    scroll = QScrollArea(self)
    listBox.addWidget(scroll)
    scroll.setWidgetResizable(True)
    scrollContent = QWidget(scroll)

    scrollLayout = QVBoxLayout(scrollContent)
    scrollContent.setLayout(scrollLayout)
    for item in items:
        scrollLayout.addWidget(item)
    scroll.setWidget(scrollContent)

rawDescription: How to make QWidget contents scrollable in PyQt?

description: Make QWidget contents scrollable in PyQt


code:
import urllib.request
import urllib.parse
import base64

def encode_credentials(username, password):
    byte_creds = '{}:{}'.format(username, password).encode('utf-8')
    return base64.b64encode(byte_creds).decode('utf-8')

def tweet(username, password, message):
    encoded_msg = urllib.parse.urlencode({'status': message})
    credentials = encode_credentials(username, password)
    request = urllib.request.Request(
         'http://api.twitter.com/1/statuses/update.json')
    request.add_header('Authorization', 'Basic ' + credentials)
    urllib.request.urlopen(request, encoded_msg)

rawDescription: Python 3.1 twitter post with installed library,


code:
import numpy as np
import cv2

second=cv2.imread('second.png') # read the picture

for i in range(second.shape[0]):
   for j in range(second.shape[1]):
       if second[i,j,0]!=0 or second[i,j,1]!=0 or second[i,j,2]!=0:# if it is not black pixel
           second[i,j,0]=0
           second[i,j,1]=0
           second[i,j,2]=255 # color it in red
cv2.imwrite('result.png',second) # save the colored picture

rawDescription: OpenCV: Colorization failure

description: OpenCV: Colorization failure


code:
all_lists = []
for name in iter(lambda: input("monster name"), ""): # loop until empty name
    # ...
    titles = [link["title"] for link in content.findAll('a', title=True)]
    all_lists.append(titles)

rawDescription: Link Fetching List

description: Link Fetching List


rawDescription: empty_string in some_string - always true?

description: Empty_string in some_string - always true


code:
from selenium.webdriver.common.keys import Keys
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.SHIFT + 'k')

rawDescription: How to open console in firefox python selenium?

description: Open console in firefox python selenium


code:
for num in range (1,24):
   label = getattr(self.ui, 'mylabel_{}'.format(num))
   label.setTest('foobar')

rawDescription: Loop to Update Labels in PyQT GUI

description: Loop to Update Labels in PyQT GUI


code:
color = colorchooser.askcolor()
color_name = color[1]    #to pick up the color name in HTML notation, i.e. the 2nd element of the tuple returned by the colorchooser
root.configure(background=color_name)

rawDescription: Changing color of background of tkinter window by using colorchooser in python 3 and tkinter


code:
iframe = self.driver.find_element_by_css_selector("#webcam-container")
self.driver.switch_to_frame(iframe)
record = self.driver.find_element_by_css_selector("#record-button > span.yt-uix-button-content")
record.click()

rawDescription: How to automate webpage button control using Selenium?

description: Automate webpage button control using Selenium


code:
from PySide import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.textEdit = Editor(self)
        self.toolBar = QtGui.QToolBar(self)
        self.actionZoomIn = QtGui.QAction('Zoom In', self)
        self.actionZoomOut = QtGui.QAction('Zoom Out', self)
        self.textEdit.setHtml('Hello world')
        self.setCentralWidget(self.textEdit)
        self.addToolBar(self.toolBar)
        self.toolBar.addAction(self.actionZoomIn)
        self.toolBar.addAction(self.actionZoomOut)
        self.actionZoomIn.triggered.connect(self.onZoomInClicked)
        self.actionZoomOut.triggered.connect(self.onZoomOutClicked)

    def onZoomInClicked(self):
        self.textEdit.zoom(+1)

    def onZoomOutClicked(self):
        self.textEdit.zoom(-1)

class Editor(QtGui.QTextEdit):
    def __init__(self, parent=None):
        super(Editor, self).__init__(parent)

    def zoom(self, delta):
        if delta < 0:
            self.zoomOut(1)
        elif delta > 0:
            self.zoomIn(5)

    def wheelEvent(self, event):
        if (event.modifiers() & QtCore.Qt.ControlModifier):
            self.zoom(event.delta())
        else:
            QtGui.QTextEdit.wheelEvent(self, event)

if __name__ == '__main__':

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

rawDescription: How to scale/zoom a QTextEdit area from a toolbar button click and/or ctrl + mouse wheel

description: Scale/zoom a QTextEdit area from a toolbar button click and/or ctrl + mouse wheel


code:
import wx

class PhoneNumbers(wx.HtmlListBox):
    def __init__(self, parent):
        wx.HtmlListBox.__init__(self, parent)
        self.data = [
            ("Foo", "3452-453"),
            ("Bar", "5672-346"),
        ]
        self.SetItemCount(len(self.data))

    def OnGetItem(self, n):
        return "%s
%s" % self.data[n]

    def add_number(self, name, number):
        self.data.append((name, number))
        self.SetItemCount(len(self.data))
        self.Refresh()

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(200, 400))

        self.numbers = PhoneNumbers(self)
        self.contact_name = wx.TextCtrl(self)
        self.contact_number = wx.TextCtrl(self)
        self.add_btn = wx.Button(self, label="Add contact")

        self.Sizer = wx.BoxSizer(wx.VERTICAL)
        self.Sizer.Add(self.numbers, 1, wx.EXPAND)
        self.Sizer.Add(wx.SearchCtrl(self), 0, wx.EXPAND)
        self.Sizer.Add(wx.StaticText(self, label="Name"), 0, wx.TOP, 10)
        self.Sizer.Add(self.contact_name)
        self.Sizer.Add(wx.StaticText(self, label="Number"), 0, wx.TOP, 5)
        self.Sizer.Add(self.contact_number)
        self.Sizer.Add(self.add_btn, 0, wx.ALL, 10)

        self.numbers.Bind(wx.EVT_LISTBOX, self.OnSelectNumber)
        self.add_btn.Bind(wx.EVT_BUTTON, self.OnAddNumber)

    def OnSelectNumber(self, event):
        name, number = self.numbers.data[event.Selection]
        self.contact_name.Value = name
        self.contact_number.Value = number

    def OnAddNumber(self, event):
        self.numbers.add_number(
            self.contact_name.Value,
            self.contact_number.Value
        )

app = wx.PySimpleApp()
app.TopWindow = f = Frame()
f.Show()
app.MainLoop()

rawDescription: how to make multiline wx.ListBox

description: Make multiline wx.ListBox


code:
def index(request):
   hat_id = request.GET.get('hat_id', None)
   if hat_id:
       return HttpResponseRedirect(reverse('detay', args=[hat_id]))

rawDescription: Django url patterns dont match

description: Django url patterns dont match


code:
from sklearn.base import BaseEstimator
from mne.decoding.mixin import TransformerMixin
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import GaussianNB
from sklearn import cross_validation
from sklearn.grid_search import GridSearchCV
from sklearn.externals import six

class SampleAndFeatureFilter(BaseEstimator, TransformerMixin):
    def __init__(self, perc = None):
        self.perc = perc

    def fit(self, X, y=None):
        self.X = X
        sum_per_feature = X.sum(0)
        sum_per_sample = X.sum(1)
        self.featurefilter = sum_per_feature >= np.percentile(sum_per_feature, self.perc)
        self.samplefilter  = sum_per_sample >= np.percentile(sum_per_sample, self.perc)
        return self

    def transform(self, X, y=None, copy=None):
        idx = id(X)
        X=X[:,self.featurefilter]
        if idx == id(self.X):
            X = X[self.samplefilter, :]
            if y is not None:
                y = y[self.samplefilter]
            return X, y
        return X

    def fit_transform(self, X, y=None, **fit_params):
        if y is None:
            return self.fit(X, **fit_params).transform(X)
        else:
            return self.fit(X, y, **fit_params).transform(X,y)

class PipelineWithSampleFiltering(Pipeline):
    def fit_transform(self, X, y=None, **fit_params):
        Xt, yt, fit_params = self._pre_transform(X, y, **fit_params)
        if hasattr(self.steps[-1][-1], 'fit_transform'):
            return self.steps[-1][-1].fit_transform(Xt, yt, **fit_params)
        else:
            return self.steps[-1][-1].fit(Xt, yt, **fit_params).transform(Xt)

    def fit(self, X, y=None, **fit_params):
        Xt, yt, fit_params = self._pre_transform(X, y, **fit_params)
        self.steps[-1][-1].fit(Xt, yt, **fit_params)
        return self

    def _pre_transform(self, X, y=None, **fit_params):
        fit_params_steps = dict((step, {}) for step, _ in self.steps)
        for pname, pval in six.iteritems(fit_params):
            step, param = pname.split('__', 1)
            fit_params_steps[step][param] = pval
        Xt = X
        yt = y
        for name, transform in self.steps[:-1]:
            if hasattr(transform, "fit_transform"):
                res = transform.fit_transform(Xt, yt, **fit_params_steps[name])
                if len(res) == 2:
                    Xt, yt = res
                else:
                    Xt = res
            else:
                Xt = transform.fit(Xt, y, **fit_params_steps[name]) \
                              .transform(Xt)
        return Xt, yt, fit_params_steps[self.steps[-1][0]]

if __name__ == '__main__':
    X = np.random.random((100,30))
    y = np.random.random_integers(0, 1, 100)
    pipe = PipelineWithSampleFiltering([('flt', SampleAndFeatureFilter()), ('cls', GaussianNB())])
    X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size = 0.3, random_state = 42)
    kfold = cross_validation.KFold(len(y_train), 10)
    clf = GridSearchCV(pipe, cv = kfold, param_grid = {'flt__perc':[10,20,30,40,50,60,70,80]}, n_jobs = 1)
    clf.fit(X_train, y_train)

rawDescription: sklearn: Have an estimator that filters samples

description: Sklearn: Have an estimator that filters samples


code:
import pytz
from pytz import timezone
a = datetime.now(timezone("UTC"))
b = a.astimezone(timezone("Europe/Zurich"))
a
b
b.utcoffset()

rawDescription: Python: Convert to local time

description: Python: Convert to local time


code:
import re
my_string='Shall I compare thee to a summer\'s day?'
search_items = ['a', ' ', 'e', 'h', 'm', 'l', 'o', 'e ', 's', 'r', 't', ' t', 'e t']
results_dict = {}
for search_item in search_items:
    results_dict[search_item] = [m.start() for m in re.finditer(search_item, my_string)]

for elem in results_dict:
    print("%s: %s" % (elem, results_dict[elem]))

rawDescription: Finding the indices of all matches in a string, appending search term and indices to a dictionary.


code:
try:
    time.strptime(input_string, "%d-%H.%M")
except ValueError:
    print("Incorrect date format")

rawDescription: How to check string is laid out in correct format (Python)

description: Check string is laid out in correct format (Python)


code: #!/usr/bin/env python

rawDescription: Calling a python script from command line without typing "python" first


rawDescription: list indices must be integer python

description: List indices must be integer python


code:
#ToDO write output file
# INPUTS TO BE UPDATED
inputNDP = r"N:\Parcels\Parcels2012\57-11-115.ndp"
# END OF INPUTS TO BE UPDATED
fileNDP = open(inputNDP, 'rb')
def strip_nonascii(b):
    return b.decode('ascii', errors='ignore')

n = 0
for line in fileNDP:
    if n > 5:
        if '|' in line:
            break
        print(strip_nonascii(line)).strip('\n') # + str(n)
    n += 1

rawDescription: How can I ignore binary data headers (or just read the serialized data) when enumerating a file with Python?

description: Ignore binary data headers (or just read the serialized data) when enumerating a file with Python


code:
from tkinter import *

def multiplier(*args):
    try:
        value = float(ment.get())
        res = value *2
        result.set(res)
        mEntry.delete(0, END) #deletes the current value
        mEntry.insert(0, res) #inserts new value assigned by 2nd parameter

    except ValueError:
        pass

mGui = Tk()
mGui.geometry("300x300+300+300")

ment = StringVar()
result = StringVar()

mbutton = Button (mGui, text = "Calculate", command = multiplier)
mbutton.pack()

mEntry = Entry(mGui, textvariable = ment, text="bebe")
mEntry.pack()

mresult = Label(mGui, textvariable = result)
mresult.pack()

rawDescription: Updating Text In Entry (Tkinter)

description: Updating Text In Entry (Tkinter)


code:
f=open("studentname.txt", 'r')
f2=open ("student-firstname.txt",'w')

for line in f.readlines():
     token=line.split()
     f2.write(token[1]+"\n")
f.close()
f2.close()

rawDescription: I am having a problem with my python program that im running


code: reduce(set.intersection, map(set , bigstringlist))

rawDescription: Python how to iterate through a list and compare lists of strings found within


code:
def get_input():
    invalid_attempts = 0

    while invalid_attempts < 3:
        number = float(input('please enter a number (must be greater thatn zero): '))

        if number >= 0 :
            print ('you choose number:', number)
            return number # so you can call the method as 'some_variable = get_input()'
        else:
            print ('invalid input')
            invalid_attempts += 1

rawDescription: limiting invalid input in python 3

description: Limiting invalid input in python 3


code:
from django.db import models
from django.contrib.auth.models import Group
from django.db.models.signals import post_save

class YourModel(models.Model):
    name = models.CharField('name', max_length=50)
    group = models.ForeignKey(Group)
    # ...

    @classmethod
    def create_after_group(cls, sender, instance, created, **kwargs):
        if created:
            group_created = instance
            m = cls(name="Some name", group=group_created)
            m.save()

post_save.connect(YourModel.create_after_group, sender=Group)

rawDescription: Create model after group has been created django


code:
from django.core.files.base import ContentFile
def save_item(request, uname, data):
    item = Item()
    myFile = ContentFile(base64.b64decode(data))
    item.preview.save('fakename.jpg', myFile, save=False)

rawDescription: File handling in Django when posting image from service call


code:
from bs4.builder import HTMLParserTreeBuilder

class MyBuilder(HTMLParserTreeBuilder):
    def __init__(self):
        super(MyBuilder, self).__init__()
        # BeautifulSoup, please don't treat "class" as a list
        self.cdata_list_attributes["*"].remove("class")

soup = BeautifulSoup(data, "html.parser", builder=MyBuilder())

rawDescription: Disable special "class" attribute handling


code:
from PyQt4 import QtCore, QtGui

class Validator(QtGui.QDoubleValidator):
    def validate(self, value, pos):
        text = value.strip().title()
        for null in ('None', 'Null', 'Nothing'):
            if text == null:
                return QtGui.QValidator.Acceptable, text, pos
            if null.startswith(text):
                return QtGui.QValidator.Intermediate, text, pos
        return super(Validator, self).validate(value, pos)

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.edit = QtGui.QLineEdit(self)
        self.edit.setValidator(Validator(self.edit))
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 200, 50)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt QWizard validation and button override


rawDescription: Routine in python to test for a string if has a *nix valid absolute path?


code:
entry = Gtk.Entry()
entry_buffer = entry.get_buffer()
entry_buffer.connect('inserted-text', callback)

rawDescription: Python and Gtk+3 Entry problems

description: Python and Gtk+3 Entry problems


code:
import time
time.ctime(1263538277)

rawDescription: Windows file creation date/time using python


code:
def is_shifted_copy(l1, l2):
    l1l1 = l1 * 2
    n = len(l1)
    return next((i for i in range(n) if l1l1[i:i + n] == l2), None)

rawDescription: In Python, efficiently determine if two lists are shifted copies of one another


code:
import Image

#load image, get bands and pixel arrays
img = Image.open('sample.jpg')
r,g,b = img.split()
r_array = r.load()
g_array = g.load()
b_array = b.load()
x,y = r.size

#divide red band by green band (+1 to prevent divide by 0)
for i in xrange(x):
  for j in xrange(y):
    r_array[i, j] /= (g_array[i, j] + 1)

#normalize red band, set green and blue to 0
scalar = 255.0 / r.getextrema()[1]
for i in xrange(x):
  for j in xrange(y):
    r_array[i, j] *= scalar
    g_array[i, j] = 0
    b_array[i, j] = 0

#merge the bands
img = Image.merge('RGB', (r, g, b))
img = img.convert("P", palette=Image.ADAPTIVE, colors=8)
img.show()

rawDescription: Divide band by another band using img.split()


code:
import random

def biased_flip(prob_true=0.5):
    return random.random() < prob_true

rawDescription: Biased coin flip in Python

description: Biased coin flip in Python


rawDescription: Python 2.7: check if a sublist contains an item


code:
with open('file.dat') as input_file:
    newLines = []
    for line in input_file:
        newLine = [x.strip() for x in line.split('|')]
        if len(newLine) == 6 and newLine[3] and newLine[4]:
            newLines.append(newLine)

rawDescription: How to convert .dat to .csv using python?

description: Convert .dat to .csv using python


code:
class ShowForm(forms.ModelForm):
    class Meta:
        model = Show

    def __init__(self, *args, **kwargs):
        super(ShowForm, self).__init__(*args, **kwargs)
        if Address.objects.exists():
            self.fields['optional_address'].required = True

rawDescription: Optional ForeignKey in ModelForm

description: Optional ForeignKey in ModelForm


code:
urlpatterns = patterns('',
    url(r'^user/', include('registration.urls')),
    url(r'^user/', include('profile.urls')),
)

rawDescription: Django: Multiple url patterns starting at the root spread across files


code:
len(b'a')
sys.getsizeof(b'a')

rawDescription: counting bits in a message sent over a serial port

description: Counting bits in a message sent over a serial port


code:
try:
    from urllib.request import urlretrieve
except ImportError:
    from urllib import urlretrieve

urlretrieve('http://example.org', 'outfile.dat')

rawDescription: Downloading a file from the command line using python


code:
from sqlalchemy import inspect

def getattr_from_column_name(instance, name, default=Ellipsis):
    for attr, column in inspect(instance.__class__).c.items():
        if column.name == name:
            return getattr(instance, attr)

    if default is Ellipsis:
        raise KeyError
    else:
        return default

rawDescription: How to get value from SQLAlchemy instance by column name?

description: Get value from SQLAlchemy instance by column name


code:
from sqlalchemy.sql.expression import false

TestCase.obsoleted == false()

rawDescription: flake8 complains on boolean comparison "==" in filter clause

description: Flake8 complains on boolean comparison "==" in filter clause


code:
from pyramid.scripts.pviews import PViewsCommand

pvcomm = PViewsCommand()

urlpath = request.environ['PATH_INFO']
parts = urlpath.split('/')
existing_views = {}

for i in range(1, len(parts)):
    path = '/'.join(parts[:i])
    view = pvcomm._find_view(path, request.registry)
    if view is not None:
        existing_views[path] = view

rawDescription: Is it a way to check whether all the subpaths of the current request.path have a view callable associated with?


rawDescription: OpenCV - Scan an image with a rectangle

description: OpenCV - Scan an image with a rectangle


code:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# set up the bins
Nbins = 10
bins = np.linspace(0, 1, Nbins +1, endpoint=True)
# get some fake data
x = np.random.rand(300)
y = np.arange(300)
# figure out which bin each x goes into
bin_num = np.digitize(x, bins, right=True) - 1
# compute the counts per bin
hist_vals = np.bincount(bin_num)
# set up array for bins
means = np.zeros(Nbins)
# numpy slicing magic to sum the y values by bin
means[bin_num] += y
# take the average
means /= hist_vals

# make the figure/axes objects
fig, ax = plt.subplots(1,1)
# get a color map
my_cmap = cm.get_cmap('jet')
# get normalize function (takes data in range [vmin, vmax] -> [0, 1])
my_norm = Normalize()
# use bar plot
ax.bar(bins[:-1], hist_vals, color=my_cmap(my_norm(means)), width=np.diff(bins))

# make sure the figure updates
plt.draw()
plt.show()

rawDescription: Color-coding a histogram

description: Color-coding a histogram


code:
import nltk
tokens = nltk.word_tokenize("People took to the streets and protested")
nltk.pos_tag(tokens)

rawDescription: Natural Language Processing using nltk

description: Natural Language Processing using nltk


code: super_list.sort(key=lambda row: row[0]) #sort by seconds field

rawDescription: Uniquely sorting a list of lists in Python


rawDescription: Convert 64-bits floating-point format string to floating-point number


rawDescription: How to plot different CSV file data into a single graph, day as reference at x-axis

description: Plot different CSV file data into a single graph, day as reference at x-axis


code:
def fun(a=1):
    a = 1 if a is None else a
    print(a)

rawDescription: How can I accept default parameter in function when 'None' or no argument is passed?

description: Accept default parameter in function when 'None' or no argument is passed


code:
import numpy as np
from sklearn.cluster import AgglomerativeClustering
import itertools

X = np.concatenate([np.random.randn(3, 10), np.random.randn(2, 10) + 100])
model = AgglomerativeClustering(linkage="average", affinity="cosine")
model.fit(X)

ii = itertools.count(X.shape[0])
[{'node_id': next(ii), 'left': x[0], 'right':x[1]} for x in model.children_]

rawDescription: How to traverse a tree from sklearn AgglomerativeClustering?

description: Traverse a tree from sklearn AgglomerativeClustering


code:
class EstDateTimeProperty(db.DateTimeProperty):
  def make_value_from_datastore(self, value):
    naive_utc = db.DateTimeProperty(self, value)
    aware_utc = naive_utc.replace(tzinfo=UTC)
    return aware_utc.astimezone(EST)

rawDescription: Google app engine after refresh from datastore


code:
from gevent import monkey
monkey.patch_all(thread=False)

rawDescription: python win32api blocking bottle routes

description: Python win32api blocking bottle routes


code:
title = "my title"
name = "my name"

things_I_want = "title", "name"
scope = vars()
{name: scope[name] for name in things_I_want}
#>>> {'title': 'my title', 'name': 'my name'}

rawDescription: Is there an idiomatic way to establish a dictionary with the variable name as the key and value as the value?


code:
def ftp_image_to(ftp_ip, ftp_dir, filename, data):
    ftp = FTP(ftp_ip)
    print("logging in")
    ftp.login('autoftp', 'autoftp')
    print("making dir")
    ftp.mkd('FTP/' + ftp_dir)
    ftp.cwd('FTP/' + ftp_dir)
    print("formatting image")
    bytes = BytesIO()
    plt.imsave(bytes, data, format='png')
    bytes.seek(0)
    print("storing binary")
    ftp.storbinary('STOR ' + filename, bytes)
    ftp.quit()

rawDescription: Image handling in Python With Numpy

description: Image handling in Python With Numpy


code:
@get('/', apply=[auth])
def handler():
    ...

rawDescription: Python Bottle.py decorator confusion

description: Python Bottle.py decorator confusion


code:
class Data(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()

class Photo(models.Model):
    photo = models.ImageField(upload_to='img')
    data = models.ForeignKey(Data)

class DataForm(forms.ModelForm):
    class Meta:
        model = Data

class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        exclude = ('data',)

def your_view(request):
    data_form = DataForm(request.POST or None)
    photo_form = PhotoForm(request.POST or None, request.FILES or None)

    if request.method == 'POST':
        if data_form.is_valid() and photo_form.is_valid():
            data = data_form.save()
            photo = photo_form.save(commit=False)
            photo.data = data
            photo.save()
            # do something else here, like a redirect to another view.
    return render(request, 'your-template.html',
        {'data_form': data_form, 'photo_form': photo_form})

rawDescription: Models form with foreign key

description: Models form with foreign key


code:
class Three(object):
    def __getattr__(self, name):
        return lambda *args, **kw: 3

rawDescription: I need an object to do anything

description: I need an object to do anything


code:
query = db.GqlQuery("SELECT * FROM Pages WHERE pageName=:1", pageName)
for page in query:
  page.content = content
  page.put()

rawDescription: How to modify entry in database in appengine?

description: Modify entry in database in appengine


rawDescription: Working with unicode encoded Strings from Active Directory via python-ldap


code:
results = soup.findAll('div', class_='name')
for each in results:
    if each.text:
        worksheet.write(row,1,each.text)
        row += 1

rawDescription: Using the Join command to eliminate extra paragraph breaks


code:
import nose

argv = ['fake', '--with-xunit']
nose.main(argv=argv)

rawDescription: Passing options to nose in a Python test script


code:
import os
from glob import glob
from itertools import islice
path = "full_path/"
import ntpath

for f in glob(path + "*.csv"): # find all .csh files
    with open(os.path.join(path, f)) as fl:
        data = fl.readlines()
    with open(os.path.join(path, f), "w") as w:
        # write filename - .csh
        w.write("#$ -N {}\n".format(ntpath.basename(f).rstrip(".csh")))
        for line in data[4:]:
            # write remaining lines
            w.write(line.replace("//", "/"))

rawDescription: Delete and modify text in a bunch of files with python


code:
import ipaddress
addr = ipaddress.ip_address('192.168.0.1')
net = ipaddress.ip_network('192.168.0.0/20')
net[256]
next(i for i, a in enumerate(net) if a == addr)

rawDescription: Calculate the N IP of a network

description: Calculate the N IP of a network


code:
if item.bin_field:
    bin_val = item.bin_field.decode('base64')

rawDescription: Default values for Binary fields in Odoo


code:
import numpy as np
import theano
import theano.tensor as tt

def numpy_v1(a, b):
    ainvb = np.zeros((3, 2, 4))
    for i in range(4):
        ainvb[:, :, i] = a / b[:, i].T
    return ainvb

def numpy_v2(a, b):
    return a[:, :, None] / b

def compile_theano_v1():
    a, b = tt.matrices('a', 'b')
    return theano.function([a, b], a[:, :, None] / b)

def main():
    dt = np.dtype(np.float32)

    a = [[12, 3],
         [2, 4],
         [2, 4], ]

    b = [[12, 3, 2, 3],
         [2, 4, 4, 5]]

    a = np.asarray(a, dtype=dt)
    b = np.asarray(b, dtype=dt)
    print(a.shape)
    print(b.shape)

    theano_v1 = compile_theano_v1()

    numpy_v1_ainvb = numpy_v1(a, b)
    numpy_v2_ainvb = numpy_v2(a, b)
    theano_v1_ainvb = theano_v1(a, b)

    assert np.allclose(numpy_v1_ainvb, numpy_v2_ainvb)
    assert np.allclose(numpy_v2_ainvb, theano_v1_ainvb)

main()

rawDescription: matrix divided by rows of another matrix, without a loop in theano

description: Matrix divided by rows of another matrix, without a loop in theano


code:
#!/usr/bin/python

# datastruct
# name, avg, [scores]

datastruct = [
    ['AZ', 0.0, [0]],
    ['ED', 0.6666666666666666, [0, 1, 1]],
    ['JAKE', 2.0, [0, 4]],
    ['SAM', 0.0, [0]],
    ['ZAC', 0.0, [0]]
]

print('before')
for item in datastruct:
    print(item)

print('after')
for item in sorted(datastruct, key=lambda k: k[1], reverse=True):
    print("{}'s avg is: {}. From (up to 3) most recent scores which were: {}".format(item[0], item[1], item[2]))

rawDescription: Function produces output alphabetically, order by average score instead


code:
def define_var_hdr(size):
   class Var(Structure):
       fields = [("size", c_int),
                 ("Array", c_ubyte * size)]

   return Var

var_class_10 = define_var_hdr(10)
var_class_20 = define_var_hdr(20)
var_instance_10 = var_class_10()
var_instance_20 = var_class_20()

rawDescription: How do I emulate a dynamically sized C structure in Python using ctypes

description: Emulate a dynamically sized C structure in Python using ctypes


code:
ap = argparse.ArgumentParse()
ap.add_argument('-a')
args, unknown = ap.parse_known_args()
if args.a and '-x' in unknown:
    ap.add_argument('-x')
args = ap.parse_args()

rawDescription: Iterative command line arguments in Python


code: sum(a==b for a, b in zip('bob', 'boa'))

rawDescription: Count number of matches between two strings python


code:
from itertools import repeat
func(repeat(string_iterable))

rawDescription: Python method to remove iterability

description: Python method to remove iterability


code:
def counter():
    count = 0
    def c():
        nonlocal count
        count += 1
        return count
    return c

x = counter()
print([x(),x(),x()])

rawDescription: Read/Write Python Closures

description: Read/Write Python Closures


code:
# Import modules
import numpy as np
import os

main = 'root/dir'
dir = 'data_dir'
complete = os.path.join(main,dir)
ext = '.odt'     # Extension of the file to look for

# Initialize data array
all_data = []

for root, _, filenames in os.walk(path.complete):
    for filename in filenames:
        if os.path.splitext(filename)[-1] != ext:
            continue

        odt_data = {}
        # Only ODT-files
        # Extract parameters from filename
        odt_data['parameterx'], odt_data['parametery'] = filename.split('__')

        # Import data from file and assign to correct attribute of 'odt_data'
        fname = os.path.join(root, filename)
        data = np.loadtxt(fname)
        odt_data['data1'] = data[:,0]
        odt_data['data2'] = data[:,1]

        # Append new data to array of all data
        all_data.append(odt_data)

rawDescription: python class array with different data types

description: Python class array with different data types


code:
import requests
import json

url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
    "Host": "www.mywbsite.fr",
    "Connection": "keep-alive",
    "Content-Length": 129,
    "Origin": "https://www.mywbsite.fr",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Referer": "https://www.mywbsite.fr/data/mult.aspx",
    "Accept-Encoding": "gzip,deflate,sdch",
    "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)

rawDescription: python send POST with header

description: Python send POST with header


code:
s = "a \tb     c\t\t\td"
s.split()

rawDescription: Splitting strings separated by multiple possible characters?


code:
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.text import slugify

register = template.Library()

@register.filter
@stringfilter
def germanslugify(value):
    replacements = [(u'ä', u'ae')]
    for (s, r) in replacements:
            value = value.replace(s, r)
    return slugify(value)

rawDescription: django slugify - customize for german umlauts

description: Django slugify - customize for german umlauts


code: list(itertools.product(Is, Js, Ks))

rawDescription: Faster way to build list from array of floats


code:
lst = [string1, string2, string3, string4]  # BTW, `list` is a bad variable name
iterable = iter(lst)
for item in iterable:
    if condition(item):
        skipped = next(iterable, None)
        continue  # it's unclear from your question if you would want to continue or not...
    do_something(item)

rawDescription: looping lists, but skip element on a condition

description: Looping lists, but skip element on a condition


code:
with open(filename, 'rb') as h:
    data = csv.reader(h)
    headers = next(data)
    RowTuple = namedtuple('RowTuple', headers)
    for row in data:
        row = RowTuple(row)

rawDescription: Save memory overhead with DictReader

description: Save memory overhead with DictReader


code:
import tkinter as tk
import random

# Define some data. For each series, define the number of
# episodes in each season. For this example we're only defining
# one series.
APP_DATA = {"Castle": [10, 24, 24, 23, 24, 23]}

# Define which element of APP_DATA we want to use
SERIES="Castle"

# Define a function that can update the display with new results
def update_display():
    max_seasons = len(APP_DATA[SERIES])
    season = random.randint(1, max_seasons)
    # Note: list indexes start at zero, not one.
    # So season 1 is at index 0, etc
    max_episodes = APP_DATA[SERIES][season-1]
    episode = random.randint(1, max_episodes)

    text.delete("1.0", "end")
    text.insert("insert", "%s:\n" % SERIES)
    text.insert("insert", "The Random Season Chosen is Season %s\n" % str(season))
    text.insert("insert", "The Random Episode Chosen is Episode %s\n" % str(episode))

# Create a root window
root = tk.Tk()

# Create a text widget to "print" to:
text = tk.Text(root, width=40, height=4)

# Create a button to update the display
run_button = tk.Button(root, text="Click to run again", command=update_display)

# Arrange the widgets on the screen
text.pack(side="top", fill="both", expand=True)
run_button.pack(side="bottom")

# Display the first random values
update_display()

# Enter a loop, which will let the user click the button
# whenever they want
root.mainloop()

rawDescription: Custom Module in Window

description: Custom Module in Window


code: {s[0]:s[3:] for s in strlist}

rawDescription: Trouble With Dictionary Comprehension

description: Trouble With Dictionary Comprehension


code:
class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

rawDescription: Is there a way to keep lines from being skipped when using csv.dictWriter.writerow(somerow)


rawDescription: Using %f with strftime() in Python to get microseconds


code:
import operator
from itertools import izip
query = reduce(
    operator.or_,
    (Q(firstname=fn, lastname=ln) for fn, ln in izip(first_list, last_list))
    )

Person.objects.filter(query)

rawDescription: Django filter queryset on "tuples" of values for multiple columns


code:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, cbar=False, vmin=0, vmax=1)
cbar = ax.figure.colorbar(ax.collections[0])
cbar.set_ticks([0, 1])
cbar.set_ticklabels(["0%", "100%"])

rawDescription: Seaborn Heatmap Colorbar Label as Percentage


code:
from flask import make_response

@app.route('/index')
def index():
    resp = make_response("Hello, World!")
    resp.headers['server'] = 'ASD'
    return resp

rawDescription: Flask change the server header

description: Flask change the server header


code:
import scipy.io
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

data = scipy.io.loadmat('myfile.mat')
X = data['X']
Y = data['Y']
U = data['U']

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, U, rstride=1, cstride=1, cmap=cm.jet)
fig.colorbar(surf)

plt.show()

rawDescription: Plotting data contained in .mat file with python


code:
from typing import Union

class Bar:
    pass
class Baz:
    pass

def foo(garply : str) -> Union[Bar, Baz]:
    pass

rawDescription: Dynamic return types with PEP 484

description: Dynamic return types with PEP 484


code:
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

yellow_patch = mpatches.Patch(color='yellow')
blue_dotted_line = mlines.Line2D([], [], linewidth=2, linestyle="--", dashes=(3.7, 2), color='blue')
brown_line = mlines.Line2D([], [], linewidth=2, color='brown')

plt.legend([(yellow_patch, blue_dotted_line), brown_line], ["Entry One", "Entry Two"])

plt.show()

rawDescription: Overlay several artists in legend entry

description: Overlay several artists in legend entry


code:
#!/usr/bin/env/python
par = self.gui.get_widget('your_parent_window')

msg = gtk.MessageDialog(type=gtk.MESSAGE_INFO, buttons = gtk.BUTTONS_OK, parent=par)
if msg.run():
    msg.destroy()
    return None

rawDescription: pygtk: how to force message dialogs to show up in the center of the screen?

description: Pygtk: how to force message dialogs to show up in the center of the screen


code:
for rule in makelist(path) or yieldroutes(callback):
    for verb in makelist(method):
        verb = verb.upper()
        route = Route(self, rule, verb, callback, name=name,
                      plugins=plugins, skiplist=skiplist, **config)
        self.add_route(route)

rawDescription: How does python bottle framework install routing handler through decorator?


code:
with pd.option_context('mode.use_inf_as_null', True):
   df = df.dropna()

rawDescription: Keep finite entries only in Pandas

description: Keep finite entries only in Pandas


code: l2 = [{'score': (el['likes'] - el['dislikes']), 'title': el['title']} for el in l1]

rawDescription: How to make a new list of dicts from an old one in python?

description: Make a new list of dicts from an old one in python


code:
for i in range(5):
    obj = getattr(cpi6x, 'ONrelay{}'.format(i))
    cpi6x.setbit(board1, obj)
    time.sleep(.300)

rawDescription: Python help using for loop to change x

description: Python help using for loop to change x


code:
a = "aaabbbcccdddeeefffggg"
[a[i:i+3] for i in range(0, len(a), 3)]

rawDescription: How to turn a string of letters into 3 letter words in Python 2.7.1

description: Turn a string of letters into 3 letter words in Python 2.7.1


code:
import requests
import pandas
from bs4 import BeautifulSoup

url = 'http://hydromet.lcra.org/repstage.asp'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
tables = soup.find_all('table')

# convert the html table data into pandas data frames, skip the heading so that it is easier to add a column
df = pandas.read_html(str(tables[1]), skiprows={0}, flavor="bs4")[0]

# loop over the table to find out station id and store it in a dict obj
a_links = soup.find_all('a', attrs={'class': 'tablink'})
stnid_dict = {}
for a_link in a_links:
    cid = ((a_link['href'].split("dataWin('STAGE','"))[1].split("','")[0])
    stnid_dict[a_link.text] = cid

# add the station id column from the stnid_dict object above
df.loc[:, (len(df.columns)+1)] = df.loc[:, 0].apply(lambda x: stnid_dict[x])
df.columns = ['Station', 'Time', 'Stage', 'Flow', 'StationID']

# added custom order of columns to add in csv, and to skip row numbers in the output file
df.to_csv('station.csv', columns=['Station', 'StationID', 'Time', 'Stage', 'Flow'], index=False)

rawDescription: Scraping asp and java script generated table with python 2.7, beautiful soup and selenium


code:
for m in modules:
    globals()[m] = __import__(m)

rawDescription: How do I import modules from an array in python?

description: Import modules from an array in python