code:
import httplib2, re

def search_for_Title(content):

    searchBounds = re.compile('title(.{1,100})title')
    Title = re.findall(searchBounds,content)
    return Title

def main():

    url = "http://www.nytimes.com/services/xml/rss/index.html"
    h = httplib2.Http('.cache')
    content = h.request(url)
    print(content)
    print(findTitle(str(content)))

main()

rawDescription: Not understanding what's going on with my python code and httplib2 package


code:
def slicedict(d, s):
    return {k:v for k,v in d.iteritems() if k.startswith(s)}

rawDescription: Slicing a dictionary by keys that start with a certain string


rawDescription: Converting a string that represents a list, into an actual list object


code:
def testfunction(S):
    S_temp = S.split(";")
    i=0
    good_list=[]
    while i < len(S_temp):
        str_temp = S_temp[i]
        temp_list = str_temp.split(" ")
        z=0
        while z < len(temp_list):
            temp_list[z] = float(temp_list[z])
            z += 1
        z = 0
        good_list.append(temp_list)
        i += 1

rawDescription: Convert a program to a function in Python?


code: property_name = getattr(Game, dictname)

rawDescription: Python: Reference an object attribute by variable name?


code:
class AuthedUserHandler(RequestHandler):
    def get(self):
        ...

class UserHandler(RequestHandler):
    def get(self, user_id):
        ...

app = Application([
    ('/user', AuthedUserHandler),
    ('/user/(.*)', UserHandler),
])

rawDescription: python tornado how to get id of a edge

description: Python tornado how to get id of a edge


code:
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.app import App
from kivy.core.audio import SoundLoader
from kivy.uix.listview import ListItemButton
from kivy.properties import ListProperty, NumericProperty

Builder.load_string('''
#:import la kivy.adapters.listadapter
#:import factory kivy.factory

<MenuButton>:
    size_hint_y: None
    height: dp(24)
    on_release: app.on_menu_selection(self.index)

<MenuPage>:
    BoxLayout:
        BoxLayout:
            size_hint:(.1, None)
            Button:
                text: 'Credit'
                #on_press:root.show_popup()
        ListView:
            size_hint: .8,.9
            adapter:
                la.ListAdapter(
                data=app.data,
                cls=factory.Factory.MenuButton,
                selection_mode='single',
                allow_empty_selection=True,
                args_converter=root.args_converter)

        BoxLayout:
            size_hint:(.1, None)
            Button:
                text: 'atlas'

<Page>:
    BoxLayout:
        BoxLayout:
            size_hint:(.1, None)
            Button:
                text: 'MENU'
                on_press: root.manager.current = 'menu'
        BoxLayout:
            orientation:'vertical'
            Button:
                text:'Title'
                size_hint:(1, .2)
            Image:
                source: '/home/hosein/Pictures/1.png'
                size_hint:(1, .8)
        BoxLayout:
            size_hint:(.1, None)

            Button:
                text: 'atlas'
''')

class MenuButton(ListItemButton):
    index = NumericProperty(0)

class MenuPage(Screen):
    M = SoundLoader.load('/home/hosein/Music/Man.mp3')

    def plays(self):
        if MenuPage.M.state == 'stop':
            MenuPage.M.play()
        else:
            MenuPage.M.stop()

    def args_converter(self, row_index, title):
        print ("{0}={1}".format(row_index, title))

        return {
            'index': row_index,
            'text': title
        }

class Page(Screen):
    pass

class TestApp(App):
    data = ListProperty(["Item #{0}".format(i) for i in range(50)])

    def build(self):
        sm = ScreenManager()
        menu = MenuPage(name='menu')
        sm.add_widget(menu)
        for i in range(50):
            name = Page(name=str(i))
            sm.add_widget(name)
        return sm

    def on_menu_selection(self, index):
        self.root.current = str(index)

if __name__ == '__main__':
    TestApp().run()

rawDescription: Make a listview of buttons that switch to different screens in kivy


code:
dt
dt.date()

rawDescription: How to parse a date and only the date from a `date_string` in python?

description: Parse a date and only the date from a `date_string` in python


code:
pl.plot(actual_measurements[finish - 60:finish - 59, 0],
        actual_measurements[finish - 60:finish - 59, 1], 'ro',
        label="Diverging")

rawDescription: How to draw a point on the graph

description: Draw a point on the graph


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

# random data
x = np.random.random_integers(0, 1, (10, 10))

fig, ax = plt.subplots()

# define the colors
cmap = mpl.colors.ListedColormap(['r', 'k'])

# create a normalize object the describes the limits of
# each color
bounds = [0., 0.5, 1.]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# plot it
ax.imshow(x, interpolation='none', cmap=cmap, norm=norm)

rawDescription: matplotlib: binary heat plot

description: Matplotlib: binary heat plot


rawDescription: How to retrieve the data of my matrix?

description: Retrieve the data of my matrix


code:
class CheckingThread(threading.Thread):
    '''
    This class runs a check on Parent Window to see if it still is running
    If Parent Window closes, this class kills the Python Window application in memory
    '''
    def run(self):
        '''
        Checks Parent Window in 5 seconds intervals to make sure it is still alive.
        If not alive, exit application
        '''
        self.needKill = False

        while not self.needKill:
            if self.handle is not None:
                if not win32gui.IsWindow(self.handle):
                    os._exit(0)
                    break
            time.sleep(5)

    def Kill(self):
        '''
        Call from Python Window main application that causes application to exit
        '''
        self.needKill = True

    def SetHandle(self, handle):
        '''
        Sets Handle so thread can check if handle exists.
        This must be called before thread is started.
        '''
        self.handle = handle

rawDescription: wxPython won't close Frame with a parent who is a window handle

description: WxPython won't close Frame with a parent who is a window handle


rawDescription: Read file with mixed types (floats and strings)


code:
def comma_separated(lst):
    """
    >>> comma_separated(['a'])
    'a'
    >>> comma_separated(['a', 'b'])
    'a and b'
    >>> comma_separated(['a', 'b', 'c'])
    'a, b and c'
    """
    if len(lst) == 1:
        return lst[0]
    comma_part = ", ".join(lst[:-1])
    return "%s and %s" % (comma_part, lst[-1])

if __name__ == "__main__":
    import doctest
    doctest.testmod()

rawDescription: What's the best way to join an array into a readable list?


code:
import sqlalchemy.types as types

class ChoiceType(types.TypeDecorator):

    impl = types.String

    def __init__(self, choices, **kw):
        self.choices = dict(choices)
        super(ChoiceType, self).__init__(**kw)

    def process_bind_param(self, value, dialect):
        return [k for k, v in self.choices.iteritems() if v == value][0]

    def process_result_value(self, value, dialect):
        return self.choices[value]

rawDescription: SQLAlchemy - How to make "django choices" using SQLAlchemy?


code:
import os.path
from glob import glob
from xlrd import open_workbook

def open_arbitrary_workbook(folder, *args, **kwargs):
    try:
        path = glob(os.path.join(folder, "*.xlsx"))[0]
    except IndexError:
        raise IOError("No .xlsx files found in %r" % folder)
    return open_workbook(path, *args, **kwargs)

rawDescription: Opening Unknown Excel Filename Python

description: Opening Unknown Excel Filename Python


code:
from Carbon import AppleEvents
from Carbon import AE
target = AE.AECreateDesc(AppleEvents.typeApplicationBundleID, "org.mozilla.FireFox")
activateEvent  = AE.AECreateAppleEvent( 'misc', 'actv', target, AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
activateEvent.AESend(AppleEvents.kAEWaitReply, AppleEvents.kAENormalPriority, AppleEvents.kAEDefaultTimeout)

rawDescription: Python: Activate window in OS X

description: Python: Activate window in OS X


code:
class ResultView(FormView):

    context_object_name = 'result_list'
    template_name = 'result_list.html'
    form_class = InputForm

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        context["results"] = Result.objects.all()
        context["sales"] = context.results.aggregate(Sum('sales'))
        return context

    def form_valid(self,form):
        company = form.cleaned_data['company']
        region = form.cleaned_data['region']
        queryset = Result.objects.filter(region=region).aggregate(Sum('sales'))
        return HttpResponse(json.dumps(queryset))

rawDescription: Django- why after using ajax, it becomes an empty page


code:
from django.contrib.auth.models import User

User.objects.get(username=the_username).pk

rawDescription: how to get User id from auth_user table in django?

description: Get User id from auth_user table in django


code:
import logging
MYLEVEL = 15
logging.addLevelName(MYLEVEL, 'MYLEVEL')
logging.basicConfig(level=0, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.log(MYLEVEL, "ABCDEF")

rawDescription: Logging with Python - how to change the display name of custom level


code: sorted(d, key=lambda k: d[k][1])

rawDescription: Sorting dictionary keys based on their values


code:
from django.conf import settings
from django import http

class AllowHostsMiddleware(object):

    def process_request(self, request):
        referer_url = request.META.get('HTTP_REFERER','')
        if referer_url.startswith(settings.ALLOWED_REFERER_URL):
            return None
        return http.HttpResponseForbidden('
Forbidden
')

rawDescription: django ALLOWED_HOSTS not working

description: Django ALLOWED_HOSTS not working


code:
import os

def lowercase_rename( dir ):
    # renames all subforders of dir, not including dir itself
    def rename_all( root, items):
        for name in items:
            try:
                os.rename( os.path.join(root, name),
                                    os.path.join(root, name.lower()))
            except OSError:
                pass # can't rename it, so what

    # starts from the bottom so paths further up remain valid after renaming
    for root, dirs, files in os.walk( dir, topdown=False ):
        rename_all( root, dirs )
        rename_all( root, files)

rawDescription: (python) recursively remove capitalisation from directory structure?


code:
class MyModelAdmin(admin.ModelAdmin):
    def save_formset(self, *args, **kwargs):
        super(MyModelAdmin, self).save_formset(*args, **kwargs)
        # do your calculation here

rawDescription: extend django admin commit operation

description: Extend django admin commit operation


code:
import turtle as tt

def main():
    tt.reset()
    print(tt.window_width(), tt.window_height())
    tt.setx(tt.window_width()//2)

if __name__ == '__main__':
    main()
    tt.mainloop()

rawDescription: How to move turtle to edges of the canvas?

description: Move turtle to edges of the canvas


code:
from shutil import rmtree
from django.conf import settings
from django.test import TestCase

class MyTests(TestCase):
    def setUp(self):
        rmtree(settings.MEDIA_ROOT, ignore_errors=True)

    def tearDown(self):
        rmtree(settings.MEDIA_ROOT, ignore_errors=True)

rawDescription: Automatically delete MEDIA_ROOT between tests


code:
index = str.find('!')
if index > -1:
    str = str[index:] # or (index+1) to get rid of the '!', too

rawDescription: Repeating a python regular expression until a certain char


rawDescription: How to convert an string file to matrix with Python

description: Convert an string file to matrix with Python


code:
from subprocess import check_output

build = check_output(['\\build.rb', '-p', 'test'])
with open('out1.txt', 'w') as out1:
    out1.write(build)

release = check_output(['\\newRelease.rb', '-l', 'bat'])
with open('out2.txt', 'w') as out2:
    out2.write(release)

rawDescription: Ruby script executed by os.system() using python


code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot(x1,y1,'go',x2,y2,'bo')
plt.savefig(filename)
plt.clf()

rawDescription: Python tkinter freezes when trying to use matplotlib to save an image


code:
from tkinter import *

parent=Tk() # parent object
canvas = Canvas(parent, height=200) # a canvas in the parent object
frame = Frame(canvas) # a frame in the canvas
# a scrollbar in the parent
scrollbar = Scrollbar(parent, orient="vertical", command=canvas.yview)
# connect the canvas to the scrollbar
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y") # comment out this line to hide the scrollbar
canvas.pack(side="left", fill="both", expand=True) # pack the canvas
# make the frame a window in the canvas
canvas.create_window((4,4), window=frame, anchor="nw", tags="frame")
# bind the frame to the scrollbar
frame.bind("<Configure>", lambda x: canvas.configure(scrollregion=canvas.bbox("all")))
parent.bind("<Down>", lambda x: canvas.yview_scroll(3, 'units')) # bind "Down" to scroll down
parent.bind("<Up>", lambda x: canvas.yview_scroll(-3, 'units')) # bind "Up" to scroll up
# bind the mousewheel to scroll up/down
parent.bind("<MouseWheel>", lambda x: canvas.yview_scroll(int(-1*(x.delta/40)), "units"))
labels = [Label(frame, text=str(i)) for i in range(20)] # make some Labels
for l in labels: l.pack() # pack them

parent.mainloop() # run program

rawDescription: Scrolling through multiple labels in Tkinter


code:
def _log_support(self):

    pi = self.pi; mu = self.mu

    log_support = np.ndarray(shape=(self.k, self.n))

    for k in range(self.k):
        log_support[k, :] = np.log(pi[k]) \
            + np.sum(self.x * np.log(mu[k, :].clip(min=1e-20)), 1) \
            + np.sum(self.xc * np.log((1 - mu[k, :]).clip(min=1e-20)), 1)

    return log_support

def expectation_step(self, log_support):

    log_normalisation = np.logaddexp.reduce(log_support, axis=0)
    log_responsibilities = log_support - log_normalisation

    self.z = np.exp(log_responsibilities)

rawDescription: Python - Parallelisation of a loop

description: Python - Parallelisation of a loop


code:
def __init__(self, a, arg1):
    self.__dict__ = dict(a.__dict__)
    self.attr3 = arg1

rawDescription: Subclass that adds

description: Subclass that adds


code:
def swap(a, i, j):
    a[i], a[j] = a[j], a[i]

def permute(a, i, n):
    if i == n:
        print(a)
        return
    for j in range(i, n+1):
        swap(a, i, j)
        permute(a, i+1, n)
        swap(a, i, j)  # backtrack

def main():
    a = list('ABC')
    permute(a, 0, 2)

if __name__ == '__main__':
    main()

rawDescription: Backtracking permuting a list

description: Backtracking permuting a list


rawDescription: how to change internal sorting system of glob module in python

description: Change internal sorting system of glob module in python


code: re.split('\W+', 'Words, words, words.')

rawDescription: Regex punctuation split [Python]

description: Regex punctuation split [Python]


code: print(sum(map(len, sublists)))

rawDescription: Adding all lengths of sublists

description: Adding all lengths of sublists


code:
# Open a file
fo = open("foo.txt", "a") # safer than w mode
fo.write( "Python is a great language.\nYeah its great!!\n");

# Close opend file
fo.close()

rawDescription: How to open and edit an existing file in Python?

description: Open and edit an existing file in Python


code:
regex1 = re.compile('\{.*\}')
regex2 = re.compile('\{\{.*\}\}')

def replace(match):
    match = match.group(0)
    if regex2.match(match):
        return match
    return 'replacement'

regex1.sub(replace, data)

rawDescription: Substituting a regex only when it doesn't match another regex (Python)


code:
from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())

rawDescription: Convert date to datetime in Python

description: Convert date to datetime in Python


code:
result_proxy = query.fetchall()
for row in result_proxy:
    d = dict(row.items())
    d['Tags'] = d['Keywords']

rawDescription: Can I assign values in RowProxy using the sqlalchemy?

description: Assign values in RowProxy using the sqlalchemy


code:
import re
s = 'bla{% comment %} bli {% useless %}blu'
regexp = '{% .*? %}'
s = re.sub(regexp, "", s)
print(s) # bla bli blu

rawDescription: Remove patterns of the form "{% ... %}" in a string


code:
whole_names = list()
for line in infile.readlines():
    objects = line.split(" ")
    whole_names.append(' '.join(objects[0:2]))

rawDescription: Taking a word from a string inside another file


code:
from Tkinter import * # Python 3.x: from tkinter import *

def hello(e=None):
    print('Hello')

root = Tk()
Button(root, text='say hello', command=hello).pack()
root.bind('<Escape>', lambda e: root.quit())
root.bind('h', hello)
root.mainloop()

rawDescription: Tracing keypresses in python

description: Tracing keypresses in python


code:
from rest_framework.decorators import api_view

@api_view(['GET'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def test_view(request):
    return HttpResponse("Allowed")

rawDescription: Django rest framework not authenticating custom user model


code:
class BaseModel(models.Model):

    def clean(self, *args, **kwargs):
        # add custom validation here
        super(BaseModel, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(BaseModel, self).save(*args, **kwargs)

rawDescription: Adding Custom Django Model Validation

description: Adding Custom Django Model Validation


code:
myList = ['a','b','c']
myStr = 'z'
res = [[myStr, x] for x in myList]

rawDescription: Python: pair a single element with every element in a list


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

x_cords = [1,2,4,2,5,3,2,5,3,4,6,2,3,4,5,3,4,2,4,5]
y_cords = [6,5,3,4,5,6,3,5,4,6,3,4,5,6,3,4,5,6,3,4]
z_cords = [3,1,3,4,2,4,5,6,3,4,5,6,2,4,5,7,3,4,5,6]
classlbl= [0,2,0,1,2,0,2,0,1,2,0,1,0,2,0,2,0,1,0,2]

colors  = ['r','g','b']
Labels  = ['RED','GREEN','BLUE']

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#plotlabels = ['Acer campestre L',...,'Viburnum tinus']

#Creating colorlist from labels indexes
colors = np.asarray(colors)
colorslist = colors[classlbl]
Labels = np.asarray(Labels)
labellist = Labels[classlbl]

# Plot point by point
for x,y,z,c,l in zip(x_cords, y_cords, z_cords,colorslist,labellist):
    ax.scatter(x, y, z, color=c,label=l)

# Get the labels and handles
handles, labels = ax.get_legend_handles_labels()

# Filter the labels and handles to remove duplicates
newLeg=dict()
for h,l in zip(handles,labels):
    if l not in newLeg.keys():
        newLeg[l]=h

# Create new handles and labels
handles=[]
labels=[]
for l in newLeg.keys():
    handles.append(newLeg[l])
    labels.append(l)

# Create new Legend
ax.legend(handles, labels)

plt.show()

rawDescription: Add a list of labels in Pythons matplotlib


code:
import csv

data = {
   "food_type1":{
              "brand1": "a",
              "brand3": "b"
              },
   "food_type2":{
              "brand1": "c",
              "brand2": "d",
              "brand3": "e",
              "brand4": "f"
              },
   "food_type3":{
              "brand2": "g"
              }
  }

headers = ["food_type",  "brand1", "brand2", "brand3", "brand4"]

with open("/tmp/test.csv", "w") as f:
    dict_writer = csv.DictWriter(f, headers, delimiter=',')
    dict_writer.writeheader()

    rows = []

    for key, row in data.iteritems():
        d = {header: row[header] if header in row else "" for header in headers}
        d["food_type"] = key
        rows.append(d)

    for row_dict in rows:
        dict_writer.writerow(row_dict)

rawDescription: Save multiple dict values to a single csv row


code:
# enable custom window hint
self.setWindowFlags(self.windowFlags() | QtCore.Qt.CustomizeWindowHint)

# disable (but not hide) close button
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowCloseButtonHint)

rawDescription: Can't hide or disable the close button on QWizard


code:
pygame.init()
screen = pygame.display.set_mode([320, 240])
enemy = Enemy()
screen.blit(enemy.image, enemy.rect)
pygame.display.update()

rawDescription: Pygame subclassing issues?

description: Pygame subclassing issues


code:
import re
split = re.compile(r"'\w{2}'")

with open("file2","w") as fw:
    for word in split.findall(open("file","r").read()):
            fw.write(word.strip("'")+"\n")

rawDescription: filtering strings of particular length from file

description: Filtering strings of particular length from file


code:
# Python's datetime strftime doesn't handle dates before 1900.
# These classes override date and datetime to support the formatting of a date
# through its full "proleptic Gregorian" date range.

rawDescription: What is django.utils.datetime_safe and should I use it instead of standard datetime?


code:
import datetime
from pytz import timezone
est = datetime.datetime.now(timezone('US/Eastern'))
day, hour = est.weekday(), est.hour
if (day == 5 and hour > 17) or (day == 6) or (day == 7 and hour <17):
    print('Stop work.  It is a weekend!')

rawDescription: How to ensure code is not execute between two times?

description: Ensure code is not execute between two times


code:
from numpy import array
my_var = [array([ 1.,  0.]), array([ 0.,  1.]), array([ 0.,  1.]), array([ 1.,  0.])]
print(my_var)
print(type(my_var))
print(type(my_var[0]))

rawDescription: Python array([]) function

description: Python array([]) function


code:
f = open(fileName)
while not endOfFile:
    f.read(128)

rawDescription: Get MD5 hash of big files in Python

description: Get MD5 hash of big files in Python


code:
ip_hdr = eth.data
ip_hdr.dst  # will contain your destination IP address in BINARY

# adapted from http://www.commercialventvac.com/dpkt.html#mozTocId303989
import socket
dst_ip_addr_str = socket.inet_ntoa(ip_hdr.dst)

rawDescription: Parsing ip address with dpkt

description: Parsing ip address with dpkt


code: table = [vol_tank(R, h) for R, h in zip(*values)]

rawDescription: Trouble with function in the for-loop

description: Trouble with function in the for-loop


code:
input1 = open('file')
eof = False
while (True):
    while (True):
        line = input1.readline()
        if line == '':
            eof = True
            break
        output.write(line)
        if '[FOR_RECORD]' in line:
            offset = input1.tell()
            break

    if eof: break
    for i in range(4):
        input1.seek(offset)
        while (True):
            line = input1.readline()
            if line == '':
                eof = True
                break
            if '[/FOR_RECORD]' in line:
                break
            if '[REG_NAME]' in line:
                line=line.replace('[REG_NAME]',reg_name[i]['name'])
                output.write(line)
    if eof: break

rawDescription: How to keep track of lines in a file python

description: Keep track of lines in a file python


code:
import mechanize
browser = mechanize.Browser()
browser.set_handle_refresh(False)

rawDescription: how do i get python's mechanize to stop following meta refresh redirects?

description: Get python's mechanize to stop following meta refresh redirects


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

data = """\
        a       b       c       d       e
alpha   5.51    0.60    -0.12   26.90   76284.53
beta    3.39    0.94    -0.17   -0.20   -0.20
gamma   7.98    3.34    -1.41   7.74    28394.93
delta   2.29    1.24    0.40    0.29    0.28
"""

df = pd.read_csv(StringIO(data), sep='\s+')

f, axis = plt.subplots(2, 1, sharex=True)
df.plot(kind='bar', ax=axis[0])
df.plot(kind='bar', ax=axis[1])
axis[0].set_ylim(20000, 80000)
axis[1].set_ylim(-2, 30)
axis[1].legend().set_visible(False)

axis[0].spines['bottom'].set_visible(False)
axis[1].spines['top'].set_visible(False)
axis[0].xaxis.tick_top()
axis[0].tick_params(labeltop='off')
axis[1].xaxis.tick_bottom()
d = .015
kwargs = dict(transform=axis[0].transAxes, color='k', clip_on=False)
axis[0].plot((-d,+d),(-d,+d), **kwargs)
axis[0].plot((1-d,1+d),(-d,+d), **kwargs)
kwargs.update(transform=axis[1].transAxes)
axis[1].plot((-d,+d),(1-d,1+d), **kwargs)
axis[1].plot((1-d,1+d),(1-d,1+d), **kwargs)
plt.show()

rawDescription: Histogram with breaking axis and interlaced colorbar


code:
jrange = np.arange(self.max_j - j_start)
joffset = np.round(jrange * discriminant).astype(int)
i = np.arange(self.max_i)

for j in jrange:
    new_i = i + joffset[j]
    in_range = new_i < self.max_i
    self.grid[new_i[in_range], j+j_start] = standard[i[in_range]]

rawDescription: How to rewrite this code from python loops to numpy vectors (for perfomance)?

description: Rewrite this code from python loops to numpy vectors (for perfomance)


code:
from PySide import QtGui
import sys

class myApplication(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(myApplication, self).__init__(parent)

        self.setWindowTitle('No Tool is Selected')

        #---- create instance of each tool widget ----

        self.tool1 = Tool1(self)
        self.tool2 = Tool2(self)

        #---- layout for central widget ----

        centralWidget = QtGui.QWidget()
        centralLayout = QtGui.QGridLayout()
        centralLayout.addWidget(self.tool1, 0, 0)
        centralLayout.addWidget(self.tool2, 1, 0)
        centralWidget.setLayout(centralLayout)

        self.setCentralWidget(centralWidget)

        #---- set the menu bar ----

        contentMenu = self.menuBar().addMenu(("Tools"))
        contentMenu.addAction('show Tool 1', self.show_Tool1)
        contentMenu.addAction('show Tool 2', self.show_Tool2)
        contentMenu.addAction('show All', self.show_All)

    def show_Tool1(self):
        self.tool1.show()
        self.tool2.hide()
        self.setWindowTitle('Tool #1 is Selected')

    def show_Tool2(self):
        self.tool1.hide()
        self.tool2.show()
        self.setWindowTitle('Tool #2 is Selected')

    def show_All(self):
        self.tool1.show()
        self.tool2.show()
        self.setWindowTitle('All Tools are Selected')

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

        layout = QtGui.QGridLayout()
        layout.addWidget(QtGui.QPushButton('Tool #1'))
        self.setLayout(layout)
        self.hide()

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

        layout = QtGui.QGridLayout()
        layout.addWidget(QtGui.QTextEdit('Tool #2'))
        self.setLayout(layout)
        self.hide()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    instance = myApplication()
    instance.show()
    sys.exit(app.exec_())

rawDescription: How to change a content in a window in PySide?

description: Change a content in a window in PySide


code:
people = ["john", "mike", "patrick", "vince", "mike", "foo"]

def build(l):
    d = {}
    i = 1
    for p in people:
        if not p in d:
            d[p] = 'p' + str(i)
            i += 1
        yield d[p]

people_ids = list(build(people))

rawDescription: Converting all the names to identifiers in Python


code:
import difflib
s = difflib.SequenceMatcher(None, "GHSKWITNIFSI", "GHSKWAGDITNIFSI")
s.get_matching_blocks()[:-1]
s = difflib.SequenceMatcher(None, "GHSKWITNIFSI", "GHSKWITNIFSI")
s.get_matching_blocks()[:-1]

rawDescription: Finding an Insertion in a String

description: Finding an Insertion in a String


rawDescription: Check if datetime object is present in database


code:
original = input('Enter a word:')
print("".join(x for x in original if x.lower() not in "aeiou"))

rawDescription: Is there a program that will only return the constants in a word python


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

fig, ax = plt.subplots()

x_locs = np.arange(5)
width = 0.9

email_labels = ["Inbox", "Sent", "Important", "Starred", "Unread"]
email_volumes = [1500, 1200, 900, 600, 300]

ax.bar(x_locs-width/2.0, email_volumes, width)
ax.set_xticks(x_locs)
ax.set_xticklabels(email_labels)

plt.show()

rawDescription: How to get the x axis labels to fit the width of the graph?

description: Get the x axis labels to fit the width of the graph


code:
config = wx.Config()
checkBoxes = ['option_1', 'option_2']
for key in checkBoxes:
    config.Write(key, str(getattr(self, 'm_checkBox_'+key).Value()))

rawDescription: Is eval() always wrong?

description: Is eval() always wrong


code:
from __future__ import print_function  # For Python 2/3 support

demo_affiliations = {
    'Alex Dunphy': ['Orchestra', 'Chess Club'],
    'Manny Delgado': ['Chess Club'],
    'Cameron Tucker': ['Clown School', 'Wizard of Oz Fan Club'],
    'Claire Dunphy': ['Parent Teacher Association'],
    'Gloria Pritchett': ['Parent Teacher Association'],
    'Phil Dunphy': ['Real Estate Association'],
    'Mitchell Pritchett': ['Law Association'],
    }
demo_person = 'Alex Dunphy'

# This is the main function; it'll take affiliations and a person
# as arguments, and returns a list of associates.

def get_associates(affiliations, person):
    associates = []
    persons_organizations = set(affiliations[person])

    for possible_associate, organizations in affiliations.items():
        intersection = set(organizations).intersection(persons_organizations)
        num_intersections = len(intersection)

        if intersection:  # This isn't needed, but it's more readable
            associates.extend([possible_associate] * num_intersections)

    return associates

def main(affiliations, person):
    associates = sorted(get_associates(affiliations, person))
    print('Associates:', associates)

if __name__ == '__main__':
    main(demo_affiliations, demo_person)

rawDescription: Python for loops inquiry

description: Python for loops inquiry


code: chatTo = cursor.fetchone()[0]

rawDescription: Python difference between data

description: Python difference between data


code: struct.pack("<f", .5).encode('hex')

rawDescription: Float number to inverse order hex?

description: Float number to inverse order hex


code:
IJ.run(InputImg, "32-bit", "");
IJ.run(InputImg, "Add...", "value=0.375 stack");
IJ.run(InputImg, "Square Root", "stack");
IJ.run(InputImg, "Multiply...", "value=2 stack");

rawDescription: Mathematical Operations on a Jython array


rawDescription: Is it possible to make own syntax rules in Python?


code:
for element in doc.iterfind('.//%s'%tag):
    element.getparent().remove(element)

rawDescription: When using iterdescendants() on an etree, is it ok to modify the tree?


code:
df3
df3.mean(axis=1, level=0)

rawDescription: Mean of repeated columns in pandas dataframe


code:
class xmlParser:
   def __init__(self, filepath, funcname, *args):
        # code to parse data etc.
        exec_func_from_file(funcname, args)

   def exec_func_from_file(self, funcname, *args):
        # code to call function.
        ...
        ...
        functionsobj = functions() # do you really need a class for this?
        funcobj = getattr(functionsobj, funcname)
        funcname(*args)

rawDescription: Call function from a custom file with parameters


code:
adjacent = hypothenuse * math.cos(angle)
opposite = hypothenuse * math.sin(angle)

rawDescription: Python (pygame) Sin, Cos and Tan

description: Python (pygame) Sin, Cos and Tan


code:
class Dicty(models.Model):
    name      = models.CharField(max_length=50)

class KeyVal(models.Model):
    container = models.ForeignKey(Dicty, db_index=True)
    key       = models.CharField(max_length=240, db_index=True)
    value     = models.CharField(max_length=240, db_index=True)

rawDescription: How to store a dictionary on a Django Model?

description: Store a dictionary on a Django Model


code:
def pendingOrders(request):
    userprof = UserProfile.objects.get(user= request.user)
    if userprof.is_student:
        student_account = request.user
        dish = Dishes.objects.all()
        #Getting all pending orders
        order_all_pending = Orders.objects.filter(student_id = student_account,delivered = False)
        pending_orders = Orders.objects.filter(~Q(status = 2),delivered = False)
        for order in order_all_pending:
            #Hack to change QuerySet to pass as JSON
            order.quantity = pending_orders.filter(id__lt = order.id,counterid= order.counterid).count() + 1

        #Returning JSON response to the objects obtained in above statement
        return HttpResponse(serializers.serialize('json',order_all_pending,use_natural_keys=True),mimetype='application/json')
    else:
        return HttpResponse("Something went wrong")

rawDescription: In what format should I respond from django to android after getting http get?


code:
import platform
platform.platform()

rawDescription: Detecting OS platform in Sikuli (jython)


code:
import win32api as w
import win32con as c

def load_device_list():
    """loads all Monitor which are plugged into the pc
    The list is needed to use setPrimary
    """
    workingDevices = []
    i = 0
    while True:
        try:
            Device = w.EnumDisplayDevices(None, i, 0)
            if Device.StateFlags & c.DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: #Attached to desktop
                workingDevices.append(Device)

            i += 1
        except:
            return workingDevices

def setPrimary(id, workingDevices, MonitorPositions):
    """
    param id: index in the workingDevices list.
              Designates which display should be the new primary one

    param workingDevices: List of Monitors returned by load_device_list()

    param MonitorPositions: dictionary of form {id: (x_position, y_position)}
                            specifies the monitor positions

    """

    FlagForPrimary = c.CDS_SET_PRIMARY | c.CDS_UPDATEREGISTRY | c.CDS_NORESET
    FlagForSec = c.CDS_UPDATEREGISTRY | c.CDS_NORESET
    offset_X = - MonitorPositions[id][0]
    offset_Y = - MonitorPositions[id][1]
    numDevs = len(workingDevices)

    #get devmodes, correct positions, and update registry
    for i in range(numDevs):
        devmode = w.EnumDisplaySettings(workingDevices[i].DeviceName, c.ENUM_CURRENT_SETTINGS)
        devmode.Position_x = MonitorPositions[i][0] + offset_X
        devmode.Position_y = MonitorPositions[i][1] + offset_Y
        if(w.ChangeDisplaySettingsEx(workingDevices[i].DeviceName, devmode,
            FlagForSec if i != id else FlagForPrimary) \
            != c.DISP_CHANGE_SUCCESSFUL): return False

    #apply Registry updates once all settings are complete
    return w.ChangeDisplaySettingsEx() == c.DISP_CHANGE_SUCCESSFUL;

if(__name__ == "__main__"):
    devices = load_device_list()
    for dev in devices:
        print("Name: ", dev.DeviceName)

    MonitorPositions = {
        0: (0, -1080),
        1: (0, 0),
        2: (1920, 0)
    }

    setPrimary(0, devices, MonitorPositions)

rawDescription: (WinApi) ChangeDisplaySettingsEx does not work


code:
import sqlalchemy
import pyodbc
engine = sqlalchemy.create_engine("mssql+pyodbc://<username>:<password>@<dsnname>")

# write the DataFrame to a table in the sql database
df.to_sql("table_name", engine)

rawDescription: Get data from pandas into a SQL server with PYODBC


rawDescription: How to modify pythonpath for a WSGI application in alwaysdata.net

description: Modify pythonpath for a WSGI application in alwaysdata.net


code: ast.literal_eval(u"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}")

rawDescription: Convert Unicode Object to Python Dict

description: Convert Unicode Object to Python Dict


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbosity', help='more debug info', action='store_true')
parser._option_string_actions.keys()

rawDescription: How to get available flags out of an ArgumentParser object?

description: Get available flags out of an ArgumentParser object


code:
import os
os.system("rhythmbox <filename>")

rawDescription: Play music in rhythmbox using python

description: Play music in rhythmbox using python


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

from scipy import ndimage

def main():
    measurements = cPickle.load(open('walk_sliced_data', 'r'))
    plot(measurements['ser_1'].values())
    plt.show()

def raw_moment(data, iord, jord):
    nrows, ncols = data.shape
    y, x = np.mgrid[:nrows, :ncols]
    data = data * x**iord * y**jord
    return data.sum()

def intertial_axis(data):
    data_sum = data.sum()
    m10 = raw_moment(data, 1, 0)
    m01 = raw_moment(data, 0, 1)
    x_bar = m10 / data_sum
    y_bar = m01 / data_sum
    u11 = (raw_moment(data, 1, 1) - x_bar * m01) / data_sum
    u20 = (raw_moment(data, 2, 0) - x_bar * m10) / data_sum
    u02 = (raw_moment(data, 0, 2) - y_bar * m01) / data_sum
    angle = 0.5 * np.arctan(2 * u11 / (u20 - u02))
    return x_bar, y_bar, angle

def plot(impacts):
    def plot_subplot(pawprint, ax):
        x_bar, y_bar, angle = intertial_axis(pawprint)
        ax.imshow(pawprint)
        plot_bars(x_bar, y_bar, angle, ax)
        return angle

    fig1 = plt.figure()
    fig2 = plt.figure()
    for i, impact in enumerate(impacts[:9]):
        ax1 = fig1.add_subplot(3,3,i+1)
        ax2 = fig2.add_subplot(3,3,i+1)

        pawprint = impact.sum(axis=2)
        angle = plot_subplot(pawprint, ax1)

        pawprint = ndimage.rotate(pawprint, np.degrees(angle))
        plot_subplot(pawprint, ax2)

    fig1.suptitle('Original')
    fig2.suptitle('Rotated')

def plot_bars(x_bar, y_bar, angle, ax):
    def plot_bar(r, x_bar, y_bar, angle, ax, pattern):
        dx = r * np.cos(angle)
        dy = r * np.sin(angle)
        ax.plot([x_bar - dx, x_bar, x_bar + dx],
                [y_bar - dy, y_bar, y_bar + dy], pattern)
    plot_bar(1, x_bar, y_bar, angle + np.radians(90), ax, 'wo-')
    plot_bar(3, x_bar, y_bar, angle, ax, 'ro-')
    ax.axis('image')

if __name__ == '__main__':
    main()

rawDescription: How to calculate the axis of orientation?

description: Calculate the axis of orientation


code:
def get(self):

    que = db.Query(models.URL).order('-created')
    url_list = que.fetch(limit=100)

    path = self.request.path
    if doRender(self,path):
        return
    doRender(self,'base/index.html', { 'url_list' : url_list })

rawDescription: Display GAE list by most recent entry

description: Display GAE list by most recent entry


code:
import wx

class TreeFrame(wx.Frame):

    def __init__(self):

        wx.Frame.__init__(self, None, title='TreeCtrl')
        tree_ctrl = wx.TreeCtrl(self, -1, style=wx.TR_DEFAULT_STYLE | \
                                wx.TR_FULL_ROW_HIGHLIGHT | \
                                wx.TR_EDIT_LABELS)

        # NOTE: Bind callback which will be called when the button is clicked.
        button = wx.Button(self, -1, label='Add banana')
        button.Bind(wx.EVT_BUTTON, self.add_banana)

        # NOTE sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(tree_ctrl, 1, wx.EXPAND|wx.ALL)
        sizer.Add(button, 0, wx.EXPAND|wx.ALL)
        self.SetSizer(sizer)

        # Add the tree root
        root = tree_ctrl.AddRoot('Food')
        tree_ctrl.AppendItem(root,'Fruit (3)')
        tree_ctrl.AppendItem(tree_ctrl.GetLastChild(root),'Apple (1)')
        tree_ctrl.AppendItem(tree_ctrl.GetLastChild(root),'Orange (2)')

        tree_ctrl.ExpandAll()
        self.Centre()

         # NOTE: Save tree_ctrl, root as attribute
         #       to make them available in add_banana method.
        self.tree_ctrl = tree_ctrl
        self.root = root

    # called when the button is clicked.
    def add_banana(self, evt):
        self.tree_ctrl.AppendItem(self.tree_ctrl.GetLastChild(self.root), 'Banana (3)')

if __name__ == '__main__':
    app = wx.App(0)
    frame = TreeFrame()
    frame.Show()
    app.MainLoop()

rawDescription: Updating treectrl in wxPython

description: Updating treectrl in wxPython


rawDescription: How to get reference to module by string name and call its method by string name?

description: Get reference to module by string name and call its method by string name


code:
total = 0.0
count = 0.0
for s in G:
    G1=ShortestPaths(G,s)
    total += sum([G1[s] for s in G1])
    count += (len(G1)-1)
return float(total / count) if count else None

rawDescription: Finding the mean of nodes in an undirected graph


code:
import weakref

class A:
    pass

# a new object is created, and the name "x" is set to reference the object,
# giving a reference count of 1
x = A()

# a weak reference is created referencing the object that the name x references
# the reference count is still 1 though, because x is still the only strong
# reference
weak_reference = weakref.ref(x)

# the only strong reference to the object is deleted (x), reducing the reference
# count to 0 this means that the object is destroyed, and at this point
# "weak_reference" becomes dangling, and calls return None
del x

assert weak_reference() is None

rawDescription: How to create dangling pointer (in stack or heap) in python

description: Create dangling pointer (in stack or heap) in python


rawDescription: Sort and show objects with True in BooleanField first


code:
def setworldcoordinates(self, llx, lly, urx, ury):
    """Set up a user defined coordinate-system.

    Arguments:
    llx -- a number, x-coordinate of lower left corner of canvas
    lly -- a number, y-coordinate of lower left corner of canvas
    urx -- a number, x-coordinate of upper right corner of canvas
    ury -- a number, y-coordinate of upper right corner of canvas

    Set up user coodinat-system and switch to mode 'world' if necessary.
    This performs a screen.reset. If mode 'world' is already active,
    all drawings are redrawn according to the new coordinates.

    But ATTENTION: in user-defined coordinatesystems angles may appear
    distorted. (see Screen.mode())

    Example (for a TurtleScreen instance named screen):
    >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
    >>> for _ in range(36):
    ...     left(10)
    ...     forward(0.5)
    """
    if self.mode() != "world":
        self.mode("world")
    xspan = float(urx - llx)
    yspan = float(ury - lly)
    wx, wy = self._window_size()
    self.screensize(wx-20, wy-20)
    oldxscale, oldyscale = self.xscale, self.yscale
    self.xscale = self.canvwidth / xspan
    self.yscale = self.canvheight / yspan
    srx1 = llx * self.xscale
    sry1 = -ury * self.yscale
    srx2 = self.canvwidth + srx1
    sry2 = self.canvheight + sry1
    self._setscrollregion(srx1, sry1, srx2, sry2)
    self._rescale(self.xscale/oldxscale, self.yscale/oldyscale)
    self.update()

rawDescription: what does the turtle.setworldcoordinates function do?

description: What does the turtle.setworldcoordinates function do


code: session.query(TableName).filter(func.convert(func.VARCHAR(8), TableName.datetimefield, 8) >= datetime.time(0,0)).all()

rawDescription: filtering time range in datetime field in sqlalchemy

description: Filtering time range in datetime field in sqlalchemy


code:
import sys
import re

def ordnaText(text):
    text = text.lower()
    text = re.sub(u'\W', '', text, flags=re.UNICODE)
    if text.isalnum() == True:
        return text

userinput = raw_input('....')
userinput = userinput.decode(sys.stdin.encoding)
something = ordnaText(userinput)

rawDescription: Remove non alphanumeric from sting but keeping åäö


rawDescription: How to convert a dict of lists to a list of tuples of key and value in python?

description: Convert a dict of lists to a list of tuples of key and value in python


code: start_time = start_time.replace(minute=ceil_to, second=0, microsecond=0)

rawDescription: How to alter the time in python?

description: Alter the time in python


code:
import boto

s3 = boto.connect_s3()

#Create a versioned bucket
bucket = s3.create_bucket("versioned.example.com")
bucket.configure_versioning(True)

#Create a new key and make a few versions
key = new_key("versioned_object")
key.set_contents_from_string("Version 1")
key.set_contents_from_string("Version 2")

#Try to delete bucket
bucket.delete()   ## FAILS with 409 Conflict

#Delete our key then try to delete our bucket again
bucket.delete_key("versioned_object")
bucket.delete()   ## STILL FAILS with 409 Conflict

#Let's see what's in there
list(bucket.list())   ## Returns empty list []

#What's in there including versions?
list(bucket.list_versions())   ## Returns list of keys and delete markers

#This time delete all versions including delete markers
for version in bucket.list_versions():
    #NOTE we're still using bucket.delete, we're just adding the version_id parameter
    bucket.delete_key(version.name, version_id = version.version_id)

#Now what's in there
list(bucket.list_versions())   ## Returns empty list []

#Ok, now delete the bucket
bucket.delete()   ## SUCCESS!!

rawDescription: How to delete a s3 version from a bucket using boto and python

description: Delete a s3 version from a bucket using boto and python


code:
def controlTextDidChange_(self, notification):
    NSLog("textdidchange")

rawDescription: Implimenting NSText delegate methods in PyObjc and Cocoa


code:
import os
for root, dirs, files in os.walk(top):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))

rawDescription: reading a file and getting the MD5 hash in python

description: Reading a file and getting the MD5 hash in python


code:
d = math.sqrt(mouse_x * mouse_x + mouse_y * mouse_y)
self.slope_x = mouse_x / d - 300
self.slope_y = mouse_y / d - 400

rawDescription: Pygame Object Movement With Slopes/Angles


code:
df = pd.DataFrame(np.random.randint(0, 2, (2, 8)))
df
df == 0
(df == 0).all()
df.columns[(df == 0).all()]
df.ix[:, (df == 0).all()]

rawDescription: Python pandas: select columns with all zero entries in dataframe


code:
coldict = {c: c.split('-', 2)[2] for c in df.columns[1:]}
df = df[['gene'] + sorted(df.ix[:, 1:].columns, key=lambda x: coldict[x])]

rawDescription: Column sorting by label

description: Column sorting by label


code:
def __repr__(self):
        routes = self.match_routes + [v for k, v in \
            self.build_routes.iteritems() if v not in self.match_routes]

        return '<Router(%r)>' % routes

rawDescription: In webapp2, how can I get a list of all route URIs?


rawDescription: Checking if a field allows null values in Django


code:
#!/usr/bin/env python
import itertools
import socket
import sys
from functools import partial
from multiprocessing import Pool

def resolve(host, domain=""):
    host = ''.join(host) + domain
    try:
        return host, socket.gethostbyname(host), None
    except EnvironmentError as e:
        return host, None, e

def main():
    alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
    size = int(sys.argv[2])
    resolve_host = partial(resolve, domain="." + sys.argv[3])
    combo = itertools.combinations_with_replacement(alphabet, size)

    pool = Pool(20)
    for host, ip, error in pool.imap_unordered(resolve_host, combo):
        if error is None:
           print("%s resolved to --> %s" % (host, ip))
        else: # error
           print("Can't resolve %s, error: %s" % (host, error))

if __name__=="__main__":
   main()

rawDescription: Python write out itertools

description: Python write out itertools


code:
song_points = {}
for response in survey_responses.find():
    for song in response['favorite_songs_of_2009']:
        title = song['title']
        song_points[title] = song_points.get(title, 0) + song['points']

rawDescription: Grouping by Nested Object Keys in MongoDB


code:
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile

profile = FirefoxProfile(path_to_my_profile)
driver = webdriver.Firefox(profile)

rawDescription: python selenium import my regular firefox profile ( add-ons)

description: Python selenium import my regular firefox profile ( add-ons)


code:
from django.core import management

@task()
def my_task():
    management.call_command('my_task')

rawDescription: how can i split up a large django-celery tasks.py module into smaller chunks?

description: Split up a large django-celery tasks.py module into smaller chunks


code:
class DuplicateFilter(object):
    def __init__(self):
        self.msgs = set()

    def filter(self, record):
        rv = record.msg not in self.msgs
        self.msgs.add(record.msg)
        return rv

dup_filter = DuplicateFilter()
logger.addFilter(dup_filter)
for i in range(10):
    canned_example()
logger.removeFilter(dup_filter)

rawDescription: Python logging: print message only once

description: Python logging: print message only once


code:
import pandas as pd
import numpy as np
from string import ascii_uppercase
dt_rng = pd.date_range(start = pd.tseries.tools.to_datetime('2012-12-31'),
                       end   = pd.tseries.tools.to_datetime('2014-12-28'),
                       freq  = 'D')
df = pd.DataFrame(index = xrange(len(dt_rng) * 10),
                  columns = ['product', 'dt', 'unit_sales'])
df.product = sorted(np.tile([chr for chr in ascii_uppercase[:10]], len(dt_rng)))
df.dt = reduce(lambda x, y: x.append(y), [dt_rng] * 10)
df.unit_sales = np.random.random_integers(0, 25, len(dt_rng) * 10)

rawDescription: `numpy.tile()` sorts automatically - is there an alternative?


code:
root = tk.Tk()
root.overrideredirect(True)

rawDescription: How to edit the root window in Python Tkinter

description: Edit the root window in Python Tkinter


code:
from itertools import islice

# Line that data starts from, zero-indexed.
START_LINE = 20
# The column containing the data in question, zero-indexed.
DATA_COL = 10
# The value present when a measurement failed.
FAILED_MEASUREMENT = '-999.9'

with open('data.txt', 'r') as f:

    bt_values = []

    for val in (row.split()[DATA_COL] for row in islice(f, START_LINE, None)):

        if val != FAILED_MEASUREMENT:
            bt_values.append(float(val))

    min_bt = min(bt_values)
    max_bt = max(bt_values)

with open('minBt.txt', 'a') as minFile:
    print(min_bt, file=minFile)

with open('maxBt.txt', 'a') as maxFile:
    print(max_bt, file=maxFile)

rawDescription: Using Python v3.5 to load a tab-delimited file, omit some rows, and output max and min floating numbers in a specific column to a new file


rawDescription: convert HEX STRING to Binary and Right Shift 22 and with 0F

description: Convert HEX STRING to Binary and Right Shift 22 and with 0F


code: outfile = open(os.path.join(dir, os.path.basename(name)), 'wb')

rawDescription: Logical python question - handling directories and files in them


code:
print('a\nb')
print(r'a\nb')

rawDescription: regex syntax in python, the r before the opening quote

description: Regex syntax in python, the r before the opening quote


code:
import urllib.request

def download_data(url, file_to_save):
    filename, rsp = urllib.request.urlretrieve(url, file_to_save)
    # Assuming everything worked, the file has been downloaded to file_to_save

with open('Links.txt') as file:
    for line in file:
        url = line.rstrip() # adding this here to remove extraneous '\n' from string
        file_name = url[54:].rsplit('.ST', 1)[0]
        save_destination = 'C:\\Download data\\Data\\' + file_name + '.csv'
        download_data(url, save_destination)

rawDescription: Python: CSV directly from the web, resulting in unusable data


code:
b = '%s' * 3
b % tuple(range(3))

rawDescription: format string in python 2.5 unpacking a list

description: Format string in python 2.5 unpacking a list


code: b.reindex(a.index, method='ffill')

rawDescription: Resample a time series with the index of another time series


code:
from urllib2 import ProxyHandler,build_opener,install_opener

PROXY="http://USERNAME:PASSWD@ADDRESS:PORT"

opener = build_opener(ProxyHandler({"http" : PROXY}))

install_opener(opener)

rawDescription: Python: urllib2 multipart/form-data and proxies


code:
import random

acceptable_words = []
acceptable_letters = []
user_words = []

dice = [
    ['r', 'i', 'f', 'o', 'b', 'x'],
    ['i', 'f', 'e', 'h', 'e', 'y'],
    ['d', 'e', 'n', 'o', 'w', 's'],
    ['u', 't', 'o', 'k', 'n', 'd'],
    ['h', 'm', 's', 'r', 'a', 'o'],
    ['l', 'u', 'p', 'e', 't', 's'],
    ['a', 'c', 'i', 't', 'o', 'a'],
    ['y', 'l', 'g', 'k', 'u', 'e'],
    ['qu', 'b', 'm', 'j', 'o', 'a'],
    ['e', 'h', 'i', 's', 'p', 'n'],
    ['v', 'e', 't', 'i', 'g', 'n'],
    ['b', 'a', 'l', 'i', 'y', 't'],
    ['e', 'z', 'a', 'v', 'n', 'd'],
    ['r', 'a', 'l', 'e', 's', 'c'],
    ['u', 'w', 'i', 'l', 'r', 'g'],
    ['p', 'a', 'c', 'e', 'm', 'd']]

def load_acceptable_words():
    with open('TWL06.txt') as word_file:
        for line in word_file:
            acceptable_words.append(line.strip().lower())

def roll_dice():
    for die in dice:
        acceptable_letters.append(random.choice(die))

def print_game_grid():
    for i in range(4):
        print_game_row(i)

def print_game_row(i):
    print (' '.join(acceptable_letters[i:i+4]))

def run_game_loop():
    while True:
        run_one_turn()

def run_one_turn():
    candidate = input("Enter a word you found.").strip().lower()
    if (check_is_long_enough(candidate)
        and check_can_be_spelled(candidate)
        and check_is_acceptable_word(candidate)):
        accept_user_word(candidate)

def check_is_long_enough(candidate):
    if len(candidate) >= 3:
        return True
    else:
        print("That word is to short.")
        return False

def check_can_be_spelled(candidate):
    if all(letter in acceptable_letters for letter in candidate):
        return True
    else:
        print("That word is not in the dice.")
        return False

def check_is_acceptable_word(candidate):
    if candidate in acceptable_words:
        return True
    else:
        print("That is not one of the ", len(acceptable_words), "words I know.")
        return False

def accept_user_word(word):
    user_words.append(word)

def main():
    print("This game is similar to Boggle.")
    print("Your goal is to guess as many words from the rolled dice as you can.")
    print("You can use any letters in the grid to play.")
    print("Your words must be 3 letters or longer.")
    play_quit = input("Press 'p' to play or any other key to quit.").strip().lower()
    if play_quit == "p":
        load_acceptable_words()
        roll_dice()
        print_game_grid()
        run_game_loop()
    else:
        print("Thanks for not playing.")

main()

rawDescription: It's in the indents (I think) Python

description: It's in the indents (I think) Python


code:
from itertools import groupby
from operator import itemgetter
res = []
for k,v in groupby(sorted(d.items(),key=itemgetter(1)),key=itemgetter(1)):
    v = list(v)
    mx = max(v,key=lambda x:len(x[0]))
    res += [x for x in v if len(x[0]) == len(mx[0])]

res.sort()
for k,v in res:
    print(k,v)
('/a/b/c/d', [10, 22, 12])
('/e/f/h/i', [11, 28, 16])
('/j/k/l/m', [10, 22, 12])

rawDescription: Python: unique values with longest keys

description: Python: unique values with longest keys


rawDescription: Python3 re.split() via character which is not in special substring


code:
class Constraint:
    def __init__(self, table, column, constraint, error_or_warning):
        """
        examples:
            Constraint('Lib_Cable','kV', '> 0', 'error')
            Constraint('Lib_Cable','Insulation', '!= 0', 'warning')

        """
        self.table, self.column, self.constraint, self.error_or_warning = \
        table, column, constraint, error_or_warning

    def check (self, db_conn):
        c = db_conn.cursor()
        c.row_factory = sqlite3.Row

        query = "SELECT * FROM %(table)s WHERE NOT (%(column)s %(constraint)s)" % \
                {'table'      : self.table,
                 'column'     : self.column,
                 'constraint' : self.constraint }
        # [FIXME] start a transaction here - guard against novice SQL injections?
        res = c.execute(query)

        for row in res:
            print ( "%(error_or_warning)s: Row with key %(key)s in table %(table)s violates constraint %(column)s %(constraint)s)." % \
                {'key'        : row['KeyName'],
                 'table'      : self.table,
                 'column'     : self.column,
                 'constraint' : self.constraint,
                 'error_or_warning' : self.error_or_warning} )

        # [FIXME] discard transaction

Constraint_1 = Constraint('Lib_Cable', 'Insulation', '!= 0', 'error')
Constraint_1.check(db_conn)

rawDescription: Check data from SQLite meets constraints like "number in range x-y"


code:
s = Series(np.random.rand(10))
np.argsort(s.values)
s[np.argsort(s.values)]

rawDescription: pandas sort with smaller memory footprint?

description: Pandas sort with smaller memory footprint


rawDescription: Iterating through lists of different lengths which are inside a list


code:
import Orange
iris = Orange.data.Table("iris")
# Add some weights to the iris dataset
weight = Orange.feature.Continuous("weight")
weight_id = -10
iris.domain.add_meta(weight_id, weight)
iris.add_meta_attribute(weight, 1.0)
for i in range(50, 150):
     iris[i][weight] = 10

# Train a tree classifier on weighted data.
clsf = Orange.classification.tree.TreeLearner(iris, weight_id)

# Evaluate learner performance on weighted data
results = Orange.evaluation.testing.cross_validation(
    [Orange.classification.tree.TreeLearner,
     Orange.classification.bayes.NaiveLearner],
    (iris, weight_id)  # Note how you pass the weight id to testing functions
)
auc = Orange.evaluation.scoring.AUC(results)
ca = Orange.evaluation.scoring.CA(results)

rawDescription: How to set up and use sample weight in the Orange python package?

description: Set up and use sample weight in the Orange python package


code:
closest_events = []
for t in no1:
    #sort
    i = np.argsort(np.abs(t['time']-no2['time']))
    # select only events with the same no_of_interest_time and electrode
    i = i[(no2['electrode']==t['electrode']) &
          (no2['no_of_interest_time']==t['no_of_interest_time'])]
    closest = i[0] if len(i)>0 else np.nan
    closest_events.append(closest)

rawDescription: find close elements in numpy recarray

description: Find close elements in numpy recarray


code:
import matplotlib.pyplot as plt
import time
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([],[])
ax.set_xlim(3)
ax.set_ylim(3)
line.set_data([1,2,3],[1,2,3])

def init():
            """ Initializes the plots to have zero values."""
            line.set_data([],[])
            return line,

def animate(n, *args, **kwargs):
    if(n%2==0):
        line.set_data([],[])
    else:
        line.set_data([1,2,3],[1,2,3])

    return line,

ani = animation.FuncAnimation(fig, animate, init_func=init,frames =100, interval=10, blit=False, repeat =False)
fig.show()

rawDescription: Plot a graph, clear its axes, then plot a new graph


code:
import tkinter
from functools import partial

def font_config(widget, fontslant, event):
    widget.configure(font=fontslant)

parent = tkinter.Tk()
text = tkinter.Label(parent, text="Hello Text")
text.bind("<Enter>", partial(font_config, text, "Helvetica 9 italic"))
text.bind("<Leave>", partial(font_config, text, "Helvetica 9"))
text.pack()

tkinter.mainloop()

rawDescription: Italicize tkinter label text on focus

description: Italicize tkinter label text on focus


code:
from PIL import Image
img = Image.open('test.png')
img.show()

rawDescription: Showing an image from console in Python

description: Showing an image from console in Python


code:
import subprocess
import os

p = subprocess.Popen([os.path.join("C:/", "Program Files(x86)", "VideoLAN", "VLC", "vlc.exe"),os.path.join("C:/", "Users", "Kamilos", "Desktop", "TBT", "Tbt_S01E17.avi")])

rawDescription: Launch VLC through Python

description: Launch VLC through Python


code:
RX = re.compile(r'^.*?\(\d+,\s0,.*\s0\)\s*$')

outfile = open('destination.sql', 'w')
for ln in open('source.sql', 'r').xreadlines():
    replace1 = ln.replace("INSERT INTO `Tbl_ABC` VALUES (", "")
    replace2 = replace1.replace(")", "")
    list_replace = replace2.split(',')
    #print list_replace
    #print '%s ,%s' % (list_replace[1], list_replace[6])
    if list_replace[6]==0 and list_replace[1] == 0:
        #start write line to destination.sql!!!!!!!! NEED HELP
        #if RX.match(ln):
        outfile.write(ln)

rawDescription: Read from source.sql write to destiantion.sql with python script?


code:
def myfunction():
    while True: # loop forever
        if time.time() > 5 + last_time:
            last_time = time.time()
            print(mylist[0]) # doesn't print anything
        time.sleep(1) # wait for one second for mylist to be updated, yield to main thread

rawDescription: Python 3.3 - Send variable to thread

description: Python 3.3 - Send variable to thread


code:
for line in pot:
    temp = []
    for i in range(len(line)-1):
        temp.append( (line[i],line[i+1]) )
    val.append(temp)

rawDescription: Changing nested list of numbers to nested list o tuples


code:
class Attribute(object):
    def __init__(self,attr,*args): # no transform parameter or instance variable
        self.attr = attr
        self.string = "string" in args
    def __set__(self, instance, value): # look up transform on instance, rather than self
        if self.string:
            cmds.setAttr(instance.transform.path()+"."+self.attr,value,dt="string")
        else:
            cmds.setAttr(instance.transform.path()+"."+self.attr,value)
    def __get__(self, instance, owner): # here too
        if self.string:
            return     cmds.getAttr(instance.transform.path()+"."+self.attr,dt="string")
        return cmds.getAttr(instance.transform.path()+"."+self.attr)

# Transform can stay the same, though you could merge set_object into __init__

class Clip(object):
    # no more transform class variable
    start = Attribute("STA") # no more transform argument passed to the Attributes
    end = Attribute("END")
    loop = Attribute("Loop")
    relative = Attribute("RelativeToStart")
    speedState = Attribute("SpeedState")
    speed = Attribute("SpeedVal")

    def __init__(self,transform):
        self.transform = Transform() # create transform as an instance variable
        self.transform.setObject(transform)

rawDescription: Initialization order causes class instance problems


code:
def make_daymenu():
    daymenu.delete(0,31)
    for the_day in list_of_days:
        daymenu.add_command(label=the_day, command=lambda : day_setter(the_day))
    window.config(menu=menubar)

rawDescription: Tkinter menu for chosing a date

description: Tkinter menu for chosing a date


code: correctlyNamedDirectories = [os.path.join(path, subname) for path, dirnames, filenames in os.walk(directory) for subname in dirnames + filenames]

rawDescription: Cannot seem to crawl a deep directory with my Python script, any idea?


rawDescription: format and Print a list in a file

description: Format and Print a list in a file


code:
from PySide import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import sys

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.fft_frame = FftFrame(self)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.fft_frame)
        self.setLayout(self.layout)
        self.setCentralWidget(self.fft_frame)

class FftFrame(QtGui.QFrame):
    def __init__(self, parent=None):
        super(FftFrame, self).__init__(parent)
        self.setFrameShape(QtGui.QFrame.StyledPanel)
        self.parent = parent
        self.graph_view = GraphView('fftFrame', 'FFT Transform:', 'FFT Transform of Signal', self)

    def resizeEvent(self, event):
        self.graph_view.setGeometry(self.rect())

class GraphView(QtGui.QWidget):
    def __init__(self, name, title, graph_title, parent = None):
        super(GraphView, self).__init__(parent)

        self.name = name
        self.graph_title = graph_title

        self.dpi = 100
        self.fig = Figure((5.0, 3.0), dpi = self.dpi, facecolor = (1,1,1), edgecolor = (0,0,0))
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.Title = QtGui.QLabel(self)
        self.Title.setText(title)

        self.layout = QtGui.QVBoxLayout()
        self.layout.addWidget(self.Title)
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.canvas.show()

    def update_graph(self, data, title = None):
        self.axes.clear()
        self.axes.plot(data)
        if title != None:
            self.axes.set_title(title)

        self.canvas.draw()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()

rawDescription: How do I auto fit a Matplotlib figure inside a PySide QFrame?

description: Auto fit a Matplotlib figure inside a PySide QFrame


code:
import numpy as np
from mayavi import mlab
vertices = np.array([[0, 1, 0, 0],[0, 0, 1, 0],[0, 0, 0, 1]])
faces = np.array([[0, 1, 0, 0],[1, 2, 1, 2],[2, 3, 3, 3]])
mlab.triangular_mesh(vertices[0,:], vertices[1,:], vertices[2,:], faces.T)
mlab.show()

rawDescription: How to visualize 3D delaunay triangulation in Python?

description: Visualize 3D delaunay triangulation in Python


code:
if not os.path.exists("/var/log/folder"):
    os.makedirs("/var/log/folder")

rawDescription: Install folder under /var/log in Python setup script


rawDescription: Addpath for Python like in Octave

description: Addpath for Python like in Octave


rawDescription: Deep copy a filtered PySpark dataframe from a Hive query


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

x1 = np.random.randn(1000,1)
y1 = np.random.randn(1000,1) # dense data
x2 = np.random.randn(100,1)
y2 = np.random.randn(100,1)
x3 = np.random.randn(10,1)
y3 = np.random.randn(10,1) # sparse data

fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# plot sparse data after dense data
ax.scatter(x1, y1, c='none', edgecolors='blue')
ax.scatter(x2, y2, c='none', edgecolors='green')
ax.scatter(x3, y3, c='none', edgecolors='red')

rawDescription: What is the best way to represent density in matplotlib without using color?


code:
"""
os.path.getsize(path)
Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.
"""

rawDescription: What is the size denomination in os.path.size()? - python


code:
messages = [string for string in messages
              if not any(word in bannedWords for word in string)]

rawDescription: How to iterate through two lists without the use of nested "for" loops

description: Iterate through two lists without the use of nested "for" loops


code:
class Machine(object):
    lst = []
    def __init__(self, name):
        self.name = name
        self.id = len(Machine.lst)
        Machine.lst.append(self)

m0 = Machine("zero")
m1 = Machine("one")

print(Machine.lst[1].name)  # prints "one"

rawDescription: How to call a different instance of the same class in python?

description: Call a different instance of the same class in python


code:
from django.core.paginator import Paginator
d = {'a': [1,2], 'b': [3,4]}
p = Paginator(d, 1)
p1 = p.page(1)
t = tuple(d.items())
t
p = Paginator(t, 1)
p.page(1).object_list
p.page(2).object_list

rawDescription: Django pagination with dictionary where key is a list


code: yourVar = "Total of the sale is: ${:,.2f}".format(TotalAmount)

rawDescription: Python - Add Formatted Number To String

description: Python - Add Formatted Number To String


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

N = 5
men1 = (130, 90, 70, 64, 55)
men2 = (120, 85, 62, 50, 53)
men3 = (100, 70, 60, 45, 50)

ind = np.arange(N) + .15 # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, men1, width, color='g')
rects2 = ax.bar(ind, men2, width, color='r')
rects3 = ax.bar(ind, men3, width, color='b')

women4 = (140, 90, 78, 65, 50)
women5 = (130, 80, 70, 60, 45)
women6 = (120, 60, 60, 55, 44)

xtra_space = 0.05
rects2 = ax.bar(ind + width + xtra_space , women1, width, color='orange')
rects2 = ax.bar(ind + width + xtra_space, women2, width, color='cyan')
rects2 = ax.bar(ind + width + xtra_space, women3, width, color='purple')

# add some text for labels, title and axes ticks
ax.set_ylabel('Population, millions')
ax.set_title('Population: Age Structure')

ax.set_xticks(ind+width+xtra_space)
ax.set_xticklabels( ('USA', 'Brazil', 'Russia', 'Japan', 'Mexico') )

plt.show()

rawDescription: How do I plot stacked histograms side by side in matplotlib?

description: Plot stacked histograms side by side in matplotlib


code:
import numpy as np
import matplotlib.pylab as pl
from matplotlib.colors import ListedColormap

# Random data
data1 = np.random.random((4,4))

# Choose colormap
cmap = pl.cm.RdBu

# Get the colormap colors
my_cmap = cmap(np.arange(cmap.N))

# Set alpha
my_cmap[:,-1] = np.linspace(0, 1, cmap.N)

# Create new colormap
my_cmap = ListedColormap(my_cmap)

pl.figure()
pl.subplot(121)
pl.pcolormesh(data1, cmap=pl.cm.RdBu)
pl.colorbar()

pl.subplot(122)
pl.pcolormesh(data1, cmap=my_cmap)
pl.colorbar()

rawDescription: Add alpha to an existing matplotlib colormap


rawDescription: select pandas rows by excluding index number

description: Select pandas rows by excluding index number


code:
if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        cd = form.cleaned_data
        username = request.session['username']
        if Member.objects.filter(username=username).exists():
            member_obj = Member.objects.get(username=username)
            profile_pic = ProfilePic.objects.get(user=member_obj)
            profile_pic.user = member_obj
            # you can update other fields by using object.field_name (e.g. profile_pic.text = request.POST.get['text']
            profile_pic.save()
        else:
            ProfilePic.objects.create(user=username)
        return HttpResponse('success')
    else:
        return HttpResponse(form.errors)
else:
    form = UploadFileForm

rawDescription: Update existing row in database in forms - Django


code:
from operator import mul
''.join(map(mul, seq, rep))

rawDescription: Best way to multiply string by array

description: Multiply string by array


code: np.where(mask_cntr == cntr, 1.0, 0.0)

rawDescription: Masking values in numpy array

description: Masking values in numpy array


code:
import numpy as np
import itertools

a_dict = {'a': [1,2], 'b': [2,], 'c': [1,3]}
b_dict = {'a': [6], 'c': [4]}

print(list(itertools.chain.from_iterable(
    itertools.product(value, b_dict[key]) for key,value in a_dict.iteritems()
    if key in b_dict)))
# [(1, 6), (2, 6), (1, 4), (3, 4)]

rawDescription: List of products of values for all keys that match in two dictionaries


code:
from PIL import Image
import numpy as np
import sys

sub = Image.open(sys.argv[1])
sub = sub.convert("RGBA")
data = np.array(sub)
red, green, blue, alpha = data.T
data = np.array([blue, green, red, alpha])
data = data.transpose()
sub = Image.fromarray(data)

rawDescription: How to convert BGR image to RGB image using PIL in Python?

description: Convert BGR image to RGB image using PIL in Python


code:
import pandas as pd
orig_df = pd.read_excel(orig_excel_path, sheetname=sheetname)
orig_df[orig_df['Visited'] == 'UK'].to_excel(new_excel_path, sheet_name=new_sheetname)

rawDescription: Python to save needed rows in Excel contents


rawDescription: Subprocess head versus DictReader to get header data (quickest way to pull file header info)


code:
cookies = {'MSW_unitgroup': 'eu'}  # european units

headers = {'Accept': '*/*',
           'Accept-Encoding': 'gzip, deflate',
           'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2,ru;q=0.2,ja;q=0.2',
           'User-Agent': 'python-requests/2.6.0 CPython/2.7.6 Darwin/14.1.0'}

r = requests.get(url, headers=headers, cookies=cookies)

rawDescription: How does a website know your metric system, date format ...?


code:
import csv

with open('file2.csv', 'rb') as updates_fh:
    updates = {tuple(r[:2]): r for r in csv.reader(updates_fh)}

with open('file1.csv', 'rb') as infh, open('output.csv', 'wb') as outfh:
    writer = csv.writer(outfh)
    writer.writerows((updates.get(tuple(r[:2]), r) for r in csv.reader(infh)))

rawDescription: python:compare two large csv files by two reference columns and update another column

description: Python:compare two large csv files by two reference columns and update another column


rawDescription: Regular Expression to test the presence and match a string at the same time


code:
from twython import Twython

twitter = Twython(
    twitter_token = 'consumer_key',
    twitter_secret = 'consumer_secret',
    oauth_token = 'access_token',
    oauth_token_secret = 'access_token_secret'
)

twitter.updateStatusWithMedia('/home/blah/projects/pathexample/static/example.png', status='hello!')

rawDescription: Python, how to POST statuses/update_with_media to Twitter?


code:
def search(p):
    s=read_wordsearch()
    for line in s:
        if p in ''.join(line):
            return True

rawDescription: Search in matrix - python

description: Search in matrix - python


code:
from PIL import Image
img = Image.open("image.jpg")
img.size
img2 = img.resize((144,144), Image.ANTIALIAS)
img.size
img2.size

rawDescription: How to force Pillow to resize an image to an arbitrary size?

description: Force Pillow to resize an image to an arbitrary size


code:
for file in os.listdir(mydir):
  if file.endswith(".fasta"):
    with open(file, 'r') as myfile:
      data = "".join(line for line in myfile if line[:1]!='>')

rawDescription: How do I delete line starting with ">" while reading a file to string in Python

description: Delete line starting with ">" while reading a file to string in Python


code:
from django.db.models import Q
expense.objects.filter(
    Q(name__icontains=q) | Q(amount__icontains=q) | Q(category__icontains=q)
)

rawDescription: How to get more than one field with django filter icontains

description: Get more than one field with django filter icontains


code:
def random_unique_floats(n):
    used = bytearray(0 for i in xrange(2**32 // 8))
    count = 0
    while count < n:
        bits = random.getrandbits(32)
        value = struct.unpack('f', struct.pack('I', bits))[0]
        if not math.isinf(value) and not math.isnan(value):
            index = bits // 8
            mask = 0x01 << (bits & 0x07)
            if used[index] & mask == 0:
                yield value
                used[index] |= mask
                count += 1

for num in random_unique_floats(size):
    file.write(struct.pack('f', num))

rawDescription: Generate large number of unique random float32 numbers


code: from my_app.api import my_function

rawDescription: Django: call API function from inside models


code:
sprite.x=20
pixels=10
def update(dt):
    if sprite.x != 40:
        if move_right == True:
            sprite.x = min(sprite.x + pixels * dt, 40)
pyglet.clock.schedule_interval(update, 1/60.0)

rawDescription: Using the update method to control sprite animations in Pyglet


rawDescription: Get formula from Excel cell with python xlrd


code:
x = bitarray(b'0000')
y = bitarray(b'0000')
x == y
hash(x) == hash(y)

rawDescription: Python bitarray set

description: Python bitarray set


code:
def message(sock, delimiter):
    buf = ''
    while True:
        data = sock.read(4096)
        if not data:
            # If the socket closes with no delimiter, this will
            # treat the last "partial file" as a complete file.
            # If that's not what you want, just return, or raise.
            yield buf
            return
        buf += data
        messages = buf.split(delimiter)
        for message in messages[:-1]:
            yield message
        buf = message[-1]

rawDescription: Python Client/Server send big size files


code:
SLOT_LENGTH = 1000 * 60 *5
for line in file:
    slot = convert_time_string_to_unix_time(line) / SLOT_LENGTH
    bucket[slot] = bucket.get(slot, 0) + 1

for slot in sorted(bucket.keys()):
    print(
        convert_unix_time_to_time_string(slot * SLOT_LENGTH),
        convert_unix_time_to_time_string((slot + 1) * SLOT_LENGTH - 1),
        bucket[slot]
    )

rawDescription: Parse timestamps in plain text file and count them per 5 minute intervals


code: np.where(a=='Call', b, c)

rawDescription: Map one numpy array on to another on condition


code:
threads = [threading.Thread(target=myFunc) for i in range(n)]
for t in threads:
    t.start()
...
for t in threads:
    t.join()

rawDescription: How can I force IPython to only give me a new prompt when all threads have finished

description: Force IPython to only give me a new prompt when all threads have finished


code:
import ast

with open("test.txt", "r") as f:
    for line in f:
        li = ast.literal_eval(line)
        edge_u = [x[0] for x in li]
        edge_v = [x[1] for x in li]

rawDescription: Python parsing the lines from a file

description: Python parsing the lines from a file


code:
now  = time.strftime("%X")
peer = socket.getpeername()
print("{} - {}".format(now, peer))

rawDescription: Python several variables/functions resutl same line


code:
import Tkinter
import tkFileDialog
import tkSimpleDialog
from tkFileDialog import askopenfilename
import os

# Set up GUI

def main():

    root = Tkinter.Tk();
    root.withdraw()

    # Prompt for user info
    File_number = tkSimpleDialog.askinteger("File number",
                                            "How many files do you want to compare?")

    if not File_number:
        return

    user_fiels = []

    max_file_no = int(File_number)
    current_file = 1;

    while(current_file <= max_file_no):

        fileloc = tkFileDialog.askopenfilename(parent=root, title='Choose file {}'.format(current_file))

        if not fileloc:
            continue

        fileloc_name_clean = os.path.splitext(fileloc)[0]
        fileloc_name = os.path.basename(fileloc_name_clean)

        user_fiels.append([fileloc, fileloc_name_clean, fileloc_name])

        current_file += 1

        #print(fileloc_name_clean, fileloc_name)

    print(user_fiels)

main()

rawDescription: Python: Looping a certain amount of time in order different process


code:
self.p3 = PatchCollection(self.selectionPatches,
                          match_original=True,
                          visible=False)

rawDescription: Why is PatchCollectin overriding visibility?


code: bin_avg[index] = np.average(items_in_bin, weights=my_weights)

rawDescription: Weighted moving average in python

description: Weighted moving average in python


code:
clibblah = ctypes.cdll.LoadLibrary('clibblah.dylib')
get_pixels = clibblah.get_pixels
get_pixels.restype = ctypes.POINTER(ctypes.c_char)

pixels = get_pixels()
num_pixels = clibblah.get_pixel_length()

# Slice the ctypes array into a Python string
a = pixels[:num_pixels]

rawDescription: How do you convert a char * with 0-value bytes into a python string?

description: Convert a char * with 0-value bytes into a python string


rawDescription: How to save trimmed wave file in python?

description: Save trimmed wave file in python


code:
import smtplib
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.ehlo
server.login('xxxxxxxxxxxx','xxxxxxxx')
msg = "test message"
server.sendmail('xxxxxxxxxxxx@gmail.com','xxxxxxx@yahoo.com',msg)
server.quit()

rawDescription: Errno 10060 python sending email through gmail


code:
import subprocess

subprocess.call([crysol, pdb_name, dat_name])

rawDescription: Opening an external program

description: Opening an external program


code:
with open('output.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(['Column 1', 'Column 2', ...])
    writer.writerows(data)

rawDescription: Export sqlite3 table to csv or txt file with python


code:
changespec = P4.fetch_change()
changespec[ "Description" ] = "placeholder"
P4.save_change( changespec )

rawDescription: How to create numbered changelist using P4Python?

description: Create numbered changelist using P4Python


rawDescription: Python - Create new column in dataframe with year and month together


code:
l=['Peripheral Blood Mononuclear Cells;peripheral blood mononuclear cells', 'Blood;peripheral blood mononuclear cells', 'Hispanic or Latino;hispanic', 'Black;black', 'Black;black', 'Asian;asian', 'Asian;asian', 'Asian;caucasian', 'caucasian;caucasian', 'caucasian;caucasian', 'Seizures;seizures', 'Seizure;seizures', 'Seizures;seizures', 'Seizures;seizures', 'Abscess;abscess']
seen = set()
res = []
for ele in l:
    a,b = ele.split(";",1)
    # make sure we don't have not seen the full string nor left/right hand substring
    # or we find exact matches both sides and we don't already have that perfect match added
    if ele.lower() not in seen and not any(x.lower() in seen for x in (a,b)) or a == b and ele not in seen:
        res.append(ele)
    # keep track of all full strings and left/right substrings
    seen.update([a.lower(),b.lower(),ele.lower()])
print(res)
['Peripheral Blood Mononuclear Cells;peripheral blood mononuclear cells', 'Hispanic or Latino;hispanic', 'Black;black', 'Asian;asian', 'caucasian;caucasian', 'Seizures;seizures', 'Abscess;abscess']

rawDescription: Print the best match in the Python list, where each element is separated internally


code:
import subprocess

output = subprocess.check_output(['git', 'status'], cwd='/path/to/git/workingdir')

rawDescription: How to execute git command in a identified path?

description: Execute git command in a identified path


rawDescription: Python - how do I create a new decorated function that takes arguments?


code:
class MyComboBox(QComboBox):
    def __init__(self):
        super(MyComboBox,self).__init__()  # your super was wrong.
                                           # you need to pass the _current_ class name
        self.setView(QTreeView())

        self.view().setHeaderHidden(True)
        self.view().setItemsExpandable(False)
        self.view().setRootIsDecorated(False)

    def showPopup(self):
        self.setRootModelIndex(QModelIndex()) # you need to add this
        self.view().expandAll()
        QComboBox.showPopup(self)

    def setModel(self, model):
        super(MyComboBox, self).setModel(model)
        parent, row = self._firstSelectableItem()
        if row is not None:
            self.setRootModelIndex(parent)
            self.setCurrentIndex(row)

    def _firstSelectableItem(self, parent=QModelIndex()):
        """
        Internal recursive function for finding the first selectable item.
        """
        for i in range(self.model().rowCount(parent)):
            itemIndex = self.model().index(i,0,parent)
            if self.model().itemFromIndex(itemIndex).isSelectable():
                return parent, i
            else:
                itemIndex, row = self._firstSelectableItem(itemIndex)
                if row is not None:
                    return itemIndex, row
        return parent, None

rawDescription: How do i select at item in a QTreeView that is inside a QComboBox

description: Select at item in a QTreeView that is inside a QComboBox


code:
x = numpy.linspace(-2., 2.)
y = numpy.linspace(-2., 2.)[:, None]
contour(x, y.ravel(), 3*x + 2*y, [1])

rawDescription: Plotting system of (implicit) equations in matpotlib


code:
sql_update = ('''\
    UPDATE table_a SET value1 = :value1, value2 = :value2
    WHERE key1 = :key1 and key2 = :key2''')
self.dbcur.executemany(sql_update, dictrows)

rawDescription: Update table using a list of dictionaries


code:
from html.parser import HTMLParser

class StripTextParser(HTMLParser):
    def __init__(self, *args, **kwargs):
        self.data = []
        super(StripTextParser, self).__init__(*args, **kwargs)

    def handle_data(self, data):
        if data.strip():
            # Only use wtrings which are contain more than whitespace
            startpos = self.getpos()
            # `self.getpos()` returns `(line, column)` of start position.
            # Use that plus length of data to calculate end position.
            endpos = (startpos[0], startpos[1] + len(data))
            self.data.append((data, startpos, endpos))

def strip_text(html):
    parser = StripTextParser()
    parser.feed(html)
    return parser.data

test1 = "There was another thread like this"

print(strip_text(test1))

# Ouputs: [('There', (1, 10), (1, 15)), ('was', (1, 38), (1, 41)), ('another', (1, 64), (1, 71)), ('thread', (1, 94), (1, 100)), ('like', (1, 123), (1, 127)), ('this', (1, 150), (1, 154))]

test2 = """

https://steamcommunity.com/tradeoffer/new/partner=30515749&token=WOIxg5eB

79

Why did the elephants get kicked out of the public pool?  THEY KEPT DROPPING THEIR TRUNKS!

"""

print(strip_text(test2))

# Outputs: [('https://steamcommunity.com/tradeoffer/new/partner=30515749&token=WOIxg5eB', (3, 4), (3, 77)), ('79', (4, 4), (4, 6)), ('Why did the elephants get kicked out of the public pool?  THEY KEPT DROPPING THEIR TRUNKS! ', (5, 4), (5, 95))]

test3 = "a"

print(strip_text(test3))

# Outputs: [('a', (1, 12), (1, 13))]

rawDescription: Remove html tags AND get start/end indices of marked-down text?


code:
timeit.timeit("import time; time.sleep(1)", number=1)
timeit.timeit("import time; time.sleep(1)", number=5)
timeit.repeat("import time; time.sleep(1)", number=5, repeat=3)

rawDescription: What is time unit returned by Python's timeit module for multiple repetitions?


code:
from numpy import meshgrid,column_stack
x,y=meshgrid(coord_x,coord_y)
coord = column_stack((x.T.flatten(),y.T.flatten()))

rawDescription: getting a list of coordinates from a 2D matrix

description: Getting a list of coordinates from a 2D matrix


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

def myhist(ax, color):
    ax.hist(np.log(np.arange(1, 10, .1)), facecolor=color)

def say_something(ax, words):
    t = ax.text(.2, 20., words)
    make_a_dim_yellow_bbox(t)

def make_a_dim_yellow_bbox(txt):
    txt.set_bbox(dict(facecolor='yellow', alpha=.2))

fig = plt.figure()
ax0 = fig.add_subplot(1,2,1)
ax1 = fig.add_subplot(1,2,2)

myhist(ax0, 'blue')
myhist(ax1, 'green')

say_something(ax0, 'this is the blue plot')
say_something(ax1, 'this is the green plot')

plt.show()

rawDescription: Python with matplotlib - reusing drawing functions


code:
from itertools import groupby
def splitWithIndices(s, c=' '):
 p = 0
 for k, g in groupby(s, lambda x:x==c):
  q = p + sum(1 for i in g)
  if not k:
   yield p, q # or p, q-1 if you are really sure you want that
  p = q
a = "This is a sentence"
list(splitWithIndices(a))
a[0:4]
a[5:7]
a[8:9]
a[10:18]

rawDescription: String split with indices in Python

description: String split with indices in Python


code:
a = np.array([[1, 2], [3, 4]])
m = np.matrix([[1, 2], [3, 4]])
b = np.array([4,5])
np.dot(a, b)
np.dot(a, b).shape
np.dot(m, b)
np.dot(m, b).shape

rawDescription: numpy dot behaving strange

description: Numpy dot behaving strange


code:
def a_function(someval=None):
    if someval:
        print(someval)
    else:
        print("None")

rawDescription: Passing argument to function assigned to a variable


code:
def iplookup(srcip):
    for ip in srcip:
        ip = ip.strip()
        try:
            print(geolite2.lookup(ip))
        except:
            pass

iplookup(sys.stdin)

rawDescription: python sys.stdin.read() from tail -f

description: Python sys.stdin.read() from tail -f


code:
app.jinja_env.globals.update(global_key1=global_value1,
                             global_key2=global_value2,
                             global_key3=global_value3)

rawDescription: get_template_attribute() - how to inject template globals

description: Get_template_attribute() - how to inject template globals


code:
import time,random

def withTimer():
    playAgain = "yes"
    correct = 0
    total = 0
    totalTime = 0
    etime = []
    while playAgain[0] == "y":
        total = total + 1
        random1 = random.randint(1, 12)
        random2 = random.randint(1, 12)
        realAnswer = random1 * random2
        start = time.time()
        humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
        if realAnswer == humanAnswer:
            elapsed = round((time.time() - start), 1)
            etime.append(elapsed)
            correct = correct + 1
            score = str(int(correct / total * 100)) + "%"
            if elapsed < 2:
                print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nThat is a very good time!\nScore: " + score)
            else:
                print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nNow work on your time.\nScore: " + score)
        else:
            score = str(int(correct / total * 100)) + "%"
            print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
        totalTime += elapsed
        playAgain = input("Do you wish to play again? (yes or no)\n")
    averageTime = totalTime / total
    averageTime1 = sum(etime) / len(etime)
    if playAgain[0] != "y":
        print("Thank you for practicing your multiplication tables\nwith me\nFinal Score: " + score + "\nAverage Time: " + str(averageTime) + " AverageTime1 = "  + str(averageTime))

withTimer()

rawDescription: Average Time on While Loop

description: Average Time on While Loop


code:
fig=plt.figure(1)
...
ax=fig.add_subplot(111)
bx=fig.add_subplot(211)
...
fig.savefig('test.png', bbox_extra_artists=(lgd,))

rawDescription: Pyplot not plotting subplots

description: Pyplot not plotting subplots


code:
import numpy as np
a=np.array(([1,2,3],[4,5,6],[7,8,9]))
b=a[:,1] # took one column
c=a[:,0] # again took 1 column
np.vstack((b,c))

rawDescription: slicing column in numpy array and creating new matrix

description: Slicing column in numpy array and creating new matrix


code:
def query_to_model(query):
  return ndb.Model._kind_map[query.name]

rawDescription: How can I get the ndb.Model when my only input is an ndb.Query?

description: Get the ndb.Model when my only input is an ndb.Query


code:
from selenium.webdriver.common.action_chains import ActionChains

def hover(self):
    wd = webdriver_connection.connection
    element = wd.find_element_by_link_text(self.locator)
    hov = ActionChains(wd).move_to_element(element)
    hov.perform()

rawDescription: How to mouseover in python Webdriver

description: Mouseover in python Webdriver


code:
def insert_ngram(queue, managerDict):
    # create a local dictionary with vivification
    localDict = Vividict()
    # copy the existing manager.dict to the local dict.
    localDict.update(managerDict)
    #do stuff
    # copy the local dictionary to the manager dict
    managerDict.update(localDict)
    return

rawDescription: autovivificating multiprocessing manager() dictionaries in python

description: Autovivificating multiprocessing manager() dictionaries in python


code:
c1 = "St. Louis       12             Cardinals"
words = [w.strip() for w in c1.split('  ') if w]
# words == ['St. Louis', '12', 'Cardinals']

rawDescription: How do I split these strings into arrays of strings?

description: Split these strings into arrays of strings


code:
# tests/test_foo.py
import asyncio

@asyncio.coroutine
def test_coro(loop):
    yield from asyncio.sleep(0.1)
    assert 0

# tests/conftest.py
import asyncio

@pytest.yield_fixture
def loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    yield loop
    loop.close()

def pytest_pycollect_makeitem(collector, name, obj):
    """Collect asyncio coroutines as normal functions, not as generators."""
    if asyncio.iscoroutinefunction(obj):
        return list(collector._genfunctions(name, obj))

def pytest_pyfunc_call(pyfuncitem):
    """If ``pyfuncitem.obj`` is an asyncio coroutinefunction, execute it via
    the event loop instead of calling it directly."""
    testfunction = pyfuncitem.obj

    if not asyncio.iscoroutinefunction(testfunction):
        return

    # Copied from _pytest/python.py:pytest_pyfunc_call()
    funcargs = pyfuncitem.funcargs
    testargs = {}
    for arg in pyfuncitem._fixtureinfo.argnames:
        testargs[arg] = funcargs[arg]
    coro = testfunction(**testargs)  # Will no execute the test yet!

    # Run the coro in the event loop
    loop = testargs.get('loop', asyncio.get_event_loop())
    loop.run_until_complete(coro)

    return True  # TODO: What to return here?

rawDescription: py.test mixing fixtures and asyncio coroutines

description: Py.test mixing fixtures and asyncio coroutines


code:
df1 = df.set_index("DATE")
df1
df1.max(1)
df1.div(df1.max(1), axis=0)

rawDescription: Percentile ranking in a dataframe. Pandas


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = "http://website_url.com"

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)
driver.get(url)

elm = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#monetary_offer_content > div.monetary_offer > div.offers.clear > div > div.clearfix > h3 > span")))
print(elm.text)

driver.close()

rawDescription: Scrape a PHP variable with Beautiful Soup, urllib2, and Python


code:
from mpl_toolkits.basemap import Basemap, cm
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 1)
ax.hold(True)

map = Basemap(projection='ortho',lat_0=45,lon_0=-100,resolution='l')
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='aqua')
map.drawmapboundary(fill_color='aqua')
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))

nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1)
lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])
lons = (delta*np.indices((nlats,nlons))[1,:,:])
wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons))
mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)
x, y = map(lons*180./np.pi, lats*180./np.pi)

map.contourf(x,y,wave+mean,15, alpha=0.5, cmap=cm.GMT_drywet)
cb = map.colorbar()
plt.show()

rawDescription: How can I create a discrete colorbar using a colormap from mpl_toolkits.basemap.cm?

description: Create a discrete colorbar using a colormap from mpl_toolkits.basemap.cm


code:
import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.subplots(figsize=(8,5))
df = pd.DataFrame({'type': dataFrame['Country'], labelName: 'Infant mort. rate'})
ax = df.plot(kind='bar', x=dataFrame['Country'], legend=False, ax=ax)
ax.set_ylabel('Infant mort. rate')
ax.set_xlabel('Country')
fig.tight_layout()
plt.show()

rawDescription: pandas matplotlib resizing and removing labels

description: Pandas matplotlib resizing and removing labels


code:
pattern = r'\b[a-zA-Z]{3}\d{3}\b'
re.findall(pattern, "My word is bla123")
re.findall(pattern, "My word345 is bla123")
re.findall(pattern, "My word345 and bla56 is bla123 and abc343")

rawDescription: Puzzled about use of regex to match exactly 3 letters followed by exactly 3 numbers


code:
for bone in bpy.context.selected_pose_bones:
    nc = bone.constraints.new(type='COPY_ROTATION')
    nc.target = bpy.data.objects['Armature']
    nc.subtarget = bone.parent
    nc.influence = 0.5

rawDescription: Blender 3D python For Every pose bone add a constraint not working


code:
# input = list of (start, stop, symbol) tuples
points = [] # list of (offset, plus/minus, symbol) tuples
for start,stop,symbol in input:
    points.append((start,'+',symbol))
    points.append((stop,'-',symbol))
points.sort()

ranges = [] # output list of (start, stop, symbol_set) tuples
current_set = set()
last_start = None
for offset,pm,symbol in points:
    if pm == '+':
         if last_start is not None:
             #TODO avoid outputting empty or trivial ranges
             ranges.append((last_start,offset-1,current_set))
         current_set.add(symbol)
         last_start = offset
    elif pm == '-':
         # Getting a minus without a last_start is unpossible here, so not handled
         ranges.append((last_start,offset-1,current_set))
         current_set.remove(symbol)
         last_start = offset

# Finish off
if last_start is not None:
    ranges.append((last_start,offset-1,current_set))

rawDescription: How to divide a set of overlapping ranges into non-overlapping ranges?

description: Divide a set of overlapping ranges into non-overlapping ranges


code:
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="smoker", row="time", sharey="col")
g.map(plt.hist, "total_bill")

rawDescription: Seaborn - FacetGrid axes sharing x axis across rows / y-axis across columns


code:
for x in [1, 2, 3, 4]:
  for y in [1, 2, 3, 4]:
    for z in [1, 2, 3, 4]:
      # start of the alignment is given by (x, y, z).
      for dx in [-1, 0, +1]:
        for dy in [-1, 0, +1]:
          for dz in [-1, 0, +1]:
            # add (dx, dy, dz) for each successive point.
            # check that it makes a valid alignment first.
            if ((dx, dy, dz) != (0, 0, 0) and
                1 <= x + 3*dx <= 4 and
                1 <= y + 3*dy <= 4 and
                1 <= z + 3*dz <= 4):
              # that's a valid alignment.
              print (x, y, z), (x + 3*dx, y + 3*dy, z + 3*dz)

rawDescription: Search 3d points to find if any are in a row


code:
for x in range(3):
    psutil.cpu_percent(interval=1, percpu=True)

rawDescription: How to capture the CPU core usage from system monitor program?

description: Capture the CPU core usage from system monitor program


code:
def be_awesome():
    pass

if __name__ == '__main__':
   def be_more_awesome():
        pass

rawDescription: Python Design: Code after "if __name__ == __main__" test


code:
from shutil import copytree
copytree(original_directory_path, copy_directory_path)

rawDescription: How to copy folder and subfolder using PyQt

description: Copy folder and subfolder using PyQt