rawDescription: Qt designer Python Tableview Item

description: Qt designer Python Tableview Item


code:
class KpeWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self,parent)
        main = QVBoxLayout(self)

        label = QLabel(self)
        label.setText('Test the keyPressEvent')
        main.addWidget(label)

        self.adjustSize()
        self.setLayout(main)

    def keyPressEvent(self, event):
        QMessageBox.warning(self, 'MDI', 'keyPressEvent')
        self.parent().keyPressEvent(event)

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('KeyPressEvent Test')
        main = QVBoxLayout(self)
        child = KpeWindow(self)
        child.setFocusPolicy(Qt.StrongFocus)
        self.setFocusProxy(child)
        main.addWidget(child)
        child.setFocus(True)

        self.adjustSize()
        self.setLayout(main)

rawDescription: PyQt keyPressEvent not triggered from QDialog


code:
def eprimo(num):
    if num < 2:
        return False
    if num == 2:
        return True
    else:
        for div in range(2,num):
            if num % div == 0:
                return False
        return True

rawDescription: Python, prime number checker

description: Python, prime number checker


code:
import numpy as np
from mayavi import mlab
r = 1.0
phi, theta = np.mgrid[0:np.pi:200j, 0:2*np.pi:101j]

x = r*np.sin(phi)*np.cos(theta)
y = r*np.sin(phi)*np.sin(theta)
z = r*np.cos(phi)

intensity = phi * theta

obj = mlab.mesh(x, y, z, scalars=intensity, colormap='jet')
obj.enable_contours = True
obj.contour.filled_contours = True
obj.contour.number_of_contours = 20
mlab.show()

rawDescription: Python 3D plotting of measurement data

description: Python 3D plotting of measurement data


code:
class TestUser(TestCase):
    def setUp(self):
        db.create_all()

    def session_commit(self):
        try:
            db.session.commit()
        except:
            db.session.rollback()
        finally:
            pass

    def test_new_user(self):
        """
        test that new user is persisted in database
        """
        user = User('test_new_user@none.com', 'welcome')
        db.session.add(user)
        self.session_commit()
        users_in_db = db.session.query(User).all()
        self.assertEquals(1, len(users_in_db))
        self.assertEquals(user.email, users_in_db[0].email)
        self.assertEquals(user._password, users_in_db[0]._password)

    def tearDown(self):
        db.session.close()
        for tbl in reversed(db.metadata.sorted_tables):
            db.engine.execute(tbl.delete())

rawDescription: python PostgreSQL unit test not completing execution

description: Python PostgreSQL unit test not completing execution


code:
def grocery_list(foods):
    with open(foods, 'r') as L:
        food = []
        sublist = []

        while True:
            line = L.readline()
            if len(line) == 0:
                break

            #remove the trailing \n or \r
            line = line.rstrip()

            if len(line) == 0:
                food.append(sublist)
                sublist = []
            else:
                sublist.append(line)
        if len(sublist) > 0:
            food.append(sublist)

        return food

rawDescription: Python list building

description: Python list building


code:
keylist = os.listdir('./SomeFolder/')
keycount = len(keylist)

for keynum, key in enumerate(keylist, 1):
    print('{} : {}'.format(keynum, key))

rawDescription: Interactively selecting items from a list


code:
import re
startwith = "MOON"
endwith = "GOLF"
cklength = re.compile('.{' + str(len(startwith)) + '}(\n)?$', re.I)
filename = "C:/dict.txt"
words = set(x.strip().upper() for x in open(filename) if x.match(cklength))

rawDescription: Free word list for use programatically?

description: Free word list for use programatically


rawDescription: how to view doc on connect function in socket module in python

description: View doc on connect function in socket module in python


code:
def histogram(lenghts):
    xmax = max(lenghts.keys())
    ymax = max(lenghts.values())
    symbol = ""
    indexing = ""

    step = 10
    for j in range(ymax, -1, -step):
        if j % 100 < step:
            symbol = "{0:>3}{1:>3}".format(j, "-|")
        else:
            symbol = "{0:>3}{1:>3}".format(" ", "|")

        #fill histogram
        for i in range(1, xmax+1):
            if i in lenghts.keys() and lenghts[i] >= j:
                symbol += "***"
            else:
                symbol += "   "
        print(symbol)

    #x-axis
    symbol= "{0:>8}".format("-+--")
    for i in range(1, xmax+1):
        symbol += "+--"
    print(symbol)

    #indexing x-axis
    indexing = "    "
    for i in range(1, xmax+1):
        indexing += "{0:>3}".format(i)
    print(indexing)

lenghts = {4:104, 6:257, 10:157}
histogram(lenghts)

rawDescription: python - how to put values in a word length histogram

description: Python - how to put values in a word length histogram


rawDescription: How to simulate a "myscript.py > mylog.txt"

description: Simulate a "myscript.py > mylog.txt"


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import math

xdata = np.array([2.65, 2.80, 2.96, 3.80, 3.90, 4.60, 4.80, 4.90, 5.65, 5.92])
ydata = np.sin(xdata)

def func(x,p1,p2,p3): # HERE WE DEFINE A SIN FUNCTION THAT WE THINK WILL FOLLOW THE DATA DISTRIBUTION
    return p1*np.sin(x*p2+p3)

# Here you give the initial parameters for p0 which Python then iterates over
# to find the best fit
popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,1.0,1.0)) #THESE PARAMETERS ARE USER DEFINED

print(popt) # This contains your two best fit parameters

# Performing sum of squares
p1 = popt[0]
p2 = popt[1]
p3 = popt[2]
residuals = ydata - func(xdata,p1,p2,p3)
fres = sum(residuals**2)

print(fres) #THIS IS YOUR CHI-SQUARE VALUE!

xaxis = np.linspace(1,7,100) # we can plot with xdata, but fit will not look good
curve_y = func(xaxis,p1,p2,p3)
plt.plot(xdata,ydata,'*')
plt.plot(xaxis,curve_y,'-')
plt.show()

rawDescription: What is the most simple and proper way to fitting data to sinc function using by numpy?


code:
def on_touch_down(self, touch):
    if self.children[0] is self.img2:
        self.remove_widget(self.img1)
        self.add_widget(self.img1)
    else:
        self.remove_widget(self.img2)
        self.add_widget(self.img2)

rawDescription: How to change draw order of already created widgets?

description: Change draw order of already created widgets


code:
# This program computes
# the area of polygons
import math

def main():
    side_length = get_side_length()
    for number_of_sides in range(3, 10):
        report (side_length, number_of_sides)

def report(side_length, number_of_sides):
    area = polygon_area(number_of_sides, side_length)
    print('Side Length: {0}    Number of Sides: {1} Area: {2}'.format(side_length, number_of_sides, area))

def polygon_area( num_sides, side_length ):
    area = (num_sides * side_length * side_length) / (4 * math.tan(math.pi / num_sides))

def get_side_length():
    return int(input( 'Input the length of a side '))

# start the program
main()

rawDescription: Python: Area of a polygon

description: Python: Area of a polygon


code:
import svgwrite
from gi.repository import GdkPixbuf

drawing = svgwrite.Drawing(size=('100px', '100px'))
line = drawing.line(start=(50, 0), end=(50, 100), stroke='blue')
drawing.add(line)
encoded = drawing.tostring().encode()

loader = GdkPixbuf.PixbufLoader()
loader.write(encoded)
loader.close()
pixbuf = loader.get_pixbuf()

rawDescription: PyGI: Create pixbuf from 0

description: PyGI: Create pixbuf from 0


code:
import sys
import re
from os.path import join, dirname
def install_sip(version='6.0'):
    assert version in ('6.0', '8.0'), "unsupported version"
    keep = []
    if 'sip' in sys.modules:
       del sys.modules['sip']
    for path in sys.path:
        if not re.match('.*sip\d\.\d', path):
            keep.append(path)
    sys.path[:] = keep # remove other paths
    sys.path.append(join(dirname(__file__), 'sip-%s' % version))

rawDescription: Python: how to deal with several .pyd dependencies with the same name?


rawDescription: finding probablity of values in dictionary

description: Finding probablity of values in dictionary


code: urllib.quote_plus('hello how\'re you?')

rawDescription: Taking Spaces out of a string and Replacing them with "+"


code:
from django.views.generic.edit import ModelFormMixin, ProcessFormMixin

class MyView(ModelFormMixin, ProcessFormMixin):
    def get(self, request, *args, **kwargs):
        try:
            self.object = MyModel.objects.latest("id")
        except MyModel.DoesNotExist:
            self.object = None
        return super(MyView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        try:
            self.object = MyModel.objects.latest("id")
        except MyModel.DoesNotExist:
            self.object = None
        return super(MyView, self).post(request, *args, **kwargs)

rawDescription: Django Class Based View: retrieve lastly viewed entry


code:
from __future__ import print_function
import sys

class ScreenRes(object):
    @classmethod
    def set(cls, width=None, height=None, depth=32):
        '''
        Set the primary display to the specified mode
        '''
        if width and height:
            print('Setting resolution to {}x{}'.format(width, height, depth))
        else:
            print('Setting resolution to defaults')

        if sys.platform == 'win32':
            cls._win32_set(width, height, depth)
        elif sys.platform.startswith('linux'):
            cls._linux_set(width, height, depth)
        elif sys.platform.startswith('darwin'):
            cls._osx_set(width, height, depth)

    @classmethod
    def get(cls):
        if sys.platform == 'win32':
            return cls._win32_get()
        elif sys.platform.startswith('linux'):
            return cls._linux_get()
        elif sys.platform.startswith('darwin'):
            return cls._osx_get()

    @classmethod
    def get_modes(cls):
        if sys.platform == 'win32':
            return cls._win32_get_modes()
        elif sys.platform.startswith('linux'):
            return cls._linux_get_modes()
        elif sys.platform.startswith('darwin'):
            return cls._osx_get_modes()

    @staticmethod
    def _win32_get_modes():
        '''
        Get the primary windows display width and height
        '''
        import win32api
        from pywintypes import DEVMODEType, error
        modes = []
        i = 0
        try:
            while True:
                mode = win32api.EnumDisplaySettings(None, i)
                modes.append((
                    int(mode.PelsWidth),
                    int(mode.PelsHeight),
                    int(mode.BitsPerPel),
                    ))
                i += 1
        except error:
            pass

        return modes

    @staticmethod
    def _win32_get():
        '''
        Get the primary windows display width and height
        '''
        import ctypes
        user32 = ctypes.windll.user32
        screensize = (
            user32.GetSystemMetrics(0),
            user32.GetSystemMetrics(1),
            )
        return screensize

    @staticmethod
    def _win32_set(width=None, height=None, depth=32):
        '''
        Set the primary windows display to the specified mode
        '''
        # Gave up on ctypes, the struct is really complicated
        #user32.ChangeDisplaySettingsW(None, 0)
        import win32api
        from pywintypes import DEVMODEType
        if width and height:

            if not depth:
                depth = 32

            mode = win32api.EnumDisplaySettings()
            mode.PelsWidth = width
            mode.PelsHeight = height
            mode.BitsPerPel = depth

            win32api.ChangeDisplaySettings(mode, 0)
        else:
            win32api.ChangeDisplaySettings(None, 0)

    @staticmethod
    def _win32_set_default():
        '''
        Reset the primary windows display to the default mode
        '''
        # Interesting since it doesn't depend on pywin32
        import ctypes
        user32 = ctypes.windll.user32
        # set screen size
        user32.ChangeDisplaySettingsW(None, 0)

    @staticmethod
    def _linux_set(width=None, height=None, depth=32):
        raise NotImplementedError()

    @staticmethod
    def _linux_get():
        raise NotImplementedError()

    @staticmethod
    def _linux_get_modes():
        raise NotImplementedError()

    @staticmethod
    def _osx_set(width=None, height=None, depth=32):
        raise NotImplementedError()

    @staticmethod
    def _osx_get():
        raise NotImplementedError()

    @staticmethod
    def _osx_get_modes():
        raise NotImplementedError()

if __name__ == '__main__':
    print('Primary screen resolution: {}x{}'.format(
        *ScreenRes.get()
        ))
    print(ScreenRes.get_modes())
    #ScreenRes.set(1920, 1080)
    #ScreenRes.set() # Set defaults

rawDescription: Resize display resolution using python with cross platform support


code:
def _replaceitem(x):
    if x == '?':
        return 'i'
    elif x == 'x':
       return 10
    else:
        return x

a = map(_replaceitem, a)

rawDescription: Learning Python: Changing value in list based on condition


code:
class CustomUserSerializer(serializers.ModelSerializer):

    groups = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    def create(self, validated_data):
        user = CustomUser.objects.create_user(
            username    =validated_data['email'], # HERE
            email       =validated_data['email'],
            password    =validated_data['password'],
            first_name  =validated_data['first_name'],
            last_name   =validated_data['last_name'],
            avatar      =validated_data['avatar'],
        )

        user.groups = validated_data['groups']
        return user

    class Meta:
       model = CustomUser
       fields = (
           'id',
           'first_name',
           'last_name',
           'email',
           'password',
           'avatar',
           'groups'
       )

rawDescription: Viewset 'create' custom assign value in Django Rest Framework


code:
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
r.headers['content-type']
r.encoding
r.text
r.json()

rawDescription: Pulling data from a webserver

description: Pulling data from a webserver


code:
import numpy as np
import pandas as pd
import seaborn as sns
df = pd.DataFrame(dict(x=np.repeat([0, 3, 5, 6], 10),
                       y=np.random.randn(40)))
sns.boxplot(x="x", y="y", data=df, order=np.arange(7))

rawDescription: seaborn boxplots at desired distances along the x axis

description: Seaborn boxplots at desired distances along the x axis


code:
import tensorflow as tf
import numpy as np

# Define dimensions
d = 10     # Size of the parameter space
N = 1000   # Number of data sample

# create random data
w = .5*np.ones(d)
x_data = np.random.random((N, d)).astype(np.float32)
y_data = x_data.dot(w).reshape((-1, 1))

# Define placeholders to feed mini_batches
X = tf.placeholder(tf.float32, shape=[None, d], name='X')
y_ = tf.placeholder(tf.float32, shape=[None, 1], name='y')

# Find values for W that compute y_data = <x, W>
W = tf.Variable(tf.random_uniform([d, 1], -1.0, 1.0))
y = tf.matmul(X, W, name='y_pred')

# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y_ - y))
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# Before starting, initialize the variables
init = tf.initialize_all_variables()

# Launch the graph.
sess = tf.Session()
sess.run(init)

# Fit the line.
mini_batch_size = 100
n_batch = N // mini_batch_size + (N % mini_batch_size != 0)
for step in range(2001):
    i_batch = (step % n_batch)*mini_batch_size
    batch = x_data[i_batch:i_batch+mini_batch_size], y_data[i_batch:i_batch+mini_batch_size]
    sess.run(train, feed_dict={X: batch[0], y_: batch[1]})
    if step % 200 == 0:
        print(step, sess.run(W))

rawDescription: How to implement multivariate linear stochastic gradient descent algorithm in tensorflow?

description: Implement multivariate linear stochastic gradient descent algorithm in tensorflow


code:
def undefaulted(x):
  return dict(
    (k, undefaulted(v))
    for (k, v) in x.iteritems()
  ) if isinstance(x, nesteddict) else x

a = undefaulted(a)

rawDescription: How do I convert a derived recursive data type to a base data type?

description: Convert a derived recursive data type to a base data type


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

x = np.linspace(1,2,10)
y = np.linspace(1,2,10)

plt.plot(x[:4],y[:4],'-ko',x[3:],y[3:],'--ko')
plt.show()

rawDescription: using more than one linestyle in the same trend line with matplotlib

description: Using more than one linestyle in the same trend line with matplotlib


code:
TourItemFormSet = inlineformset_factory(Tour,TourItem,can_delete=True,extra=4)
TourItemFormSet.form.base_fields["TourItemType"].queryset = TourItemType.objects.filter(Lang__iexact=request.LANGUAGE_CODE)
# then create an instance of TourItemFormSet and add to template context

rawDescription: filtering fields of an inlineformset_factory

description: Filtering fields of an inlineformset_factory


code:
import unittest

import os
import sys
import subprocess
import time

import dbus
import dbus.service
import dbus.glib
import gobject

class MyDBUSService(dbus.service.Object):

    def __init__(self):
    	bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus())
    	dbus.service.Object.__init__(self, bus_name, '/test/helloservice')

    def listen(self):
    	loop = gobject.MainLoop()
    	loop.run()

    @dbus.service.method('test.helloservice')
    def hello(self):
    	return "Hello World!"

class BaseTestCase(unittest.TestCase):

    def setUp(self):
    	env = os.environ.copy()
    	self.p = subprocess.Popen(['python', './dbus_practice.py', 'server'], env=env)
    	# Wait for the service to become available
    	time.sleep(1)
    	assert self.p.stdout == None
    	assert self.p.stderr == None

    def testHelloService(self):
    	bus = dbus.SessionBus()
    	helloservice = bus.get_object('test.helloservice', '/test/helloservice')
    	hello = helloservice.get_dbus_method('hello', 'test.helloservice')
    	assert hello() == "Hello World!"

    def tearDown(self):
    	# terminate() not supported in Python 2.5
    	#self.p.terminate()
    	os.kill(self.p.pid, 15)

if __name__ == '__main__':

    arg = ""
    if len(sys.argv) > 1:
    	arg = sys.argv[1]

    if arg == "server":
    	myservice = MyDBUSService()
    	myservice.listen()

    else:
    	unittest.main()

rawDescription: How to write a functional test for a DBUS service written in Python?

description: Write a functional test for a DBUS service written in Python


code:
form = methodThatGetsForm(somearg)
new_form = ExampleModelForm(form.cleaned_data, instance=ExampleModel.objects.get(pk=getID(somearg)))
new_form.save()

rawDescription: django change model form instance

description: Django change model form instance


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""csv_dict.py
"""
import csv
import pprint
from collections import namedtuple

Row = namedtuple('Row', [
    'name',
    'value_1',
    'value_2',
    'extra_name',
    'extra_value_1',
    'extra_value_2'
])

l = [
    ('Apple', 1, 2, {'gala': (2, 1.0)}),
    ('Grape ', 2, 4, {'malbec': (4, 0.25), 'merlot': (4, 0.75)}),
    ('Pear', 4, 5, {
        'anjou': (5, 0.2),
        'bartlet': (5, 0.4),
        'seckel': (5, 0.2)}
    ),
    ('Berry', 5, 5, {
        'blueberry': (5, 0.2),
        'blackberry': (5, 0.2),
        'straw': (5, 0.2)
    })
]

print('List before writing: ')
pprint.pprint(l)

# Writing the data.
with open('test1.csv', 'wb') as fout:
    writer = csv.writer(fout)

    for row in l:
        for k, v in row[3].iteritems():
            writer.writerow(row[0:3] + (k,) + v)

# Reading the data.
format_extra = lambda row: (int(row.extra_value_1), float(row.extra_value_2))

with open('test1.csv', 'rU') as fin:
    reader = csv.reader(fin)

    ll = []
    hl = {}

    for row in (Row(*r) for r in reader):
        if row.name in hl:
            ll[hl[row.name]][3][row.extra_name] = format_extra(row)
            continue

        ll.append(row[0:3] + ({
            row.extra_name: format_extra(row)
        },))
        hl[row.name] = len(ll) - 1

    pprint.pprint(ll)

rawDescription: How to write a list with a nested dictionary to a csv file?

description: Write a list with a nested dictionary to a csv file


code:
import textwrap
s = 'aaaaaaaaaaaaaaaaaaaaaaa'
textwrap.wrap(s, 4)

rawDescription: Split a string to even sized chunks

description: Split a string to even sized chunks


code:
import numpy as np
type(a)
type(a).__module__
type(a).__module__ == np.__name__

rawDescription: How to identify numpy types in python?

description: Identify numpy types in python


code:
def filter_by_vowel_count(words, count):
    result = []
    for word in words:
        if sum(p in 'aeiou' for p in word) == count:
            result.append(word)
    return result
fruits = ['banana', 'apple', 'lemon', 'pineapple', 'coconut']
filter_by_vowel_count(fruits, 2)
filter_by_vowel_count(fruits, 3)

rawDescription: Function to return a list filtered by vowel count in Python


rawDescription: Creating instances of class based on string name of class


code:
def score(key_str,dct):
    keys = key_str.split()
    v = sum(dct[key] for key in keys)
    return float(v)/len(keys)

rawDescription: Computing average of scores for strings in a dictionary


code:
from datetime import timedelta
from flask import session, app

@app.before_request
def make_session_permanent():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=5)

rawDescription: Is there an easy way to make sessions timeout in flask?


code:
import wx
from floatcanvas import FloatCanvas

class MyPanel(wx.Panel):
    def __init__(self, parent):
        super(MyPanel, self).__init__(parent)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)

        # add a canvas
        self.Canvas = FloatCanvas.FloatCanvas(self, BackgroundColor = "LIGHT GREY")
        self.Canvas.Bind(wx.EVT_SIZE, self.OnSize)
        self.sizer.Add(self.Canvas, -1, flag=wx.EXPAND)

        # add a toggle button
        image_dis = wx.Image('file_disabled.png')
        image_ena = wx.Image('file_enabled.png')
        img_dis = self.Canvas.AddScaledBitmap(image_dis, (x,-y), Height=image_dis.GetHeight(), Position = 'tl')
        img_ena = self.Canvas.AddScaledBitmap(image_ena, (x,-y), Height=image_ena.GetHeight(), Position = 'tl')
        img_dis.other = img_ena
        img_ena.other = img_dis
        img_ena.Visible = False

        # bind the toggle button event
        img_dis.Bind(FloatCanvas.EVT_FC_LEFT_UP, self.OnToggle)
        img_ena.Bind(FloatCanvas.EVT_FC_LEFT_UP, self.OnToggle)

    def OnToggle(self, button):
        button.other.Visible = True
        button.Visible = False
        self.Canvas.Draw(True)

    def OnSize(self, event):
        event.Skip()
        wx.CallLater(1, self.Canvas.ZoomToBB)

rawDescription: wxPython for image and buttons (resizable)

description: WxPython for image and buttons (resizable)


code:
import datetime as dt
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
x = []
d = dt.datetime(2013, 7, 4)
for i in range(30):
        d = d+dt.timedelta(days=1)
        x.append(d)

y = range(len(x))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.bar(x, y, align='center') # center the bars on their x-values
plt.title('DateLocator with interval=5')
plt.gcf().autofmt_xdate()
plt.show()

rawDescription: Not write out all dates on an axis, Matplotlib


code:
html
soup = BeautifulSoup(html)
ass = soup.find_all('a')
r = re.compile('uid=(\d+)')
uids = []
for a in ass:
    uids.append(r.search(a['href']).group(1))

uids

rawDescription: python extract id value from href source

description: Python extract id value from href source


code:
import urllib
data = urllib.urlencode({"postField1" : "postValue1", "postField2" : "postValue2", "etc" : "etc"})
f = urllib.urlopen("http://www.domain.com/storePostData.php", data)
# At this point your storePostData.php file stores all the post
# info in either an sql DB or temporary file so this can accessed later on and
# an uuid is passed back which we now read below. In may case I store all post
# fields in a sql DB and each column represents each post field.
uuid = f.read()
# the uuid is the sql table id field which is auto_incremented.
# SO now we load the default browser below and send it the uuid so the php script
# can access the sql data. Once it has been accessed and the form fields have been
# received then we delete that row as the information is useless to us now that we
# have filled in the forms fields
import webbrowser
webbrowser.open_new("http://www.domain.com/someOtherUrl?uuid=" + uuid)

rawDescription: How can I use python to load a browser session that posts values to a url?

description: Use python to load a browser session that posts values to a url


code:
from collections import defaultdict

words = "apple banana apple strawberry banana lemon"

d = defaultdict(int)
for word in words.split():
    d[word] += 1

rawDescription: item frequency count in python

description: Item frequency count in python


rawDescription: python to change '|' into tab delimenated

description: Python to change '|' into tab delimenated


code:
import math
math.exp(709)
math.exp(710)

rawDescription: Scipy expit: Unexpected behavour. NaNs

description: Scipy expit: Unexpected behavour. NaNs


code:
from win32com.client import Dispatch
ex = Dispatch("Excel.Application")
# you can use the ex object to invoke Excel methods etc.

rawDescription: use python to generate graph in excel

description: Use python to generate graph in excel


rawDescription: In django, how can I filter or exclude multiple things?


code:
import re
s = 'Global across "Modules" ?'
'-'.join(item.lower() for item in re.findall(r'\w+', s))

rawDescription: Python code to create link based on the title


code:
class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.everb5 = Entry(self)
        self.everb5.grid(row = 19, column = 2) #<-- here
        self.btn = Button(self, text = "Generate", command = self.generate)
        self.btn.grid(row = 25, column = 3, columnspan = 3) #<-- here

    def generate(self):
        self.everb5.config(text= "Hello")

rawDescription: Python error when trying to use multiple functions in a class. Tkinter


code:
p = c_char_p("Hello, World")
p
type(p)
s = p.value
s
type(s)

rawDescription: Retrieve the string from ctypes's c_char_p


rawDescription: invert a tuple array python

description: Invert a tuple array python


code:
def parse_xml_document(self, response):

    xxs = XmlXPathSelector(response)

    items = []

    # common field values
    stateOrCountryDescription = xxs.select('./primaryIssuer/issuerAddress/stateOrCountryDescription/text()').extract()[0]
    zipCode = xxs.select('./primaryIssuer/issuerAddress/zipCode/text()').extract()[0]
    issuerPhoneNumber = xxs.select('./primaryIssuer/issuerPhoneNumber/text()').extract()[0]

    for person in xxs.select('./relatedPersonsList//relatedPersonInfo'):

        # instantiate one item per loop iteration
        item = SecformD()

        # save common parameters
        item["stateOrCountryDescription"] = stateOrCountryDescription
        item["zipCode"] = zipCode
        item["issuerPhoneNumber"] = issuerPhoneNumber

        item["firstName"] = person.select('./relatedPersonName/firstName/text()').extract()[0]
        item["middleName"] = person.select('./relatedPersonName/middleName/text()')
        if item["middleName"]:
            item["middleName"] = item["middleName"].extract()[0]
        else:
            item["middleName"] = "NA"

        items.append(item)

    return items

rawDescription: How to use a for loop in Scrapy?

description: Use a for loop in Scrapy


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

import cairo

# You need colors in rgb floats

Dict= {(70,60): (1,1,0), (100,90): (0,1,0), (130,120): (0,0,1)}
your_dict={(0,0): (1,0,0)}

radius=10 # The radius of the dot

w=100 # width of the square
h=100 # height of the square

WIDTH, HEIGHT = 200, 200 # Canvas size

surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
context = cairo.Context (surface)

# Background Neutral Gray ----------
context.set_source_rgb(0.25, 0.25, 0.25)
context.rectangle(0, 0, WIDTH, HEIGHT)
context.fill()

# Your Square -----------------------

for e in your_dict:
    posX = e[0]
    posY = e[1]

    r = your_dict[e][0]
    g = your_dict[e][1]
    b = your_dict[e][2]

    context.set_source_rgb(r, g, b) # rgb color
    context.rectangle(posX, posY, w, h)
    context.fill()

# White Example Circle -------------------
context.set_source_rgb(1, 1, 1) # rgb color
context.arc(20, 20, 10.0, 0, 360)
context.fill()

# Dots from Dict -------------------

for e in Dict:

    posX = e[0]
    posY = e[1]

    r = Dict[e][0]
    g = Dict[e][1]
    b = Dict[e][2]

    context.set_source_rgb(r, g, b) # rgb color
    context.arc(posX, posY, radius, 0, 360)
    context.fill()

surface.write_to_png ("img.png") # Output to PNG

rawDescription: Writing a dict into a png file

description: Writing a dict into a png file


rawDescription: How to convert Series into DataFrame preserving the columns?

description: Convert Series into DataFrame preserving the columns


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

df = pd.DataFrame({'x': [0, 1], 'y': [0, 1]})
plt.plot(df['x'], df['y'], label='')
plt.legend(loc='best')

rawDescription: How can I disable the label when plotting pandas data?

description: Disable the label when plotting pandas data


code:
import pylab as pl
import numpy as np
cm = pl.get_cmap('OrRd')

x = np.linspace(0, 1, 100)

def update_colors(ax):
    lines = ax.lines
    colors = cm(np.linspace(0, 1, len(lines)))
    for line, c in zip(lines, colors):
        line.set_color(c)

fig, ax = pl.subplots()
for i in range(10):
    ax.plot(x, x**(1+i*0.1))
    update_colors(ax)

rawDescription: Matplotlib: change colormap after the fact


code:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations
from django.conf import settings

sql = """UPDATE django_content_type
         SET name = 'member',
             model = 'member'
         WHERE name = 'profile' AND
               model = 'profile' AND
               app_label = 'open_humans';"""

reverse_sql = """UPDATE django_content_type
                 SET name = 'profile',
                     model = 'profile'
                 WHERE name = 'member' AND
                       model = 'member' AND
                       app_label = 'open_humans';"""

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('open_humans', '0004_auto_20150106_1828'),
    ]

    operations = [
        migrations.RunSQL(sql, reverse_sql)
    ]

rawDescription: Django rename model. New django_content_type is created instead of renaming the old record


code:
import csv

with open('somefile.csv') as f:
  reader = csv.DictReader(f, delimiter=',')
  rows = list(reader)

for row in rows:
   print(row['Energy'])

rawDescription: Error while reading csv file using python


rawDescription: Convert first element of list A to list of first two elements of list A


code:
keys = set()
biglist = [keys.add(sublist[0]) or sublist
              for sublist in biglist
                  if sublist[0] not in keys]
del keys # if you don't need it any more

rawDescription: How do I remove partial duplicates from an unsorted list in Python?

description: Remove partial duplicates from an unsorted list in Python


code:
import PyV8
ctxt = PyV8.JSContext()          # create a context with an implicit global object
ctxt.enter()                     # enter the context (also support with statement)
ctxt.eval("1+2")

rawDescription: calling javascript in python?

description: Calling javascript in python


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

# (modified from one of the matplotlib gallery examples)
resolution = 50 # the number of vertices
N = 100
x       = np.random.random(N)
y       = np.random.random(N)
radii   = 0.1*np.random.random(N)
patches = []
for x1,y1,r in zip(x, y, radii):
    circle = Circle((x1,y1), r)
    patches.append(circle)

fig = plt.figure()
ax = fig.add_subplot(111)

colors = 100*np.random.random(N)
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
p.set_array(colors)
ax.add_collection(p)
plt.colorbar(p)

plt.show()

rawDescription: setting color range in matplotlib patchcollection

description: Setting color range in matplotlib patchcollection


code:
import csv
import time
import numpy as np

count = 0

with open('test.csv','r') as infile:
    reader=csv.reader(infile, delimiter='\t',lineterminator='\n',)
    reader.next()
    for row in reader:
        rec = np.fromiter(row[1:], dtype=np.float32)
        if (rec > 0.5).sum() >= (len(rec) - 1) * 0.5:
            count += 1

rawDescription: calculation of no. of rows (data from csv) satisfying condition and also slower code

description: Calculation of no. of rows (data from csv) satisfying condition and also slower code


code:
import win32file

win32file.QueryDosDevice('E:')

rawDescription: How can I get the NT name of a partition in python (Windows)?

description: Get the NT name of a partition in python (Windows)


code:
play = input('| Please enter h or s (h = Hit, s = Stand:) ')
while play == 's' and totalplayer <= 15:
    print('Cannot stand on value less then 15')

rawDescription: blackjack python code player cannot stand on a value of 15 or less

description: Blackjack python code player cannot stand on a value of 15 or less


code:
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.stacked_widget = QtGui.QStackedWidget()
        self.button = QtGui.QPushButton("Next")

        self.button.clicked.connect(self.__next_page)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.stacked_widget)
        layout.addWidget(self.button)

        widget = QtGui.QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.stacked_widget.addWidget(QtGui.QLabel("Page 1"))
        self.stacked_widget.addWidget(QtGui.QLabel("Page 2"))
        self.stacked_widget.addWidget(QtGui.QLabel("Page 3"))

    def __next_page(self):
        idx = self.stacked_widget.currentIndex()
        if idx < self.stacked_widget.count() - 1:
            self.stacked_widget.setCurrentIndex(idx + 1)
        else:
            self.stacked_widget.setCurrentIndex(0)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())

rawDescription: How can i create Multi-page applications in PyQt4?

description: Create Multi-page applications in PyQt4


rawDescription: How to glob only files without an extension?

description: Glob only files without an extension


code:
from multiprocessing import Pool, Manager, current_process
import time

def do_work(x, ll):
    time.sleep(.2)
    ll.append(current_process().name + ' took task '+str(x)+' at '+str(time.time()))

if __name__ == '__main__':
    with Manager() as manager:
        timestamp = manager.list()
        p = Pool(processes=4)
        for x in range(10):
            p.apply_async(do_work, (x, timestamp))
        p.close()
        p.join()
        print(timestamp)

rawDescription: Python multiprocessing apply_async read/write var in main process at starting subprocess


code:
import re

regex = re.compile('==============.+?==============', re.DOTALL)

with open('in.txt', 'r') as f:
    content = f.read()
matches = regex.findall(content)

rawDescription: Read file, create new file with only the blocks of snippets in it


code:
import pylab as pl
from matplotlib.ticker import FixedLocator, FormatStrFormatter

pl.plot(range(100))

pl.axes().xaxis.set_major_locator(FixedLocator(range(0, 100, 10)))
pl.axes().xaxis.set_minor_locator(FixedLocator(range(5, 100, 10)))
pl.axes().xaxis.set_minor_formatter(FormatStrFormatter("%d"))
pl.axes().tick_params(which='major', pad=20, axis='x')

rawDescription: Alternating tick labels in matplotlib

description: Alternating tick labels in matplotlib


code:
def combos(data):
    for i in xrange(1, len(data) + 1):
        for item in itertools.combinations(data, i):
            for j in itertools.product(*item):
                yield j

rawDescription: itertools and selection from partitioned sets

description: Itertools and selection from partitioned sets


code:
if request.method == 'POST':
    from django.core.files.uploadedfile import SimpleUploadedFile
    object = Model.objects.get(pk=1)
    file_contents = SimpleUploadedFile("%s.mp3" % "myfile", request.raw_post_data, "audio/mp3")
    object.audio.save("%s.mp3" % "myfile", upfile, True)

rawDescription: Save raw_post_data to FileField using Django


rawDescription: Python regular expressions repeated sequence of decimal number followed by whitespaces


code:
from tkinter import *
import subprocess

output = subprocess.check_output('sleep 2 ; date', shell=True)

win = Tk()
f1 = Frame( win )
tp = Label( f1 , text='Date: ' + str(output[:-1]))
f1.pack()
tp.pack()

def task():
    output = subprocess.check_output('date', shell=True)
    tp.configure(text = 'Date: ' + str(output[:-1]))
    win.after(2000, task)
win.after(2000, task)

win.mainloop()

rawDescription: How to repeat command in Python indefinitely

description: Repeat command in Python indefinitely


code:
import csv
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import matplotlib

def plot_bar(dataset):
    matplotlib.rc('font', family='sans-serif')
    matplotlib.rc('font', serif='Helvetica Neue')
    matplotlib.rc('text', usetex='false')
    matplotlib.rcParams.update({'font.size': 30})
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(30.0,7.5)
    N = len(dataset[1])

    Load    = dataset[0]
    QoS     = dataset[1]
    Energy  = dataset[2]

    ind = np.arange(N)
    width = 0.35
    spare_width = (1 - width*2)/2

    plt.tick_params(axis='both', which='major', labelsize=35, pad=15)
    plt.tick_params(axis='y', which='minor', labelsize=35, pad=15)

    rects1 = ax.bar(ind, QoS, width,
                color='0.2',
                label='HP')

    rects3 = ax.bar(ind+width, Energy, width,
                color='0.4',
                label='OM')

    lns = [rects1, rects3]
    labs = [l.get_label() for l in lns]

    ax.legend(lns, labs, ncol=2, fontsize=30,framealpha=0)

    ax.set_xlim(-spare_width,len(ind)-spare_width)
    ax.set_ylim(0, 16000)

    ax.set_ylabel('RPS/Watt', fontsize=35)
    ax.set_xlabel('Percentage of Max Capacity', fontsize=35)

    xTickMarks = dataset[0]
    ax.set_xticks(ind+width)
    xtickNames = ax.set_xticklabels(xTickMarks)
    plt.setp(xtickNames, rotation=0, fontsize=40)
    plt.xticks([])
    ax.yaxis.grid()

    cell_text = [['2S\n0.65', '3S\n0.65', '4S\n0.65', '4S\n0.65',
                  '2B2S\n1.15','2B2S\n1.15', '3B2S\n1.15', '2S\n1.15',
                  '2S\n1.15', '2S\n1.15', '2S\n1.15','2S\n1.15',
                  '2S\n1.15', '2S\n1.15', '2S\n1.15', '2S\n1.15'],
            ['2S\n0.65', '3S\n0.65', '4S\n0.65', '4S\n0.65',
             '2S\n1.15', '2S\n1.15', '2S\n1.15', '2S\n1.15',
             '2S\n1.15', '2S\n1.15', '2S\n1.15', '2S\n1.15',
             '2S\n1.15', '2S\n1.15', '2S\n1.15', '2B\n1.15']]
    colors=['0.2','0.4']
    rows = ['HP\nGHz','OM\nGHz']
    Loc='right'
    the_table = plt.table(cellText=cell_text,
                          rowLabels=rows,
                          colLabels=Load,
                          rowColours=colors,
                        cellLoc='center',
                          loc='bottom',
                          bbox=[0,-0.65,1,0.65])#x,y,w,h
    the_table.scale(1,2.5)

    the_table.auto_set_font_size(False)
    the_table.set_fontsize(35)
    plt.subplots_adjust(left=0.2, bottom=0.2)

    ax.xaxis.labelpad = 260

    ax.yaxis.labelpad = 20
    fig.savefig('rps-watt' +'.eps',format='eps',bbox_inches='tight', pad_inches=0.1, dpi=1000)

dataset = [['29%', '40%', '51%', '63%', '69%', '71%', '74%', '77%', '80%', '83%', '86%', '89%', '91%', '94%', '97%', '100%'], [6524.0, 8749.0, 10470.0, 13096.0, 13126.0, 12965.0, 13493.0, 13717.0, 14351.0, 14993.0, 15308.0, 14320.0, 13179.0, 9809.0, 10168.0, 10621.0], [6524.0, 8749.0, 10470.0, 13096.0, 6827.0, 5586.0, 7697.0, 8205.0, 8298.0, 8733.0, 8887.0, 9278.0, 9659.0, 9809.0, 10168.0, 10621.0]]
plot_bar(dataset)

rawDescription: Aligning table to x-axis using matplotlib python


rawDescription: Python List Class __contains__ Method Functionality


code:
import nltk
s = "This is some sample data.  Nltk will use the words in this string to make ngrams.  I hope that this is useful.".split()
model = nltk.NgramModel(2, s)
model._ngrams

rawDescription: Training Naive Bayes Classifier on ngrams


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

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 10):
    ax.plot(x, i * x + x, picker=5)

def on_pick(event):
    event.artist.set_visible(not event.artist.get_visible())
    fig.canvas.draw()

fig.canvas.callbacks.connect('pick_event', on_pick)
plt.show()

rawDescription: Matplotlib event_handling line picker

description: Matplotlib event_handling line picker


code:
import numpy as np
n = 2
u = np.array([v for v in range(19*n)])
u = u.reshape(n,19)
sorted(c, key=np.average)

rawDescription: Sorting containers in Python/numpy

description: Sorting containers in Python/numpy


rawDescription: Get request object in a db model?

description: Get request object in a db model


code:
import glob, os
for filename in glob.glob(os.path.join(yourPath, "*&*")):
   os.rename(filename, filename.replace('&','+'))

rawDescription: Rename files, Python/Jython

description: Rename files, Python/Jython


code:
from __future__ import print_function
from pylab import arange, plot, sin, ginput, show
import matplotlib as plt
from pylab import *
import numpy as np

def closest_point(vec,val):
    ind = np.where(vec==min(vec,key=lambda x:abs(x-val)))
    return ind[0][0]

t = np.linspace(0,250,5000)
y = sin(t)

fig = plt.figure()
plt.suptitle('chosing points over a possibly dense signal...',fontsize=14)
zoom_ok = False
while not zoom_ok:
    plt.plot(t,y)
    plt.title('1 - click on the two corners of the area to enlarge',fontsize=12)
    zoom = ginput(2,timeout=-1)
    xzoom = np.zeros([0])
    for i in range(2):
        xzoom = np.concatenate((xzoom,[int(closest_point(t,zoom[i][0]))]))
    temps_zoom = t[xzoom[0]:xzoom[1]]
    dep_zoom = y[xzoom[0]:xzoom[1]]
    plt.clf()
    plt.plot(temps_zoom,dep_zoom,'b')
    plt.title('2 - if zoom ok -> press Enter, otherwise -> mouse click',fontsize=12)
    zoom_ok = plt.waitforbuttonpress()
plt.title('3 - you may now select the points ',fontsize=16)
x = ginput(2,timeout=-1)
plt.show()

rawDescription: can Python Matplotlib "ginput" be independent from "zoom to rectangle"?

description: Can Python Matplotlib "ginput" be independent from "zoom to rectangle"


code:
files_url = "%s/files/content" % (settings.BOX_API_HOST)
headers = {"Authorization": "BoxAuth api_key=%s&auth_token=%s" %
              (settings.BOX_API_KEY, self.doctor.box_auth_token)
          }

file_root, file_suffix = os.path.splitext(str(self.document))
filename = "%s%s" % (slugify(self.description), file_suffix)
files = {
        'filename1': open(settings.MEDIA_ROOT + str(self.document), 'rb'),
        }
data = {
        'filename1': filename,
        'folder_id': str(self.patient.get_box_folder()),
       }

r = requests.post(files_url,
                  headers=headers,
                  files=files,
                  data=data)

file_response = simplejson.loads(r.text)

try:
    if int(file_response['entries'][0]['id']) > 0:
        box_file_id = int(file_response['entries'][0]['id'])

        #Update the name of file
        file_update_url = "%s/files/%s" % (settings.BOX_API_HOST, box_file_id)
        data_update = {"name":  filename}
        file_update = requests.put(file_update_url,
                                   data=simplejson.dumps(data_update),
                                   headers=headers)

        LocalDocument.objects.filter(id=self.id).update(box_file_id=box_file_id)
except:
    pass

rawDescription: Upload file using python requests

description: Upload file using python requests


code:
def obj_update(self, bundle, **kwargs):
        old_text = bundle.obj.text
        new_text = bundle.data['text']
        Comment.objects.filter(uuid=bundle.data['uuid']).update(text=new_text) # update comment
        c = Comment.objects.get(uuid=bundle.data['uuid'])
        EditedComment(cmt=c, old_text = old_text, new_text = new_text).save()
        return bundle

rawDescription: How to write helper method for PATCH request using django-tastypie?

description: Write helper method for PATCH request using django-tastypie


code: dict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))

rawDescription: Parse a map of int -> list from a string


code:
from compiler.ast import flatten

A=[['11@N3'], ['23@N0'], ['62@N0'], ['99@N0'], ['47@N7']]
B=[['23@N0'], ['12@N1']]

a = flatten(A)
b = flatten(B)
common_elements = list(set(a).intersection(set(b)))
common_elements
['23@N0']

rawDescription: Finding intersection of two lists of strings in python


code:
import inspect
inspect.getfile(inspect) # returns '/usr/lib/python2.7/inspect.pyc'

rawDescription: Check path to imported module without __file__


code:
products = (OrderProduct.objects
            .filter(order_id=order.id)
            .values('product_id'))
Product.objects.filter(id__in=products)

rawDescription: Django multipart ORM query including JOINs


rawDescription: iterate over a len of list in Django Template

description: Iterate over a len of list in Django Template


code:
from multiprocessing import Process, Queue

def square(a, qOut):
    qOut.put(a**2)

if __name__ == "__main__":
    qOut = Queue()
    params = (10, 20, 30)
    jobs = []
    for p in params:
        proc = Process(target=square, kwargs={'a':p, 'qOut':qOut})
        jobs.append(proc)
        proc.start()
    for job in jobs:
        job.join()
    for i in range(len(params)):
        print(qOut.get())

rawDescription: How to join returned data from different processes

description: Join returned data from different processes


code:
class MyTests(unittest.TestCase):
    #  ....
    def shortDescription(self):
        return None

rawDescription: How to stop Python unittest from printing test docstring?

description: Stop Python unittest from printing test docstring


code:
def foo(start, stop=None, step=1):
    if stop == None:
        start, stop = 0, start
    #rest of the code goes here

rawDescription: optional arguments of functions in python

description: Optional arguments of functions in python


code:
import wx
import wx.lib.scrolledpanel as scrolled

########################################################################
class MyPanel(scrolled.ScrolledPanel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        super(MyPanel, self).__init__(parent,
                                      style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
        self.SetupScrolling()

        box = wx.StaticBox(self, label="Test Box")
        bsizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        for i in range(15):
            txt = wx.TextCtrl(self)
            bsizer.Add(txt, 0, wx.ALL, 5)

        main_sizer = wx.BoxSizer()
        main_sizer.Add(bsizer, 1, wx.EXPAND)
        self.SetSizer(main_sizer)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        super(MainFrame, self).__init__(None, title="Static")
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: wxPython need to add scrollbar to StaticBox; is this possible?

description: WxPython need to add scrollbar to StaticBox; is this possible


code:
from django.contrib.auth.models import *
from django.db import connection
connection.queries
query = User.objects.filter(pk=1)
connection.queries
query.exists()
connection.queries
query.get()
connection.queries

rawDescription: When is a Django QuerySet evaluated?

description: When is a Django QuerySet evaluated


code:
def roll_dice():
    return (random.randint(1,6), random.randint(1,6))

equal_7 = 0
doubles = 0
ten_or_more = 0

for i in range(100):
    d1, d2 = roll_dice()
    if d1 + d2 == 7:
        equal_7 += 1
    if d1 == d2:
        doubles += 1
    if d1 + d2 >= 10:
        ten_or_more += 1

rawDescription: Roll Two Dice Python 3.5.1

description: Roll Two Dice Python 3.5.1


code:
sprite_back = pygame.image.load('CharacterBack.png')
sprite_front = pygame.image.load('CharacterFront.png')
sprite_right = pygame.image.load('CharacterRight.png')
sprite_left = pygame.image.load('CharacterLeft.png')

sprite = sprite_front

while True:

    DISPLAYSURF.blit(sprite,(spritex,spritey))

    if charLeft == True:
        spritex -= 10
    elif charRight == True:
        spritex += 10
    elif charUp == True:
        spritey -= 10
    elif charDown == True:
        spritey += 10

    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()

        if event.type == KEYDOWN:
            if (event.key == K_LEFT):
                charLeft = True
                sprite=sprite_left
            elif (event.key == K_d):
                charRight = True
                sprite=sprite_right
            elif (event.key == K_w):
                charUp = True
                sprite=sprite_back
            elif (event.key == K_s):
                charDown = True
                sprite=sprite_front
        if event.type == KEYUP:
            if (event.key == K_LEFT):
                charLeft = False
            elif (event.key == K_d):
                charRight = False
            elif (event.key == K_w):
                charUp = False
            elif (event.key == K_s):
                charDown = False

rawDescription: Pygame: Why won't my Movement code work?

description: Pygame: Why won't my Movement code work


code:
class InboundEmailHandler(base.BaseHandler):

    def head(self):
        """ Satisfy Mandril that this url exists"""
        self.finish()

rawDescription: tornado requesthandler overwrite head method

description: Tornado requesthandler overwrite head method


rawDescription: Can you do LINQ-like queries in a language like Python or Boo?

description: Do LINQ-like queries in a language like Python or Boo


code:
from datetime import datetime,timedelta
from suds.client import Client

client = Client(MAGENTO_WSDL_ADDRESS)
sid = client.service.login(username=USER_NAME, apiKey=API_KEY)

# Fetch all new users in last 24 hours
filter = {
    "complex_filter":{
        "item":{
            "key":"created_at",
            "value":{
                "key":"from",
                "value": datetime.strftime(datetime.now() - timedelta(hours=24), "%Y-%m-%d %H:%M:%S")
            }
        }
    }
}

res = client.services.customerCustomerList(sid, filters=filter)

# New customer ids from last 24 hours.
new_uids = [x.customer_id for x in res]

rawDescription: Magento can not list customers

description: Magento can not list customers


code: growth.clip(-maxg, maxg, out=growth)

rawDescription: Numpy clip function takes twice as long as expected


code:
class ForeignKey(RelatedField, Field):
    # snip
    def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
        # snip
        if 'db_index' not in kwargs:
            kwargs['db_index'] = True

rawDescription: Do I need to add a db_index to this Django model?


code:
def parse(self, response):
    hxs = HtmlXPathSelector(response)
    completeSchedule= hxs.select("//div[@class='fixturelist section']//table[@class='contentTable']")
    items = []
    for schedule in completeSchedule:
        matchDate = schedule.select("tr//th[@colspan='6']/text()").extract()[0]
        times = schedule.select("tr//td[@class='time']//text()").extract()
        matches = schedule.select("tr//td[@class='clubs']//a/text()").extract()

        for m, t in zip(matches, times):
            item = FplserviceItem()
            item["matchDate"] = matchDate
            item["match"] = m
            item["time"] = t
            items.append(item)
    return items

rawDescription: Data not scraped in XML or JSON using scrapy


code:
def formData(dataset):

    listOfTransaction = list()
    listOfTransaction = dataset.values.tolist()
    cleanedList = []
    for transaction in listOfTransaction:
        itemList = []
        for item in transaction:
            if False ==  pd.isnull(item):
                itemList.append(item)
        cleanedList.append(itemList)

    return cleanedList

def formToPandas(result):
    return pd.DataFrame(result)

rawDescription: Azure Machine Learning - python

description: Azure Machine Learning - python


code:
from ast import literal_eval
data = "(\'unpredictable\', \'JJ\'), (\'man\', \'NN\')"
literal_eval(data)
dict(literal_eval(data))

rawDescription: How do I split a string and put it into a dictionary?

description: Split a string and put it into a dictionary


rawDescription: Maintaining 'focus' on Leap Motion Python (IDLE) code execution


code:
import urllib2
import lxml.etree

url = "http://weather.yahooapis.com/forecastrss?w=24260013&u=c"
doc = lxml.etree.parse( urllib2.urlopen(url) ).getroot()
conditions = doc.xpath('*/*/yweather:condition',
                       namespaces={'yweather': 'http://xml.weather.yahoo.com/ns/rss/1.0'})
try:
    condition=conditions[0]
except IndexError:
    print('yweather:condition not found')
print(condition.items())
# [('text', 'Fair'), ('code', '33'), ('temp', '16'), ('date', 'Wed, 19 May 2010 9:55 pm EDT')]

rawDescription: python feedparser with yahoo weather rss

description: Python feedparser with yahoo weather rss


rawDescription: pandas >= 0.18 - changes to resample, how to upsample with groupby

description: Pandas >= 0.18 - changes to resample, how to upsample with groupby


code:
def getOsFullDesc():
    name = ''
    if os.path.isfile('/etc/lsb-release'):
        lines = open('/etc/lsb-release').read().split('\n')
        for line in lines:
            if line.startswith('DISTRIB_DESCRIPTION='):
                name = line.split('=')[1]
                if name[0]=='"' and name[-1]=='"':
                    return name[1:-1]
    if os.path.isfile('/suse/etc/SuSE-release'):
        return open('/suse/etc/SuSE-release').read().split('\n')[0]
    try:
        import platform
        return ' '.join(platform.dist()).strip().title()
        #return platform.platform().replace('-', ' ')
    except ImportError:
        pass
    if os.name=='posix':
        osType = os.getenv('OSTYPE')
        if osType!='':
            return osType
    ## sys.platform == 'linux2'
    return os.name

rawDescription: Gtk/python and portability

description: Gtk/python and portability


rawDescription: Modify matrix based on column values

description: Modify matrix based on column values


code:
IFoo

IPublishable

rawDescription: Python naming conventions for interfaces and abstract classes?


code:
import itertools
for combination in itertools.product(*[(True, False)]*5):
    assertEqual(foo(*combination), 10)

rawDescription: Pythonic Way To Test All Combinations Of Function Parameters


code:
#!/usr/bin/env python3

import os
import sys
import psycopg2
import argparse

db_conn_str = "dbname=regress user=craig"

create_table_stm = """
CREATE TABLE files (
    id serial primary key,
    orig_filename text not null,
    file_data bytea not null
)
"""

def main(argv):
    parser = argparse.ArgumentParser()
    parser_action = parser.add_mutually_exclusive_group(required=True)
    parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB")
    parser_action.add_argument("--fetch", type=int, help="Fetch an image from the DB and store it in the named file, overwriting it if it exists. Takes the database file identifier as an argument.", metavar='42')
    parser.add_argument("filename", help="Name of file to write to / fetch from")

    args = parser.parse_args(argv[1:])

    conn = psycopg2.connect(db_conn_str)
    curs = conn.cursor()

    # Ensure DB structure is present
    curs.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = %s AND table_name = %s", ('public','files'))
    result = curs.fetchall()
    if len(result) == 0:
        curs.execute(create_table_stm)

    # and run the command
    if args.store:
        # Reads the whole file into memory. If you want to avoid that,
        # use large object storage instead of bytea; see the psycopg2
        # and postgresql documentation.
        f = open(args.filename,'rb')

        # The following code works as-is in Python 3.
        #
        # In Python 2, you can't just pass a 'str' directly, as psycopg2
        # will think it's an encoded text string, not raw bytes. You must
        # either use psycopg2.Binary to wrap it, or load the data into a
        # "bytearray" object.
        #
        # so either:
        #
        #   filedata = psycopg2.Binary( f.read() )
        #
        # or
        #
        #   filedata = buffer( f.read() )
        #
        filedata = f.read()
        curs.execute("INSERT INTO files(id, orig_filename, file_data) VALUES (DEFAULT,%s,%s) RETURNING id", (args.filename, filedata))
        returned_id = curs.fetchone()[0]
        f.close()
        conn.commit()
        print("Stored {0} into DB record {1}".format(args.filename, returned_id))

    elif args.fetch is not None:
        # Fetches the file from the DB into memory then writes it out.
        # Same as for store, to avoid that use a large object.
        f = open(args.filename,'wb')
        curs.execute("SELECT file_data, orig_filename FROM files WHERE id = %s", (int(args.fetch),))
        (file_data, orig_filename) = curs.fetchone()

            # In Python 3 this code works as-is.
            # In Python 2, you must get the str from the returned buffer object.
        f.write(file_data)
        f.close()
        print("Fetched {0} into file {1}; original filename was {2}".format(args.fetch, args.filename, orig_filename))

    conn.close()

if __name__ == '__main__':
    main(sys.argv)

rawDescription: How to save a image file on a Postgres database?

description: Save a image file on a Postgres database


rawDescription: Parse String to Float or Int

description: Parse String to Float or Int


code:
class Team(Model):
    name = CharField(max_length=50)

    def get_captain(self):
        return PlayerRole.objects.get(team=self).player

class Player(Model):
    first_name = CharField(max_length=50)
    last_name = CharField(max_length=50, blank=True)

    def get_team(self):
        return PlayerRole.objects.get(player=self).team

PLAYER_ROLES = (
    ("Regular", "Regular"),
    ("Captain", "Captain")
    )

class PlayerRole(Model):
    player = OneToOneField(Player, primary_key=True)
    team = ForeignKey(Team, null=True)
    role = CharField(max_length=20, choices=PLAYER_ROLES, default=PLAYER_ROLES[0][0])
    class Meta:
        unique_together = ("player", "team")

rawDescription: Django circular model reference

description: Django circular model reference


code:
for subfolder_name in os.listdir(MAIN_FOLDER):
    # exercise left to reader: filter out non-folders
    subfolder_path = os.path.join(MAIN_FOLDER, subfolder_name)
    for excel_file_name in os.listdir(os.path.join(MAIN_FOLDER, subfolder_name)):
        # exercise left to reader: filter out non-excel-files
        excel_file_path = os.path.join(subfolder_path, excel_file_name)
        new_excel_file_name = extract_filename_from_excel_file(excel_file_path)
        new_excel_file_path = os.path.join(NEW_MAIN_FOLDER, subfolder_name,
            new_excel_file_name)
        shutil.copyfile(excel_file_path, new_excel_file_path)

rawDescription: Renaming and Saving Excel Files With Python


code: #pragma comment(lib, "python25.lib");

rawDescription: How can I link (C++) with renamed Python .lib and .dll?

description: Link (C++) with renamed Python .lib and .dll


code:
from string import ascii_uppercase

buttons = [form.Button("btn", id="btn{0}".format(char), value=char,
                       html=movie, class_="btn{0}".format(char))
           for char, movie in zip(ascii_uppercase, movies)]

my_form = form.Form(buttons)

rawDescription: Getting this output, with generators/list comprehensions?


code:
df
pd.melt(df, id_vars='Identifier',
        value_vars=['Data1', 'Data2', 'Data3'],
        var_name='Measure', value_name='Value')

rawDescription: Re-structuring data in a csv file

description: Re-structuring data in a csv file


code:
# Django settings for foo project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'vwbv9j#2vauzpvya8#_qm=rgm&4w6t@yj+howvng0pv-6=@)ji'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'foo.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'foo.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

rawDescription: raise ImportError "Settings cannot be imported" ENVIRONMENT_VARIABLE

description: Raise ImportError "Settings cannot be imported" ENVIRONMENT_VARIABLE


code:
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE':
        'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://127.0.0.1:9200/',
        'INDEX_NAME': 'haystack',
        'EXCLUDED_INDEXES': ['my_destination_app.search_indexes.DestinationIndex'],
    },
    'autocomplete': {
        'ENGINE':
        'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://127.0.0.1:9200/',
        'INDEX_NAME': 'autcomplete',
        'EXCLUDED_INDEXES': ['my_product_app.search_indexes.ProductIndex'],
    }
}

rawDescription: Haystack Multiple Indices - indexed same even there are different search_indexes


code:
g = collection.data["karate"]
u, v = g.vertex(0), g.vertex(1)
n = vertex_similarity(g, "dice", [(u, v)], self_loops=False) * (u.out_degree() + v.out_degree()) / 2
print(n)

rawDescription: common neighbour of two vertices on graph-tool

description: Common neighbour of two vertices on graph-tool


code:
from xml.dom.minidom import parseString
import json
def bar(somejson, key):
    def val(node):
        # Searches for the next Element Node containing Value
        e = node.nextSibling
        while e and e.nodeType != e.ELEMENT_NODE:
            e = e.nextSibling
        return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e
                else None)
    # parse the JSON as XML
    foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),)))
    # and then search all the name tags which are P1's
    # and use the val user function to get the value
    return [val(node) for node in foo_dom.getElementsByTagName('name')
            if node.firstChild.nodeValue in key]

bar(foo, 'P1')
[u'cccc', u'aaa', u'ss']
bar(foo, ('P1','P2'))
[u'cccc', u'cccc', u'aaa', u'ss']

rawDescription: How can I use python finding particular json value by key?

description: Use python finding particular json value by key


code:
def anonymous(code):
    # To fix the indentation
    fixed_code = '\n'.join(line[4:] for line in code.splitlines())

    _globals = {}
    exec(compile(fixed_code, '<string>', 'exec'), _globals)

    if 'f' not in _globals:
        raise ValueError('You must name your function "f"')

    return _globals['f']

anonymous('''
    def f(x):
        return x + 2
''')(12)

rawDescription: Using eval and exec, how to write an anonymous function?


code:
User.objects.all().extra(select={
    'guide_likes': 'select count(*) from tbl_guide_likes where user_id=tbl_users.id',
    'news_like': 'select count(*) from tbl_news_likes where user_id=tbl_users.id'
}).\
values_list('first_name', 'last_name', 'guide_like','news_like')

rawDescription: Django, How to make multiple annotate in a single queryset


code:
df.index = df.index.to_datetime()
df.index

rawDescription: Python pandas read_csv like functionality from list to a DataFrame?


code:
array = [('item1',90),('item2',76),('item3',83),('item4',90)]
srt = sorted(array,key=lambda x: x[1], reverse=True)
rankings = []
rank = 0
from itertools import groupby
for k,v in groupby(srt,lambda x: x[1]): # group by score
    grp = [(rank,tup[0]) for tup in v] # get item tup[0] and put it in a tuple with the rank
    rankings += grp
    rank += len(grp) # increase rank for next grouping
print(rankings)
[(0, 'item1'), (0, 'item4'), (2, 'item3'), (3, 'item2')]

rawDescription: Rank an array of tuples

description: Rank an array of tuples


code:
import stat

def downLoadFile(sftp, remotePath, localPath):
    for fileattr in sftp.listdir_attr(remotePath):
        if stat.S_ISDIR(fileattr.st_mode):
            sftp.get(fileattr.filename, os.path.join(localPath, fileattr.filename))

rawDescription: How to check a remote path is a file or a directory?

description: Check a remote path is a file or a directory


code:
strings = ['foo','','bar','moo']
' '.join(filter(None, strings))

rawDescription: join 4 strings to the one if they are not empty in python

description: Join 4 strings to the one if they are not empty in python


code:
a = b = [1, 2, 3]
c = d = ['a', 'b', 'c']
a[:] = []
a, b         #affects all references
c = ['foo'] #decrements one reference count from the list pointed by `d`
c, d        #d is unaffected

rawDescription: What is the difference between these two ways to clear lists?


code:
def __getattr__(self, val):
    if not val or not val[0].isupper():
        return tuple.__getattribute__(self, val)
    new = _TokenType(self + (val,))
    setattr(self, val, new)
    self.subtypes.add(new)
    new.parent = self
    return new

rawDescription: Can the value of an undefined and non-initialized class attribute be assigned to variable?


code:
body = {'key1': user['info1'], 'key2': user['info2']}
service = build("myAPI", "v1", http=http, discoveryServiceUrl=DISCOVERY_URL)
service.updateFan(websafeFanKey=fan['websafeKey'], body=body).execute()

rawDescription: apiclient.discovery.build POST request body

description: Apiclient.discovery.build POST request body


code:
import json

dates = ["25 Jun 2015", "26 Jun 2015", "27 Jun 2015"]

result = {}
for each, date in enumerate(dates):
    result.update({each: {"posted_data": date}})

jsoned = json.dumps(result)

rawDescription: Use python to create a nested json

description: Use python to create a nested json


code:
foo = object(); foo
foo = object(); foo
foo = object(); foo
foo = object(); foo
foo = object(); foo

rawDescription: python class instances referring to same location

description: Python class instances referring to same location


code: import traceback

rawDescription: How do I find the name of the file that is the importer, within the imported file?

description: Find the name of the file that is the importer, within the imported file


code:
def open_file(path_to_file, attempts=0, timeout=5, sleep_int=5):
    if attempts < timeout and os.path.exists(path_to_file) and os.path.isfile(path_to_file):
        try:
            file = open(path_to_file)
            return file
        except:
            # perform an action
            sleep(sleep_int)
            open_file(path_to_file, attempts + 1)

rawDescription: Python while loop to check if file exists


code:
import numpy as np

array_a = np.arange(100)
gaussian = np.random.normal(loc=array_a.mean(), scale=0.1, size=2 * len(array_a))

rawDescription: The size of an array created from np.random.normal


code:
def sortQuerySetByAttr(queryset, attribute, order="ASC", type="str"):
    '''
        Order Items by attribute
        queryset: QuerySet
        attribute: Attribute name
        order: Order direction DESC / ASC
        type: Attribute value type str/int
            Example: qSet = Item.objects.filter(#Many filters)
            qSet = sortQuerySetByAttr(qSet, "NAME", "DESC", "int")[:15]
    '''

    '''
        You should change the field type if it's Text field
        CORE_VALUE - Table name
        VALUE - Field name
    '''

    if type != "str":
        case = 'TO_NUMBER("CORE_VALUE"."TITLE", \'999999999.999\')'
    else:
        case = 'CAST("CORE_VALUE"."TITLE" AS VARCHAR(100))'

    if order != "ASC":
        case = '-' + case

    return queryset.model.objects.filter(pk__in=queryset, item2value__attr__title=attribute).extra(order_by=[case])

rawDescription: Django + Oracle + Order

description: Django + Oracle + Order


code:
db_path = 'FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx'
file_to_delete = 'Logging a Defect.docx'
file_separator = ","
new_db_path = [
    path.strip()
    for path in db_path.split(file_separator)
    if path.strip() and file_to_delete not in path
]
string_to_save = file_separator.join(new_db_path)
string_to_save

rawDescription: Need some help in deleting the data from list and again append it in same list


code:
A = defaultdict(list)
B = defaultdict(list)
filename = sys.argv[1]

with open(filename) as fin:
    for line in fin:
      vals = line.split()
      vals[2] = int(vals[2])
      A[vals[1]].append(vals[2])
      B[vals[0]].append(vals[2])

for v in A.itervalues():
    v.sort();
for v in B.itervalues():
    v.sort()

rawDescription: How to speed up making large dictionary

description: Speed up making large dictionary


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode

def fun(t, z, omega):
    """
    Right hand side of the differential equations
      dx/dt = -omega * y
      dy/dt = omega * x
    """
    x, y = z
    f = [-omega*y, omega*x]
    return f

# Create an `ode` instance to solve the system of differential
# equations defined by `fun`, and set the solver method to 'dop853'.
solver = ode(fun)
solver.set_integrator('dop853')

# Give the value of omega to the solver. This is passed to
# `fun` when the solver calls it.
omega = 2 * np.pi
solver.set_f_params(omega)

# Set the initial value z(0) = z0.
t0 = 0.0
z0 = [1, -0.25]
solver.set_initial_value(z0, t0)

# Create the array `t` of time values at which to compute
# the solution, and create an array to hold the solution.
# Put the initial value in the solution array.
t1 = 2.5
N = 75
t = np.linspace(t0, t1, N)
sol = np.empty((N, 2))
sol[0] = z0

# Repeatedly call the `integrate` method to advance the
# solution to time t[k], and save the solution in sol[k].
k = 1
while solver.successful() and solver.t < t1:
    solver.integrate(t[k])
    sol[k] = solver.y
    k += 1

# Plot the solution...
plt.plot(t, sol[:,0], label='x')
plt.plot(t, sol[:,1], label='y')
plt.xlabel('t')
plt.grid(True)
plt.legend()
plt.show()

rawDescription: how to use dorpi5 or dop853 in python

description: Use dorpi5 or dop853 in python


code: "blah" * 5

rawDescription: Is there a Python equivalent of Perl's x operator?


code:
pages = Page.objects.annotate(num_countries=Count('country'))
pages[0].num_countries  # 3
pages[1].num_countries  # 4

rawDescription: Django group by to find the count

description: Django group by to find the count


code:
s = [2, 3, 1, 4, 5]
sorted(range(len(s)), key=lambda k: s[k])

rawDescription: how to return index of a sorted list?

description: Return index of a sorted list


code: tx = TextInput(background_normal = "textinput_unfocused.png")

rawDescription: Kivy TextInput background problems

description: Kivy TextInput background problems


code:
parser.DefaultHandlerExpand = self._default
parser.StartElementHandler = self._start
parser.EndElementHandler = self._end
parser.CharacterDataHandler = self._data
# optional callbacks
parser.CommentHandler = self._comment
parser.ProcessingInstructionHandler = self._pi

rawDescription: Can I disable entities resolving in ElementTree XMLParser?

description: Disable entities resolving in ElementTree XMLParser


code:
def getEnvironmentVariable(name):
    name= unicode(name) # make sure string argument is unicode
    n= ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0)
    if n==0:
        return None
    buf= ctypes.create_unicode_buffer(u'\0'*n)
    ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n)
    return buf.value

rawDescription: Problems with umlauts in python appdata environvent variable


code:
def queryset(self, request):
    current = Cycle.objects.latest() # or whatever to get the current cycle
    qs = super(StudentEnrolmentsInline, self).queryset(request)
    return qs.filter(school_class__cycle=current)

rawDescription: Django inline formset filters in manytomany relationship through another model


code:
from itertools import chain
chained_qs = chain(qs1, qs2)

rawDescription: Chain Multiple Objects into parent Object Django


code:
headers = {
    "X-Auth-Token": "dddddsssb04411b4c6a2",
    "Access-Control-Allow-Origin": "*",
}
r = requests.post("https://verylong/url", headers=headers)

rawDescription: Python Request Module To Add Header to CDN URL Using Token


code:
from matplotlib.ticker import NullFormatter
ax.xaxis.set_major_formatter(NullFormatter())

rawDescription: remove x ticks but keep grid lines

description: Remove x ticks but keep grid lines


rawDescription: Python itertools lambda / best LINQ-alike approach in python


code:
# given an iterable of pairs return the key corresponding to the greatest value
def argmax(pairs):
    return max(pairs, key=lambda x: x[1])[0]

# given an iterable of values return the index of the greatest value
def argmax_index(values):
    return argmax(enumerate(values))

# given an iterable of keys and a function f, return the key with largest f(key)
def argmax_f(keys, f):
    return max(keys, key=f)

rawDescription: implementing argmax in Python

description: Implementing argmax in Python


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

x, y, u, v = np.random.random((4,10))
plt.quiver(x, y, u, v)
plt.show()

rawDescription: Random vector plot in matplotlib

description: Random vector plot in matplotlib


code:
import random
length=13
ListOfChars=[]
codes=list(range(48,57))+list(range(65,90))+list(range(97,122))
for a in range(length):
    ASCIIcode=random.choice(codes)
    ListOfChars.append(chr(ASCIIcode))
print(''.join(ListOfChars))

rawDescription: Password generator (defining character set and length of password with random length range)


code:
#!/usr/bin/env python
#
# Counts the IP addresses of a log file.
#
# Assumption: the IP address is logged in the first column.
# Example line: 117.195.185.130 - - [06/Mar/2012:00:00:00 -0800] \
#    "GET /mysidebars/newtab.html HTTP/1.1" 404 0 - -
#

import sys

def urlcheck(line, url):
    '''Checks if the url is part of the log line.'''
    lsplit = line.split()
    if len(lsplit)<7:
        return False
    return url==lsplit[6]

def extract_ip(line):
    '''Extracts the IP address from the line.
       Currently it is assumed, that the IP address is logged in
       the first column and the columns are space separated.'''
    return line.split()[0]

def increase_count(ip_dict, ip_addr):
    '''Increases the count of the IP address.
       If an IP address is not in the given dictionary,
       it is initially created and the count is set to 1.'''
    if ip_addr in ip_dict:
        ip_dict[ip_addr] += 1
    else:
        ip_dict[ip_addr] = 1

def read_ips(infilename, url):
    '''Read the IP addresses from the file and store (count)
       them in a dictionary - returns the dictionary.'''
    res_dict = {}
    log_file = file(infilename)
    for line in log_file:
        if line.isspace():
            continue
        if not urlcheck(line, url):
            continue
        ip_addr = extract_ip(line)
        increase_count(res_dict, ip_addr)
    return res_dict

def write_ips(outfilename, ip_dict):
    '''Write out the count and the IP addresses.'''
    out_file = file(outfilename, "w")
    for ip_addr, count in ip_dict.iteritems():
        out_file.write("%s\t%5d\n" % (ip_addr, count))
    out_file.close()

def parse_cmd_line_args():
    '''Return the in and out file name.
       If there are more or less than two parameters,
       an error is logged in the program is exited.'''
    if len(sys.argv)!=4:
        print("Usage: %s [infilename] [outfilename] [url]" % sys.argv[0])
        sys.exit(1)
    return sys.argv[1], sys.argv[2], sys.argv[3]

def main():
    infilename, outfilename, url = parse_cmd_line_args()
    ip_dict = read_ips(infilename, url)
    write_ips(outfilename, ip_dict)

if __name__ == "__main__":
    main()

rawDescription: How to find how many times a particular ip is pinged to the url?

description: Find how many times a particular ip is pinged to the url


code:
class GUI:
    def __init__(self):
        self.tk = Tk()
        self.tk.resizable(0, 0)
        self.tk.title('watch clipboard')
        self.last_content = ''
        self.tk.after(100, self.watch_clipboard)
        self.tk.mainloop()
    def watch_clipboard(self):
        try:
            content = self.tk.clipboard_get()
            if content != self.last_content and content.startswith('http:'):
                self.last_content = content
                self.tk.clipboard_clear()
                messagebox.askokcancel('', 'add this in?', default='ok')
        except TclError:
            pass
        self.tk.after(100, self.watch_clipboard)

rawDescription: Using tkinter to watch for clipboard,what's wrong with my code?


code:
payments = invoicePayments.objects.filter(invoice__store_id=3,
                                          date__range=["2016-05-01", "2016-05-06"])

rawDescription: select in (select ..) using ORM django

description: Select in (select ..) using ORM django


code:
(''.join(s) for s in itertools.product(*['TO', 'G', 'ZDO', 'DEO', 'SGT', 'D', 'Z', 'FT', 'OV']))
# to demonstrate:

list(itertools.islice((''.join(s) for s in itertools.product(*['TO', 'G', 'ZDO', 'DEO', 'SGT', 'D', 'Z', 'FT', 'OV'])), 3))

rawDescription: With variable length list of variable length strings, how do I create all combinations


code:
#!/usr/bin/env python

from __future__ import print_function

from cmd import Cmd
import readline  # noqa

class Zoo(Cmd):

    def __init__(self, animals):
        Cmd.__init__(self)

        self.animals = animals

    def do_add(self, animal):
        print("Animal {0:s} added".format(animal))

    def completedefault(self, text, line, begidx, endidx):
        tokens = line.split()
        if tokens[0].strip() == "add":
            return self.animal_matches(text)
        return []

    def animal_matches(self, text):
        matches = []
        n = len(text)
        for word in self.animals:
            if word[:n] == text:
                matches.append(word)
        return matches

animals = ["Bear", "Cat", "Cheetah", "Lion", "Zebra"]
zoo = Zoo(animals)
zoo.cmdloop()

rawDescription: Tab autocomplete and simple implementation of subcommands in python cmd module?


code:
from twisted.internet import reactor, defer
def simple_task():
    status = query_your_api()
    return status

def repeating_call(status):
    print(status)
    d = threads.deferToThread(simple_task)
    d.addCallback(repeating_call)

data_series = [data1, data2, data3]
for data in data_series:
    repeating_call('starting everything up')

reactor.run()

rawDescription: Signaling between threads in Python

description: Signaling between threads in Python


code: data = json.dumps([columns for key, columns in crime.get_range()])

rawDescription: Python Append JSON list within for loop

description: Python Append JSON list within for loop


code:
reshaped = np.reshape(X,N*M)
result = np.delete(reshaped, np.where(reshaped==32744))

rawDescription: Convert NxM numpy array to (N*M)x1

description: Convert NxM numpy array to (N*M)x1


code:
datetime.datetime.now()
datetime.datetime.now() - datetime.timedelta(minutes=15)

rawDescription: How to create a DateTime equal to 15 minutes ago?

description: Create a DateTime equal to 15 minutes ago


code:
self.return_code = subprocess.call(args = self.cmd_string,
                                   stdout = open(self.out_log_filepath, 'w'),
                                   stderr = open(self.err_log_filepath, 'w'),
                                   shell = True,
                                   env=my_env)

rawDescription: How to ensure that script only executes subsequent methods after subprocess.Popen has completed execution

description: Ensure that script only executes subsequent methods after subprocess.Popen has completed execution


code:
class Mother:
    def __init__(self):
        super().__init__()
        print("Mother")

class Father:
    def __init__(self):
        super().__init__()
        print("Father")

class Daughter(Mother, Father):
    def __init__(self):
        super().__init__()
        print("Daughter")

rawDescription: Is there a way to use super() to call the __init__ method of each base class in Python?


code:
def fun1(a,b):
    return a + b

def fun2(a,b,c):
    return a * b / c

def set_globals(**kwargs):
    for argname in kwargs:
        globals()['%s_in' % argname] = kwargs[argname]

def fun_wrap(func, **kwargs):
    set_globals(**kwargs)       # made the call to set_globals before calling your function
    return func(**kwargs)       # return the value returned by the functions called

rawDescription: Passing uncertain amount of inputs to one function's sub-functions


code:
expr = sympify("9+3/3+6/2", evaluate=False)
expr
latex(expr)
print (latex(expr))

rawDescription: Converting fraction using numerals to a string which uses \\frac{}{} Latex format


rawDescription: Python math adding numbers from two list index by index


code:
header = "\xca\xfe\xba\xbe"
struct.unpack(">L", header)
struct.unpack(">L", header)[0] == 0xcafebabe

rawDescription: Compare bytes in Python 2 from file with hex literal?


code:
class Rational(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __add__(self, other):
        if isinstance(other, Rational):
            d = self.b * other.b
            return Rational(self.a * other.b + other.b * self.a, d)
        elif isinstance(other, int):
            return Rational(self.a + self.b * other, self.b)
        else:
            return NotImplemented

    # __add__ is invoked for Rational + other
    # __radd__ will be called by other + Rational if other doesn't
    # know about your class.
    def __radd__(self, other):
        return self.__add__(other)

rawDescription: Overloading operators for different states


code:
from py2neo import Graph, Relationship
from py2neo.cypher import CreateStatement

graph = Graph()
tx = graph.cypher.begin()

statement = CreateStatement(graph)
statement.create(Relationship(node1, "LINKS_TO", node2))
tx.append(statement)

tx.commit()

rawDescription: Neo4J / py2neo -- create `Relationship` in transaction?


code:
li = iter(object_list)

obj = next(li)

do_first_thing_with(obj)

while True:
    try:
        do_something_with(obj)
        obj = next(li)
    except StopIteration:
        do_final_thing_with(obj)
        break

rawDescription: Python check first and last index of a list


code: teams = {team:i for i, team in enumerate(df['team_1'].unique())}

rawDescription: Adding unique items to dictionary from data frame


code:
from bs4 import BeautifulSoup
html = """..."""
soup = BeautifulSoup(html, 'lxml')
...

rawDescription: Remove specific element from html page using lxml python etree


code:
import numpy as np
np.arange(200, dtype=np.float)/200

rawDescription: creating timesliced array in numpy

description: Creating timesliced array in numpy


rawDescription: Python unescape URL

description: Python unescape URL


code:
with tarfile.open(archive_name + '.tar.gz', mode='w:gz') as archive:
    archive.add('/Users/localuser/Downloads/backup', recursive=True)

rawDescription: how to make a tar file backup of a directory in python

description: Make a tar file backup of a directory in python


rawDescription: python - extract coordinates from a variable string

description: Python - extract coordinates from a variable string


code:
from django.utils.cache import add_never_cache_headers

class UserPhoneNumberView(FormView):
    form_class = UserPhoneNumberForm
    template_name = "get_user_phonenumber.html"

    def form_valid(self, form):
        phonenumber = self.request.POST.get("mobile_number")
        unique = self.request.POST.get("unique")
        url = "http://example.com/"+unique
        response = HttpResponse("", status=302)
        body = "See this url: "+url
        nonhttp_url = "sms:"+phonenumber+"?body="+body
        response['Location'] = nonhttp_url

        # This will add the proper Cache-Control and Expires
        add_never_cache_headers(response)

        # Now just add the 'Vary' header
        response['Vary'] = '*'
        return response

rawDescription: How to set Cache-Control of a URL embedded within a special non-http URL (Python/Django)

description: Set Cache-Control of a URL embedded within a special non-http URL (Python/Django)


code:
import csv
import re
regex = re.compile("""
    ([^:]*)  # Match and capture any characters except colons
    :[ ]*    # Match a colon, followed by optional spaces
    (.*)     # Match and capture the rest of the line""",
    re.VERBOSE)
with open("in.txt") as infile, open("out.csv", "wb") as outfile:
    writer = csv.writer(outfile)
    for line in infile:
       writer.writerow(regex.match(line).groups())

rawDescription: Parsing semi-structured json data(Python/R)


code:
import re
r=re.compile('(?![a-zA-Z]{4}$).{4}$')
r.search('hello.com')
r.search('hellobcom')

r.search('hello.ca')

rawDescription: regex that match iff there are nor more than 4 alphabet at the end of the string

description: Regex that match iff there are nor more than 4 alphabet at the end of the string


code:
from xml.etree import ElementTree as etree

if etree.VERSION[0:3] == '1.2':
    #in etree < 1.3, this is a workaround for supressing prefixes

    def fixtag(tag, namespaces):
        import string
        # given a decorated tag (of the form {uri}tag), return prefixed
        # tag and namespace declaration, if any
        if isinstance(tag, etree.QName):
            tag = tag.text
        namespace_uri, tag = string.split(tag[1:], "}", 1)
        prefix = namespaces.get(namespace_uri)
        if namespace_uri not in namespaces:
            prefix = etree._namespace_map.get(namespace_uri)
            if namespace_uri not in etree._namespace_map:
                prefix = "ns%d" % len(namespaces)
            namespaces[namespace_uri] = prefix
            if prefix == "xml":
                xmlns = None
            else:
                if prefix is not None:
                    nsprefix = ':' + prefix
                else:
                    nsprefix = ''
                xmlns = ("xmlns%s" % nsprefix, namespace_uri)
        else:
            xmlns = None
        if prefix is not None:
            prefix += ":"
        else:
            prefix = ''

        return "%s%s" % (prefix, tag), xmlns

    etree.fixtag = fixtag
    etree._namespace_map['http://some.namespace'] = None
else:
    #For etree > 1.3, use register_namespace function
    etree.register_namespace('', 'http://some.namespace')

rawDescription: Supressing namespace prefixes in ElementTree 1.2


code:
new_args = [arg.upper() for arg in args]
return func(*new_args)

rawDescription: Decorators changing arguments to a function


code:
import importlib
path = importlib.import_module('os.path')
print(path.join('a','b'))

rawDescription: python: better workaround for treating argument in bash/cmd line as an object

description: Python: better workaround for treating argument in bash/cmd line as an object


rawDescription: How to deal with <FE><FF> in what should be valid utf-8? What am I doing wrong?

description: Deal with <FE><FF> in what should be valid utf-8? What am I doing wrong


code:
def func(self):
    layout=QtGui.QHBoxLayout()  # layout for the central widget
    widget=QtGui.QWidget(self)  # central widget
    widget.setLayout(layout)

    number_group=QtGui.QButtonGroup(widget) # Number group
    r0=QtGui.QRadioButton("0")
    number_group.addButton(r0)
    r1=QtGui.QRadioButton("1")
    number_group.addButton(r1)
    layout.addWidget(r0)
    layout.addWidget(r1)

    letter_group=QtGui.QButtonGroup(widget) # Letter group
    ra=QtGui.QRadioButton("a")
    letter_group.addButton(ra)
    rb=QtGui.QRadioButton("b")
    letter_group.addButton(rb)
    layout.addWidget(ra)
    layout.addWidget(rb)

    # assign the widget to the main window
    self.setCentralWidget(widget)
    self.show()

rawDescription: grouping radio buttons in PyQt

description: Grouping radio buttons in PyQt


code:
import Tkinter as tk
from Tkinter import Frame
root = tk.Tk()
frame1 = Frame(root, bg='blue',width='100px', height='100px')
frame1.pack()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

frame1.bind('<Motion>', motion)
root.mainloop()

rawDescription: Change Cursor when Hovering Over Part of Frame TKinter


code:
class Foo(object):
    def spam(self): pass

class Bar(object):
    def ham(self): pass

class CustomDirMetaclass(type):
    def __dir__(cls):
        return ['eggs']

class Baz(Foo, Bar):
    __metaclass__ = CustomDirMetaclass
    def eggs(self): pass

dir(Baz)
getMembers(Baz)
getMembersWithBases(Baz)

rawDescription: Python class members scanning - Why __bases__ recursive scan is required in get members?


code:
def walk_on_the_beach(sig, t, interval=1000):
    """
    :param sig: signal.
    :param t: threshold.
    :param interval: interval between next value check (ms).
    """
    last_value = 0
    interval_flag = True
    interval_iterator = 0
    markers = np.zeros(np.size(sig))
    for i in np.arange(np.size(sig)):
        absolute = np.abs(last_value - sig[i])
        last_value = sig[i]
        if interval_flag:
            if absolute > t:
                markers[i] = np.max(sig)
                interval_flag = False
        else:
            if interval_iterator == interval:
                interval_flag = True
                interval_iterator = 0
            else:
                interval_iterator += 1

    return markers

py.plot(time_scale[:100000], walk_on_the_beach(filtered, 0.02))

rawDescription: Marking a signal

description: Marking a signal


rawDescription: Translating for loop into list comprehension


code:
# WARNING: do NOT attempt this in production code!

import ctypes

def magic_get_dict(o):
    # find address of dict whose offset is stored in the type
    dict_addr = id(o) + type(o).__dictoffset__

    # retrieve the dict object itself
    dict_ptr = ctypes.cast(dict_addr, ctypes.POINTER(ctypes.py_object))
    return dict_ptr.contents.value

def magic_flush_mro_cache():
    ctypes.PyDLL(None).PyType_Modified(ctypes.cast(id(object), ctypes.py_object))

# monkey-patch file.write
dct = magic_get_dict(file)
dct['write'] = lambda f, s, orig_write=file.write: orig_write(f, '42')

# flush the method cache for the monkey-patch to take effect
magic_flush_mro_cache()

# magic!
import sys
sys.stdout.write('hello world\n')

rawDescription: Set a Read-Only Attribute in Python?

description: Set a Read-Only Attribute in Python


code:
output = open('myoutputfile.txt', 'w')
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()

# Construct query to get type, there's no need to include this in the loop
query = ("""SELECT type FROM table1, table2
    WHERE table1.name = %s AND table1.id = table2.id""")

with open("input.txt") as f:
    for line in f:

        # Query arguments
        args = (line.strip(), ) # added .strip()

        cursor.execute(query, args)       # Exec query

        entries = cursor.fetchall()
        for entry in entries:
            output.write(str(entry[0]) + "\n")

cnx.close()
output.close()

rawDescription: MySQL query with Python not returning all results


code:
if foo is None:
    ...

rawDescription: null object in Python?

description: Null object in Python


code:
while not stop:
        original_txt = 'Click ENTER to continue...'
        text_to_be_displayed = original_txt[1]
        gameDisplay.blit(Map, (0,0))

        StoryText = pygame.font.SysFont("monospace",25)

        StoryFont = StoryText.render(text_to_be_displayed,5,(red))
        gameDisplay.blit(StoryFont,(50,500))

rawDescription: How do I blit specific indexes of text to the screen in pygame

description: Blit specific indexes of text to the screen in pygame


rawDescription: How to include external css, image, etc in django template?

description: Include external css, image, etc in django template


code: pages = [myQuerySet.filter(myfield__istartswith=i) for i in "ABC...XYZ"] #full alphabet here

rawDescription: Paginated based on the alphabet (A-Z)

description: Paginated based on the alphabet (A-Z)