code:
import wx

class Frame ( wx.Frame ):

    def __init__( self, parent ):
        wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Test", pos = wx.DefaultPosition, size = wx.Size( 600,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

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

        sizer = wx.BoxSizer( wx.VERTICAL )

        self.notebook = wx.Notebook( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )
        self.login = wx.Panel( self.notebook, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
        self.notebook.AddPage( self.login, u"Login", False )
        self.entry = wx.ScrolledWindow( self.notebook, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.HSCROLL|wx.VSCROLL )
        self.entry.SetScrollRate( 5, 5 )
        entry_sizer = wx.BoxSizer( wx.VERTICAL )

        self.text = wx.StaticText( self.entry, wx.ID_ANY, u"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.text.Wrap( 600 )
        entry_sizer.Add( self.text, 1, wx.ALL, 0 )

        self.entry.SetSizer( entry_sizer )
        self.entry.Layout()
        entry_sizer.Fit( self.entry )
        self.notebook.AddPage( self.entry, u"Entry", True )

        sizer.Add( self.notebook, 1, wx.EXPAND |wx.ALL, 0 )

        self.SetSizer( sizer )
        self.Layout()

        self.Centre( wx.BOTH )
        self.Show()

if __name__ == "__main__":
    app = wx.App()
    Frame(None)
    app.MainLoop()

rawDescription: wxPython Vertical Scroll for Notebook Tab

description: WxPython Vertical Scroll for Notebook Tab


code:
import random
content_pks = Content.objects.values_list('pk', flat=True)
selected_pks = random.sample(content_pks, 30)
content_objects = Content.objects.filter(pk__in=selected_pks)

rawDescription: How to select 30 unique random values from database(MySQL) with django?

description: Select 30 unique random values from database(MySQL) with django


code:
@classmethod
def desc(self):
  return a + '-' + b

rawDescription: Nested classes: Accessing the methods of the outer class from the inner one


code:
for name in found:
    print(name, useraccounts[name]['totalscore'])

rawDescription: Using items in a list as dictionary keys


rawDescription: Python - formatting output with varying numbers of spaces


code:
with open('test.txt') as f:
    pass
# Automatically closes file on with block exit

rawDescription: Method of exiting and closing file for both Windows + Linux


code:
from os.path import *
file = '/Users/myMac/Desktop/MemoryAccess/BasicTest.asm/someStuff'
splitext(basename(dirname(file)))[0]

rawDescription: Finding last char appearance in string

description: Finding last char appearance in string


code:
class Post(db.Document):
    demo = db.DateTimeField(default=datetime.date.today())
    slug = db.StringFieldField(default=datetime.date.today())

rawDescription: Why does date.today() return time as well?


rawDescription: parsing output of stdout

description: Parsing output of stdout


code:
def func(d1, d2):
    m = (0, 0)
    for k in d1:
        res = abs(d1[k][1] - d2[k][1]) #func1
        #res = abs(d1[k][0] - d2[k][0]) # func2
        #res = abs(sum(d1[k]) - sum(d2[k])) # func3
        if res > m[1]: m = (k, res)
    return m[0]

rawDescription: python dictionary search, compare, and calculate values

description: Python dictionary search, compare, and calculate values


code:
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info, save_as=urllib.quote(blob_info.filename.encode('utf-8')))

rawDescription: Non ascii filename in blobstore (Google App Engine)


code:
import time
time.strftime("%H%M%S")
for d in time.strftime("%H%M%S"):
    display_digit(int(d))

rawDescription: Single digit clock on Raspberry Pi in Python


code:
import os,re
for f in os.listdir("/path/to/dir"):
    if re.match(r"^\d+\.txt$", f):
        print(f)

rawDescription: glob "one or more" in Python

description: Glob "one or more" in Python


code:
url = ("%s://%s/static/css/thingy.css" %
          (self.request.protocol,
          self.request.host,)
      )

rawDescription: Tornado: Create full URL from partial URL


code:
import itertools

def readloop(DBFILE):
  txtdb=open(DBFILE, 'r')
  tag = "customernum:  "
  BIGBLOCK = 1024 * 1024
  # locate first occurrence of tag at line-start
  # (assumes the VERY FIRST line doesn't start that way,
  # else you need a special-case and slight refactoring)
  blob = ''
  while True:
    blob = blob + txtdb.read(BIGBLOCK)
    if not blob:
      # tag not present at all -- warn about that, then
      return
    where = blob.find('\n' + tag)
    if where != -1:  # found it!
      blob = blob[where+1:] + txtdb.readline()
      break
    blob = blob[-len(tag):]
  # now make a by-line iterator over the part of interest
  thelines = itertools.chain(blob.splitlines(1), txtdb)
  sline = next(thelines, '')
  while sline.startswith(tag):
    data = []
    data.append(sline)
    sline = next(thelines, '')
    while not sline.startswith(tag):
      data.append(sline)
      sline = next(thelines, '')
      if not sline:
        break
    customernum = getitem(data, "customernum:  ")
    street = getitem(data, "street:  ")
    country = getitem(data, "country:  ")
    zip = getitem(data, "zip:  ")

rawDescription: How to improve speed of this readline loop in python?

description: Improve speed of this readline loop in python


code:
from email.mime.text import MIMEText

filename = "text.txt"
f = file(filename)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)

rawDescription: Attach a txt file in Python smtplib

description: Attach a txt file in Python smtplib


code:
from openpyxl import formatting, styles

wb = Workbook()
ws = wb.active

red_color = 'ffc7ce'
red_color_font = '9c0103'

red_font = styles.Font(size=14, bold=True, color=red_color_font)
red_fill = styles.PatternFill(start_color=red_color, end_color=red_color, fill_type='solid')

for row in range(1,10):
    ws.cell(row=row, column=1, value=row-5)
    ws.cell(row=row, column=2, value=row-5)

ws.conditional_formatting.add('A1:A10', formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font))
ws.conditional_formatting.add('B1:B10', formatting.CellIsRule(operator='lessThan', formula=['0'], fill=red_fill))
wb.save("test.xlsx")

rawDescription: openpyxl font conditional formatting

description: Openpyxl font conditional formatting


code:
for keywordurl in open("textfile.txt").readlines():
    self.br.execute_script( "document.getElementById('ctl00_phMainContent_KeywordForm_ControlPanel_txtKeywords').value = '%s';" % keywordurl )

rawDescription: Combine Python String With Javascript Value


code:
import numpy
surf_array = pygame.surfarray.pixels3d(surface)
window_array = numpy.zeros(surf_array.shape[:2], dtype=numpy.int8)
...
surf_array[numpy.nonzero(window_array == 1)] = np.array([0, 0, 0])
surf_array[numpy.nonzero(window_array == 2)] = np.array([50, 50, 50])

rawDescription: Using Array to Store Pixels of Window

description: Using Array to Store Pixels of Window


code:
import logging
import sys
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest
from PyQt4.QtCore import QUrl, QEventLoop

log = logging.getLogger(__name__)

class Manager(QNetworkAccessManager):
    def __init__(self, table=list()):
        QNetworkAccessManager.__init__(self)
        self.finished.connect(self._finished)
        self.table = table

    def _finished(self, reply):
        headers = reply.rawHeaderPairs()
        headers = {str(k): str(v) for k, v in headers}
        content_type = headers.get("Content-Type")
        url = reply.url().toString()
        status = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        status, ok = status.toInt()
        self.table.append([str(url), str(status), content_type])
        log.info(self.table)
        request = reply.request()
        log.info(request.rawHeader("User-Agent"))
        method = reply.operation()
        if method == QNetworkAccessManager.GetOperation:
            log.info("get")
            request.url().queryItems()
        if method == QNetworkAccessManager.PostOperation:
            log.info("post")

def test():
    manager = Manager()
    log.info("Sending request")
    manager.get(QNetworkRequest(QUrl("http://www.google.com/")))

    # just for testing purpose to wait for the request to finish
    l = QEventLoop()
    manager.finished.connect(l.quit)
    l.exec_()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    app = QApplication(sys.argv)
    test()

rawDescription: Showing headers in QWebview Browser Pyqt Python


code:
with open('platenon.txt', 'w') as f:
   for platecode in range(100):
       f.write('KJA{0:03d}AA'.format(platecode))

rawDescription: how to range letter aa to zz

description: Range letter aa to zz


code:
class FakeSocketHandlerForTesting(SocketHandler):
    def __init__(self, *args, **args):
        pass

rawDescription: How can I unit-test a method without instantiating the class?

description: Unit-test a method without instantiating the class


rawDescription: How to convert octal escape sequences with Python

description: Convert octal escape sequences with Python


code:
import operator
tuple(map(operator.add, a, b))

rawDescription: Python element-wise tuple operations like sum


rawDescription: Python string LCS bug

description: Python string LCS bug


code:
serializers.py
class FooSerializer(serializers.ModelSerializer):

    class Meta:
        model = Foo
        fields = ('bar', 'baz')
        extra_kwargs = {
            'bar': { # add additional arguments for 'bar' field
                'min_value':0, # specify 'min_value' argument
                'max_value': 9 # specify 'max_value' argument
            }
        }

rawDescription: Inherits help_text from django.db.models.Field in rest_framework.serializer.Field


code: result = [{'Letter': chr(i+97)} for i in range(26)]

rawDescription: Auto create next Key in python dictionary


code:
data = {
        'temperature_reading': {'CelciusReading': temperature}
}

rawDescription: Posting to Ruby service with Python

description: Posting to Ruby service with Python


code:
import select

def fromAtoB(A, B):
    r, w = select.select([A], [B], [])
    if not r: select.select([A], [], [])
    elif not w: select.select([], [B], [])
    B.sendall(A.recv(4096))

rawDescription: How to correctly relay TCP traffic between sockets?

description: Correctly relay TCP traffic between sockets


code:
class Human():
    def __init__(self, name):
        self.name = name

class Dog(Pet):
    def __init__(self, name):
        self.name = name

    def bark_at(self, person):
        "do something"

class OwnerPetRelation():
    def __init__(self, dog, human):
        self.owner=human
        self.pet=dog

rawDescription: Mutually Reference-able Instances in Python


code:
keys = pygame.key.get_pressed()

if keys[K_LEFT]:
    self.char_x += 10

if keys[K_RIGHT]:
    self.char_x -= 10

if keys[K_UP]:
    self.char_y -= 10

if keys[K_DOWN]:
    self.char_y += 10

rawDescription: Programming Pygame so that I can press multiple keys at once to get my character to move diagonally


code:
list1 = [505,504,503,502,207,206]

from itertools import groupby

for k,v in groupby(list1,key=lambda x: str(x)[0]): # use x // 100 if you only have three digit numbers
    print(max(v))

505
207

rawDescription: Python retain maximal integer from list

description: Python retain maximal integer from list


code:
visited = set()

queue = ['www.google.com', 'www.yahoo.com', 'www.microsfot.com']

def crawl_the_page(link):
    # ...crawling...
    visited.add(link)
    return

# you just for through the queue list
# no need to pop the list, use the set() to compare instead
for url in queue:
    if url not in visited:
        #... do your stuff ...
        #... crawl your pages ...
        crawl_the_page(url)

rawDescription: Queue datastruct -- find first element in queue that has not previously been queued


code:
class VarietyCreate(CreateView):
    template_name = "generic_create.html"
    model = Variety
    form_class = VarietyForm

    def get_initial(self):
        return {"product_group" : self.kwargs.get('pk')}

    def get_success_url(self):
        return reverse("purchases:Variety Index", kwargs={'pk': self.kwargs.get('pk')})

rawDescription: Django: Passing Kwargs as form Values to generic CBV Form


code:
#!/usr/bin/env python2.6

from lxml import etree
from StringIO import StringIO

schema_doc = etree.parse(StringIO('''
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:simpleType name="httpURL">
        <xs:restriction base="xs:anyURI">
            <xs:pattern value='https?://.+'/>

        </xs:restriction>
    </xs:simpleType>

    <xs:element name="a">
        <xs:complexType>
            <xs:attribute name="link-url" type="httpURL"/>
        </xs:complexType>
    </xs:element>
    </xs:schema>
''')) #/
schema = etree.XMLSchema(schema_doc)

schema.assertValid(etree.parse(StringIO('')))
assert not schema(etree.parse(StringIO('')))

rawDescription: xml validation: validating a URI type

description: Xml validation: validating a URI type


code:
class BaseBase(object):
    """
    This class is a superclass of SA-generated Base class,
    which in turn is the superclass of all db-aware classes
    so we can define common functions here
    """

    def __setattr__(self, name, value):
        """
        Raise an exception if attempting to assign to an atribute which does not exist in the model.
        We're not checking if the attribute is an SQLAlchemy-mapped column because we also want it to work with properties etc.
        See http://stackoverflow.com/questions/12032260/ for more details.
        """
        if name != "_sa_instance_state" and not hasattr(self, name):
            raise AttributeError("Attribute %s is not a mapped column of object %s" % (name, self))
        super(BaseBase, self).__setattr__(name, value)

Base = declarative_base(cls=BaseBase)

rawDescription: How do I raise an exception when assigning to an attribute which is NOT mapped to an SQLAlchemy column?

description: Raise an exception when assigning to an attribute which is NOT mapped to an SQLAlchemy column


code:
if(event.is_directory):
    files_in_dir = [event.src_path+"/"+f for f in os.listdir(event.src_path)]
    mod_file_path = max(files_in_dir, key=os.path.getmtime)

rawDescription: Watchdog library in Python on OS X -- not showing full event path


code:
import random
random.seed()

def do_action1():
    print("Hello")
    yield
    print("HELLO!")
    yield
    print("hello?")
def do_action2():
    print("Are you there?")
    yield
    print("ARE YOU THERE!")
    yield
    print("I'm scared.")
def do_action3():
    print("Is somebody out there?")
    yield
    print("SOMEBODY IS OUT THERE!")
    yield
    print("I'm dead.")

def bot(*actions):
    actions = [action() for action in actions]
    while actions:
        action = random.choice(actions)
        try:
            next(action)
        except StopIteration:
            actions.remove(action)
    return

bot(do_action1, do_action2, do_action3)

rawDescription: Pause and resume a function

description: Pause and resume a function


code:
import networkx as nx
import matplotlib.pyplot as plt

content = '''\
Node1 Node2
A       B
A       C
C       A
D       A'''

lines = content.splitlines()
G = nx.DiGraph()
for line in lines[1:]: # skip the first (header) line
    a, b = map(str.strip, line.split())
    G.add_edge(a, b)

nx.draw(G)
plt.savefig('/tmp/graph.png')
# plt.show()

rawDescription: Networkx Dataset Creation

description: Networkx Dataset Creation


code:
def _append_or_remove(source, pattern, dirs = True, recurse = False, append = True):
    for item in os.listdir(source):
        path =  os.path.join(source, item)
        if "svn" not in item:
            if os.path.isdir(path):
                # Recurse first
                if recurse:
                    if append:
                        append_items(path, pattern, dirs, recurse)
                    else:
                        remove_string_from_items(path, pattern, dirs, recurse)
                if dirs and pattern in item:
                    target = os.path.join(source, string.replace(item, pattern, ""))
                    rename(path, target)
            elif os.path.isfile(path) and pattern in item:
                if append:
                    name, ext = os.path.splitext(item)
                    # Append pattern, add extension back
                    target = os.path.join(source, "%s%s" % (name, pattern) + ext)
                else:
                    target = os.path.join(source, string.replace(item, pattern, ""))
                rename(path, target)

def append_items(source, pattern, dirs = True, recurse = False):
    """
    Append the pattern to all items within a directory

    source = act on this directory
    pattern = add this to the start of the file
    dirs = apply to directorys
    recurse = work recursively
    """
    return _append_or_remove(source, pattern, dirs, recurse, True)

def remove_string_from_items(source, pattern, dirs = True, recurse = False):
    """
    Remove a pattern from all items within a directory

    source =  directory
    pattern = text to replace
    """
    return _append_or_remove(source, pattern, dirs, recurse, False)

rawDescription: Unix Style Wildcard Renaming Python

description: Unix Style Wildcard Renaming Python


code:
from django.db.models.signals import post_save

# method for updating
def update_parent(sender, instance, **kwargs):
     parent = Parent.object.get() #the parent you need to update
     parent.modification_date = instance.modification_date
     parent.save()

# register the signal
post_save.connect(update_parent, sender=Child)

rawDescription: Updating two field from different models simultaneously


rawDescription: Testing python programs without using python shell


code:
import wx

class NoteBookPage(wx.Panel):
    def __init__(self,parent,message):
        wx.Panel.__init__(self,parent)
        sizer= wx.BoxSizer(wx.VERTICAL)
        message= wx.StaticText(self,label=message)
        sizer.Add(message,1,wx.ALIGN_CENTRE)
        self.SetSizer(sizer)

class AppFrame(wx.Frame):
    def __init__(self,parent,id=-1,title='program'):
        wx.Frame.__init__(self,parent,id,title,size=((400,400)))
        # Panels
        self.AppPanel = wx.Panel(self,-1)
        self.AppPanel.SetBackgroundColour('grey')

        main_sizer= wx.BoxSizer(wx.HORIZONTAL)

        button_sizer= wx.BoxSizer(wx.VERTICAL)

        #buttons
        self.button1= wx.Button(self.AppPanel,label="Button 1")
        button_sizer.Add(self.button1,0,wx.EXPAND)
        self.button2= wx.Button(self.AppPanel,label="Button 2")
        button_sizer.Add(self.button2,0,wx.EXPAND)
        self.button3= wx.Button(self.AppPanel,label="Button 3")
        button_sizer.Add(self.button3,0,wx.EXPAND)
        main_sizer.Add(button_sizer,0,wx.ALL,5)

        #notebook
        self.Notebook= wx.Notebook(self.AppPanel)
        page1= NoteBookPage(self.Notebook,"I'm on page 1")
        page2= NoteBookPage(self.Notebook,"I'm on page 2")
        self.Notebook.AddPage(page1,"Page 1")
        self.Notebook.AddPage(page2,"Page 2")
        main_sizer.Add(self.Notebook,1,wx.ALL|wx.EXPAND,5)

        #panel on the right (I'm just re-using the NoteBookPage panel to save making a new one)
        right_panel= NoteBookPage(self.AppPanel,"right panel")
        main_sizer.Add(right_panel,0,wx.ALL,5)

        self.AppPanel.SetSizer(main_sizer)

        self.Show()

if __name__ == "__main__":
    app= wx.App(False)
    frame= AppFrame(None)
    app.MainLoop()

rawDescription: Can/How do I create a class panel and use it in my main frame (wxpython)


code:
def _rvs(self, *args):
    ## Use basic inverse cdf algorithm for RV generation as default.
    U = mtrand.sample(self._size)
    Y = self._ppf(U,*args)
    return Y

rawDescription: What method does scipy use to select random values from continuous distributions?


rawDescription: What is the most efficient way to repeatedly use regular expressions in a Python loop?


code:
with PdfPages('review_count.pdf') as pdf:
    plt.figure()
    plt.axis('off')
    plt.text(0.5,0.5,"my title",ha='center',va='center')
    pdf.savefig()
    plt.close()
    for cat in self.cat_vars.keys():
        if len(self.cat_vars[cat]) > 1:
            plt.figure()
            self.cat_vars[cat].plot(kind='bar')
            plt.title(cat)
            # saves the current figure into a pdf page
            pdf.savefig()
            plt.close()

rawDescription: How to create a title page for a PDF document created using matplotlib

description: Create a title page for a PDF document created using matplotlib


code:
ftp.retrlines('RETR ' + weatherfile,
              callback=lambda line: handleData(line, other_arg, another_arg))

rawDescription: Handling ftp data in python

description: Handling ftp data in python


code:
urlpatterns += i18n_patterns('',
    url(r'^admin/', include(admin.site.urls)),
)

rawDescription: How can I change Django admin language?

description: Change Django admin language


code:
from socket import *
import base64
import time

msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
mailserver = ("smtp.gmx.com", 25) #Fill in start #Fill in end
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(mailserver)
recv = clientSocket.recv(1024)
recv = recv.decode()
print("Message after connection request:" + recv)
if recv[:3] != '220':
    print('220 reply not received from server.')
heloCommand = 'EHLO Alice\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024)
recv1 = recv1.decode()
print("Message after EHLO command:" + recv1)
if recv1[:3] != '250':
    print('250 reply not received from server.')

#Info for username and password
username = "xxxxxx"
password = "xxxxxx"
base64_str = ("\x00"+username+"\x00"+password).encode()
base64_str = base64.b64encode(base64_str)
authMsg = "AUTH PLAIN ".encode()+base64_str+"\r\n".encode()
clientSocket.send(authMsg)
recv_auth = clientSocket.recv(1024)
print(recv_auth.decode())

mailFrom = "MAIL FROM:<xxxxxxxx>\r\n"
clientSocket.send(mailFrom.encode())
recv2 = clientSocket.recv(1024)
recv2 = recv2.decode()
print("After MAIL FROM command: "+recv2)
rcptTo = "RCPT TO:<xxxxxxxxxx>\r\n"
clientSocket.send(rcptTo.encode())
recv3 = clientSocket.recv(1024)
recv3 = recv3.decode()
print("After RCPT TO command: "+recv3)
data = "DATA\r\n"
clientSocket.send(data.encode())
recv4 = clientSocket.recv(1024)
recv4 = recv4.decode()
print("After DATA command: "+recv4)
subject = "Subject: testing my client\r\n\r\n"
clientSocket.send(subject.encode())
date = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
date = date + "\r\n\r\n"
clientSocket.send(date.encode())
clientSocket.send(msg.encode())
clientSocket.send(endmsg.encode())
recv_msg = clientSocket.recv(1024)
print("Response after sending message body:"+recv_msg.decode())
quit = "QUIT\r\n"
clientSocket.send(quit.encode())
recv5 = clientSocket.recv(1024)
print(recv5.decode())
clientSocket.close()

rawDescription: Mail Client in Python using sockets only(no smtplib)


code:
print("Enter two Numbers\n")
a = int(raw_input('A='))
b = int(raw_input('B='))
c=a+b
print ('C= %s' %c)
raw_input() # waits for you to press enter

rawDescription: Simple addition program in python

description: Simple addition program in python


rawDescription: Bash: How refresh shell after installing virtualenvwrapper [Without restarting the shell]?


rawDescription: How to initialize many arrays dynamically in Python?

description: Initialize many arrays dynamically in Python


code:
buf = "000000111111222222"
a = np.ndarray(len(buf), np.dtype('>i1'), buf)
e = np.zeros(len(buf) / 6, np.dtype('>i8'))
for i in range(3):
    e.view(dtype='>i2')[i + 1::4] = a.view(dtype='>i2')[i::3]
[hex(x) for x in e]

rawDescription: Reading and storing arbitrary byte length integers from a file


rawDescription: Python glob and bracket characters ('[]')


code:
def evenrow(lst):
    for i in range(len(lst)-1):
       if sum(lst[i]) % 2 != 0:     # here is the problem, it only iterates over the first item in the lst [1, 3] - i cant figure this out - range problem?
           return False
    return True

rawDescription: sum of items in a 2d list

description: Sum of items in a 2d list


code:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
s = str(now)
s
s[:26]
datetime.strptime(s[:26]+s[26:].replace(':',''), '%Y-%m-%d %H:%M:%S.%f%z')

rawDescription: Get a datetime object from the result of str(datetime)


code:
db.session.query(Case.court_id.distinct()).filter(
        Case.last_updated.between(start, end)).filter(
                (Case.last_scraped_by != "RSS") |
                (Case.last_scraped_by.is_(None))).order_by(Case.last_updated.desc())

rawDescription: sqlalchemy: Controlling columns selected from query

description: Sqlalchemy: Controlling columns selected from query


rawDescription: ValueError: data type must provide an itemsize?


code: str = 'The {} are {}, {}, {}, and {}'.format('numbers', *lstData)

rawDescription: Python - short way to unpack list for string formating operator?


code:
import decimal
decimal.getcontext().prec = 100              #Set precision
decimal.Decimal('22') / decimal.Decimal('7')

rawDescription: how can i measure more than 16 digits after zero with python?

description: Measure more than 16 digits after zero with python


code:
DICT_COLOR = {'#':'red', 'X':'green', 'O':'yellow'}
SIZE_X = 300/len(grid[0])
SIZE_Y = 300/len(grid)
for i, line in enumerate(grid):
    for j, value in enumerate(line):
        self._canvas.create_rectangle(j*SIZE_X,
                                      i*SIZE_Y,
                                      (j+1)*SIZE_X,
                                      (i+1)*SIZE_Y,
                                      fill=DICT_COLOR[value])

rawDescription: Creating shapes with Tkinter canvas

description: Creating shapes with Tkinter canvas


rawDescription: Pulling all numbers from a quadratic equation using RE


rawDescription: Django JSON string to json object

description: Django JSON string to json object


code:
import textwrap
s = "This is a long line. "*15
w = 75 # width
print(textwrap.fill(s, w))

rawDescription: How to print the value of a variable in multiple lines in python?

description: Print the value of a variable in multiple lines in python


code: map(lambda x: callable(getattr(object, x)), dir(object))

rawDescription: How to use pythons map with a non-iterable and iterable set of parameters?

description: Use pythons map with a non-iterable and iterable set of parameters


code:
import socket, struct, fcntl

SIOCSIFADDR = 0x8916

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def setIpAddr(iface, ip):
    bin_ip = socket.inet_aton(ip)
    ifreq = struct.pack('16sH2s4s8s', iface, socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8)
    fcntl.ioctl(sock, SIOCSIFADDR, ifreq)

setIpAddr('em1', '192.168.0.1')

rawDescription: How to assign IP address to interface in python?

description: Assign IP address to interface in python


code:
vpan = gtk.VPaned()
vpan.show()
vpan.pack1(box1, shrink=False)
vpan.pack2(box2, shrink=False)

rawDescription: Resizing gtk widgets by user

description: Resizing gtk widgets by user


code:
def getprimefactors(n):
    primefactors = []
    primeind = 0
    p = listOfAllPrimes[primeind]
    while p <= n:
        if n % p == 0:
            primefactors.append(p)
            n //= p
        else:
            primeind += 1
            p = listOfAllPrimes[primeind]
    return primefactors

rawDescription: I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors?


code:
['ChangeSet',
 'ChangeSetForeachFunc',
 'Client',
 'ClientClass',
 'ClientErrorHandlerFunc',
 'ClientErrorHandlingMode',
 'ClientNotifyFunc',
 'ClientPreloadType',
 'Entry',
 'EnumStringPair',
 'Error',
 'ListenersForeach',
 'ListenersPredicate',
 'UnsetFlags',
 'Value',
 'ValueType',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__file__',
 '__format__',
 '__getattr__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__loader__',
 '__module__',
 '__name__',
 '__new__',
 '__path__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_introspection_module',
 '_load',
 '_namespace',
 '_overrides_module',
 '_version',
 'concat_dir_and_key',
 'debug_shutdown',
 'enum_to_string',
 'error_quark',
 'escape_key',
 'init',
 'is_initialized',
 'key_is_below',
 'postinit',
 'preinit',
 'string_to_enum',
 'unescape_key',
 'unique_key',
 'valid_key',
 'value_decode']

rawDescription: How do I make a Gnome Panel applet (written in python) store seperate settings for each instance?

description: Make a Gnome Panel applet (written in python) store seperate settings for each instance


code:
im = cv2.imread('c:\\diff.jpg')
im1 = cv2.imread('c:\\Edited.jpg')

imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(im1, contours, -1, (0,255,0), 1)
cv2.imwrite("c:\\see_this.jpg", im1)

rawDescription: To use OpenCV/cv2 to compare and mark the difference between 2 images (with pictures)


code: import sympy

rawDescription: How can I call sympy by javascript with django / jquery or ajax

description: Call sympy by javascript with django / jquery or ajax


code:
def process_item(self, items, spider):
    session = self.Session()

    try:
        for title, link, date in zip(items['title'], items['link'], items['date']):
            print(title, link, date)
            item = Presstv(title = title, link = link, date = date)

            if session.query(Presstv).filter_by(link=item.link).first() == None:
                session.add(item)
                session.commit()
                logger.info('Item saved')
    finally:
        session.close()

    return items

rawDescription: Why does my script only save one out of the 40 objects that I insert?


code:
import myplt
myplt.setmydefaults()

rawDescription: Matplotlib, globally set number of ticks. X-axis, Y-axis, colorbar


code:
import boto.sqs
c = boto.sqs.connect_to_region()
q = c.lookup('myqueue')
messages = c.receive_message(q, num_messages=1, attributes='All')
messages[0].attributes

rawDescription: How to get messages receive count in Amazon SQS using boto library in Python?

description: Get messages receive count in Amazon SQS using boto library in Python


code:
class Borg( object ):
    __ss = {}
    def __init__( self ):
            self.__dict__ = self.__ss
foo = Borg()
foo.x = 1
bar = Borg()
bar.x

rawDescription: Passing class instantiations (layering)

description: Passing class instantiations (layering)


code:
def ensure_list(it):
    if isinstance(it, (list, tuple, dict)):
        return it
    else:
        return list(it)

rawDescription: Caching a generator

description: Caching a generator


rawDescription: Use Python re to get rid of links

description: Use Python re to get rid of links


rawDescription: How to get 3rd level Object count in Django

description: Get 3rd level Object count in Django


code:
posts = Post.objects.filter(content__contains="test"
    ).extra(select={
                    #extra selects vote status here for current user
                    "my_vote_status":"""SELECT status FROM blog_vote as vt
                                WHERE vt.user_id = %s
                                AND   vt.post_id = blog_posts.id
                             """ % (request.user.pk) #
    }, tables=['blog_vote'])

rawDescription: Selecting filtered related objects in django


rawDescription: Creating new matrix from existing matrix by specifying rows/columns


code:
def get_scores(names, scores):
    x, y, results = a_number, another_number, {}
    for name in names:
        results[name] = scores[y:x]
        x, y = x + an_amount, y + some_amount
    return results

rawDescription: Python way to grab one item from list 1 and assign it four items from list 2?


code:
l=[['bob','tob','mom'],['tom','apa'],['cat']]
d=[dict(enumerate(i)) for i in l]
d

rawDescription: Dictionary of dictionaries with constant keys in python


code:
import requests
...
url = 'https://api.telegram.org/bot'+self.token+'/sendPhoto' #'/sendmessage'
print('request to '+url+' with params '+chat_id+' ' + text)

headers = {'Content-Type': 'multipart/form-data'}

files = {'photo': open('file.jpg', 'rb')}
params = {'chat_id': chat_id, 'caption': text}
r = requests.post(url,  files=files, params=params)
print(r.text)

rawDescription: upload file with post params

description: Upload file with post params


code:
docu = ''
dom = xml.dom.minidom.parseString(docu)
a = dom.getElementsByTagName("a")[0]
a.attributes.items()

rawDescription: Getting all attributes of an element with minidom


code:
import scrapy
from scrapy.selector import Selector

class HnItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    score = scrapy.Field()

class HnSpider(scrapy.Spider):
    name = 'hackernews'
    allowed_domains = ["news.ycombinator.com"]
    start_urls = ["https://news.ycombinator.com/"]

    def parse(self, response):
        sel = Selector(response)
        item = HnItem()
        title_list = sel.xpath('.//td[@class="title"]/a/text()').extract()[:-2]
        link_list= sel.xpath('.//tr[@class="athing"]/td[3]/a/@href').extract()
        score_list = sel.xpath('.//td[@class="subtext"]/span/text()').extract()
        for x in range(0,len(title_list)):
            item['title'] = title_list[x]
            item['link'] = link_list[x]
            item['score'] = score_list[x]
            yield item

rawDescription: Scrapy pipeline extracting in the wrong csv format


code:
from gi.repository import Gtk
class Patch(Gtk.DrawingArea):
  def __init__(self):
    super(Patch,self).__init__()

  def do_get_preferred_width(self):
    print("test")
    return 100, 100

  def do_get_preferred_height(self):
    print("test")
    return 100, 100

win = Gtk.Window()
win.add(Patch())
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: Overriding virtual methods in PyGObject

description: Overriding virtual methods in PyGObject


code:
import matplotlib.pyplot as plt

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

# Directly instantiate polygons
coordinates = [[0.5,0.6],[0.5,0.7],[0.55,0.75],[0.6,0.7],[0.6,0.6]]
poly = plt.Polygon(coordinates, facecolor='black')
ax.add_patch(poly)

# If you just need a Rectangle, then there is a class for that too
rect = plt.Rectangle([0.2,0.2], 0.1, 0.1, facecolor='red')
ax.add_patch(rect)

plt.show()

rawDescription: Mask quiver plot with imshow in matplotlib


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--sqlite-file', type=argparse.FileType('r'))
args = parser.parse_args(['--sqlite-file', '/tmp/demo.db'])
args.sqlite_file
args.sqlite_file.name

rawDescription: How to get filename with argparse while specifying type=FileType(...) for this argument

description: Get filename with argparse while specifying type=FileType(...) for this argument


code: s1.align(s2, join='inner')

rawDescription: comparison of two pandas-timeseries

description: Comparison of two pandas-timeseries


code:
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
X.shape
lsvc = LinearSVC(C=0.01, penalty="l1", dual=False)
X_new = lsvc.fit_transform(X, y)
X_new.shape
lsvc.coef_
~np.all(lsvc.coef_==0, axis=0)

rawDescription: Which features selects fit_transform?

description: Which features selects fit_transform


code:
import json
import os
import shutil
import tempfile

def rewriteJsonFile(sourceObj, targetFilePath, **kwargs):
  temp = tempfile.mkstemp()
  tempHandle = os.fdopen(temp[0], 'w')
  tempFilePath = temp[1]
  json.dump(sourceObj, tempHandle, **kwargs)
  tempHandle.close()
  shutil.move(tempFilePath, targetFilePath)

rawDescription: Python json - editing a .json file

description: Python json - editing a .json file


code:
import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
grid = sns.JointGrid(iris.petal_length, iris.petal_width, space=0, size=6, ratio=50)
grid.plot_joint(plt.scatter, color="g")
plt.plot([0, 4], [1.5, 0], linewidth=2)

rawDescription: Using seaborn, how can I draw a line of my choice across my scatterplot?


code:
p_values = scipy.stats.norm.sf(abs(z_scores)) #one-sided

p_values = scipy.stats.norm.sf(abs(z_scores))*2 #twosided

rawDescription: Convert Z-score (Z-value, standard score) to p-value for normal distribution in Python


code: fig = plt.quiver(x, y, vector_field_x, vector_field_y, m, clim=[-2,2])

rawDescription: How to set a color bar range in Matplotlib?

description: Set a color bar range in Matplotlib


code: f = open(fn, 'rb')

rawDescription: Python 2.7: len() returns wrong value for line from file with newline character


code:
widgets = [deadparrotlabel, sillywalkslabel, ... ]
for w in widgets:
    w.config(state=DISABLED)

rawDescription: Using a for loop to set attributes of a list of objects in Python


code:
def f(event):
    caller = event.widget

rawDescription: Getting the widget that triggered an Event?


code:
def status_generator(iterable, update_interval=10):
    for i, x in enumerate(iterable):
        if not (i % update_interval):
            print("On count {}".format(unicode(i)))
        yield x

map(f, status_generator(my_iterable))

rawDescription: Native counter on a for-loop iterative in python


code: from ..utl import server

rawDescription: python import (project organization)

description: Python import (project organization)


code:
from tkinter import *
x = []
root = Tk()
data = {'parakeet': ['fly', 'bird'], 'dog': 'animal', 'cat': 'feline'}
for key in data.keys():
    x.append(key)

Label(root, text = "Enter your name").grid(row=0,ipadx = 10,ipady = 10)
Label(root, text = x ).grid(row=1,ipadx = 10,ipady = 50)

mainloop()

rawDescription: Tkinter display dictionary key into text widget?


code: set1['PLSAM'] = set2['PLSAM']

rawDescription: Merging Random Lat/Long Points to Travel Survey Data on Census Tract Field in Pandas


code:
import time
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.label = QtGui.QLabel(self)
        layout.addWidget(self.label)
        self.buttonStart = QtGui.QPushButton('Start', self)
        self.buttonStart.clicked.connect(self.handleStart)
        layout.addWidget(self.buttonStart)
        self.buttonStop = QtGui.QPushButton('Stop', self)
        self.buttonStop.clicked.connect(self.handleStop)
        layout.addWidget(self.buttonStop)
        self._running = False

    def handleStart(self):
        self.buttonStart.setDisabled(True)
        self._running = True
        while self._running:
            self.label.setText(str(time.clock()))
            QtGui.qApp.processEvents()
            time.sleep(0.05)
        self.buttonStart.setDisabled(False)

    def handleStop(self):
        self._running = False

if __name__ == '__main__':

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

rawDescription: Pause execution until button press

description: Pause execution until button press


code:
t = (1,2,3,4,[5,6,7,8],9)
lst = list(t)
lst[4] is t[4]  #outermost container is now a list() but inner items are still same.
lst1 = [[[2,3,4]]]
id(lst1)
lst2 = list(lst1)
id(lst2)
lst1[0] is lst2[0]

rawDescription: What does the list() function do in Python?


code:
import numpy as np
import random

numRounds = 10
numTimes = 5
finalList = []

def runRounds(numberOfRounds, firstList, finalList):
    for xRound in range(numberOfRounds):
        if random.randint(0,100) >= 85:
            firstList.append(1)
        else:
            firstList.append(0)
    finalList.append(max(firstList))
    return (firstList, finalList)

def runTimes(numTimes, numRounds, finalList):
    for time in range(numTimes):
        firstList = []
        firstList, finalList = runRounds(numRounds, firstList, finalList)
        print(firstList)
    return (firstList, finalList)

firstList, finalList = runTimes(numTimes, numRounds, finalList)

print(finalList)

rawDescription: python: Is it possible to create a list inside of a function?

description: Python: Is it possible to create a list inside of a function


code:
from sklearn.cluster import KMeans
import numpy as np
x = np.random.random(13876)

km = KMeans()
km.fit(x.reshape(-1,1))  # -1 will be calculated to be 13876 here

rawDescription: Scikit-learn: How to run KMeans on a one-dimensional array?


code:
class EnvhostsCreate(CreateView):
    model = Capacity.models.Envhosts
    fields = ['hostname', 'count']
    template_name_suffix = '_create_form'

    def form_valid(self, form):
        form.instance.env = Envhosts.objects.get(pk=self.kwargs['envid'])
        return super(EnvhostsCreate, self).form_valid(form)

rawDescription: Django CreateView customise form default field based on url parameter


code:
s = "He got to go to New York"
re.sub(r'\b([A-Z][a-z]*)\b', lambda m: str(len(m.group(1))), s)

rawDescription: Replace substrings in python with the length of each substring


code:
class A(object):
    pass

import inspect
inspect.getmro(A)
[c.__name__ for c in inspect.getmro(A)]

rawDescription: How to parse the list data in python

description: Parse the list data in python


code: common_keys = list(dict_a.viewkeys() & dict_b.viewkeys())

rawDescription: iteritems in Python

description: Iteritems in Python


code:
# work for == as well as is
class START(object): pass
def START(): pass
class Whatever(object): pass
START = Whatever()

# if you don't care for "accidental" == and only check with `is`
START = []
START = {}
START = set()

rawDescription: Proper way of having a unique identifier in Python?


code:
from itertools import product
list(product(range(2), repeat=3))
all((a & b | c) == ((a & b) | c) for a, b, c in product(range(2), repeat=3))
all((a & b | c) == (a & (b | c)) for a, b, c in product(range(2), repeat=3))

rawDescription: Numpy bitwise operator priority?

description: Numpy bitwise operator priority


code: d.update((extract_the_key(r), extract_the_value(r)) for r in responses)

rawDescription: What's a Pythonic way to add a list (or other iterator) of key/value pairs to a dict?


code:
import inspect,dis

def expecting():
    """Return how many values the caller is expecting"""
    f = inspect.currentframe()
    f = f.f_back.f_back
    c = f.f_code
    i = f.f_lasti
    bytecode = c.co_code
    instruction = bytecode[i+3]
    if instruction == dis.opmap['UNPACK_SEQUENCE']:
        howmany = bytecode[i+4]
        return howmany
    elif instruction == dis.opmap['POP_TOP']:
        return 0
    return 1

def cleverfunc():
    howmany = expecting()
    if howmany == 0:
        print("return value discarded")
    if howmany == 2:
        return 1,2
    elif howmany == 3:
        return 1,2,3
    return 1

def test():
    cleverfunc()
    x = cleverfunc()
    print(x)
    x,y = cleverfunc()
    print(x,y)
    x,y,z = cleverfunc()
    print(x,y,z)

test()

rawDescription: Python check for the number of output arguments a function is called with


code:
import datetime

from tornado.ioloop import IOLoop
from tornado import gen

handlers = set()

@gen.coroutine
def auto_loop():
    while True:
        for handler in handlers:
            handler.write_message('automatic message')

        yield gen.Task(
            IOLoop.current().add_timeout,
            datetime.timedelta(milliseconds=500))

if __name__ == '__main__':
    # ... application setup ...

    # Start looping.
    auto_loop()
    IOLoop.current().start()

rawDescription: Infinite "background" loop for Tornado WebSockets handler


code:
def replace_not_first(str, word, replace):
    str_arr = str.split(word)
    return str_arr[0] + word + replace.join(str_arr[1:])

str = "change the string in the sentence and the save"
print(replace_not_first(str, 'the', 'hello'))

rawDescription: String replace without replacing the first instance


code:
notifier = pyinotify.Notifier(wm, handler)
wm.add_watch('/tmp', pyinotify.IN_CREATE)
notifier.loop()

rawDescription: python dbus method for watching a directory change?

description: Python dbus method for watching a directory change


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

# Initialize the Simulation

dim = 50
a = np.matrix(np.zeros((dim, dim)))
pos = np.matrix([[dim // 2], [dim // 2]])  # current position of ant
direction = np.matrix([[1], [0]])  # direction ant is currently moving

# Rotation Matrices
clock = np.matrix([[0, 1], [-1, 0]])
counter = np.matrix([[0, -1], [1, 0]])

def takestep(a, pos, direction):
    pos[:] = pos + direction
    if a[pos[0, 0], pos[1, 0]] == 0:  # landed on white
        a[pos[0, 0], pos[1, 0]] = 1
        direction[:] = clock * direction
    else:
        a[pos[0, 0], pos[1, 0]] = 0
        direction[:] = counter * direction

fig = plt.figure()
im = plt.imshow(a, interpolation='none', vmin=0, vmax=1)

def animate(i):
    takestep(a, pos, direction)
    im.set_data(a)
    return [im]

anim = animation.FuncAnimation(fig, animate,
                               frames=200, interval=0, blit=True,
                               repeat=False)
plt.show()

rawDescription: Animating Langdon's Ant in Python with Matplotlib


code:
lableArray=['l1','l2','l3']
dataArray=['d1','d2','d3']
rdd2=sc.parallelize(lableArray)
rdd1=sc.parallelize(dataArray)
rdd1.collect()
rdd2.collect()
rdd=rdd2.zipWithIndex().map(lambda x:(x[1],x[0])).join(rdd1.zipWithIndex().map(lambda y:(y[1],y[0]))).map(lambda x:x[1])
rdd.collect()

rawDescription: RDD from label Array and data Array in python/spark


code:
xarr, yarr = [], []
for i in range(1,n):
    dx = random.uniform(-2,2)
    x = x+dx
    y += ((v**2 - dx**2)**(0.5))*(random.randint(-1,1))
    xarr.append(x)
    yarr.append(y)
pl.plot(xarr,yarr)

pl.show()

rawDescription: Creating plots from 2-D values generated in a for loop in Python


code:
a = np.arange(3)
a + a[:,np.newaxis] * 1j

rawDescription: 2D Array Creations to containing real and imaginary numbers along each axis


code:
import urllib2

from bs4 import BeautifulSoup, SoupStrainer

content = urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_Telugu_films_of_2015").read()
filter_tag = SoupStrainer("table", {"class":"wikitable"})
soup = BeautifulSoup(content, parse_only=filter_tag)

links=[]
for sp in soup.find_all(align="center"):
    a_tag = sp('a')
    if a_tag:
        links.append(a_tag[0].get('href'))

rawDescription: How does table parsing work in python? Is there an easy way other that beautiful soup?


code:
def headerFormat1(list1):
    char_to_remove = ['(', ')']
    list2 = list1[:]
    list1 = []
    for headers in list2:
        headers = headers.replace(' ', '_')
        for character in char_to_remove:
            headers = headers.replace(character, '')
        list1.append(headers)
    del list2
    return list1

def headerFormat2(list1):
    char_to_remove = ['(', ')']
    for i, headers in enumerate(list1):
        headers = headers.replace(' ', '_')
        for character in char_to_remove:
            headers = headers.replace(character, '')
        list1[i]=headers
    return list1

theList = ['I want Underscores Instead', 'R(e(m(o(v(e()P)a)r)e)n)t)h)e)s)e)s', 'LetMeBe']
print(headerFormat1(theList))
print(headerFormat2(theList))

rawDescription: Modifying List Values

description: Modifying List Values


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

from PyQt4 import QtGui, QtCore

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

        self.pushButtonClose = QtGui.QPushButton(self)
        self.pushButtonClose.setText("Close")
        self.pushButtonClose.clicked.connect(self.on_pushButtonClose_clicked)

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

        titleBarHeight = self.style().pixelMetric(
            QtGui.QStyle.PM_TitleBarHeight,
            QtGui.QStyleOptionTitleBar(),
            self
        )

        geometry = app.desktop().availableGeometry()
        geometry.setHeight(geometry.height() - (titleBarHeight*2))

        self.setGeometry(geometry)

    @QtCore.pyqtSlot()
    def on_pushButtonClose_clicked(self):
        QtGui.QApplication.instance().quit()

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: How to make a window that occupies the full screen without maximising?

description: Make a window that occupies the full screen without maximising


code:
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

rawDescription: Django: Can't render STATIC_URL from settings in template


code:
import pylab as plt
import numpy as np

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

def f1(x): return 1/x
def f2(x): return 2/x
def f3(x): return np.sqrt(x**2-1)
def f4(x): return np.sqrt(x**2-2)

t=np.arange(1,5,1e-4) # use this if you want a better fill
t=np.arange(1,5,0.05)
y1=f1(t)
y2=f2(t)
y3=f3(t)
y4=f4(t*(t**2>2) + np.sqrt(2)*(t**2<=2) ) # Condition checking

y5 = np.array(map(min, zip(y2, y3)))
y6 = np.array(map(max, zip(y1, y4)))

ax.plot(t,y1, 'red')
ax.plot(t,y2, 'blue')
ax.plot(t,y3, 'green')
ax.plot(t,y4, 'purple')

ax.plot(t, y5, '+', ms=5, mfc='None', mec='black')
ax.plot(t, y6, 's', ms=5, mfc='None', mec='black')

ax.fill_between(t, y5, y6, where=y5>=y6)

plt.xlim([1.1,2.1])
plt.ylim([0.5,1.5])

plt.show()

rawDescription: Python, How to fill between multiple (4) curves?


rawDescription: Using an Environmental Variables In a Variety of Path Types


code:
user = session.query(User).filter_by(username=request.params['username']).first()
if user is None:
   "not found" # do whatever appropriate in your case e.g., return 404

headers = {'content-type': 'application/json'}
requests.put('http://localhost:9200/master/user/{userid}'.format(user.user_id),
             data=json.dumps(dict(name=request.params['name'], reputation=0,
                                  username=request.params['username'])),
             headers=headers)

rawDescription: Weird behavior between pyramid and python's requests library


rawDescription: Auto fill np.nan for arrays of different size


rawDescription: how to find possible numbers which can fit a row and column of sudoku board on python?

description: Find possible numbers which can fit a row and column of sudoku board on python


code:
import sqlalchemy
from sqlalchemy.schema import DDL

sqlalchemy.event.listen(
    metadata,
    'before_create',
    DDL('CREATE OR REPLACE FUNCTION myfunc() ...')
)

rawDescription: User defined function creation in SQLAlchemy


code:
class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

rawDescription: Limiting Admin Choices Using limit_choices_to


code:
import datetime, os
def mtime(filename):
    return datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
time_diff = mtime(file_path_a) - mtime(file_path_b)

rawDescription: How to get and compare date and time of given files in python

description: Get and compare date and time of given files in python


code:
import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
   html = response.read()
soup = BeautifulSoup(html.decode('utf-8', 'ignore').encode("utf-8"))

rawDescription: BeautifulSoup parser and cirillic characters


code:
class Category(models.Model):
    name = models.CharField('Name', max_length=255)

    class Meta:
        db_table = 'tbl_category'

class Entry(models.Model):
    category = models.ForeignKey(Category, db_column='id_tbl_category')
    contents = models.TextField('Contents')

    class Meta:
        db_table = 'tbl_entry'

rawDescription: Django how to customize table name and foreign key field


code:
class SomeClass(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)
    name =  deferred(Column(String(50)))

rawDescription: SQLAlchemy.declarative and deferred column loading


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
map = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
          lat_0=0, lon_0=-130)
map.drawcoastlines()
map.drawcountries()
map.fillcontinents(color = 'gray')
map.drawmapboundary()
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))

x,y = map(0, 0)
point = map.plot(x, y, 'ro', markersize=5)[0]

def init():
    point.set_data([], [])
    return point,

# animation function.  This is called sequentially
def animate(i):
    lons, lats =  np.random.random_integers(-130, 130, 2)
    x, y = map(lons, lats)
    point.set_data(x, y)
    return point,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(plt.gcf(), animate, init_func=init,
                               frames=20, interval=500, blit=True)

plt.show()

rawDescription: Matplotlib Basemap animation

description: Matplotlib Basemap animation


code:
arr = {('value1',): 3, ('value2',): 11, (u'value3',): 5, (u'value4',): 35, ('value5',): 3}
vals = arr.values() # Get list of values, [3, 11, 5, 34, 3]
average = reduce(lambda x,y: (x + y) / 2.0, vals)
# Perform whatever operations you want

rawDescription: How to peform mathematical operations on some fields in Python?

description: Peform mathematical operations on some fields in Python


code: data = data.groupby(['type', 'name']).agg({'min':np.min, 'max':np.max, 'calculation': calculation})

rawDescription: Calculations within pandas aggregate

description: Calculations within pandas aggregate


code:
test = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
d = 'DEF'
head, sep, tail = test.partition(d)
[head, sep+tail]

rawDescription: Python: Split string at the start of delimiter rather than the end


code:
import ctypes, win32gui
def getPalette(hwnd):
    #hwnd = win32gui.GetDesktopWindow() #if you want desktop window palette?

    hwndDC = win32gui.GetWindowDC(hwnd)

    buff = ctypes.c_buffer("0"*(256*4)) #R, G, B, and flags
    ctypes.windll.gdi32.GetSystemPaletteEntries(hwndDC, 0, 256, buff)

    win32gui.ReleaseDC(hwnd, hwndDC)

    #ignore every 4th entry which is the flags
    res = [ord(x) for i,x in enumerate(buff) if i%4 != 3]
    return res

rawDescription: pywin32: GetSystemPaletteEntries

description: Pywin32: GetSystemPaletteEntries


code:
result = p.parseDateText("March 5th, 1980")
result = p.parseDate("4/4/80")

rawDescription: Best way to get date strings with Python

description: Get date strings with Python


code:
import os
import time

## run indefinitely
while True:
    ## get the directory listing
    pdffiles = [name for name in os.listdir('somedir')
               if name.endswith('.pdf')]

    ## print the most recent listing
    for file in pdffiles:
        print(file)

    ## wait a little bit before getting the next listing
    ## if you want near instantaneous updates, make the sleep value small.
    time.sleep(1)

rawDescription: How to list (certain) files in a directory dynamically in Python?

description: List (certain) files in a directory dynamically in Python


code:
listA = ['a', 'b', 'c', 'd']
listB = [ 1 ,  2 ,  3 ,  4 , 5 ]
listC = ['!', '?', '=']
result = list(itertools.product(listA, listB, listC))
result[:5]

rawDescription: Cross merge list elements to get a list of tuples in Python


code:
import re
s = "q1)whatq2)whenq3)where"
m = re.findall(r'q\d+\)(?:(?!q\d+).)*', s)
m

rawDescription: Regex pattern to extract substring

description: Regex pattern to extract substring


code:
d=[]
cur = ''
for i in sys.stdin.readline():
    if i in ' .':
        if cur not in d and (cur != ''):
            d.append(cur)
        cur = '' # note the different indentation
    else:
        cur = cur + i.lower()

rawDescription: Tokenizing a string gives some words merged


code: ext_id = db.Column(db.Integer, primary_key=True, autoincrement=False)

rawDescription: sqlalchemy primary key without auto-increment

description: Sqlalchemy primary key without auto-increment


code:
import matplotlib.colors as colors

ind = (np.abs(D.T - 0.5) > 0.1)
new_D = np.ma.masked_array(D.T,mask=ind)
greenmap = colors.ListedColormap(['g'])
ax.pcolormesh(xbin,ybin,new_D,cmap=greenmap,edgecolors='None')

rawDescription: Python matplotlib mask multiple (more than three) values using pcolormesh


code:
class Gene(object):
    def __init__(self, color, properties):
        self.color = color
        self.properties = properties

geneA = Gene('red', ['a', 'b', 'c'])
geneB = Gene('blue', ['d', 'e', 'f'])
genes = [geneA, geneB]

inverted = {}
for gene in genes:
    for prop in gene.properties:
        inverted[prop] = gene.color

rawDescription: Map two lists into an inverted dictionary


code:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
                'admin_tools.template_loaders.Loader',
            ],
        },
    },
]

description: Django-admin-tools Raises ImproperlyConfigured


code:
label = ["first","second"]
lists = [[1,2],[11,22]]
[dict(zip(label, l)) for l in lists]

rawDescription: Python list to dictionary

description: Python list to dictionary


code:
routes = Routes.objects.select_related('vehicle').filter(**conditions).only(
            'externalid', 'vehicle__name')

rawDescription: Django : load a restricted set of fields of objects loaded using a foreign key


code:
def any_HE():
    global config
    config = ConfigParser.RawConfigParser()
    config.read('config.cfg')
    for section in config.sections():
        list = {} #start with empty list for each section
        env.user = config.get(section, 'db.user_name')
        env.password = config.get(section, 'db.password')
        host = config.get(section, 'db.ip')
        with settings(hide('warnings', 'running', 'stdout', 'stderr'), \
                        warn_only=True, host_string=host):
            paramiko.util.log_to_file(section + '.log')
            files = run('ls -ltr /opt/nds')
            with open(section + ".txt", "w") as fo:
                fo.write(files)
            components = []
            with open(section + ".txt", 'rb') as fo:
                strings = ("/installed/")
                i=0
                for line in fo:
                    if strings in line:
                        id = re.search('installed/(.+)',line)
                        if id:
                            components.append(id.group(1))
                            component,version = components[i].rstrip().split('-',1)
                            list[component] = version
                            i+=1
            write_data(list, section + "_HE", 1)

rawDescription: Reading all sections in a config file

description: Reading all sections in a config file


code:
def __init__(self, *args, **kwargs):
    initial = kwargs.get('initial', {})
    initial['material'] = 'Test'
    kwargs['initial'] = initial
    super(ArtefactForm, self).__init__(*args, **kwargs)

rawDescription: Overriding initial value in ModelForm

description: Overriding initial value in ModelForm


code:
def parse(self, response):
    for elm in response.xpath("//span[@class='pl']//a"):
        item = CraigslistSampleItem()
        item["title"] = elm.xpath("text()").extract_first()
        item["link"] = elm.select("href").extract_first()
        yield item

rawDescription: Scrapy print to json file

description: Scrapy print to json file


code:
import lxml.html
import urllib2

html = urllib2.urlopen("http://http://environmentalchemistry.com/yogi/periodic/W.html").read()
doc = lxml.html.document_fromstring(html)
result = doc.xpath("/html/body/div[2]/div[2]/div[1]/div[1]/ul[7]/li[8]")

rawDescription: Parse data from html page to table

description: Parse data from html page to table


code:
def diameter_height(node):
    if node is None:
        return 0, 0
    ld, lh = diameter_height(node.left)
    rd, rh = diameter_height(node.right)
    return max(lh + rh + 1, ld, rd), 1 + max(lh, rh)

def find_tree_diameter(node):
    d, _ = diameter_height(node)
    return d

rawDescription: Optimize finding diameter of binary tree in Python


code:
import tkinter as tk
import tkinter.simpledialog

class My_QueryString(tkinter.simpledialog._QueryString):

      def body(self, master):
          self.bind('<KP_Enter>', self.ok) # KeyPad Enter
          super().body(master)

def myaskstring(title, prompt, **kw):
    d = My_QueryString(title, prompt, **kw)
    return d.result

#---------------------------------------------------------

root = tk.Tk()

new_name = myaskstring("Name Change", "New name")
if new_name:
    print(new_name)

root.mainloop()

rawDescription: Python tkinter simpledialog. How to bind a key to the OK button in simpledialog


code:
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

rawDescription: What algorithm does Python employ in fractions.gcd()?


code:
records = []
record1 = {"name":"Bob", "email":"bob@email.com"}
records.append(record1)
record2 = {"name":"Bob2", "email":"bob2@email.com"}
records.append(record2)

rawDescription: Generating json in python for app engine


code:
class NoOverrideMeta(type):
    def __new__(mcs, name, bases, dct, no_override=None):
        if no_override is None:
            no_override = []
        cls = super().__new__(name, bases, dct)
        for meth_name in no_override:
            assert not hasattr(super(cls, cls), meth_name)
        return cls

class EchoSoma(Soma, metaclass=NoOverideMeta, no_override=['inject_basic_evidence']):

    def inject_basic_evidence(self, basic_in):
        super().fire(basic_in)

rawDescription: Is there a nice way to express the opposite of an "override specifier" in Python?


code: df.index = df.index.str.encode('utf-8')

rawDescription: Dataframe encoding

description: Dataframe encoding


code:
with open('file','r') as f:
  entries = set()
  for row in f:
    entries.add(row.rstrip())

rawDescription: Importing file lines into a set without EOL characters and without post-processing


code:
def is_running():
    try:
        with open(PID_PATH) as f:
            pid = int(f.read())
        os.kill(pid, 0)
    except Exception:
        return False
    else:
        return True

def stop():
    with open(PID_PATH) as f:
        pid = int(f.read())
    os.kill(pid, signal.SIGUSR1)

def start():
    subprocess.check_call(DAEMON_PATH)

rawDescription: Python: GUI for continuously running script


code:
class SomeStruct(ctypes.Structure):
    _fields_ = [
        ('field', ctypes.c_char)
    ]

res = bytearray(b'12345')
ctypes.cast(ctypes.create_string_buffer(bytes(res)), ctypes.POINTER(SomeStruct)).contents

rawDescription: Casting a bytearray instance in ctypes

description: Casting a bytearray instance in ctypes


code:
for index,each in enumerate(myCollection.find({})):
    each["count"] = index
    id = each["_id"]
    each.pop("_id", None)
    collection.update({"_id":id},{"$set":each},upsert=True)

rawDescription: How to update all documents in a collection with same key but different values?

description: Update all documents in a collection with same key but different values


code:
# Strip any hashes on the left.
string.lstrip('#')

# Remove hashes anywhere in the string, not necessarily just from the front.
string.replace('#', '')

# Remove only the first hash in the string.
string.replace('#', '', 1)

# Unconditionally remove the first character, no matter what it is.
string[1:]

# If the first character is a hash, remove it. Otherwise do nothing.
import re
re.sub('^#', '', string)

rawDescription: Modifying strings in Python

description: Modifying strings in Python


code:
import sqlite3
import pkg_resources

db_path = pkg_resouces.resource_filename('londontweetgrabber', 'data/data.db')
conn = sqlite3.connect(db_path)

rawDescription: Loading sqlite database in python distribution


code:
def __init__(self, *args, **kwargs):
    super(UserProfileForm, self).__init__(*args, **kwargs)
    try:
        self.fields['first_name'].initial = self.instance.user.first_name
        self.fields['last_name'].initial = self.instance.user.last_name
        self.fields['email'].initial = self.instance.user.email
    except models.User.DoesNotExist:
        pass

email = forms.EmailField(label = "Główny adres email",
                         help_text="",
                         required=True)
first_name = forms.CharField(label = "Imię",
                             required=False)
last_name = forms.CharField(label = "Nazwisko",
                            required=False)
kod_pocztowy = forms.RegexField('\d{2}-\d{3}',
                                required = False,
                                label="Kod pocztowy",
                                error_messages={"invalid":'Poprawna wartość to np: 41-200'})

class Meta:
    model = UserExtended
    exclude  = ('user')

def save(self, *args, **kwargs):
    u = self.instance.user
    u.email = self.cleaned_data['email']
    u.first_name = self.cleaned_data['first_name']
    u.last_name = self.cleaned_data['last_name']
    u.kod_pocztowy = self.cleaned_data['kod_pocztowy']
    u.save()
    profile = super(UserProfileForm, self).save(*args, **kwargs)
    return profile

rawDescription: Django extending user model and displaying form


code:
def has_five_or_more_in_ANY_30_days(timestamps):
    tssorted = sorted(timestamps)
    time_to_check = 30 * 24 * 60 * 60
    for i in range(0,len(tssorted)-5):
        time_diff = 0
        for j in range(i+1,i+5):
            time_diff += tssorted[j] - tssorted[i]
        if time_diff < time_to_check:
            return True
    return False

rawDescription: Calculating count of timestamp

description: Calculating count of timestamp


code:
from part import *
from sketch import *

p=session.viewports[session.currentViewportName].displayedObject
currentModel=mdb.models[p.modelName]

for faceNum,face in enumerate(p.faces):
    try:  # Will only work on valid sketch planes.  Must be a flat face
        t = p.MakeSketchTransform(sketchPlane=face, sketchUpEdge=p.edges[0],
            sketchPlaneSide=SIDE1, origin=(659.077803, 0.256062, -816.16))
        s = currentModel.ConstrainedSketch(name='__profile__',
            sheetSize=834.36, gridSpacing=20.85, transform=t)
        edgeList=[p.edges[edgeNum] for edgeNum in face.getEdges()]
        p.projectEdgesOntoSketch(sketch=s, edges=tuple(edgeList))
        currentModel.ConstrainedSketch(name='Sketch-face' + str(edgeNum), objectToCopy=s)
    except:
        pass

rawDescription: How to extract sketches from shell part in ABAQUS

description: Extract sketches from shell part in ABAQUS


rawDescription: Send an image with flask by using urllib2


code:
from datetime import datetime, time, timedelta

yesterday = datetime.utcnow() - timedelta(days=1)
dt = datetime.combine(yesterday.date(), time(0, 0)) # midnight
rfc3339str = dt.isoformat() + "Z"

rawDescription: Python RFC 3339 format for JSON serialization


code:
def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

original = [{1: "xxx [pear] yyy", 2: "xxx [apple] zzz"}, {0: "aaa [cat] yyy", 1: "bbb [dog] zzz"}]

for dct in original:
    for key in dct:
        dct[key] = find_between(dct[key], "[", "]")

rawDescription: Slicing string values in each dict from list of dicts?


code:
import mmap

offsets = [0, 12, 32, 56]

with open(..., 'rb') as fp:
    mm = mmap.mmap(fp.fileno(), 0)

    # Load the octects in a list.
    octects = [mm[i:i+4] for i in offsets]
    # Or concatenate them into a byte string.
    val = b''.join(mm[i:i+4] for i in offsets)

rawDescription: Read in binary file

description: Read in binary file


code:
import glob
import json
from bs4 import BeautifulSoup

def main():
    data = []
    for filename in glob.iglob('*.html'):
        with open(filename) as f:
            soup = BeautifulSoup(f)

            title = soup.find("span", id="btAsinTitle")
            data.append({
                "title":  title.get_text(),
                "author": title.find_next("a", href=True).get_text(),
                "isbn":   soup.find('b', text='ISBN-10:').next_sibling,
                "weight": soup.find('b', text='Shipping Weight:').next_sibling,
                "price":  soup.findAll('span', {"class":'bb_price'})
            })

    with open("my_output.json", "w") as outf:
        json.dump(data, outf)

main()

rawDescription: How to dump data from python as JSON

description: Dump data from python as JSON


code:
def save(self, *args, **kwargs):
    self.name = self.parent_set.all()[0].parent_name
    super(Child, self).save(*args, **kwargs)

rawDescription: Django: calling parent variable on django models


code:
def view_function(request,id):
    object_to_edit = get_object_or_404(Model,id=id) #Or slug=slug
    form = ModelForm(data = request.POST or None, instance=object_to_edit)
    if form.is_valid():
        form.save()
        redirect()
    return render_to_response('template_name',{},RequestContext(request))

rawDescription: Django form INSERTs when I want it to UPDATE


code: groups = groups.objects.filter(item__in=items).distinct().values_list('name', flat=True)

rawDescription: Get all related many-to-many objects from a Django QuerySet


code:
for single_list in myLists:
    for i, item in enumerate(single_list):
        single_list[i] = numParser(item)

rawDescription: "python way" to parse and conditionally replace every element in 2D list


code:
class MyFrame1 (wx.Frame):
    def __init__(self):
        super(MyFrame1, self).__init__()
        fluid_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.m_textCtrl1 = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)
        fluid_sizer.Add(self.m_textCtrl1, 0, wx.ALL, 5)
        self.SetSizer(fluid_sizer)
        self.Layout()

rawDescription: Can't edit TextCtrl built from other function than __init__ (wxPython)


code:
MAGIC_WORD = r'JPEG'  # it's example... just example
l = list(c for c in f.read(len(MAGIC_WORD)))
offset = 0
while True:
    if ''.join(l) == MAGIC_WORD:
        return offset
        offset += 1
        l.pop(0)
        l.append(f.read(1))

rawDescription: Image recovery from binary file

description: Image recovery from binary file


code: grouper = lambda x: (x["rw_worker_nick"], x["rw_date"].replace(day=1))

rawDescription: python group by 2 keys with only month in second key

description: Python group by 2 keys with only month in second key


code:
OnGetItemText(self, item, column)
OnGetItemAttr(self, item)
OnGetItemImage(self, item)

rawDescription: How do I synchronize data between an editable ListCtrl and a data source?

description: Synchronize data between an editable ListCtrl and a data source


code:
y = 10
N = 5
for _ in range(N):
    y = y ** 2

print (y)

rawDescription: Trying to do an operation N times

description: Trying to do an operation N times


code: _, bValue = foo()

rawDescription: Python: anonymous variable for part of the return value of a function


code: map(lambda item: item.blog, tag_list)

rawDescription: Change an object list to another object

description: Change an object list to another object


code:
import numpy as np
import pylab as P
#
# first create a single histogram
#
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
#
# finally: make a multiple-histogram of data-sets with different length
#
x0 = mu + sigma*P.randn(10000)
x1 = mu + sigma*P.randn(7000)
x2 = mu + sigma*P.randn(3000)

# and exercise the weights option by arbitrarily giving the first half
# of each series only half the weight of the others:

w0 = np.ones_like(x0)
w0[:len(x0)/2] = 0.5
w1 = np.ones_like(x1)
w1[:len(x1)/2] = 0.5
w2 = np.ones_like(x2)
w0[:len(x2)/2] = 0.5

P.figure()

n, bins, patches = P.hist( [x0,x1,x2], 10, weights=[w0, w1, w2], histtype='bar')

P.show()

rawDescription: how can I plot 4 histograms on the same graph

description: Plot 4 histograms on the same graph


code:
def func():
  ...

def device_view():
  return bottle.template('device_view.tpl', {'device':result, 'func':func})

{{func(data)}}

rawDescription: Switching from bottle.template to mako

description: Switching from bottle.template to mako


code:
class Proxy(object):
    def __init__(self, obj):
        object.__setattr__(self, '__obj', obj)
    def __getattribute__(self, name):
        return getattr(object.__getattribute__(self, '__obj'), name)

a = range(10)
p = Proxy(a)

p.append(10) # etc...

rawDescription: Python creating handler for an object?

description: Python creating handler for an object


rawDescription: Python Regular Expression--extracting coordinates


code:
fibonacci_matrix = numpy.matrix([[1,1],[1,0]], dtype=object)
def fib(n): return (fibonacci_matrix**(n-1)) [0,0]

fib(100)

rawDescription: Python fibonacci doesn't have infinite precision?


code: [[] for reg in reg_list]

rawDescription: Searching a file for a list of regexs, Python


code:
from django.views.generic import ListView
from django.db.models import Q
from .models import Author

def SearchAuthorView(ListView):

  def get_queryset(self):
    name = self.request.GET['author_name']
    name_tokens = name.split(' ')

    matched_authors = []
    authors = Author.objects.all()
    for author in authors:
      for name_token in author.name.split(' '):
        if name_token in name_tokens:
          matched_authors.append(author)
          break
    return matched_authors

rawDescription: Unsure about what type of Django form I should use


rawDescription: Get a suds web service XML sub group in a python list?


code:
from requests import Request, Session

def authentication(self, req):
    signup = md5(str(req.body)).hexdigest()
    req.headers['Authorization'] = signup

s = Session()
req = Request('GET', url)
prepped = s.prepare_request(req)
authentication(prepped)

resp = s.send(prepped)

rawDescription: abstraction with python-requests

description: Abstraction with python-requests


code:
numpy.uint64(-1) >> 1
numpy.uint64(-1) >> numpy.uint64(1)

rawDescription: python bit shifting with numpy

description: Python bit shifting with numpy


code:
from itertools import product
def knight_moves(position):
    x, y = position
    moves = list(product([x-1, x+1],[y-1, y+1])) + list(product([x-2,x+2],[y-1,y+1]))
    moves = [(x,y) for x,y in moves if x >= 0 and y >= 0 and x < 8 and y < 8]
    return moves

rawDescription: How do I generate all of a knight's moves?

description: Generate all of a knight's moves


code:
from google.appengine.ext import db
from google.appengine.api.datastore_types import *

def dumpStr(obj):
    return "'" + obj + "'"

def dumps(obj):
    if isinstance(obj, str):
        return dumpStr(obj)
    elif obj == None:
        return None
    elif isinstance(obj, list):
        items = [];
        for item in obj:
            items.append(dumps(item))
        return '[' + ','.join(items) + ']'
    elif isinstance(obj, datetime.datetime):
        return "new Date('%s')" % obj.ctime()
    properties = [];
    for property in dir(obj):
        if property[0] != '_':
            value = obj.__getattribute__(property)
            valueClass = str(value.__class__)
            if not(('function' in valueClass) or ('built' in valueClass) or ('method' in valueClass)):
                value = dumps(value)
                if value != None:
                    properties.append("'" + property + "':" + value)
    if len(properties) == 0:
        return str(obj)
    else:
        return '{' + ','.join(properties) + '}'

rawDescription: How to serialize db.Model objects to json?

description: Serialize db.Model objects to json


code:
from django.db.models import Case, When, Value, IntegerField
q = (
    Product.objects
           .filter(...)
           .annotate(image_count=Count('images'))
           .annotate(
               have_images=Case(
                   When(image_count__gt=0,
                        then=Value(1)),
                   default=Value(0),
                   output_field=IntegerField()))
           .order_by('-have_images')
)

rawDescription: Django query annotation with boolean field


code:
class MCClient(object):

    _mc_client = None
    _last_refresh = time.time()
    _refresh_client_in = 3600  # seconds, 1 hour
    _servers = []

    @staticmethod
    def client():
        if MCClient._mc_client is None or MCClient.client_timeout():
            MCClient._mc_client = MCClient.new_memcached_client()
        return MCClient._mc_client

    @staticmethod
    def client_timeout():
        return (time.time() - MCClient._last_refresh) > MCClient._refresh_client_in

    @staticmethod
    def fetch_memcached_servers():
        MCClient._last_refresh = time.time()
        return list(MemcachedServer.objects.filter(active=True).values_list('ip', flat=True))

    @staticmethod
    def new_memcached_client():
        servers = MCClient.fetch_memcached_servers()
        if MCClient._mc_client is not None and set(MCClient._servers) == set(servers):
            # do not bother recreating a client, if the servers are still the same
            return MCClient._mc_client
        else:
            MCClient._servers = servers
            return pylibmc.Client(MCClient._servers, binary=True, behaviors={
                'tcp_nodelay': True,
                'ketama': True,
                'no_block': True,
                'num_replicas': min(len(MCClient._servers) - 1, 4),  # if a server goes down we don't loose cache
                'remove_failed': 3,
                'retry_timeout': 1,
                'dead_timeout': 60
            })

rawDescription: Dynamically add server to memcached

description: Dynamically add server to memcached


code:
import matplotlib.pyplot as plt
f = plt.figure(figsize=(15,5))
ax = plt.gca()
ar_month_mean.plot(ax=ax, figsize=(15,5))
hist_month.plot(ax=ax, kind='bar', figsize=(15,5))

rawDescription: how to plot histogram and time series in python

description: Plot histogram and time series in python


code:
from math import log
[log(y,10) for y in x]

rawDescription: How to take the log of an array

description: Take the log of an array


code: print(dict(zip('abc', range(3))))

rawDescription: Python Dictionary or JSON

description: Python Dictionary or JSON


code: myarray.flat[-1] = 1

rawDescription: Last element of an multidimensional matrix


code: [np.random.uniform(1.5, 12.4), np.random.uniform(0, 5), ...]

rawDescription: How to create a random array in a certain range

description: Create a random array in a certain range


code:
class DiferencialItemInline(admin.TabularInline):
    model = DiferencialItem

class DiferencialAdmin(admin.ModelAdmin):
    inlines = [DiferencialItemInline]

rawDescription: How to make Django admin shows OneToMany instead of ForeignKey

description: Make Django admin shows OneToMany instead of ForeignKey


code:
import numpy as np
from numpy.lib.stride_tricks import as_strided

# test data
N = 1000
A = np.random.rand(N, N)*10
mask = np.random.choice([True, False], size=(N, N))

def filter_loop(A, mask):
    kernel = np.array([[1,1,1],[1,0,1],[1,1,1]], bool)
    A = A.copy()
    A[mask] = np.nan
    N = A.shape[0] - 2  # assuming square matrix
    out = np.empty((N, N))
    for i in xrange(N):
        for j in xrange(N):
            out[i,j] = np.nanmean(A[i:i+3, j:j+3][kernel])
    return out

def filter_broadcast(A, mask):
    A = A.copy()
    A[mask] = np.nan
    N = A.shape[0] - 2
    B = as_strided(A, (N, N, 3, 3), A.strides+A.strides)
    B = B.copy().reshape((N, N, 3*3))
    B[:,:,4] = np.nan
    return np.nanmean(B, axis=2)

rawDescription: python/numpy fastest method for 2d kernel rank filtering on masked arrays (and/or selective ranking)

description: Python/numpy fastest method for 2d kernel rank filtering on masked arrays (and/or selective ranking)


code:
from itertools import izip, cycle

def listplace(in_path):
    with open(in_path, 'wb') as file_obj:
        writer = csv.writer(file_obj)

        for row in izip(info_source, cycle([13243, 3452345, 234234])):
            writer.writerow(row)

rawDescription: How to write the items in a list down a specific column

description: Write the items in a list down a specific column


code:
a = ["Spears", "Adele", "NDubz", "Nicole", "Cristina"]
b = [1, 2, 3, 4, 5]

combined = zip(a, b)
random.shuffle(combined)

a[:], b[:] = zip(*combined)

rawDescription: randomizing two lists and maintaining order in python

description: Randomizing two lists and maintaining order in python


code:
arr = np.arange(10)
indices = [2, 3, 9]
mask = np.zeros(arr.size, dtype=bool)
mask[indices] = True
a = np.ma.array(arr, mask=mask)
np.max(a)

rawDescription: find maximum value in array with excluded indices

description: Find maximum value in array with excluded indices


code:
A = 2
B = 5
C = 6
mylist = [1,2,3,4,5,6,7,8]
mylist[A:B+1] = [i+C for i in mylist[A:B+1]]
mylist

rawDescription: Add integers to specific items in a list in python?


code:
class MasterService(models.Model):
    master = models.ForeignKey(Master)
    service = models.ForeignKey(Service)
    price = models.PositiveIntegerField(blank=True)

    class Meta:
        unique_together = ('master', 'service')

rawDescription: What's the best way to create models for this situation in django?


code:
mydict =   {
            "name" : "myname",
            "value" : 0,
            "level" : [ {
                "name" : "myname",
                "value" : 1,
                "level" : [ {
                    "name" : "something",
                    "value" : 2,
                    "level" : [ {
                        "name" : "something",
                        "value" : 3,
                        "level" : [ {
                            "name" : "Phy",
                            "value" : 4,
                            "something_retrive" : [
                                {
                                    "mysupername" : "retrive",
                                    "someID" : "blahblah"
                                }, {
                                    "something_retrive" : [ {
                                        "mysupername" : "retrive",
                                        "someID" : "blahblah",
                                        "randomdata" : [
                                            {
                                                "data1":"val1"
                                            }, {
                                                "name" : "some",
                                                "size" : 3,
                                                "type" : "float",
                                            }
                                        ]
                                    } ]
                                }
                            ]
                        } ]
                    } ]
                } ]
            }]
        }

import collections

def findpaths(container):
    def recurse(container, prefix):
        if isinstance(container, list):
            container = enumerate(container)
        else:
            container = container.items()
        for key, value in container:
            keys[key].append(prefix)
            fullkey = prefix + (key,)
            if isinstance(value, (list, dict)):
                recurse(value, fullkey)
            else:
                values[value].append(fullkey)
    keys = collections.defaultdict(list)
    values = collections.defaultdict(list)
    recurse(container, ())
    return keys, values

def retrievebypath(container, keys):
    for key in keys:
        container = container[key]
    return container

keys, values = findpaths(mydict)

print("\nBy key:\n")
for key, value in sorted(keys.items(), key=str):
    print(key, sorted(value))

print("\nBy value:\n")
for key, value in sorted(values.items(), key=str):
    print(key, sorted(value))

print("\nRetrieving container which has second appearance of mysupername\n")
print(retrievebypath(mydict, keys["mysupername"][1]))

rawDescription: How to parse JSON file in python level by level and search perticular ID based on keys available in that level?

description: Parse JSON file in python level by level and search perticular ID based on keys available in that level


code:
def main():
    players = {}
    while True: # loop forever (until a break)
        choice = input("what do you want to do (1-4)")
        if choice == "1":
            add_score(players)
        elif choice == "2":
            return_players_score(players)
        #...
        elif choice == "4":
            break # break out of the loop to quit
        else:
            print("I didn't understand that.")

rawDescription: Doing a sort of a loop while avoiding a certain prerequisite (beginner/python)


code:
from django.forms.extras.widgets import SelectDateWidget

date = forms.DateField(widget = SelectDateWidget(), label="Date")

rawDescription: Is it possible to have a datepicker without Jquery UI?


code:
get_ipython().magic('%history -l 1 -t -f history.txt /')
with open('history.txt', 'r') as history:
    lastinput = history.readline()
    with open('ilog_'+str(today)+'.py', 'a') as log:
        log.write(lastinput)
os.remove('history.txt')

rawDescription: Create Ipython magic command for saving last console input to file


code:
from ilogue.fexpect import expect, expecting, run

def sample():

    private_key = "password"
    hostname = "ubuntu"
    output_dir = '/etc/ssl/' + hostname
    prompts = []
    prompts += expect('Enter pass phrase for private.key:',private_key)
    prompts += expect('Verifying - Enter pass phrase for private.key:private_key',private_key)
    prompts += expect('Enter pass phrase for %s/server.key:' % output_dir, private_key)
    prompts += expect('Country Name \(2 letter code\) \[AU\]:','AU')
    prompts += expect('State or Province Name \(full name\) \[Some-State\]:','State')
    prompts += expect('Locality Name \(eg, city\) \[\]:','City')
    prompts += expect('Organization Name \(eg, company\) \[Internet Widgits Pty Ltd\]:','Company')
    prompts += expect('Organizational Unit Name \(eg, section\) \[\]:','Section')
    prompts += expect('Common Name \(e.g. server FQDN or YOUR name\) \[\]:','FQDN')
    prompts += expect('Email Address \[\]:','email@foo.com')
    prompts += expect('A challenge password \[\]:','challenge_password')
    prompts += expect('An optional company name \[\]:','optional_company')

    with expecting(prompts):
        run('openssl genrsa -des3 -out %s/server.key 2048' % output_dir)
        run('openssl req -new -key %s/server.key -out %s/server.csr' % (output_dir, output_dir))

# fab sample -H localhost

rawDescription: Automate SSL creation in Fabric (Python)


code:
forward_btn = self.FindWindowById(wx.ID_FORWARD)
forward_btn.Disable()

rawDescription: Disable the 'Next' button until condition is met on single page of wx.WizardPageSimple


rawDescription: What is wrong with this lambda function? Pandas and Python dataframe


code:
stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]

chooseThese = [1,0,1,1,0]

# use enumerate (two variants)
new = [s for index, s in enumerate(stuff) if chooseThese[index] == 1]
print(new)
new = [stuff[index] for index, choose in enumerate(chooseThese) if choose == 1]
print(new)

# use zip
new = [s for choose, s in zip(chooseThese, stuff) if choose == 1]
print(new)

# use indexed chooser-variable
chooseThese = [0,2,3]
new = [stuff[index] for index in chooseThese]
print(new)

rawDescription: Python: copying chosen rows form list to another


code:
import types
def copy_func(f, name=None):
    return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
        f.func_defaults, f.func_closure)

def A():
    """A"""
    pass
B = copy_func(A, "B")
B.__doc__ = """B"""

rawDescription: How can I make a deepcopy of a function in Python?

description: Make a deepcopy of a function in Python


code:
with open(sys.argv[3], "r") as f:
    graph = ast.literal_eval(f.read())
# If you don't trust your users, check that graph is indeed a dict
# and that it has the right structure

rawDescription: Python: Importing a graph

description: Python: Importing a graph


code:
from mock import Mock

def test_bar():
    mock = Mock()
    system_under_test = MyModelClass(mock)
    system_under_test.bar()
    mock.foo.assert_called_once_with()

rawDescription: How to check behavior in py.test fixtures?

description: Check behavior in py.test fixtures


code:
process = subprocess.Popen(
    ["openssl", "rsa", "-in", pathFile, "-out", "id_rsa.out", "-passin", "stdin"],
    stdin = subprocess.PIPE,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
    shell=False
)
process.communicate("passphrase\n")

rawDescription: python subprocess with openssl

description: Python subprocess with openssl


code: any(str(i) in var for i in range(10))

rawDescription: How to make boolean expressions shorter ? or or or or or

description: Make boolean expressions shorter ? or or or or or


code:
import datetime
today = datetime.datetime.today()
today
today + datetime.timedelta(days=1)

rawDescription: how to convert a timedelta object into a datetime object

description: Convert a timedelta object into a datetime object


code:
from django.core.exceptions import ObjectDoesNotExist

from rest_framework.permissions import BasePermission, SAFE_METHODS

from .models import Flight

class FlightPermission(BasePermission):

    def has_permission(self, request, view):
        if request.method in SAFE_METHODS:
            return True

        try:
            flight = Flight.objects.get(pk=view.kwargs['parent_lookup_flight'])
        except ObjectDoesNotExist:
            return False

        return request.user.has_perm('flights.change_flight', flight)

rawDescription: Check permissions on a related object in Django REST Framework


code:
type(o)
type(o.copy())
o.copy()

rawDescription: How can I convert a TypedObject to a nested dictionary in Python?

description: Convert a TypedObject to a nested dictionary in Python


code:
import wx
import re, os, sys
from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin

class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin):
    def __init__(self, parent):
        wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
        CheckListCtrlMixin.__init__(self)
        ListCtrlAutoWidthMixin.__init__(self)

class QueueDialog(wx.Dialog):

    def __init__(self, parent, title):
        super(QueueDialog, self).__init__(parent=parent,
            title=title, size=(400, 500))

        panel = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        sb = wx.StaticBox(panel, label='Queue')
        sbs = wx.StaticBoxSizer(sb, orient=wx.VERTICAL)

        hbox3 = wx.BoxSizer(wx.VERTICAL)
        listB = CheckListCtrl(panel)
        listB.InsertColumn(0, "Test", width=100)
        listB.InsertColumn(1, "Status", wx.LIST_FORMAT_RIGHT)
        hbox3.Add(listB, 1, wx.EXPAND)

        dalist = ["heh", "ha", "hello"]
        for name in dalist[0:3]:
            index = listB.InsertStringItem(sys.maxint, name[0:-1])

        sbs.Add(hbox3, proportion=1,flag=wx.EXPAND|wx.ALL)
        panel.SetSizer(sbs)

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        okButton = wx.Button(self, label='OK')
        closeButton = wx.Button(self, label='Cancel')
        hbox2.Add(okButton)
        hbox2.Add(closeButton, flag=wx.LEFT, border=5)
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(panel, proportion=1, flag=wx.EXPAND|wx.ALL, border=10)
        vbox.Add(hbox2, flag= wx.ALIGN_CENTER|wx.BOTTOM, border=10)

        self.SetSizer(vbox)

    def OnClose(self, e):
        self.Destroy()

class window(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(600, 400))

        e = QueueDialog(None, title='Queue')
        e.ShowModal()
        e.Destroy()

        self.Centre()
        self.Show(True)

app = wx.App(0)
window(None, -1, 'e')
app.MainLoop()

rawDescription: wXPython: Unable to get widget to enlarge/expand in size

description: WXPython: Unable to get widget to enlarge/expand in size


code: all_td = filter(lambda x: x.attrs == {}, all_td)

rawDescription: find tags except those with attributes: BeautifulSoup

description: Find tags except those with attributes: BeautifulSoup


code:
combos = combinations_with_replacement(a, 4)
product_strings = ['*'.join(c) for c in combos]
products = [eval(s, globals(), values) for s in product_strings]

rawDescription: Cartesian products of lists without duplicates


code:
import re
re.sub(pattern, '', s)

rawDescription: Python - Use a Regex to Filter Data

description: Python - Use a Regex to Filter Data


code:
import numpy as np
x = np.random.random(1000)
A = np.subtract.outer(x, x)
A = np.abs(A)
w, v = np.linalg.eigh(A)

rawDescription: Performance Problems, Clustering Using Affinity Matrix, Eigenvalues


code: foo = SomeClass('hello', rfI=10)

rawDescription: Python: passing arguments to __init__

description: Python: passing arguments to __init__


code:
lobbies = Lobby.all().fetch(10)
keys = [lobby.key() for lobby in lobbies]
q = aUser.gql('WHERE lobby IN :1', keys)
users = q.fetch(1000)

rawDescription: AppEngine Python getting all references

description: AppEngine Python getting all references


code:
HOUSE_X = ...
PARENT_X = ...
CHILD_X = ...
START_Y = ...
SEP_Y = ...

y = START_Y;
houses = House.objects.all()
for house in houses:
    p.drawString(HOUSE_X, y, house.address);
    y += SEP_Y
    parents = Parent.objects.filter(house=house)
    for parent in parents:
        p.drawString(PARENT_X, y, parent.name);
        y += SEP_Y
        children = Child.objects.filter(parent=parent)
        for child in children:
            p.drawString(CHILD_X, y, child.name);
            y += SEP_Y

rawDescription: django struggling with the basics reportlab

description: Django struggling with the basics reportlab


code: username = TextField('Username', [validators.Regexp(r'^[\w.@+-]+$'), validators.Length(min=4, max=25)])

rawDescription: python flask app validate text field - allow no space

description: Python flask app validate text field - allow no space


code:
def VoteCountView(request, pk):
    ques = Question.objects.get(id=pk)
    cpk = ques.category.id
    valid_user = ques.user.username

    if request.user.is_authenticated():
        if request.user.is_general_user:
            if request.user.username == valid_user:
                messages.warning(request, "You cannot vote your own question")
                return redirect("question-detail", pk, cpk)
            elif VoteCount.objects.filter(user=request.user, title=ques).exists():
                messages.warning(request,"You cannot vote twice")
                return redirect("question-detail", pk, cpk)
            else:
                ques.vote +=1
                ques.save()
                v=Votecount(title=ques, user=request.user)
                v.save()
        else:
            messages.warning(request,"You are not allowed to vote a question")
            return redirect("question-detail", pk, cpk)
    else:
        messages.warning(request, "You must login/sign up to vote.")
        return redirect("question-detail", pk, cpk)

rawDescription: django filter by current user to vote

description: Django filter by current user to vote


code: items = [str(o) for o in items]

rawDescription: Python change UUID object to string representation list