code:
import ctypes

LONG = ctypes.c_long
DWORD = ctypes.c_ulong
ULONG_PTR = ctypes.POINTER(DWORD)
WORD = ctypes.c_ushort

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (('dx', LONG),
                ('dy', LONG),
                ('mouseData', DWORD),
                ('dwFlags', DWORD),
                ('time', DWORD),
                ('dwExtraInfo', ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (('wVk', WORD),
                ('wScan', WORD),
                ('dwFlags', DWORD),
                ('time', DWORD),
                ('dwExtraInfo', ULONG_PTR))

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (('uMsg', DWORD),
                ('wParamL', WORD),
                ('wParamH', WORD))

class _INPUTunion(ctypes.Union):
    _fields_ = (('mi', MOUSEINPUT),
                ('ki', KEYBDINPUT),
                ('hi', HARDWAREINPUT))

class INPUT(ctypes.Structure):
    _fields_ = (('type', DWORD),
                ('union', _INPUTunion))

def SendInput(*inputs):
    nInputs = len(inputs)
    LPINPUT = INPUT * nInputs
    pInputs = LPINPUT(*inputs)
    cbSize = ctypes.c_int(ctypes.sizeof(INPUT))
    return ctypes.windll.user32.SendInput(nInputs, pInputs, cbSize)

INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARD = 2

def Input(structure):
    if isinstance(structure, MOUSEINPUT):
        return INPUT(INPUT_MOUSE, _INPUTunion(mi=structure))
    if isinstance(structure, KEYBDINPUT):
        return INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure))
    if isinstance(structure, HARDWAREINPUT):
        return INPUT(INPUT_HARDWARE, _INPUTunion(hi=structure))
    raise TypeError('Cannot create INPUT structure!')

WHEEL_DELTA = 120
XBUTTON1 = 0x0001
XBUTTON2 = 0x0002
MOUSEEVENTF_ABSOLUTE = 0x8000
MOUSEEVENTF_HWHEEL = 0x01000
MOUSEEVENTF_MOVE = 0x0001
MOUSEEVENTF_MOVE_NOCOALESCE = 0x2000
MOUSEEVENTF_LEFTDOWN = 0x0002
MOUSEEVENTF_LEFTUP = 0x0004
MOUSEEVENTF_RIGHTDOWN = 0x0008
MOUSEEVENTF_RIGHTUP = 0x0010
MOUSEEVENTF_MIDDLEDOWN = 0x0020
MOUSEEVENTF_MIDDLEUP = 0x0040
MOUSEEVENTF_VIRTUALDESK = 0x4000
MOUSEEVENTF_WHEEL = 0x0800
MOUSEEVENTF_XDOWN = 0x0080
MOUSEEVENTF_XUP = 0x0100

def MouseInput(flags, x, y, data):
    return MOUSEINPUT(x, y, data, flags, 0, None)

VK_LBUTTON = 0x01               # Left mouse button
VK_RBUTTON = 0x02               # Right mouse button
VK_CANCEL = 0x03                # Control-break processing
VK_MBUTTON = 0x04               # Middle mouse button (three-button mouse)
VK_XBUTTON1 = 0x05              # X1 mouse button
VK_XBUTTON2 = 0x06              # X2 mouse button
VK_BACK = 0x08                  # BACKSPACE key
VK_TAB = 0x09                   # TAB key
VK_CLEAR = 0x0C                 # CLEAR key
VK_RETURN = 0x0D                # ENTER key
VK_SHIFT = 0x10                 # SHIFT key
VK_CONTROL = 0x11               # CTRL key
VK_MENU = 0x12                  # ALT key
VK_PAUSE = 0x13                 # PAUSE key
VK_CAPITAL = 0x14               # CAPS LOCK key
VK_KANA = 0x15                  # IME Kana mode
VK_HANGUL = 0x15                # IME Hangul mode
VK_JUNJA = 0x17                 # IME Junja mode
VK_FINAL = 0x18                 # IME final mode
VK_HANJA = 0x19                 # IME Hanja mode
VK_KANJI = 0x19                 # IME Kanji mode
VK_ESCAPE = 0x1B                # ESC key
VK_CONVERT = 0x1C               # IME convert
VK_NONCONVERT = 0x1D            # IME nonconvert
VK_ACCEPT = 0x1E                # IME accept
VK_MODECHANGE = 0x1F            # IME mode change request
VK_SPACE = 0x20                 # SPACEBAR
VK_PRIOR = 0x21                 # PAGE UP key
VK_NEXT = 0x22                  # PAGE DOWN key
VK_END = 0x23                   # END key
VK_HOME = 0x24                  # HOME key
VK_LEFT = 0x25                  # LEFT ARROW key
VK_UP = 0x26                    # UP ARROW key
VK_RIGHT = 0x27                 # RIGHT ARROW key
VK_DOWN = 0x28                  # DOWN ARROW key
VK_SELECT = 0x29                # SELECT key
VK_PRINT = 0x2A                 # PRINT key
VK_EXECUTE = 0x2B               # EXECUTE key
VK_SNAPSHOT = 0x2C              # PRINT SCREEN key
VK_INSERT = 0x2D                # INS key
VK_DELETE = 0x2E                # DEL key
VK_HELP = 0x2F                  # HELP key
VK_LWIN = 0x5B                  # Left Windows key (Natural keyboard)
VK_RWIN = 0x5C                  # Right Windows key (Natural keyboard)
VK_APPS = 0x5D                  # Applications key (Natural keyboard)
VK_SLEEP = 0x5F                 # Computer Sleep key
VK_NUMPAD0 = 0x60               # Numeric keypad 0 key
VK_NUMPAD1 = 0x61               # Numeric keypad 1 key
VK_NUMPAD2 = 0x62               # Numeric keypad 2 key
VK_NUMPAD3 = 0x63               # Numeric keypad 3 key
VK_NUMPAD4 = 0x64               # Numeric keypad 4 key
VK_NUMPAD5 = 0x65               # Numeric keypad 5 key
VK_NUMPAD6 = 0x66               # Numeric keypad 6 key
VK_NUMPAD7 = 0x67               # Numeric keypad 7 key
VK_NUMPAD8 = 0x68               # Numeric keypad 8 key
VK_NUMPAD9 = 0x69               # Numeric keypad 9 key
VK_MULTIPLY = 0x6A              # Multiply key
VK_ADD = 0x6B                   # Add key
VK_SEPARATOR = 0x6C             # Separator key
VK_SUBTRACT = 0x6D              # Subtract key
VK_DECIMAL = 0x6E               # Decimal key
VK_DIVIDE = 0x6F                # Divide key
VK_F1 = 0x70                    # F1 key
VK_F2 = 0x71                    # F2 key
VK_F3 = 0x72                    # F3 key
VK_F4 = 0x73                    # F4 key
VK_F5 = 0x74                    # F5 key
VK_F6 = 0x75                    # F6 key
VK_F7 = 0x76                    # F7 key
VK_F8 = 0x77                    # F8 key
VK_F9 = 0x78                    # F9 key
VK_F10 = 0x79                   # F10 key
VK_F11 = 0x7A                   # F11 key
VK_F12 = 0x7B                   # F12 key
VK_F13 = 0x7C                   # F13 key
VK_F14 = 0x7D                   # F14 key
VK_F15 = 0x7E                   # F15 key
VK_F16 = 0x7F                   # F16 key
VK_F17 = 0x80                   # F17 key
VK_F18 = 0x81                   # F18 key
VK_F19 = 0x82                   # F19 key
VK_F20 = 0x83                   # F20 key
VK_F21 = 0x84                   # F21 key
VK_F22 = 0x85                   # F22 key
VK_F23 = 0x86                   # F23 key
VK_F24 = 0x87                   # F24 key
VK_NUMLOCK = 0x90               # NUM LOCK key
VK_SCROLL = 0x91                # SCROLL LOCK key
VK_LSHIFT = 0xA0                # Left SHIFT key
VK_RSHIFT = 0xA1                # Right SHIFT key
VK_LCONTROL = 0xA2              # Left CONTROL key
VK_RCONTROL = 0xA3              # Right CONTROL key
VK_LMENU = 0xA4                 # Left MENU key
VK_RMENU = 0xA5                 # Right MENU key
VK_BROWSER_BACK = 0xA6          # Browser Back key
VK_BROWSER_FORWARD = 0xA7       # Browser Forward key
VK_BROWSER_REFRESH = 0xA8       # Browser Refresh key
VK_BROWSER_STOP = 0xA9          # Browser Stop key
VK_BROWSER_SEARCH = 0xAA        # Browser Search key
VK_BROWSER_FAVORITES = 0xAB     # Browser Favorites key
VK_BROWSER_HOME = 0xAC          # Browser Start and Home key
VK_VOLUME_MUTE = 0xAD           # Volume Mute key
VK_VOLUME_DOWN = 0xAE           # Volume Down key
VK_VOLUME_UP = 0xAF             # Volume Up key
VK_MEDIA_NEXT_TRACK = 0xB0      # Next Track key
VK_MEDIA_PREV_TRACK = 0xB1      # Previous Track key
VK_MEDIA_STOP = 0xB2            # Stop Media key
VK_MEDIA_PLAY_PAUSE = 0xB3      # Play/Pause Media key
VK_LAUNCH_MAIL = 0xB4           # Start Mail key
VK_LAUNCH_MEDIA_SELECT = 0xB5   # Select Media key
VK_LAUNCH_APP1 = 0xB6           # Start Application 1 key
VK_LAUNCH_APP2 = 0xB7           # Start Application 2 key
VK_OEM_1 = 0xBA                 # Used for miscellaneous characters; it can vary by keyboard.
                                # For the US standard keyboard, the ';:' key
VK_OEM_PLUS = 0xBB              # For any country/region, the '+' key
VK_OEM_COMMA = 0xBC             # For any country/region, the ',' key
VK_OEM_MINUS = 0xBD             # For any country/region, the '-' key
VK_OEM_PERIOD = 0xBE            # For any country/region, the '.' key
VK_OEM_2 = 0xBF                 # Used for miscellaneous characters; it can vary by keyboard.
                                # For the US standard keyboard, the '/?' key
VK_OEM_3 = 0xC0                 # Used for miscellaneous characters; it can vary by keyboard.
                                # For the US standard keyboard, the '`~' key
VK_OEM_4 = 0xDB                 # Used for miscellaneous characters; it can vary by keyboard.
                                # For the US standard keyboard, the '[{' key
VK_OEM_5 = 0xDC                 # Used for miscellaneous characters; it can vary by keyboard.
                                # For the US standard keyboard, the '\|' key
VK_OEM_6 = 0xDD                 # Used for miscellaneous characters; it can vary by keyboard.
                                # For the US standard keyboard, the ']}' key
VK_OEM_7 = 0xDE                 # Used for miscellaneous characters; it can vary by keyboard.
                                # For the US standard keyboard, the 'single-quote/double-quote' key
VK_OEM_8 = 0xDF                 # Used for miscellaneous characters; it can vary by keyboard.
VK_OEM_102 = 0xE2               # Either the angle bracket key or the backslash key on the RT 102-key keyboard
VK_PROCESSKEY = 0xE5            # IME PROCESS key
VK_PACKET = 0xE7                # Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP
VK_ATTN = 0xF6                  # Attn key
VK_CRSEL = 0xF7                 # CrSel key
VK_EXSEL = 0xF8                 # ExSel key
VK_EREOF = 0xF9                 # Erase EOF key
VK_PLAY = 0xFA                  # Play key
VK_ZOOM = 0xFB                  # Zoom key
VK_PA1 = 0xFD                   # PA1 key
VK_OEM_CLEAR = 0xFE             # Clear key

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_SCANCODE = 0x0008
KEYEVENTF_UNICODE = 0x0004

KEY_0 = 0x30
KEY_1 = 0x31
KEY_2 = 0x32
KEY_3 = 0x33
KEY_4 = 0x34
KEY_5 = 0x35
KEY_6 = 0x36
KEY_7 = 0x37
KEY_8 = 0x38
KEY_9 = 0x39
KEY_A = 0x41
KEY_B = 0x42
KEY_C = 0x43
KEY_D = 0x44
KEY_E = 0x45
KEY_F = 0x46
KEY_G = 0x47
KEY_H = 0x48
KEY_I = 0x49
KEY_J = 0x4A
KEY_K = 0x4B
KEY_L = 0x4C
KEY_M = 0x4D
KEY_N = 0x4E
KEY_O = 0x4F
KEY_P = 0x50
KEY_Q = 0x51
KEY_R = 0x52
KEY_S = 0x53
KEY_T = 0x54
KEY_U = 0x55
KEY_V = 0x56
KEY_W = 0x57
KEY_X = 0x58
KEY_Y = 0x59
KEY_Z = 0x5A

def KeybdInput(code, flags):
    return KEYBDINPUT(code, code, flags, 0, None)

def HardwareInput(message, parameter):
    return HARDWAREINPUT(message & 0xFFFFFFFF,
                         parameter & 0xFFFF,
                         parameter >> 16 & 0xFFFF)

def Mouse(flags, x=0, y=0, data=0):
    return Input(MouseInput(flags, x, y, data))

def Keyboard(code, flags=0):
    return Input(KeybdInput(code, flags))

def Hardware(message, parameter=0):
    return Input(HardwareInput(message, parameter))

################################################################################

import string

UPPER = frozenset('~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?')
LOWER = frozenset("`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./")
ORDER = string.ascii_letters + string.digits + ' \b\r\t'
ALTER = dict(zip('!@#$%^&*()', '1234567890'))
OTHER = {'`': VK_OEM_3,
         '~': VK_OEM_3,
         '-': VK_OEM_MINUS,
         '_': VK_OEM_MINUS,
         '=': VK_OEM_PLUS,
         '+': VK_OEM_PLUS,
         '[': VK_OEM_4,
         '{': VK_OEM_4,
         ']': VK_OEM_6,
         '}': VK_OEM_6,
         '\\': VK_OEM_5,
         '|': VK_OEM_5,
         ';': VK_OEM_1,
         ':': VK_OEM_1,
         "'": VK_OEM_7,
         '"': VK_OEM_7,
         ',': VK_OEM_COMMA,
         '<': VK_OEM_COMMA,
         '.': VK_OEM_PERIOD,
         '>': VK_OEM_PERIOD,
         '/': VK_OEM_2,
         '?': VK_OEM_2}

def keyboard_stream(string):
    mode = False
    for character in string.replace('\r\n', '\r').replace('\n', '\r'):
        if mode and character in LOWER or not mode and character in UPPER:
            yield Keyboard(VK_SHIFT, mode and KEYEVENTF_KEYUP)
            mode = not mode
        character = ALTER.get(character, character)
        if character in ORDER:
            code = ord(character.upper())
        elif character in OTHER:
            code = OTHER[character]
        else:
            continue
            raise ValueError('String is not understood!')
        yield Keyboard(code)
        yield Keyboard(code, KEYEVENTF_KEYUP)
    if mode:
        yield Keyboard(VK_SHIFT, KEYEVENTF_KEYUP)

################################################################################

import time, sys

def main():
    time.sleep(5)
    for event in keyboard_stream('o2E^uXh#:SHn&HQ+t]YF'):
        SendInput(event)
        time.sleep(0.1)

##if __name__ == '__main__':
##    main()

def switch_program():
    SendInput(Keyboard(VK_MENU), Keyboard(VK_TAB))
    time.sleep(0.2)
    SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP),
              Keyboard(VK_MENU, KEYEVENTF_KEYUP))
    time.sleep(0.2)

def select_line():
    SendInput(Keyboard(VK_SHIFT, KEYEVENTF_EXTENDEDKEY),
              Keyboard(VK_END, KEYEVENTF_EXTENDEDKEY))
    time.sleep(0.2)
    SendInput(Keyboard(VK_SHIFT, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP),
              Keyboard(VK_END, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP))
    time.sleep(0.2)

def copy_line():
    SendInput(Keyboard(VK_CONTROL), Keyboard(KEY_C))
    time.sleep(0.2)
    SendInput(Keyboard(VK_CONTROL, KEYEVENTF_KEYUP),
              Keyboard(KEY_C, KEYEVENTF_KEYUP))
    time.sleep(0.2)

def next_line():
    SendInput(Keyboard(VK_HOME), Keyboard(VK_DOWN))
    time.sleep(0.2)
    SendInput(Keyboard(VK_HOME, KEYEVENTF_KEYUP),
              Keyboard(VK_DOWN, KEYEVENTF_KEYUP))
    time.sleep(0.2)

def prepare_text():
    # Open Text
    SendInput(Keyboard(KEY_M))
    time.sleep(0.2)
    SendInput(Keyboard(KEY_M, KEYEVENTF_KEYUP))
    time.sleep(0.2)
    # Goto Area
    SendInput(Keyboard(VK_TAB))
    time.sleep(0.2)
    SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP))
    time.sleep(0.2)
    # Paste Message
    SendInput(Keyboard(VK_CONTROL), Keyboard(KEY_V))
    time.sleep(0.2)
    SendInput(Keyboard(VK_CONTROL, KEYEVENTF_KEYUP),
              Keyboard(KEY_V, KEYEVENTF_KEYUP))
    time.sleep(0.2)
    # Goto Button
    SendInput(Keyboard(VK_TAB))
    time.sleep(0.2)
    SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP))
    time.sleep(0.2)

def send_one_message():
    select_line()
    copy_line()
    next_line()
    switch_program()
    prepare_text()
    # Send Message
    SendInput(Keyboard(VK_RETURN))
    time.sleep(0.2)
    SendInput(Keyboard(VK_RETURN, KEYEVENTF_KEYUP))
    time.sleep(10)
    switch_program()

def send_messages(total):
    time.sleep(10)
    for _ in range(total):
        send_one_message()

rawDescription: Python simulate keydown

description: Python simulate keydown


code:
import functools
def runoverridden(f):
    @functools.wraps(f)
    def wrapper(self, *args, **kw):
        if getattr(self, f.__name__).im_func != wrapper:
            return f(self, *args, **kw)
    return wrapper

class A(object):
    @runoverridden
    def run(self):
        print('Running in A')

class B(A):
    def run(self):
        super(B, self).run()
        print('Running in B')

class C(A):
    pass

b = B()
c = C()
b.run()
c.run()

rawDescription: Decorator design: executing a method only if it has been overridden


code:
command  = "drwxr-xr-x 4,096 2013/01/20 22:37:39 files".split()
filesize = command[1]
date = command[2]

rawDescription: Extract file size and the date when the file is created in Python/Django?


code:
import re, datetime
def get_seconds(text):
    splitted_input = filter(None, re.split('[, ]', text))
    assert len(splitted_input) % 2 == 0
    grouped_input = zip(*(iter(splitted_input),) * 2)
    # ⬆ This is tricky; see http://stackoverflow.com/questions/1624883/alternative-way-to-split-a-list-into-groups-of-n
    kwargs = {
        'year':0,
        'month':0,
        'day':0,
        'hour':0,
        'minute':0,
        'second':0,
        'microsecond':0,
    }
    for n, unit in grouped_input:
        n = int(n)
        if unit.startswith('y'):
            kwargs['year'] += n
        elif unit.startswith('mo'):
            kwargs['month'] += n
        elif unit.startswith('w'):
            kwargs['day'] += 7*n
        elif unit.startswith('d'):
            kwargs['day'] += n
        elif unit.startswith('h'):
            kwargs['hour'] += n
        elif unit.startswith('m'):
            kwargs['minute'] += n
        elif unit.startswith('s'):
            kwargs['second'] += n
        else:
            assert False, unit
    for k, v in kwargs:
        kwargs[k] += getattr(now, k)
    now = datetime.datetime.now()
    return (datetime.datetime(**kwargs) - now).total_seconds()

rawDescription: Natural time interval processing in Python


code:
for event, element in et.iterparse(f):
    if element.tag == 'interesting_part':
        # `element` is the complete <interesting_part> element, with children
        # process it
        break  # ends parsing.

rawDescription: Python ElementTree : partially parsing a large file


code:
import HTMLParser
h= HTMLParser.HTMLParser()
h.unescape(test_string)

rawDescription: python script to insert into MySQL database - special symbols - unicode : search and store

description: Python script to insert into MySQL database - special symbols - unicode : search and store


rawDescription: Deleting a record from database using Python


code:
from subprocess import Popen
commands = ['command1', 'command2']
procs = [ Popen(i) for i in command ]
for p in procs:
   p.wait()

rawDescription: How do I run multiple subprocesses in parallel and wait for them to finish in Python

description: Run multiple subprocesses in parallel and wait for them to finish in Python


code:
import numpy as np, pandas as pd
data = np.arange(1, 13)
s = pd.Series(data, pd.date_range(start='1/31/2007', periods=len(data), freq='M'))
s.resample('6M', how='sum', closed='left', loffset='-1M')

rawDescription: Using built-in pandas frequencies to simulate semiannual frequency


code:
from django.db.models import Q
from isbnlib import get_isbnlike, is_isbn10, is_isbn13, to_isbn10, to_isbn13

class Question_Admin(admin.ModelAdmin):
    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(Question_Admin, self).get_search_results(request, queryset, search_term)
        isbn = get_isbnlike(search_term, level='normal')
        if isbn:
            if is_isbn10(isbn[0]):
                converted = to_isbn13(isbn[0])
            else:
                converted = to_isbn10(isbn[0])
            queryset |= self.model.objects.filter(Q(isbn=isbn[0]) | Q(isbn=converted))
        return queryset, use_distinct

rawDescription: Implement custom function on Django search_fields


code:
with open("myfile.txt", "a") as file:
    file.write("0")

rawDescription: How can I change the data stored internally in my text file using Python?

description: Change the data stored internally in my text file using Python


code:
import pyHook
import pythoncom
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
hm = pyHook.HookManager()
def OnKeyboardEvent(event):
    if event.KeyID == 48:
        #cheat set 1
        shell.SendKeys("chttychttybangbang")
    if event.KeyID == 49:
        #cheat set 2
        shell.SendKeys("hesoyamuzumymwfullclip")
    if event.KeyID == 50:
        #cheat set 3
        shell.SendKeys("hesoyaprofessionalskitfullclip")
    if event.KeyID == 51:
        #cheat set 4
        shell.SendKeys("hesoyalxgiwylfullclip")
    if event.KeyID == 52:
        #cheat set 5
        shell.SendKeys("zeiivgylteiczflyingfisheveryoneisrichspeedfreak")
    if event.KeyID == 53:
        #cheat set 6
        shell.SendKeys("aiwprton")
    if event.KeyID == 54:
        #cheat set 7
        shell.SendKeys("oldspeeddemon")
    if event.KeyID == 55:
        #cheat set 8
        shell.SendKeys("itsallbull")
    if event.KeyID == 56:
        #cheat set 9
        shell.SendKeys("monstermash")
    if event.KeyID == 57:
        #cheat set 10
        shell.SendKeys("jumpjetkgggdkpaiypwzqpohdudeflyingtostunt")
    # return True to pass the event to other handlers
    return True
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

rawDescription: keyboard emulation with windows and python

description: Keyboard emulation with windows and python


code:
classifier = OneVsRestClassifier(MyClassifier(param1 = A, param2 = B))
classifier.fit(X_train, Y)
predicted = classifier.predict(X_test)

rawDescription: using OneVsRestClassifier from sklearn in Python to tune a customized binary classification into a multi-class classification

description: Using OneVsRestClassifier from sklearn in Python to tune a customized binary classification into a multi-class classification


code:
fig, ax = plt.subplots() # this is the only "plt" fxn you need 99% of the time
x = [2, 57]
y = [12, 112]
ax.plot(x, y, '-')
ax.set_yscale('log')
ax.set_xscale('log')

rawDescription: Python: LogLog plot combined with a linear plot


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

#array between 0 and 360 deg
#CAVEAT: it seems that is needed an array from -180 to 180, so is just a
#shift in the coordinates
RA = np.random.random(10000)*360-180
#array between -45 and 90 degrees
DEC= np.random.random(10000)*135-45

fig = plt.Figure((10, 5))
ax = fig.add_subplot(111,projection='mollweide')

ax.set_xlabel('RA')
ax.set_ylabel('DEC')
ax.set_xticklabels(np.arange(30,331,30))

hist,xedges,yedges = np.histogram2d(DEC,RA,bins=[60,40],range=[[-90,90],[-180,180]])

X,Y = np.meshgrid(np.radians(yedges),np.radians(xedges))

image = ax.pcolormesh(X,Y,hist)
ax.grid(True)
cb = fig.colorbar(image, orientation='horizontal')
canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
fig.canvas.print_figure("image4.png")

rawDescription: Curious (bad?) behavior creating all-sky projections with matplotlib


code:
#!/usr/bin/env python
#python server

import json
import threading
import time
import socket
from twitter import *
import re

#get thread lock ready
thread_lock = threading.Lock()

#set server variables
TCP_IP = '127.0.0.1'
TCP_PORT = 7001
BUFFER_SIZE  = 20

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()

#print connection address when someone connects
print ('Connection address:', addr)

#fill these in your app!
#twitter auth keys
OAUTH_TOKEN = ''
OAUTH_SECRET = ''
CONSUMER_KEY = ''
CONSUMER_SECRET = ''

t = Twitter(auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET))

auth = OAuth(OAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
stream = TwitterStream(auth = auth, secure = True)

#twitter functions
def pythonSearch():
    #lock thread to not interrupt search results
    thread_lock.acquire()

    print ('request newest tweets')

    #get 10 things from timeline
    x = t.statuses.home_timeline(count=10)

    for i in range(10):
        try:
            #get username and tweet
            userName = x[i]['entities']['user_mentions'][0]['screen_name']
            userTweet = x[i]['text']

            #print out values
            print('username: ', userName)
            print('tweet: ', userTweet)

            #send json back
            delivery = json.dumps({'type':'display','userName':userName,'userTweet':userTweet})
            conn.send(delivery.encode('utf-8'))
        except:
            #not a retweet
            print('not valid tweet')

    #unlock thread when finished
    thread_lock.release()

    return

def pythonStream():
    #open stream looking for search_term
    search_term = 'TESTING'
    tweet_iter = stream.statuses.filter(track = search_term)

    for tweet in tweet_iter:
        # check whether this is a valid tweet
        if tweet.get('text'):

            #get username and tweet
            userName = tweet["user"]["screen_name"]
            userTweet = tweet["text"]

            # now print our tweet
            print ('user: ', userName)
            print ('tweet: ', userTweet)

            #send json back
            delivery1 = json.dumps({'type':'showdown','userName':userName,'userTweet':userTweet})
            conn.send(delivery1.encode('utf-8'))

#start main loop
while 1:
    #listen for calls
    data = conn.recv(BUFFER_SIZE)
    data = data.decode('utf-8')

    #if someone calls search, do a search
    if data == 'SEARCH':
        threading.Thread(target = pythonSearch).start()

    if data == 'STREAM':
        threading.Thread(target = pythonStream).start()

conn.close()

rawDescription: Python Twitter Tool simultaneous search and stream


code:
tree = []
while len(numArr) > 1:
    numArr = [numArr[0] + numArr[1]] + numArr[2:]
    numArr = sorted(numArr)
    valHold = numArr[0] * 8
    tree.append(numArr)

indent = len(tree)
for row in tree[::-1]:
    print(" " * indent, row)
    indent -= 1

rawDescription: Printing tree levels in reverse

description: Printing tree levels in reverse


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get(url)

rawDescription: Searching for a Python API that allows to launch firefox


rawDescription: Shifting all rows in dask dataframe

description: Shifting all rows in dask dataframe


code:
def manhattan(x,y):
    'int,int==>nonetype'
    import random
    res=[]
    for i in range(x):
        res.append([])
    for i in res:
        for j in range(y):
            i.append(0)
    position=(x//2+1,y//2+1)
    z=position[0]
    v=position[1]

    while z!=-1 and z!=x and v!=-1 and v!=y:
        res[z][v] += 1
        direction=random.randrange(1,5)
        if direction==1:
            v+=1
        elif direction==2:
            z+=1
        elif direction==3:
            v-=1
        else:
            z-=1
    for i in res:
        print(i)

rawDescription: Manhattan grid directions with random walk


code:
def _another_register(self, func, subst=None, needcleanup=1):
    ...

def change_register(self):
    self.register = self._another_register

def restore_register(self):
    self.register = self._register

rawDescription: What's the point of this code pattern?

description: What's the point of this code pattern


code:
values = 'one', 'two', 'three'
A = type('A', (object,), {i: i + ' value' for i in values})
A.one
A.three

rawDescription: Dynamic class field creation before metaclass machinery


code:
import numpy as np
import matplotlib.pyplot as plt
import shapely.geometry as sg
from descartes.patch import PolygonPatch

# if I understood correctly you mainly need the difference d here
INNER_AMPLITUDE = 0.1
OUTER_AMPLITUDE = 0.2
d = OUTER_AMPLITUDE - INNER_AMPLITUDE

# fix seed, for reproducability
np.random.seed(11111)

# a function to produce a "random" polygon
def random_polygon():
    nr_p = np.random.randint(7,15)
    angle = np.sort(np.random.rand(nr_p)*2*np.pi)
    dist = 0.3*np.random.rand(nr_p) + 0.5
    return np.vstack((np.cos(angle)*dist, np.sin(angle)*dist)).T

# your input polygon
p = random_polygon()

# create a shapely ring object
ring1 = sg.LinearRing(p)
ring2 = ring1.parallel_offset(d, 'right', join_style=2, mitre_limit=10.)
ring3 = ring1.parallel_offset(2*d, 'right', join_style=2, mitre_limit=10.)

# revert the third ring. This is necessary to use it to procude a hole
ring3.coords = list(ring3.coords)[::-1]

# inner and outer polygon
inner_poly = sg.Polygon(ring1)
outer_poly = sg.Polygon(ring2, [ring3])

# create the figure
fig, ax = plt.subplots(1)

# convert them to matplotlib patches and add them to the axes
ax.add_patch(PolygonPatch(inner_poly, facecolor=(0,1,0,0.4),
    edgecolor=(0,1,0,1), linewidth=3))
ax.add_patch(PolygonPatch(outer_poly, facecolor=(1,0,0,0.4),
    edgecolor=(1,0,0,1), linewidth=3))

# cosmetics
ax.set_aspect(1)
plt.axis([-1.5, 1.5, -1.5, 1.5])
plt.grid()
plt.show()

rawDescription: Figure in a figure in a figure

description: Figure in a figure in a figure


code:
import codecs

def ent_replace(exc):
  if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)):
    s = []
    for c in exc.object[exc.start:exc.end]:
      s.append(u'&#x%4.4x;' % ord(c))
    return (''.join(s), exc.end)
  else:
    raise TypeError("can't handle %s" % exc.__name__)

codecs.register_error('ent_replace', ent_replace)

rawDescription: XML characters in python xml.dom

description: XML characters in python xml.dom


code:
from PyQt4.QtGui import *
from PyQt4.Qt import *
import sys

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.text = "Please enter some text"
        self.edit = QPlainTextEdit(self.text)
        layout.addWidget(self.edit)

        slider = QSlider(Qt.Horizontal)
        layout.addWidget(slider)
        slider.valueChanged.connect(self.change_value)

    def change_value(self, value):
        if value == 0:
            self.edit.setPlainText(self.text)
        elif value == 1:
            self.edit.setPlainText(self.text[::-1])
        elif value > 1:
            self.edit.setPlainText("Slider value is above 1, value: {0}".format(value))

app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())

rawDescription: How in pyqt change text in QPlainTextEdit() if slider's value is 1, and don't change if the value is 0?


code:
from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

rawDescription: Get IP address of visitors using Python + Flask


code:
import tkinter as tk
from tkinter import ttk

def step():
    BarVolVal_1.step(dir)
    mGui.after(50, step)

def change_dir():
    global dir
    dir *= -1
    mGui.after(2000, change_dir)

mGui = tk.Tk()
dir = 1

BarVolVal_1 = ttk.Progressbar(mGui, orient='horizontal', length=100, mode='determinate')
BarVolVal_1.pack()

step()
mGui.after(3000, change_dir)

mGui.mainloop()

rawDescription: python 3.x progressbar tkinter backwards?

description: Python 3.x progressbar tkinter backwards


code:
import codecs

def encalias(oldname, newname):
  old = codecs.lookup(oldname)
  new = codecs.CodecInfo(old.encode, old.decode,
                         streamreader=old.streamreader,
                         streamwriter=old.streamwriter,
                         incrementalencoder=old.incrementalencoder,
                         incrementaldecoder=old.incrementaldecoder,
                         name=newname)
  def searcher(aname):
    if aname == newname:
      return new
    else:
      return None
  codecs.register(searcher)

rawDescription: Adding encoding alias to python

description: Adding encoding alias to python


code:
import re
s = "bob sue jon richard harry"
r = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)')
[m.groupdict() for m in r.finditer(s)]

rawDescription: re.findall which returns a dict of named capturing groups?

description: Re.findall which returns a dict of named capturing groups


code:
import numpy as np
N = 100

mean1, mean2, std1, std2 = 1, 5, 2, 3
x0 = np.random.normal(loc=[mean1, mean2], scale=[std1, std2], size=(N, 2))

mean3, mean4, std3, std4 = 2, -2, 1, 0.1
x1 = np.random.normal(loc=[mean3, mean4], scale=[std3, std4], size=(N, 2))

rawDescription: Generate dataset for Binary Classification in k-NN using Python


code:
import Tkinter as tk
class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        # create a canvas to act as a scrollable container for
        # the widgets
        self.container = tk.Canvas(self)
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.container.yview)
        self.container.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.container.pack(side="left", fill="both", expand=True)

        # the frame will contain the grid of labels and values
        self.frame = tk.Frame(self)
        self.container.create_window(0,0, anchor="nw", window=self.frame)

        self.vars = []
        for i in range(1,301):
            self.vars.append(tk.StringVar(value="This is the value for item %s" % i))
            label = tk.Label(self.frame, text="Item %s:" % i, width=12, anchor="e")
            value = tk.Label(self.frame, textvariable=self.vars[-1], anchor="w")
            label.grid(row=i, column=0, sticky="e")
            value.grid(row=i, column=1, sticky="ew")

        # have the second column expand to take any extra width
        self.frame.grid_columnconfigure(1, weight=1)

        # Let the display draw itself, the configure the scroll region
        # so that the scrollbars are the proper height
        self.update_idletasks()
        self.container.configure(scrollregion=self.container.bbox("all"))

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

rawDescription: Tkinter Display varLabel and value cleanly


code:
import collections
print(collections.Counter([2, 3, 'a', 'wow', 3]))

rawDescription: How to initiate a dict from a array with count?

description: Initiate a dict from a array with count


code:
from PyQt4 import QtGui
# from mainwindow import Ui_MainWindow

class Login(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Login, self).__init__(parent)
        self.textName = QtGui.QLineEdit(self)
        self.textPass = QtGui.QLineEdit(self)
        self.buttonLogin = QtGui.QPushButton('Login', self)
        self.buttonLogin.clicked.connect(self.handleLogin)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.textName)
        layout.addWidget(self.textPass)
        layout.addWidget(self.buttonLogin)

    def handleLogin(self):
        if (self.textName.text() == 'foo' and
            self.textPass.text() == 'bar'):
            self.accept()
        else:
            QtGui.QMessageBox.warning(
                self, 'Error', 'Bad user or password')

class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        # self.ui = Ui_MainWindow()
        # self.ui.setupUi(self)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    login = Login()

    if login.exec_() == QtGui.QDialog.Accepted:
        window = Window()
        window.show()
        sys.exit(app.exec_())

rawDescription: Login dialog PyQt

description: Login dialog PyQt


code:
nicspec = vim.vm.device.VirtualDeviceSpec()
nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
nicspec.device = nic_type
nicspec.device.wakeOnLanEnabled = True
nicspec.device.deviceInfo = vim.Description()
nicspec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
nicspec.device.backing.network = self.get_obj(content, [vim.Network], net_name)
nicspec.device.backing.deviceName = net_name

nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nicspec.device.connectable.startConnected = True
nicspec.device.connectable.allowGuestControl = True

devices.append(nicspec)

vmconf = vim.vm.ConfigSpec(deviceChange=devices)

rawDescription: Add VM to VLAN through pyvmomi / vSphere


code:
@login_required
def process_form(request):
    form = ReviewForm(request.POST or None)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user_name = request.user
        obj.save()
        return redirect('home')
    return render(request, 'form.html', {'form': form})

rawDescription: Get current user in Django model from form


code:
import requests

links = ['link.pdf']
for link in links:
    book_name = link.split('/')[-1]
    with open(book_name, 'wb') as book:
        a = requests.get(link, stream=True)

        for block in a.iter_content(512):
            if not block:
                break

            book.write(block)

rawDescription: Downloading pdfs with python?

description: Downloading pdfs with python


code:
import requests
from multiprocessing import Pool

def process_html(url):
    url_response = requests.get(url)
    text = url_response.text
    print(text[:500])
    print('-' * 30)

urls = [
    'http://www.apple.com',
    'http://www.yahoo.com',
    'http://www.google.com',
    'http://www.apple.com',
    'http://www.yahoo.com',
    'http://www.google.com',
    'http://www.apple.com',
    'http://www.yahoo.com',
    'http://www.google.com',
]

with Pool(None) as p:  #None => uses cpu.count()
    p.map(process_html, urls)  #This blocks until all return values from process_html() have been collected.

rawDescription: Effectively requesting and processing multiple HTML files with Python


code:
gb = df.groupby('ZZ')
[gb.get_group(x) for x in gb.groups]

rawDescription: Split pandas dataframe based on groupby

description: Split pandas dataframe based on groupby


code:
UARFCNRSSI = []
x = None        # future "third element"; please choose a better name
for item in data["Sequences"]:
   if len(item) == 2:
       x = item[0]
   elif len(item) >= 22:
       UARFCNRSSI.append([item[0], item[1], x])

rawDescription: filtering lists of lists python, how to create final list?

description: Filtering lists of lists python, how to create final list


code:
os_list = ['osxx', 'centos', 'windowsx']
df.rename(columns=lambda x: x+'x' if x in os_list else x)

rawDescription: How can I change name of arbitrary columns in pandas df using lambda function?

description: Change name of arbitrary columns in pandas df using lambda function


code:
number_primes = 10
prime_list = [True]*number_primes

for i in range (2, number_primes):    #check from 2 upwards
  if prime_list[i]:                   #If not prime, don't need to bother about searching
    j = 2
    while j*i < number_primes:        # Filter out all factors of i (2...n * prime)
      prime_list[j*i] = False
      j+=1

rawDescription: My implementation of the Sieve of Eratosthenes is flawed?


code:
axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=10,
color='green')
axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=5,
color='black')

rawDescription: Can I give a border (outline) to a line in matplotlib plot function?

description: Give a border (outline) to a line in matplotlib plot function


code:
import setuptools.command.install_lib
_install_lib = setuptools.command.install_lib.install_lib
class install_lib(_install_lib):
    def finalize_options(self):
        _install_lib.finalize_options(self)
        self.install_dir = join(self.install_dir,'PKG_NAME-'+PKGVERSION)

rawDescription: Use setuptools to create an executable distribution of a package with --multi-version?


code:
import collections

aMap = collections.defaultdict(dict)

for row in csv.DictReader(csv1):
    aMap[row['id']] = row

for row in csv.DictReader(csv2):
    aMap[row['id']].update(row)

rawDescription: Python dictionary values merging based on specific key


code:
from __future__ import print_function
lambda: print(1)

rawDescription: Nullary lambda function

description: Nullary lambda function


rawDescription: Django: Grab a set of objects from ID list (and sort by timestamp)


code:
process = subprocess.Popen(shlex.split(command), stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
complete = False

while True:
  output = process.stdout.read(1)

  if output == '' and process.poll() != None:
    break

  if output != '':
    sys.stdout.write(output)
    sys.stdout.flush()

rawDescription: Needing Help Capturing STDOUT in real-time from pygtk GUI in python project


rawDescription: Pandas Plotting with Multi-Index

description: Pandas Plotting with Multi-Index


rawDescription: Extract first item of each sublist in python


code:
from __future__ import print_function
import os
import sys

def some_function_with_cached_sys_stdout(stdout=sys.stdout):
    print('cached stdout', file=stdout)

with stdout_redirected(to=os.devnull), merged_stderr_stdout():
    print('stdout goes to devnull')
    some_function_with_cached_sys_stdout()
    print('stderr also goes to stdout that goes to devnull', file=sys.stderr)
print('stdout is back')
some_function_with_cached_sys_stdout()
print('stderr is back', file=sys.stderr)

rawDescription: Temporarily Redirect stdout/stderr

description: Temporarily Redirect stdout/stderr


code:
def application(environ, start_response):
    content_type = environ.get('CONTENT_TYPE', 'text/plain')
    headers = [('Content-Type', content_type)]
    if 'CONTENT_LENGTH' in environ:
        headers.append(('Content-Length', environ['CONTENT_LENGTH']))
    start_response('200 OK', headers)
    input = environ.get('wsgi.input')
    if input is None:
        yield ''
        return
    while True:
        datum = input.read(4096)  # or so
        if not datum:
            return
        yield datum

rawDescription: Python web framework capable of chunked transfer encoding?


code:
def session(request):
    return { 'session': request.session }

rawDescription: Django flatpages

description: Django flatpages


code:
import numpy as np
a = np.array([[1,2],[3,45]])
a
[''.join(str(x) for x in row) for row in a.T]
np.array([''.join(str(x) for x in row) for row in a.T], int)

rawDescription: 'Concatenating' rows of a numpy matrix

description: 'Concatenating' rows of a numpy matrix


code:
from django.db.models.functions import Lower
qs = Language.objects.annotate(code_lower=Lower('code')) # annotate each item in the queryset with the code_lower
values = qs.values_list('code_lower', 'language')
dictionary = dict(values)

rawDescription: Lowercase django query

description: Lowercase django query


rawDescription: python dictionary item reference assignment

description: Python dictionary item reference assignment


code:
for x in year:
    exposure_tag = testsoup.new_tag('exposure', year = x)
    exp_tag.append(exposure_tag)
    intro_tag.append(exp_tag)

rawDescription: Using BeautifulSoup to loop through a list and create XML tags


code: output_list = filter(any, input_list)

rawDescription: Simultaneous condition on all line elements of a tuple


code:
import pydoc
pydoc.pager("A very long string")

rawDescription: implement similar thing like "help" command in python interactive shell

description: Implement similar thing like "help" command in python interactive shell


code:
import numpy

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.tri import Triangulation
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.cm as cm

# Generate a dataset

R = 1

# bin midpoints
theta = numpy.linspace(numpy.pi/6, numpy.pi/3, 20) + numpy.pi / 2
phi = numpy.linspace(numpy.pi/6, numpy.pi/3, 20)

ttheta, pphi = numpy.meshgrid(theta, phi)
x = R * numpy.sin(ttheta) * numpy.cos(pphi)
y = R * numpy.sin(ttheta) * numpy.sin(pphi)
z = R * numpy.cos(ttheta)

n = numpy.exp(-(ttheta - numpy.pi/4 - numpy.pi/2)**2 * 20 - (pphi - numpy.pi/4)**2 * 20)

mappable = cm.ScalarMappable(cmap=cm.coolwarm, norm=matplotlib.colors.Normalize(vmin=0, vmax=1))
colors = mappable.to_rgba(n)

# Scatter plot

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.scatter(x.flatten(), y.flatten(), z.flatten(), c=colors.reshape(x.size, 4))
ax.set_xlim(0.2, 0.8)
ax.set_ylim(0.2, 0.8)
ax.set_zlim(-0.9, -0.45)
ax.elev = 50
fig.savefig('t.png')

# Surface plot

# bin vertex spherical coordinates
dtheta = theta[1] - theta[0]
dphi = phi[1] - phi[0]
v_theta = numpy.concatenate([theta - dtheta/2, numpy.array([theta[-1] + dtheta/2])])
v_phi = numpy.concatenate([phi - dphi/2, numpy.array([phi[-1] + dphi/2])])

# bin vertex Cartesian coordinates
v_ttheta, v_pphi = numpy.meshgrid(v_theta, v_phi)
vx = R * numpy.sin(v_ttheta) * numpy.cos(v_pphi)
vy = R * numpy.sin(v_ttheta) * numpy.sin(v_pphi)
vz = R * numpy.cos(v_ttheta)

# Creating triangles and corresponding face colors

triangles = []
facecolors = []

for i in range(v_theta.size - 1):
    for j in range(v_phi.size - 1):
        triangles.extend([
            [(i, j), (i + 1, j), (i, j + 1)],
            [(i + 1, j), (i + 1, j + 1), (i, j + 1)]])
        facecolors.extend([
            colors[i, j],
            colors[i, j]
            ])

triangle_vertices = numpy.array(
    [[[vx[i,j], vy[i,j], vz[i,j]] for i, j in t] for t in triangles])
coll = Poly3DCollection(triangle_vertices, facecolors=facecolors, edgecolors=(0,0,0,0))

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.add_collection(coll)
ax.set_xlim(0.2, 0.8)
ax.set_ylim(0.2, 0.8)
ax.set_zlim(-0.9, -0.45)
ax.elev = 50
fig.savefig('t2.png')

rawDescription: Python:Curved surface plot with density colors


rawDescription: Using lists and dictionaries to store temporary information


code:
data = set( [i.strip() for i in open( filename, 'r' ).readlines()] )

for server in cmo.getServers() :
    data.add( server.getListenAddress() )

open( filename, 'w' ).write('\n'.join(data))

rawDescription: Test if string exists in file with Python


code:
from numpy import *
from pylab import ion, plot, draw, show, xlabel, ylabel, figure

sample_rate = 20000.
times = arange(0, 10., 1./sample_rate)
wfm0 = sin(2*pi*200.*times)
wfm1 = sin(2*pi*500.*times) *(10.-times)/10.
wfm = wfm0+wfm1
#  int test
#wfm *= 2**8
#wfm = wfm.astype(int16)
#wfm = wfm.astype(float)
#  abs test
#wfm = abs(wfm)
#  clip test
#wfm = clip(wfm,  -1.2, 1.2)

fft_length = 5*2048.
total_num_samps = len(times)
num_fft = (total_num_samps / fft_length ) - 2
temp = zeros((num_fft,fft_length), float)

for i in range(num_fft):
    temp[i,:] = wfm[i*fft_length:(i+1)*fft_length]
pts = fft_length/2+1
data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts]

x_axis = arange(pts)*sample_rate*.5/pts
spec_range = pts
plot(x_axis, data[2], linewidth=3)
xlabel("freq (Hz)")
ylabel('abs(FFT)')
show()

rawDescription: Clipping FFT Matrix

description: Clipping FFT Matrix


code:
import gtk
import locale

class NumericEntry(gtk.Entry):
    __gsignals__ = {
        'key_press_event': 'override'
    }
    def do_key_press_event(self, event):
        if event.keyval == gtk.gdk.keyval_from_name('KP_Decimal'):
            event.keyval = int(gtk.gdk.unicode_to_keyval(ord(locale.localeconv()['decimal_point'])))
        gtk.Entry.do_key_press_event(self, event)

rawDescription: How to transform a key pressed into a different one in pygtk

description: Transform a key pressed into a different one in pygtk


code:
from sqlalchemy import func

items = session.query(Model, func.count().over().label('full_count')).all()
obj = items[0].Model
count = items[0].full_count

rawDescription: SQLAlchemy add columns to query() on mapped class


code:
intervalx = xsize / xsegment #Get the size of the chunks
intervaly = ysize / ysegment #Get the size of the chunks

#Setup to segment the image storing the start values and key into a dictionary.
xstart = 0
ystart = 0

output = []

for y in xrange(0, ysize, intervaly):
    numberofrows = intervaly if y + (intervaly * 2) < ysize else ysize -y
    for x in xrange(0, xsize, intervalx):
        numberofcolumns = intervalx if x + (intervalx * 2) < xsize else xsize -x
        lst = [x, y, numberofcolumns, numberofrows]
        output.append(lst)

        #If it doesn't make any difference to your program, the above 2 lines could read:
        #tple = (x, y, numberofcolumns, numberofrows)
        #output.append(tple)

        #This will be slightly more efficient
        #(tuple creation is faster than list creation)
        #and less memory hungry.  In other words, if it doesn't need to be a list due
        #to other constraints (e.g. you append to it later), you should make it a tuple.

rawDescription: Pythonic way to calculate offsets of an array


code:
m.text.replace('.,..','')
interimArray = m.text.split(' ',2)
comando = interimArray[1]
idchat = interimArray[2]

rawDescription: Get multiple strings from one (Python 2.7)


code:
format = textbuffer.register_serialize_tagset('my-tagset')
exported = textbuffer.serialize(textbuffer, format, start, end)

rawDescription: Get text from Gtk3 TextView/TextBuffer with formatting tags included in Python


code:
import inspect
import math
inspect.getmembers(math, inspect.isroutine)

rawDescription: inspect.isfunction doesn't work for all modules?

description: Inspect.isfunction doesn't work for all modules


rawDescription: substring extraction

description: Substring extraction


code: print (c if a > b else d),

rawDescription: Python Using question marks in print statements?


rawDescription: Python - Using str.replace with a wildcard


code:
def csr_entries(M):
    """Generator of tuples (i,j,x) of sparse matrix entries
    meaning that M[i,j]=x."""
    for row in range(len(M.indptr)-1):
        i,j = M.indptr[row],M.indptr[row+1]
        for k in range(i,j):
            yield (row, M.indices[k], M.data[k])

rawDescription: accessing all non zero entries of a csr_matrix

description: Accessing all non zero entries of a csr_matrix


code:
import json
import collections
OrderedDict = collections.OrderedDict

def map_names_to_imports(raw_data):
    name_to_imports = OrderedDict()
    for row in raw_data:
        name_to_imports.setdefault(row['imports'], []).append(row['name'])
    return name_to_imports

def reformat(name_to_imports):
    the_output = []
    for name, imports in name_to_imports.items():
        new_dict = OrderedDict([('name', name),
                                ('imports', list(set(imports)))])
        the_output.append(new_dict)
    return the_output

def run(raw_data):
    name_to_imports = map_names_to_imports(raw_data)
    the_output = reformat(name_to_imports)
    with open('data/clean-data2.json',  'w+', encoding='utf8') as f:
        f.write(json.dumps(the_output))

if __name__ == '__main__':
  raw_data = json.load(open('data/bricsinvestorsfirst.json'), object_pairs_hook=OrderedDict)
  run(raw_data)

rawDescription: Ordering with default dict append

description: Ordering with default dict append


code:
r = requests.get('https://github.com/timeline.json', stream=True)
r.raw
r.raw.read(10)

rawDescription: How to get the raw content of a response in requests with Python?

description: Get the raw content of a response in requests with Python


code:
Var1 = range(10, 50)
print(list(Var1))

rawDescription: Assign a range to a variable (Python)

description: Assign a range to a variable (Python)


code: new_list = [ splitext(basename(i))[0] for i in inputlist ]

rawDescription: How do I extract only a part of a list 'member' in PYTHON?

description: Extract only a part of a list 'member' in PYTHON


code:
import subprocess
tagname = subprocess.check_output('git describe --tags'.split())

rawDescription: Simple python command to capture shell execution output?


code:
import pandas
df = pandas.DataFrame({"col1":["A", "A", "B"], "col2":[1,2,3]})
df.groupby("col1").sum()
df.groupby("col1").sum().reset_index()

rawDescription: Pandas Dataframe - find sums in column B across each label in column A


code:
import contextlib
@contextlib.contextmanager
def write_on_change(filename):
    with tempfile.NamedTemporaryFile(delete=False) as f:
        yield f
        tempname = f.name
    try:
        overwrite = not filecmp.cmp(tempname,filename)
    except (OSError,IOError):
        overwrite = True
    if overwrite:
        shutil.copyfile(tempname,filename)
    os.unlink(tempname)

rawDescription: Easy way of not overwriting file when output is the same


code:
def my_final_grade_calculation(filename):
    file_pointer = open(filename, 'r')
    data = file_pointer.readlines()
    dict_={}
    for line in data:
        #a=[]
        #q=[]
        #dict={}
        name, q1, q2, q3, q4, q5, q6, a1, a2, a3, a4, midterm, final =  line.strip().split(',')
        q=[int(q1),int(q2),int(q3),int(q4),int(q5),int(q6)]
        a=[int(a1),int(a2),int(a3),int(a4)]
        #int(midterm)
        #int(final)
        for i in range(0,2):
            q.remove(min(q))
        a.remove(min(a))
        a_avg=0.0
        for j in range(0,len(a)):
            a_avg+=a[j]/len(a)
        q_avg=0.0
        for i in range(0,len(q)):
            q_avg+=q[i]/len(q)
        final = ((float(q_avg)/4)) + ((float(a_avg)/4)) + ((float(midterm)/4)) + ((float(final)/4))
        if final>=60.0:
            out='pass'
            dict_[name]=out
        else:
            out='fail'
            dict_[name]=out
    return dict_

#calling function
print(my_final_grade_calculation('filename.txt'))

rawDescription: Create a function which inputs a file and calculates grade


code:
List = ['airplane',
            'fish',
            'watch',
            'balloon',
            'headphones',
            'wineglass',
            'bowtie',
            'guitar',
            'desk',
            'bottle',
            'glove'] #there is more in my final list but keeping it short here
numIters = 5
numItems = len(List)
finalList=[]
for curList in range(numIters):
    random.shuffle(List)
    finalList.append(List[0 : numItems/2]) #append first list
    finalList.append(List[numItems/2 : -1]) #append second list

return finalList

rawDescription: Pick subset from list at random and maintain equal number of picks overall in python


code:
import numpy as np
import pylab as p
from matplotlib.widgets import Slider

p.subplot(111)
x = np.arange(0,500,1)
f = np.sin(x/100.0)
l11, = p.plot(f)

ax = p.axes([0.25, 0.05, 0.7, 0.03], axisbg='lightgoldenrodyellow')
slider1 = Slider(ax, 'amplitude', -1.0, 1.5, valinit=0)

# the text on the figure
fig_text = p.figtext(0.5, 0.65,  str(slider1.val))

def update(val):
    f = slider1.val*np.sin(x/100.0)
    l11.set_ydata(f)
    np.set_printoptions(precision=2)

    # update the value of the Text object
    fig_text.set_text(str(slider1.val))

    p.draw()

slider1.on_changed(update)
p.show()

rawDescription: matplotlib slider redraw does not update figtext

description: Matplotlib slider redraw does not update figtext


code:
from collections import OrderedDict
d1 = OrderedDict((('a',1), ('b',2), ('c', 3)))
d2 = OrderedDict((('x',4), ('y',5), ('z', 6)))
d3 = OrderedDict(zip(d1.keys(), d2.values()))
d3

rawDescription: Build a new dictionary from the keys of one dictionary and the values of another dictionary


code:
import gmpy
gmpy.scan1(136)
bin(136)

rawDescription: return index of least significant bit in Python

description: Return index of least significant bit in Python


code:
for tag in tags[:]:
    if tag.lower() in ['ex1', 'ex2', 'ex3']:
        tags.remove(tag)

rawDescription: .remove() in Python list breaks a for loop


code:
import re
strs = "@ sample This is a sample string $ 1.00 # sample"
re.sub(r'([@#$])(\s+)([a-z0-9])', r'\1\3', strs, flags=re.I)

rawDescription: Search and replace using regular expressions in Python


code:
class Class(object):

     _defaults = dict(kw0=42, kw1=None, kw2=True, kw3="Ni!")

     def __init__(self, **kwargs):

        # Raise exception if any non-supported keywords supplied
        if set(kwargs.keys()) - set(self._defaults.keys()):
            raise KeyError("unsupported keyword argument")

        # Update our instance with defaults, then keyword args
        self.__dict__.update(self._defaults)
        self.__dict__.update(kwargs)

rawDescription: Manipulating large amounts of keyword arguments in a Pythonic manner


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

mpl.rcParams['axes.color_cycle'] = ['r', '#8F00FF', '#A0F0A0']

y = np.arange(5)
for i in range(7):
    plt.plot(y + i, linewidth=5)

plt.show()

rawDescription: Python matplotlib: Setting the default colours of the colour cycle


code: arr = [x for x in vec if x < 2]

rawDescription: Declare array with "where"

description: Declare array with "where"


code:
from gi.repository import Gtk
dir(Gtk.TreeModel)

rawDescription: GenericTreeModel with PyGObject Introspection Gtk+ 3?


code:
import re
import urllib.request
from bs4 import BeautifulSoup
url = 'http://www.bricklink.com/catalogPriceGuide.asp?P=3005&colorID=1&viewExclude=N&v=P'
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page.read())
td = soup.find('td', text=re.compile('Times Sold'))
tr_list = td.parent.parent.find_all('tr')
for tr in tr_list:
    print(' '.join(td.text for td in tr.find_all('td')))

rawDescription: Trying to parse a table within table within a table


rawDescription: Python Lowest Common CIDR

description: Python Lowest Common CIDR


code:
for k in d:
    print('The key is {} and the value is {}'.format(k, d[k]))

rawDescription: Python INI to Dictionary - Loop through all items in section


code:
strings = ['abc', 'abcde', 'abcd', 'abcdefgh']
outputs = map(lambda x: "%d %s" % (len(x), x), strings) # ['3 abc', '5 abcde', '4 abcd', '8 abcdefgh']
f = open("file.out", 'w')
data = '\n'.join(outputs) # Concat all strings in list, separated by line break
f.write(data)
f.close()

rawDescription: Python strings and integers to write to file?


code:
def helper(list1, list2, result):
  if not list1:
    return result + list2
  elif not list2:
    return result + list1
  elif list1[0] < list2[0]:
    return helper(list1[1:], list2, result + [list1[0]])
  else:
    return helper(list1, list2[1:], result + [list2[0]])

rawDescription: Trouble inserting in Python (None vs. empty list)


code:
import time
import threading

def func1():
    t = threading.Thread(target=func2)
    t.start()
    print("Do stuff here")
def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()
print("func1 has returned")

rawDescription: Python sleep without interfering with script?


code:
import boto.s3.key
k = boto.s3.key.Key('somebucket')
dir(k)

rawDescription: what attributes are available on key in django boto amazon s3

description: What attributes are available on key in django boto amazon s3


code:
import tkinter
import tkinter.filedialog
import getpass
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
    # Get the file
    file = tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)
    # Split the filepath to get the directory
    directory = os.path.split(file)[0]
    print(directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()

rawDescription: Get a file's directory in a string selected by askopenfilename


rawDescription: adding a trailing comma to a print command makes threads executions "serialized"

description: Adding a trailing comma to a print command makes threads executions "serialized"


rawDescription: Cartesian product to get set of indices to point to unique elements in NumPy array


code:
import jpype
import os.path

jarpath = os.path.join(os.path.abspath('.'), 'build/jar')
jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % jarpath)

# get the class
hello_world = jpype.JClass('com.stackoverflow.HelloWorld')
t = hello_world()  # create an instance of the class
t.helloWorld("Say hello")  # try to call one of the class methods
jpype.shutdownJVM()

rawDescription: Constrained minimization of multivariate function using Jython


code:
import pandas as pd
df1=pd.read_csv("1.csv")
df=pd.read_csv("2.csv")
result=df1.merge(df,on="formula")
result.to_csv("result.csv")

rawDescription: Merge two csv files based on key and secondary key


code:
_query = {'Id__istartswith': value}
return Q(**_query)

rawDescription: How to create mongoengine filter query from fields listed as string rather DocumentFields

description: Create mongoengine filter query from fields listed as string rather DocumentFields


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

px = np.arange(0,10,0.5)
py = np.random.randn(20)
pz = np.arange(0,1,0.05)
colors = plt.cm.Reds(np.arange(0,1,0.05))
colors[:,-1] = pz

plt.figure()
plt.scatter(px,py,color=colors)
plt.show()

rawDescription: Varying alpha or colors for pyplot markers based on data


code:
import numpy as np
import cv2

#Get video name from user
#Ginen video name must be in quotes, e.g. "pirkagia.avi" or "plaque.avi"
video_name = input("Please give the video name including its extension. E.g. \"pirkagia.avi\":\n")

#Open the video file
cap = cv2.VideoCapture(video_name)

#Set frame_no in range 0.0-1.0
#In this example we have a video of 30 seconds having 25 frames per seconds, thus we have 750 frames.
#The examined frame must get a value from 0 to 749.
#For more info about the video flags see here: http://stackoverflow.com/questions/11420748/setting-camera-parameters-in-opencv-python
#Here we select the last frame as frame sequence=749. In case you want to select other frame change value 749.
#BE CAREFUL! Each video has different time length and frame rate.
#So make sure that you have the right parameters for the right video!
time_length = 30.0
fps=25
frame_seq = 749
frame_no = (frame_seq /(time_length*fps))

#The first argument of cap.set(), number 2 defines that parameter for setting the frame selection.
#Number 2 defines flag CV_CAP_PROP_POS_FRAMES which is a 0-based index of the frame to be decoded/captured next.
#The second argument defines the frame number in range 0.0-1.0
cap.set(2,frame_no);

#Read the next frame from the video. If you set frame 749 above then the code will return the last frame.
ret, frame = cap.read()

#Set grayscale colorspace for the frame.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

#Cut the video extension to have the name of the video
my_video_name = video_name.split(".")[0]

#Display the resulting frame
cv2.imshow(my_video_name+' frame '+ str(frame_seq),gray)

#Set waitKey
cv2.waitKey()

#Store this frame to an image
cv2.imwrite(my_video_name+'_frame_'+str(frame_seq)+'.jpg',gray)

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

rawDescription: OpenCV/Python: read specific frame using VideoCapture


code:
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:') # wait for 'Password:' to show up
child.sendline (mypassword)

rawDescription: pass answers to popen.subprocess

description: Pass answers to popen.subprocess


code:
test_requirements = ['pytest>=2.1', 'dingus']
setup(
    # ...
    tests_require = test_requirements,
    install_requires = [
        # ... (your usual install requirements)
    ] + test_requirements,
)

rawDescription: Specifying where to install 'tests_require' dependencies of a distribute/setuptools package


code:
rawSelection = [u'crapacruk_high', u'doubidou_high', u'blahbli_high', u'crapacruk_SREF_high', u'doubidou_SREF_high', u'blahbli_SREF_high']

for obj in list(rawSelection):
    if '_SREF_' in str(obj):
        rawName = str(obj).split('_')
        rootName = rawName [0]
        defName = rootName + '_' + '_'.join(rawName[2:])
        if defName in rawSelection:
            rawSelection.remove (obj)

print(rawSelection)

rawDescription: Python: remove() doesn't seems to work

description: Python: remove() doesn't seems to work


code:
category = forms.ModelChoiceField(queryset=Category.objects.all(),
                                  empty_label="(Nothing)")

rawDescription: Django forms, getting a select box from a different model


code:
users_with_apple = list(User.objects.filter(fruit=apple))
users_with_pear = list(User.objects.filter(fruit=pear))

for user in users_with_apple:
    user.fruit = pear
    user.save()
for user in users_with_pear:
    user.fruit = apple
    user.save()

rawDescription: Django ORM query: how to swap value of a attribute?


code:
import os, sys, subprocess

def open_file(filename):
    if sys.platform == "win32":
        os.startfile(filename)
    else:
        opener ="open" if sys.platform == "darwin" else "xdg-open"
        subprocess.call([opener, filename])

rawDescription: Is there an platform independent equivalent of os.startfile()?


code:
f=open(MyFile, 'r')
for num, line in enumerate(f):
    if line=='\n' and num>100:
        break
else:
    num = None
Result = num

rawDescription: First true value if statement

description: First true value if statement


code:
import random
seed=1234
n=10
random.Random(seed).sample(range(1000),n)

rawDescription: What's the easiest way to reproduce a randomly generated level in Python?


code:
with open("myFile", "w") as f:
    # print each element on a separate line
    for elem in array:
        f.write(repr(elem))

rawDescription: Ants AI Challenge: How can I write to a file from within my Ant class?


code:
@get('/restartmyserver')
def handler():
    http_auth_data = bottle.request.auth() # returns a tuple (username,password) only basic auth.
    if http_auth_data[0] == user and http_auth_data[1] == password:
        os.system("your_shell_script_to_restart_gevent_wsgi")
    bottle.redirect('/')

rawDescription: Bottle equivalent of engine.restart()

description: Bottle equivalent of engine.restart()


code:
import pylab as pl
import numpy as np
from matplotlib.collections import Collection
from matplotlib import transforms
import matplotlib.animation as animation

fig = pl.figure()

N = 40
x, y = np.random.rand(2, N)
color = np.random.rand(N)
r = np.random.rand(N) * 0.05 + 0.05

c = pl.scatter(x, y, s=r, c=color, alpha=0.5, animated=True)
pl.gca().set_aspect("equal")

def draw(self, renderer):
    if self._sizes is not None:
        m = self.axes.transData.get_matrix()
        self._transforms = [
            transforms.Affine2D().scale(m[0, 0]*x, m[1, 1]*x)
            for x in self._sizes]
    return Collection.draw(self, renderer)

c.draw = lambda renderer:draw(c, renderer)

def update_loc(n):
    global x2, y2, x, y
    n = n % 50
    if n == 0:
        x2, y2 = np.random.rand(2, N)
    x += (x2 - x) * 0.1
    y += (y2 - y) * 0.1
    c.set_offsets(np.c_[x, y])
    return c,

ani = animation.FuncAnimation(fig, update_loc, 2500, interval=50, blit=True)

pl.show()

rawDescription: Drawing circles of variable size and position on a 2d animation


code:
import pygame, sys, random
from pygame.locals import *

# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
width = 800
height = 600
thesurface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('')

bg = pygame.image.load("bg.png")
basicFont = pygame.font.SysFont('calibri', 36)

# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
size = 10
playercolor = BLUE
# set up the player and food data structure
foodCounter = 0
NEWFOOD = 35
FOODSIZE = 10
splitting = False
player = pygame.draw.circle(thesurface, playercolor, (60, 250), 40)
foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))

# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False

MOVESPEED = 10

score = 0
# run the game loop
while True:
    # check for events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # change the keyboard variables
            if event.key == K_LEFT or event.key == ord('a'):
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == ord('d'):
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == ord('w'):
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == ord('s'):
                moveUp = False
                moveDown = True
            if event.key == K_SPACE and size >= 30: # XXX if size and space set splitting to true
                splitting = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == ord('a'):
                moveLeft = False
            if event.key == K_RIGHT or event.key == ord('d'):
                moveRight = False
            if event.key == K_UP or event.key == ord('w'):
                moveUp = False
            if event.key == K_DOWN or event.key == ord('s'):
                moveDown = False
            if event.key == ord('x'):
                player.top = random.randint(0, height - player.height)
                player.left = random.randint(0, width - player.width)

        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))

    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))
    if 100>score>50:
        MOVESPEED = 9
    elif 150>score>100:
        MOVESPEED = 8
    elif 250>score>150:
        MOVESPEED = 6
    elif 400>score>250:
        MOVESPEED = 5
    elif 600>score>400:
        MOVESPEED = 3
    elif 800>score>600:
        MOVESPEED = 2
    elif score>800:
        MOVESPEED = 1
    # move the player
    if moveDown and player.bottom < height:
        player.top += MOVESPEED
    if moveUp and player.top > 0:
        player.top -= MOVESPEED
    if moveLeft and player.left > 0:
        player.left -= MOVESPEED
    if moveRight and player.right < width:
        player.right += MOVESPEED
    thesurface.blit(bg, (0, 0))

    # draw the player onto the surface
    if not splitting: # XXX check the split flag and draw accordingly...
        pygame.draw.circle(thesurface, playercolor, player.center, size)
    else:
        pygame.draw.circle(thesurface, playercolor,(player.centerx,player.centery),int(size/2))
        pygame.draw.circle(thesurface, playercolor,(player.centerx+size,player.centery+size),int(size/2))
    # check if the player has intersected with any food squares.
    for food in foods[:]:
        if player.colliderect(food):
            foods.remove(food)
            size+=1
            score+=1

    # draw the food
    for i in range(len(foods)):
        pygame.draw.rect(thesurface, GREEN, foods[i])

    printscore = basicFont.render("Score: %d" % score, True, (0,0,0))
    thesurface.blit(printscore, (495, 10))

    pygame.display.update()
    # draw the window onto the thesurface
    pygame.display.update()
    mainClock.tick(80)

rawDescription: Pygame: Cell Physics

description: Pygame: Cell Physics


code:
import numpy as np
np.loadtxt('/tmp/sample.txt', dtype=str, delimiter='##', comments=None)

rawDescription: loading strings with spaces as numpy array

description: Loading strings with spaces as numpy array


code:
class window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(window, self).__init__(parent)
        self.TreeWidget = QtGui.QTreeWidget()
        self.TreeWidget.setColumnCount(1)
        # self.item1/2/3 = ....  save reference to the items
        #   to access them in the callback (check_status)
        item1 = self.item1 = QtGui.QTreeWidgetItem(["Item 1"])
        item1.setCheckState(0, QtCore.Qt.Checked)
        item2 = self.item2 = QtGui.QTreeWidgetItem(["Item 2"])
        item2.setCheckState(0, QtCore.Qt.Unchecked)
        item3 = self.item3 = QtGui.QTreeWidgetItem(["Item 3"])
        item3.setCheckState(0, QtCore.Qt.Unchecked)
        self.TreeWidget.addTopLevelItem(item1)
        self.TreeWidget.addTopLevelItem(item2)
        self.TreeWidget.addTopLevelItem(item3)
        self.setCentralWidget(self.TreeWidget)

        # connect the itemClicked signal to the callback check_status.
        self.TreeWidget.itemClicked.connect(self.check_status)

    def check_status(self):
        if self.item1.checkState(0) == QtCore.Qt.Checked:
            print('item 1 is checked')
        if self.item2.checkState(0) == QtCore.Qt.Checked:
            print('item 2 is checked')
        if self.item3.checkState(0) == QtCore.Qt.Checked:
            print('item 3 is checked')

rawDescription: How do I check if a checkbox is checked or unchecked? (In QTreeWidget)

description: Check if a checkbox is checked or unchecked? (In QTreeWidget)


code:
import sys

stdout_ = sys.stdout #Keep track of the previous value.
sys.stdout = open('myoutputfile.txt', 'w') # Something here that provides a write method.
# calls to print, ie import module1
sys.stdout = stdout_ # restore the previous stdout.

rawDescription: python capture print output of another module

description: Python capture print output of another module


code:
for key,value in counts.items():
    print(key,value)

rawDescription: How many times any word occurred in string. Each letter case (upper or lower) in word matters. Lines in output can be in any order.:


code:
def initgame():
    global enemies
    enemies=[]

rawDescription: "for" loop in python-pygame does not break under an "if" statement


code:
labels = (
    (1000, 'number >= 1000'),
    (200,  '200 <= number < 1000'),
    (100,  '100 <= number < 200'),
    (50,   '50 <= number < 100'),
    (0,    'number < 50'),
)

for i in number:
    for limit, label in labels:
         if i >= limit:
             categoryNumber.append(label)
             break

rawDescription: How to do elif statments more elegantly if appending to array in python

description: Do elif statments more elegantly if appending to array in python


code:
fields
output = {}
for field in fields:
    key = field.pop('name')
    _unused_key, value = field.popitem()
    output[key] = value

output

rawDescription: Generate single dictionary from a list of dictionaries


code: map(xml_to_dict, xml_document)

rawDescription: Python: Preventing a dict's key from being overwritten


code:
def on_close():

     #custom close options, here's one example:

     close = messagebox.askokcancel("Close", "Would you like to close the program?")
     if close:
          root.destroy()

root.protocol("WM_DELETE_WINDOW",  on_close)

rawDescription: Detect when the "x" or close button is pressed


code:
struct.unpack('2b', struct.pack('>h', 1000))
struct.unpack('4b', struct.pack('>I', 1000))
struct.unpack('8b', struct.pack('>Q', 1000))

rawDescription: toByteArray in Python?

description: ToByteArray in Python


code: os.kill(process.pid, signal.SIGKILL)

rawDescription: In Python 2.5, how do I kill a subprocess?


code:
f1 = open('/var/log/combined/test.log', 'a+')
print >>f1, clips.PrintFacts()

rawDescription: Output Multiple lines to file in Python 2.7.3


code:
combined = df_2.merge(df_1, on='name', how='left')
keep = combined[(combined.value1<=combined.value) & (combined.value2>=combined.value)]

rawDescription: Vectorized code to iterate one panda dataframe and compare values to a second dataframe


code:
from something.otherthing.js import foo
from something.otherthing import js as bar
import something.otherthing.js as hamspam

rawDescription: Module name different than directory name?


code:
my_order = ["dist", "dem"]
df1 = pandas.DataFrame({"dist":xm, "dem":ym}, columns=my_order)

rawDescription: Pandas re-arranges DataFrame Columns?

description: Pandas re-arranges DataFrame Columns


rawDescription: How to convert python byte string containing a mix of hex characters?

description: Convert python byte string containing a mix of hex characters


code:
from collections import OrderedDict

d = OrderedDict([("name", "David"), ("year", 2016)])

values_tuple = tuple([v for v in d.values()])
q = r'INSERT INTO myTable (%s'
for i in range(len(values_tuple)-1):  # I added first one above so -1
    q += r', %s'
q += ')'

cursor.execute(q, values_tuple)

rawDescription: Insert into mysql using dictionary

description: Insert into mysql using dictionary


rawDescription: Make an AJAX call to pass drop down value to the python script


code: v = sigma * np.random.randn(v_size) + b + sigma * W.dot(h)

rawDescription: (Python) Gaussian Bernoulli RBM on computing P(v|h)


code:
import datastore_mongo_stub

os.environ['APPLICATION_ID'] = 'test'

datastore = datastore_mongo_stub.DatastoreMongoStub(
    os.environ['APPLICATION_ID'], 'woot', '', require_indexes=False)

apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore)

rawDescription: Faster App Engine Development Datastore Alternative


code:
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

rawDescription: How can I make a subplot in a subplot?

description: Make a subplot in a subplot


code:
with open("test1.txt","a") as file1, open("test2.txt","r") as file2:
    for line in file2:
        file1.write('\n' + line)

rawDescription: how to append the content of one file at the of the content of another file in python

description: Append the content of one file at the of the content of another file in python


code:
from tkinter import *

class MainWindow(Tk):

    def __init__(self):
        Tk.__init__(self)
        Entry(self).pack(side="left")
        Button(self, text="whoami", command=lambda : print("A Tk root window.")).pack(side="left")

    def CreateChildWindow(self):
        subWindow = Toplevel(self)

        def quit_subwindow():
            subWindow.destroy()
            self.grab_set()

        Button(subWindow, text="whoami", command=lambda : print("A Toplevel child window.")).pack()
        Button(subWindow, text='Exit', command=quit_subwindow).pack()
        subWindow.grab_set()

win = MainWindow()
win.CreateChildWindow()
win.mainloop()

rawDescription: Efficient way to create a child window with access to main window disabled?


code: se = list(set([x.strip() for x in re.split('\*+', st)]) - {''})

rawDescription: Using regex to extract data from the following string


code:
def distance(tup1,tup2):
    """
        This question is unanswerable unless you can specify this

        examples for 2d (you can write more general N-dimensional code if you need):
        cartesian: math.sqrt((tup2[0]-tup1[0])**2 + (tup2[1]-tup1[1])**2)
        manhattan: (tup2[0]-tup1[0]) + (tup2[1]-tup1[1])
    """
    return # YOUR CODE HERE

min(values, key=lambda x:distance(target,x))

rawDescription: In Python, what's the best way to get the closest integers for two dimensions?


code:
def fancy_path(instance, filename):
    return 'fancy_path/file_%s.xml' % self.instance.album.id

original = models.ImageField(upload_to=fancy_path, max_length=200)

rawDescription: Creating a dynamic path when I upload images


code:
import xlwt, xlrd
from xlutils.copy import copy

read_workbook_page = xlrd.open_workbook('page_level.xlsx')

workbook_page = copy(read_workbook_page)
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')

num_rows = worksheet_page.nrows - 1
num_cols = worksheet_page.ncols - 1

for row in range(num_rows):
     column_sum = 0
     for column in range(1, num_cols):
          column_sum += worksheet_page.cell_value( row, column )
     worksheet_page.write(row, num_cols, column_sum )

worksheet_page.save('page_level.xlsx')

rawDescription: Problems whith columns in Python xlrd

description: Problems whith columns in Python xlrd


code:
from sys import stdout
from time import sleep

def show(word):
  for char in word:
    stdout.write(char)
    stdout.flush()
    sleep(1)
  for char in word:
    stdout.write('\b \b')
    stdout.flush()
    sleep(1)

show('hello')

rawDescription: Is there a way to clean output on command prompt through the code?


code:
import matplotlib.pyplot as pl
from matplotlib.ticker import ScalarFormatter

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

ax.set_xscale('log')
ax.set_xticks([1,2,5,10])
ax.get_xaxis().set_major_formatter(ScalarFormatter())
ax.set_xlim([1., 10.])

rawDescription: Matplotlib log scale formatting

description: Matplotlib log scale formatting


code:
import pandas as pd
e = {}
for i in range(0, len("length_of_the_row")):
    e[i] = "a", "b", "c", "d"

df = pd.DataFrame.from_dict(e, orient='index')

rawDescription: How to convert dictionary with multiple values into a pandas dataframe?

description: Convert dictionary with multiple values into a pandas dataframe


code:
from django.utils.translation import activate
activate('en')
# do smthg
activate('pl')
# do something in other language

rawDescription: Django switching, for a block of code, switch the language so translations are done in one language


code:
f = open('namesonly.txt', 'w')
...
for line in reader:
    if "new" in line[2]:
        #line = line.split(',') #<- you don't need this line because you are reading the input as a delimitd string already
        f.write(line[0] + '\n') # write the first thing before the first comma (your names)
f.close()

rawDescription: Remove rows by keyword in column, and then remove all columns and save as text in python


code:
from google.appengine.api import datastore
import uuid
import base64
import md5

def testSomething(self):
  upload_url = self.testapp.post('/path/to/create_upload_url/handler').body
  response = self.upload_blobstore_file(upload_url, "file", "myfile.txt", "MYDATA1").json
  # Test something on the response from the success handler and/or backing storage

def upload_blobstore_file(self, upload_url, field, filename, contents, type = "application/octet-stream"):
  session = datastore.Get(upload_url.split('/')[-1])
  new_object = "/" + session["gs_bucket_name"] + "/" + str(uuid.uuid4())
  self.storage_stub.store(new_object, type, contents)

  message = "Content-Type: application/octet-stream\r\nContent-Length: " + str(len(contents)) + "\r\nContent-MD5: " + base64.b64encode(md5.new(contents).hexdigest()) + "\r\nX-AppEngine-Cloud-Storage-Object: /gs" + new_object.encode("ascii") + "\r\ncontent-disposition: form-data; name=\"" + field + "\"; filename=\"" + filename + "\"\r\nX-AppEngine-Upload-Creation: 2015-07-17 16:19:55.531719\r\n\r\n"
  return self.testapp.post(session["success_path"], upload_files = [
  (field, filename, message, "message/external-body; blob-key=\"encoded_gs_file:blablabla\"; access-type=\"X-AppEngine-BlobKey\"")
])

rawDescription: Unit testing BlobStore create_upload_url uploads


code:
def wrapper(func):
    @functools.wraps
    def wrap(*args, **kwargs):
        # do stuff to update call graph
        return func(*args, **kwargs)
    return wrap

g = globals()
for name, value in g.items():
    if callable(value):
        g[name] = wrapper(value)

rawDescription: How to get function stack trace for any function?

description: Get function stack trace for any function


code:
data = input()
# Divide the list
div = len(data)//2
lst = []
# Add both halves to the list
lst.append(data[:div])
lst.append(data[div:])
tot = ""
# Loop through the list and add the sum as a string
for i in lst:
    tot += str(int(i[0])+int(i[1]))
# Print the final string
print(tot)

rawDescription: How to split integer and sum the splitted integer using python?

description: Split integer and sum the splitted integer using python


code:
class Foo:
    @property
    def current_time(self):
            from datetime import datetime
            return datetime.now()

f = Foo()
f.current_time
f.current_time

rawDescription: Python : How to call dictionnary-contained callables at a given time?


code:
for i, sublist in enumerate(lst):
    for j, elem in enumerate(sublist):
        sublist[j] = 3*(i+1)*(j+1)

rawDescription: positions in a list. python

description: Positions in a list. python


code:
import sys
sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.7/python/site-packages')

import py2neo

rawDescription: Cannot import 3rd party packages

description: Cannot import 3rd party packages


code:
for p in my_polynomials:
    do_something_with_polynomial(p)

rawDescription: Generate all possible polynomial combinations


code:
import trace

def trapy(arg):
    tracer = trace.Trace()
    tracer.run(arg)
    r = tracer.results()
    r.write_results()

if __name__ == '__main__':
    import module_name
    trapy('module_name.function_name()')

rawDescription: Program for Python that traces back code of a function call or instantiation and nicely prints it all out


code:
import pandas as pd
import numpy as np
df = pd.DataFrame( data=np.arange(10), index=pd.date_range( '2014/1/1', periods=10, freq='D' ) )
ax = df.plot( kind='bar')
ax.set_xticklabels(df.index.format())

rawDescription: Remove the default 00:00:00 time in daily bar plots?


code:
[d.setdefault(j, [sum(d[len(d)-1][max(i, 0):i + 2]) for i in range(-1, j)])
 for j, d in enumerate([{0: [1]}] * 5)]

rawDescription: Pascal's Triangle with iterative algorithm via list comprehension in Python


code:
class Impl(Base):
    @ClassProperty
    @classmethod
    def foo(cls):
        return 5

In [11]: Impl.foo
Out[11]: 5

rawDescription: How can I combine abc.abstractproperty with a classmethod to make an "abstract class property"?

description: Combine abc.abstractproperty with a classmethod to make an "abstract class property"


code:
#!/usr/bin/env python

from threading import Thread
import time
from gimpfu import *

def scale_image(scale):
    pdb.gimp_progress_init("Scaling Image...",None)
    time.sleep(0.5)
    thread = Thread(target = thread_scale_image, args = (scale, ))
    thread.start()
    thread.join()
pass

def thread_scale_image(scale):
    image = gimp.image_list()[0]
    w = image.width
    h = image.height
    pdb.gimp_context_set_interpolation(INTERPOLATION_LANCZOS)
    pdb.gimp_image_scale(image, w/scale, h/scale)
pass

register(
         "jeanluc_scale_image",
         "Scale Image",
         "Scale Image",
         "JeanLuc",
         "JeanLuc",
         "2015",
         "Scale Image...",
         "RGB*",
         [
          (PF_INT, "scale", "Scale of Image", 4)
          ],
         [],
         scale_image,
         menu="<Image>/JeanLuc"
)

main()

rawDescription: Scaling an image with python-fu in GIMP slower then via built-in GUI


code:
import pandas as pd
import numpy as np

N = 100
df = pd.DataFrame(
    {'date': pd.date_range('2000-1-1', periods=N, freq='H'),
     'value': np.random.random(N)})

index = pd.DatetimeIndex(df['date'])
df.iloc[index.indexer_between_time('8:00','21:00')]

rawDescription: Pandas filtering - between_time on a non-index column


code:
message = 'ROAD#WAY'
encrypted = ''

for x in message:
    if cipher_dict.get(x):
        encrypted += cipher_dict[x]

print(encrypted)

rawDescription: How do i encrypt with my dictionary

description: Encrypt with my dictionary


code:
user_input = ""
while user_input != "good bye":
   user_input = input(":")
   if user_input == "hello":
       print("Hello.")
   elif user_input == "how are you":
       print("Good, i don't feel much. You know, I'm an AI.")
   else :
      print("Say something I understand")
print("Bye!")

rawDescription: How can i make my python3 code do many "if input" operations at once

description: Make my python3 code do many "if input" operations at once


rawDescription: Python regex extract strings between <>

description: Python regex extract strings between <>


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

x = np.arange(10)
y = np.power(x, 3)

plt.plot(x, y, 'ro')

# Create a 5% (0.05) and 10% (0.1) padding in the
# x and y directions respectively.
plt.margins(0.05, 0.1)

plt.show()

rawDescription: Create padding within plot

description: Create padding within plot


code:
def get_clients(request):
    if request.method == 'GET':
        ccId = request.GET['ccId']
    elif request.method == 'POST':
        ccId = request.POST['ccId']

    lstClients = Patients.objects.filter(cr=ccId)
    data = serializers.serialize("json", lstClients, fields=('tel',))
    return http.HttpResponse(json.dumps(data), mimetype='application/javascript')

rawDescription: Input parameter in Django method

description: Input parameter in Django method


code:
def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

arr2 = numpy.append(1-arr, [0]*7)
numpy.power.at(rolling_window(arr2[1:], 7), np.arange(len(arr)), arr2[:-7, None])
arr = 1 - arr2[:-7]

rawDescription: Modifying numpy array to get minimum number of values between elements


code:
dictionary1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dictionary2 = {'value1': 'AAA', 'value3': 'CCC'}
{k: dictionary2.get(v, v) for k, v in dictionary1.items()}

rawDescription: Replacing the value of a Python dictionary with the value of another dictionary that matches the other dictionaries key


code:
input = "POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))"

def polygon_to_points(polygon):
  geometry = polygon[10:-2]
  coordinates = geometry.split(', ')
  coord_pairs = []
  for c in coordinates:
    pair = c.split(' ')
    pair_num = [float(pair[0]), float(pair[1])]
    coord_pairs.append(pair_num)
  return coord_pairs

rawDescription: Are there python libraries with spatial support for mySQL?


rawDescription: Reshape 1D numpy array to 3D with x,y,z ordering


code:
import operator, random

ops = [operator.add, operator.sub]
print(random.choice(ops)(10, 5))

rawDescription: using an operator to add in python

description: Using an operator to add in python


code:
if vartogetip is not None:
    matches = []
    for line in open(filename, 'r'):
        ip, name = json.loads(line)[:2]
        if ip == vartogetip and name != targettotrack:
            matches.append(name)

    if matches:  # matches have been found, the list is not empty
        sendtochat("I found {} with the same ip".format(', '.join(matches)))

rawDescription: Find and list items from different lists from a file in python


code:
df = pd.DataFrame({"A": np.arange(500), "B": np.arange(500.0)})
df.loc[321, "A"] = "Fred"
df.loc[325, "B"] = True
weird = (df.applymap(type) != df.iloc[0].apply(type)).any(axis=1)
df[weird]

rawDescription: What's a good strategy to find mixed types in Pandas columns?


code:
def narcissist(func):
    def wrapper(self,*args,**kwargs):
        return func(*args,**kwargs)
    return wrapper

def identity(func):
    return func

if platform_1:
    modify_args=identity
else:
    modify_args=narcissist

@modify_args
def func(this,that):
    func_body

rawDescription: python: two versions of def depending on setting

description: Python: two versions of def depending on setting


code:
if __name__ == "__main__":
    # call your code here
    main()

rawDescription: Python script doesn't work with double click


code:
class DiscountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Discount
        fields = ('discount_description', 'discount_start', 'discount_end', 'discount_title', 'discount_category', 'discount_store')
        depth = 1

rawDescription: Django rest_framework serializer with inner relationship


code:
s = "string"
map(ord, s)

rawDescription: How to find the ascii values of the characters in string?

description: Find the ascii values of the characters in string


caption: SublimeREPL

mnemonic: r

caption: Python

caption: Python - Canopy

mnemonic: p

type: subprocess

external_id: python

caption: Python - IPython - Canopy

SUBLIMEREPL_EDITOR: $editor

rawDescription: Sublime Text 3 its not using default python


code:
import pkg_resources
env = pkg_resources.Environment()
env['sqlalchemy-migrate'][0].version

rawDescription: Check version of Python library that doesn't define __version__


code:
import select

connections = []

while True:
    rlist,wlist,xlist = select.select(connections + [s],[],[])
    for i in rlist:
        if i == s:
            conn,addr = s.accept()
            connections.append(conn)
            continue
        data = i.recv(1024)
        for q in connections:
            if q != i and q != s:
                q.send(data)

rawDescription: How can I identify two different connections to sockets using python?

description: Identify two different connections to sockets using python


code:
body = render_template('sometemplate', somevar=somevalue)
return (body, 200, {'Refresh': '1;url=destination'})

rawDescription: php header('Refresh: 1;url=destination'); in Flask + python?

description: Php header('Refresh: 1;url=destination'); in Flask + python


code:
i = 2;
while i <= num:
    program()
    i = i + 1

rawDescription: Looping a code a certain amount of times


code:
text = 'Reading my book... hate it... The childs is good read. This is funny.'
import re
re.sub(r'(?<!\.)\.(?!\.)', r' .', text)  # Replace the matched dot with ` .`

rawDescription: Python regex put space infront of non-repeating period


code:
def get(self, request):
    if request.user.is_authenticated():
        # If a user is logged in, redirect them to a page informing them of such
        return render(request, 'users/already_logged_in.html')
    else:
        return super(RegisterView, self).get(request)

rawDescription: Django: Check if a user is logged in before allowing them to register?


rawDescription: Does Python have a built-in function for unindenting a multiline string?


code:
import re
data_file = open("multitest.fas","r")
data=data_file.read()
org=re.findall(r'>(\w*)',data)
org
seq=[i.replace('\n','') for i in re.split(r'>\w*',data,re.DOTALL)[1:]]
seq

rawDescription: Creating lists of organism and dna sequence data from a multiple fasta file


rawDescription: Convert string that contains url querystring encoded data to normal string


code:
import csv

to_csv = [{'name':'bob','age':25,'weight':200, 'height':181},
          {'name':'jim','age':31,'weight':180}]

# find header
s = set()
for i in to_csv:
    s.update(i)
header = list(s)

with open("foo.csv", 'w') as f:
    writer = csv.writer(f)
    writer.writerow(header)
    for d in to_csv:
        writer.writerow([d.get(i, "None") for i in header])

rawDescription: Dump list of dictionaries with non-matching keys into csv file


code:
for face, neighbors in detectedFace:
    im_face = cv.GetSubRect(imcolor, face)

rawDescription: cvGetSubRect doesn't put in frame

description: CvGetSubRect doesn't put in frame


code:
from BeautifulSoup import BeautifulSoup
s = '<address>Some street address
City, State and ZIP

(123) 456-7890
</address>'
soup = BeautifulSoup(s)
soup.address.div.extract()
[e.extract() for e in soup.address.findAll('br')]
soup.address.text

rawDescription: How do I grab text in a HTML tag without getting further embedded tag text?

description: Grab text in a HTML tag without getting further embedded tag text


code:
A = np.arange(8).reshape(2,4)
B = np.arange(12).reshape(3,4)
np.einsum('ik,jk->ijk', A, B)

rawDescription: Taking a tensor product in python numpy without performing a sum


code:
import re
soup.findAll("div", {"class":re.compile("name|number")})

rawDescription: BeautifulSoup - Help me pick out divs and classes


code:
bool('not an empty string')
bool('')

rawDescription: Why does a string in Python resolve to True?


code:
re.search('<label([^>]*)>','<label title=>') # matches
re.search('<label([^>]*)>','<label>') # matches

rawDescription: Matching html tags with conditional regular expressions


code:
import graphlab
sf = graphlab.SFrame({'a': [1, 2, None, 4],
                      'b': [None, 3, 1, None]})
mask = sf['a'] == None
mask

rawDescription: Finding rows with "Not Applicable" value from a specific column from Graphlab SFrame


code:
import uuid
str(uuid.uuid4())

rawDescription: Is there any module in Python for generating random strings?


code:
from sklearn.feature_extraction import DictVectorizer

X_train_raw = [{'a': 1}, {'b': 1}, {'c': 1}]
y_train = [('first',), ('second',), ('first', 'second')]

v = DictVectorizer()
X_train = v.fit_transform(X_train_raw)

clf = OneVsRestClassifier(MultinomialNB())
clf.fit(X_train, y_train)

rawDescription: Using scikit-learn classifier inside nltk, multiclass case


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

fig = plt.figure()

list_date = ['2015', '2016', '2017']

data_dict_A = {'2015': {1: 254, 2:567, 3:786},
             '2016':{1:567, 2:189, 3:145},
             '2017': {1:89, 2:123, 3:190}}
data_dict_B = {'2015': {1: 154, 2:597, 3:286},
             '2016':{1:967, 2:789, 3:345},
             '2017': {1:189, 2:223, 3:290}}
data_dict_C = {'2015': {1: 354, 2:591, 3:486},
             '2016':{1:267, 2:289, 3:367},
             '2017': {1:489, 2:256, 3:390}}

length = np.arange(1, 4, 1)
width = 0.2

for each_date in list_date:
    ax = fig.add_subplot(111)

    for d_A, v_A in data_dict_A.items():
        if d_A == each_date:
            graph_A = plt.bar(length-0.2, v_A.values(), width, color="blue", align='center')

    for d_B, v_B in data_dict_B.items():
        if d_B == each_date:
            graph_B = plt.bar(length, v_B.values(), width, color="red", align='center')

    for d_C, v_C in data_dict_C.items():
        if d_C == each_date:
            graph_C = plt.bar(length+0.2, v_C.values(), width, color="yellow", align='center')

    plt.legend((graph_A[0], graph_B[0], graph_C[0]), ('A', 'B', 'C'), loc='best')
    plt.title(str(each_date))
    fig.savefig( str(each_date) +'.png')
    fig.clf()

rawDescription: overlay bar chart, loops takes too long

description: Overlay bar chart, loops takes too long


code:
def poly(x, roots):
    poly = 1
    for r in roots:
        poly *= (x - r)

    return poly

# EXAMPLE
x = 1
roots = [2, 5, 7]
print ( poly(x, roots) )

rawDescription: Compute a polynomial via a product using Python


code:
def add_new(request):
        product_id = Products.objects.get(code=code).id
        x = request.POST.getlist('location_id')
        y = request.POST.getlist('location_stock')
        zipped = zip(x, y)
        for x, y in zipped:
            z = Product_stocks(product_id=product_id,warehouse_id=x,stock=y)
            z.save()
        response_data = {}
        response_data['status'] = 'true'
        response_data['message'] = 'success'
        return HttpResponse(json.dumps(response_data), mimetype='application/javascript')

rawDescription: Django same name multiple input insert to DB


code:
df['multiplied'] = df[df != 0].prod(axis=1)
df

rawDescription: How to selectively multiply or add columns in pandas DataFrame?

description: Selectively multiply or add columns in pandas DataFrame


code:
from Tkinter import *
r = Tk()
r.clipboard_append("hello")
r.mainloop()

rawDescription: Unable to append to clipboard

description: Unable to append to clipboard


code:
[
['no change', 'no change', 'no change'], #This is the 'table header' row
['pass', 'pass', 'pass'], #This is the first row that is actually tested
['pass', 'pass', 'pass'] #This is the second row that is tested
]

rawDescription: FitNesse/Waferslim Tabletable with multiple rows