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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

dim = 10

X, Y = np.meshgrid([-dim, dim], [-dim, dim])
Z = np.zeros((2, 2))

angle = .5
X2, Y2 = np.meshgrid([-dim, dim], [0, dim])
Z2 = Y2 * angle
X3, Y3 = np.meshgrid([-dim, dim], [-dim, 0])
Z3 = Y3 * angle

r = 7
M = 1000
th = np.linspace(0, 2 * np.pi, M)

x, y, z = r * np.cos(th),  r * np.sin(th), angle * r * np.sin(th)

ax.plot_surface(X2, Y3, Z3, color='blue', alpha=.5, linewidth=0, zorder=-1)

ax.plot(x[y < 0], y[y < 0], z[y < 0], lw=5, linestyle='--', color='green',
        zorder=0)

ax.plot_surface(X, Y, Z, color='red', alpha=.5, linewidth=0, zorder=1)

ax.plot(r * np.sin(th), r * np.cos(th), np.zeros(M), lw=5, linestyle='--',
        color='k', zorder=2)

ax.plot_surface(X2, Y2, Z2, color='blue', alpha=.5, linewidth=0, zorder=3)

ax.plot(x[y > 0], y[y > 0], z[y > 0], lw=5, linestyle='--', color='green',
        zorder=4)

plt.axis('off')
plt.show()

rawDescription: How to draw intersecting planes?

description: Draw intersecting planes


code:
for _ in ("boto", "elasticsearch", "urllib3"):
    logging.getLogger(_).setLevel(logging.CRITICAL)

rawDescription: How to disable loggers from other modules?

description: Disable loggers from other modules


code:
class Storage(object):

    def __init__(self):
        super(Storage, self).__init__()
        data = {}

    def fill_1(self):
        data['solo'] = 'all alone'
        return self

    def fill_2(self, buddy, bff):
        data['buddy'] = buddy
        data['bff'] = bff
        return self

    def fill_3(self, that_guy, house):
        data[that_guy] = house
        return self

box = Storage().fill_1()

rawDescription: Use an object method with the Initializer (Same line)


rawDescription: How to use Pandas rolling_* functions on a forward-looking basis

description: Use Pandas rolling_* functions on a forward-looking basis


code:
class TestCreateAuth(unittest.TestCase):
    @mock.patch('getpass.getpass')
    @mock.patch('getpass.getuser')
    def test_create_auth(self, getuser, getpw):
        getuser.return_value = 'user'
        getpw.return_value = 'pass'
        self.assertEqual(create_auth(), 'user:pass')

rawDescription: testing a function which takes input from user (python)

description: Testing a function which takes input from user (python)


code:
while True:
  c = socket.recv(4096)
  if c == '': break # no more data
  readbuffer = readbuffer + c.decode("UTF-8")
  ...

rawDescription: How to detect disconnection in python, without sending data

description: Detect disconnection in python, without sending data


code:
from datetime import datetime, timedelta
start_time = datetime.now()
start_time
first = start_time.replace(minute=0, second=0, microsecond=0)+timedelta(hours=1)
first

rawDescription: Python get whole hour values between 2 datetime objects


code:
import math
from PIL import Image

def arrangeImagesInCircle(masterImage, imagesToArrange):
    imgWidth, imgHeight = masterImage.size

    #we want the circle to be as large as possible.
    #but the circle shouldn't extend all the way to the edge of the image.
    #If we do that, then when we paste images onto the circle, those images will partially fall over the edge.
    #so we reduce the diameter of the circle by the width/height of the widest/tallest image.
    diameter = min(
        imgWidth  - max(img.size[0] for img in imagesToArrange),
        imgHeight - max(img.size[1] for img in imagesToArrange)
    )
    radius = diameter / 2

    circleCenterX = imgWidth  / 2
    circleCenterY = imgHeight / 2
    theta = 2*math.pi / len(imagesToArrange)
    for i, curImg in enumerate(imagesToArrange):
        angle = i * theta
        dx = int(radius * math.cos(angle))
        dy = int(radius * math.sin(angle))

        #dx and dy give the coordinates of where the center of our images would go.
        #so we must subtract half the height/width of the image to find where their top-left corners should be.
        pos = (
            circleCenterX + dx - curImg.size[0]/2,
            circleCenterY + dy - curImg.size[1]/2
        )
        masterImage.paste(curImg, pos)

img = Image.new("RGB", (500,500), (255,255,255))

#red.png, blue.png, green.png are simple 50x50 pngs of solid color
imageFilenames = ["red.png", "blue.png", "green.png"] * 5
images = [Image.open(filename) for filename in imageFilenames]

arrangeImagesInCircle(img, images)

img.save("output.png")

rawDescription: python arrange images on canvas in a circle

description: Python arrange images on canvas in a circle


code:
import subprocess
p = subprocess.Popen("ls", shell=True)
p.pid

rawDescription: mount command pid

description: Mount command pid


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel1 = wx.Panel(self)
        self.panel1.SetBackgroundColour(wx.GREEN)
        self.panel2 = wx.Panel(self)
        self.panel2.SetBackgroundColour(wx.RED)
        self.panel3 = wx.Panel(self)
        self.panel3.SetBackgroundColour(wx.WHITE)

        self.sizer1 = wx.BoxSizer()
        self.sizer2 = wx.BoxSizer(wx.VERTICAL)
        self.sizer1.Add(self.panel1, proportion=1, flag=wx.EXPAND)
        self.sizer1.Add(self.panel2, proportion=1, flag=wx.EXPAND)
        self.sizer2.Add(self.panel3, proportion=1, flag=wx.EXPAND)
        self.sizer2.Add(self.sizer1, proportion=0, flag=wx.EXPAND)

        self.SetSizerAndFit(self.sizer2)
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: wxpython: Prevent horizontal growth of specific fields

description: Wxpython: Prevent horizontal growth of specific fields


code:
import xml.dom.minidom

def getParentObjectNode(node):
    while node.parentNode:
        node = node.parentNode
        if node.nodeName == "Object":
            return node

xml = xml.dom.minidom.parse("C:\\myxml.xml")
for shirtNode in xml.getElementsByTagName("Object"):
    if shirtNode.getAttribute("label") == "shirt":
        break

shirtParentObject = getParentObjectNode(shirtNode)
print(shirtParentObject.getAttribute("label"))
shirtParentParentObject = getParentObjectNode(shirtParentObject)
print(shirtParentParentObject.getAttribute("label"))

rawDescription: xml python parsing get parent node name : minidom

description: Xml python parsing get parent node name : minidom


code:
import wx

def scale_bitmap(bitmap, width, height):
    image = wx.ImageFromBitmap(bitmap)
    image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
    result = wx.BitmapFromImage(image)
    return result

class Panel(wx.Panel):
    def __init__(self, parent, path):
        super(Panel, self).__init__(parent, -1)
        bitmap = wx.Bitmap(path)
        bitmap = scale_bitmap(bitmap, 300, 200)
        control = wx.StaticBitmap(self, -1, bitmap)
        control.SetPosition((10, 10))

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = wx.Frame(None, -1, 'Scaled Image')
    panel = Panel(frame, 'input.jpg')
    frame.Show()
    app.MainLoop()

rawDescription: How to resize and draw an image using wxpython?

description: Resize and draw an image using wxpython


code:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

np.random.seed(0)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0,1,size=10)))
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(10,20,size=10)),color='r')

# ADD THIS LINE
ax2.set_yticks(np.linspace(ax2.get_yticks()[0],ax2.get_yticks()[-1],len(ax1.get_yticks())))

plt.show()

rawDescription: matplotlib: two y-axis scales, how to align gridlines?

description: Matplotlib: two y-axis scales, how to align gridlines


code: foundItems = [elem for elem in results if 'type_two' in elem['types']]

rawDescription: Pythonic way of filtering by descendant element in a dictionary


code:
def wait_for_prompt(session, prompt, timeout=1):
    gotprompt = 0
    while not gotprompt:
        session.expect(prompt, timeout=None)
        gotprompt = session.expect([".", pexpect.TIMEOUT], timeout=timeout)

child = pexpect.spawn("ssh ...")
wait_for_prompt(child, "[#>]")

rawDescription: Can pexpect be told to ignore a pattern or signal?


code:
from lxml import html

tree = html.fromstring('<html>Your HTML code</html>')
rows = tree.xpath('//table/tr') #update your table XPath here
records = []
for row in rows:
    cells = [c for c in row.xpath('./td/text()') if c.strip()]
    # do something with cells content

rawDescription: python extract values from an html table

description: Python extract values from an html table


code:
content = get_object_or_404(Content, pk=content_id)
criteria = content.criteria_set.all()
user_ratings = ContRate.objects.filter(content=content, user=request.user)
ratings_dict = dict((c.crit_id, c.rate) for c in user_ratings)
for crit in criteria:
    crit.user_rating = ratings_dict.get(crit.id)

rawDescription: Django - Rating System View & Template

description: Django - Rating System View & Template


code:
class MyModelViewSet(viewsets.ModelViewSet):

    def list(self, request, *args, **kwargs):
        response = super(MyModelViewSet, self).list(request, *args, **kwargs) # call the original 'list'
        response.data = {"site": response.data} # customize the response data
        return response # return response with this custom representation

rawDescription: Return dictionary instead of array in REST framework


code:
from datetime import timedelta

date = datetime.datetime.now() - datetime.timedelta(minutes=10)
docs = db.collection.find(
    {
        'processed': 0,
        '$or': [
            {'process_lock_date': {'$lt': date}},
            {'process_lock_date': null}
        ]
    }).sort({'date_added': 1}).limit(50)

for doc in docs:
    print(doc)

rawDescription: How to properly write this query

description: Properly write this query


code:
import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# run the new command using the given tracer
tracer.run('main()')

# make a report, placing output in /tmp
r = tracer.results()
r.write_results(show_missing=True, coverdir="/tmp")

rawDescription: Method logging in Python

description: Method logging in Python


code:
import time
from gi.repository import Notify

Notify.init('myapp')

# optionally set an icon as the last argument
n = Notify.Notification.new('summary text', 'body text', "dialog-information")
n.show()

# do whatever your application is doing
time.sleep(10)

n.close()
Notify.uninit()

rawDescription: Sending notifications with GObjects

description: Sending notifications with GObjects


code:
parser = argparse.ArgumentParser()
parser.add_argument('--foo', metavar='YYY')
parser.add_argument('bar', metavar='XXX')
parser.parse_args('X --foo Y'.split())
parser.print_help()

rawDescription: is it possible to change display text of argparse argument name

description: Is it possible to change display text of argparse argument name


code:
import dbf

table = dbf.Table('big.dbf')
index = table.create_index(lambda rec: rec.field) # field should be actual field name

records = index.search(match=('value',))

rawDescription: Python: Fast querying in a big dbf (xbase) file


code: df.dropna(thresh=(len(df) - 7), axis=1)

rawDescription: Pandas - Delete Rows with only NaN values


code:
import numpy as np

def is_pos_def(x):
    return np.all(np.linalg.eigvals(x) > 0)

rawDescription: Find out if matrix is positive definite with numpy


rawDescription: How to combine array lists gets in python?

description: Combine array lists gets in python


code:
titanic = pd.read_csv('titanic_data.csv')
survival_by_age = titanic.groupby(['Age', 'Survived']).size().unstack('Survived')
survival_by_age.columns = ['No', 'Yes']
survival_by_age.plot.bar(title='Survival by Age')

rawDescription: How to create histogram from grouped data

description: Create histogram from grouped data


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(columns = ["id0", "id1", "id2"])
df.loc[2012]= [24, 25, 26]
df.loc[2013]= [28, 28, 29]
df.loc[2014]= [30, 31, 32]

df.columns = pd.MultiIndex.from_arrays([df.columns, [66,67,68], [110,111,112]],
                                       names=['id','lat','lon'])

ids = df.columns.get_level_values('id')
id_ = 'id0'
column_position = np.where(ids.values == id_)

new_lat = 90
new_lon = 0

df.columns._levels[1].values[column_position] = new_lat
df.columns._levels[2].values[column_position] = new_lon

rawDescription: How do I change or access pandas MultiIndex column headers?

description: Change or access pandas MultiIndex column headers


code:
import pandas as pd
#Considering that you have your data in a file called 'stock.txt'
#and it is tab separated, by default the blank lines are not read by read_csv,
#hence set the header=1
df = pd.read_csv('stock.txt', sep='\t',header=1)
#Rename the columns as required
df.columns= ['CompanyName', 'ASXCode', 'GICS']
#Reorder the columns as required
df = df[['ASXCode','CompanyName','GICS']]

rawDescription: renaming the header when using dictreader

description: Renaming the header when using dictreader


code:
from Tkinter import *
import tkFont

class DpWin(object):
    def run(self):
        root=Tk()
        root.geometry('768x612')
        title='dp'
        root.title(title)

        f = Frame(root)
        f.pack()

        xscrollbar = Scrollbar(f, orient=HORIZONTAL)
        xscrollbar.grid(row=1, column=0, sticky=N+S+E+W)

        yscrollbar = Scrollbar(f)
        yscrollbar.grid(row=0, column=1, sticky=N+S+E+W)

        text = Text(f, wrap=NONE,
                    xscrollcommand=xscrollbar.set,
                    yscrollcommand=yscrollbar.set)
        text.grid(row=0, column=0)

        xscrollbar.config(command=text.xview)
        yscrollbar.config(command=text.yview)
        text.insert(END, 'a'*999)
        mainloop()

    def start(self):
        self.b_start.config(state=DISABLED)
        self.b_stop.config(state=ACTIVE)

    def stop(self):
        self.b_stop.config(state=DISABLED)
        self.b_start.config(state=ACTIVE)

if __name__=='__main__':
    win=DpWin()
    win.run()

rawDescription: The horizontal scrollbar didn't work in Tkinter


code:
from azure.storage import QueueService
import base64
queue_service = QueueService(account_name, account_key)
queue_service.put_message('taskqueue', base64.b64encode('Hello world!'))

rawDescription: Putting message into azure queue

description: Putting message into azure queue


rawDescription: Itertools way to reverse mapping?

description: Itertools way to reverse mapping


code:
from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6373.0

lat1 = radians(52.2296756)
lon1 = radians(21.0122287)
lat2 = radians(52.406374)
lon2 = radians(16.9251681)

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)
print("Should be:", 278.546, "km")

rawDescription: Getting distance between two points based on latitude/longitude [python]


code:
Actual = [1, 1, 2, 3, 1]
Predicted = [1, 1, 1, 3, 3]
output = [a == p for a,p in zip(Actual,Predicted) if p==1]
output

rawDescription: How to compare two arrays in python, and get the boolean output based on a significant value

description: Compare two arrays in python, and get the boolean output based on a significant value


rawDescription: How to + the values in two lists of tuples

description: + the values in two lists of tuples


code:
while True:
    if os.path.isdir("dir_path"):
        break
    time.sleep(5)

rawDescription: How to wait till a directory exist in Python (Ubuntu)

description: Wait till a directory exist in Python (Ubuntu)


rawDescription: Slice np.array, rankdata and return ranks to parent of slice


code:
p = subprocess.Popen(call, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
for line in iter(p.stdout.readline, ''):
    print(line, end='')

rawDescription: Python 2 to 3 conversion: iterating over lines in subprocess stdout


code:
sentence = raw_input()
number = int(raw_input())
print(sentence * number)

rawDescription: Simple Python concatenation question

description: Simple Python concatenation question


code:
numbers = [
'Zero',
'One',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten' ]

text_one = 'green bottles hanging on the wall'
text_two = 'And if one green bottle should accidentally fall\nThere\'ll be'

# Each iteration of this loop prints one verse of the song
for i in range(10, 0, -1):
    print(numbers[i], text_one)
    print(numbers[i], text_one)
    print(text_two, numbers[i-1], text_one)

rawDescription: Please help a person new to python (3x)

description: Please help a person new to python (3x)


code:
from collections import Counter
import re

a = raw_input("Haystack ")
b = raw_input("Needle ")

reg = re.compile(b)
c = Counter(word.group() for word in reg.finditer(a))
print(c)

rawDescription: Python not overlapping letters

description: Python not overlapping letters


code:
@pytest.mark.parametrize('args,expected', [
    ([], expVal0),
    ([key, "city", 0], expVal1),
    ([key, 'contact_no', 2, {}, policy], expVal2)
    ([key, "contact_no", 0], expVal3)
    ([key, "contact_no", 1, {}, policy, ""], expVal4)
    ([key, "contact_no", 0, 888], expVal5)
])
def test_list_get(args, expected):
    assert list_get(*args) == expected

rawDescription: How to write a test for a function with optional arguments

description: Write a test for a function with optional arguments


code:
FORM_DATA = {
    '__EVENTTARGET': '',
    '__EVENTARGUMENT': '',
    '__VIEWSTATE': '/wEPDwUKMTA5NTA5ODU1MQ9kFgJmD2QWAgIGDxBkDxYFZgIBAgICAwIEF***REMAINDER REMOVED***',
    '__EVENTVALIDATION': '/wEdAAp4d3BHvSTs+Kv6cxGP3xEbBr8xrgRYad2tj4YCyRIw5qUAjimf****REMAINDER REMOVED****',
    'jsCheck': '',
    'ddlEngine': 'REMOVED:13008',
    'Username': uname,
    'Password': passw,
    'btnLogin.x': '42',
    'btnLogin.y': '9',
    'btnLogin': 'Login',
}

rawDescription: Python Requests - Inserting credentials as variables in FORM_DATA


code:
import csv

input_filename = 'input.csv'
output_filename = 'output.csv'

# Instantiate a CSV reader, check if you have the appropriate delimiter
reader = csv.reader(open(input_filename), delimiter=',')

# Get the first row (assuming this row contains the header)
input_header = reader.next()

# Filter out the columns that you want to keep by storing the column
# index
columns_to_keep = []
for i, name in enumerate(input_header):
    if 'net' in name:
        columns_to_keep.append(i)

# Create a CSV writer to store the columns you want to keep
writer = csv.writer(open(output_filename, 'w'), delimiter=',')

# Construct the header of the output file
output_header = []
for column_index in columns_to_keep:
    output_header.append(input_header[column_index])

# Write the header to the output file
writer.writerow(output_header)

# Iterate of the remainder of the input file, construct a row
# with columns you want to keep and write this row to the output file
for row in reader:
    new_row = []
    for column_index in columns_to_keep:
        new_row.append(row[column_index])
    writer.writerow(new_row)

rawDescription: Extracting columns containing a certain name


code:
import sys

if sys.version_info.major > 2:
    xrange = range

rawDescription: Best way to write Python 2 and 3 compatible code using nothing but the standard library

description: Write Python 2 and 3 compatible code using nothing but the standard library


code:
tokens = []
for linea in f.readlines():
    line_content = linea.split(' ')
    for token in line_content:
        tokens.append(token)
print(tokens)

rawDescription: Read a file by words in Python

description: Read a file by words in Python


code:
from fractions import Fraction
from decimal import localcontext, Decimal

def print_fraction(f, digits):
    assert(f.imag == 0)

    # Automatically reset the Decimal settings
    with localcontext() as ctx:
        ctx.prec = digits
        print(Decimal(f.numerator) / Decimal(f.denominator))

f = Fraction(5, 7)
print_fraction(f, 52)

rawDescription: How to write Fraction as decimal with x DPs in Python?

description: Write Fraction as decimal with x DPs in Python


code:
class Gallery(models.Model):
    head_image = models.ImageField(upload_to="gallery")

class Image(models.Model):
    image = models.ImageField(upload_to="gallery")
    gallery = models.ForeignKey(Gallery, related_name='images')

class Tour(Gallery):
    ...

rawDescription: change a combobox of images to a formset of inputfile

description: Change a combobox of images to a formset of inputfile


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

G = nx.DiGraph()

G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3)])

nx.draw(G,with_labels=True)
plt.savefig("graph.png")
plt.show()

rawDescription: How to show node name in graphs using networkx?

description: Show node name in graphs using networkx


code:
pyrax.cloudservers.servers.delete_meta(server, list_of_keys)
pyrax.cloudservers.servers.set_meta(server, key_value_dict)

rawDescription: Set Rackspace CloudServer Metadata with pyrax


rawDescription: How to select only specific columns from a DataFrame with MultiIndex columns?

description: Select only specific columns from a DataFrame with MultiIndex columns


code:
import json
import requests
from collections import OrderedDict

result = requests.get('http://www.dota2.com/jsfeed/heropediadata?feeds=abilitydata&l=english')
data = json.loads(result.text, object_pairs_hook = OrderedDict)

rawDescription: JSON keys are shuffled in Python

description: JSON keys are shuffled in Python


code: bt1.place(relx=1.0, y=0, anchor="ne")

rawDescription: how can I use the Button widget in python to place buttons in specific places on the screen?

description: Use the Button widget in python to place buttons in specific places on the screen


code:
def make_counter():
    i = 0
    def counter(): # counter() is a closure
        nonlocal i
        i += 1
        return i
    return counter

c1 = make_counter()
c2 = make_counter()

print (c1(), c1(), c2(), c2())
# -> 1 2 1 2

rawDescription: Can you explain closures (as they relate to Python)?

description: Explain closures (as they relate to Python)


rawDescription: The most pythonic way to slice a Python list every 100 elements


rawDescription: Translate Matlab code to Python

description: Translate Matlab code to Python


code:
import math
from PIL import Image, ImageDraw

#finds the straight-line distance between two points
def distance(ax, ay, bx, by):
    return math.sqrt((by - ay)**2 + (bx - ax)**2)

#rotates point `A` about point `B` by `angle` radians clockwise.
def rotated_about(ax, ay, bx, by, angle):
    radius = distance(ax,ay,bx,by)
    angle += math.atan2(ay-by, ax-bx)
    return (
        round(bx + radius * math.cos(angle)),
        round(by + radius * math.sin(angle))
    )

image = Image.new('L', (100, 100), 127)
draw = ImageDraw.Draw(image)

square_center = (50,50)
square_length = 40

square_vertices = (
    (square_center[0] + square_length / 2, square_center[1] + square_length / 2),
    (square_center[0] + square_length / 2, square_center[1] - square_length / 2),
    (square_center[0] - square_length / 2, square_center[1] - square_length / 2),
    (square_center[0] - square_length / 2, square_center[1] + square_length / 2)
)

square_vertices = [rotated_about(x,y, square_center[0], square_center[1], math.radians(45)) for x,y in square_vertices]

draw.polygon(square_vertices, fill=255)

image.save("output.png")

rawDescription: Rotating a square in PIL

description: Rotating a square in PIL


code:
from multiprocessing import Process
import subprocess

def run_shell(command):
    p = subprocess.Popen(command)
    p.communicate()

# Array of processes
opencv_array = [
    'opencv_haartraining -data data -vec mil.vec ...',
    'opencv_haartraining -data data -vec mil.vec ...',
]

def multiprocessing_on():
    tasks = []
    for command in opencv_array:
        task = Process(target=run_shell, args=(command,))
        task.start()
        tasks.append(task)

    # Wait for all done
    for task in tasks:
        task.join()

multiprocessing_on()

rawDescription: Python multiprocessing

description: Python multiprocessing


code:
import random, hashlib
from string import ascii_letters

salt= ''.join(random.shuffle(ascii_letters))
hash=hashlib.sha512(salt+':'+password).hexdigest()

rawDescription: Security of hashing a string using unique key in python


code:
from itertools import chain

A_1 = [1, 2, 3, 4]
A_2 = [3, 4, 5, 6]
A_3 = [3, 4, 7, 8]

# Collect the input lists for use with chain below
all_lists = [A_1, A_2, A_3]

for A in (A_1, A_2, A_3):
  # Combine all the lists into one
  super_list = list(chain(*all_lists))
  # Remove the items from the list under consideration
  for x in A:
    super_list.remove(x)
  # Get the unique items remaining in the combined list
  super_set = set(super_list)
  # Compute the unique items in this list and print them
  uniques = set(A) - super_set
  print(sorted(uniques))

rawDescription: Unique features between multiple lists

description: Unique features between multiple lists


code:
b_li = set()
output_list = []
b_li_add = b_li.add
output_list_append = output_list.append
for x in li:
    s = (x[0], x[2])
    if s not in b_li:
        b_li_add(s)
        output_list_append(x)

rawDescription: Removing the lists from a list which are duplicated for some items


code:
from pprint import pprint
from inspect import getmembers

class X:
    def __init__(self, x, y):
        self.x = x
        self.y = y

x = X([42] * 5, [True] * 15)

pprint(getmembers(x))
pprint(vars(x))

rawDescription: How to inspect Python objects in similar way like JS objects in Chrome dev console?

description: Inspect Python objects in similar way like JS objects in Chrome dev console


code:
idx = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1), ('b', 2)])
s = pd.Series(np.random.uniform(size=4), index=idx)
s  # This is what you have
s.unstack()  # This is what you want
group = vincent.GroupedBar(s.unstack())
group.display()

rawDescription: how to plot pandas groupby result using vincent

description: Plot pandas groupby result using vincent


code:
seq="MED"
["".join(x) for x in product(*(d[y] for y in seq))]

rawDescription: How to retrieve all possible combinations given a sequence of keys from a dictionary with list values

description: Retrieve all possible combinations given a sequence of keys from a dictionary with list values


code:
try:
    from local_settings import *
except ImportError:
    pass

rawDescription: Can I force Django staticfiles to load hashed filenames locally while Debug=True?

description: Force Django staticfiles to load hashed filenames locally while Debug=True


code:
def practice(request):
    world = get_world_too()

    for entry in world:
        post = Post()
        post.title = entry['text']
        post.image_url = entry['src']
        post.save()

        template = "blog/post/noindex.html"
        context = {}

    # not in the loop anymore
    return render(request, template, context)

rawDescription: Just learned to scrape data and store it in my DB but it only scrapes one object


code:
import threading
lock = threading.Lock()

def write_to_file(f, text, file_size):
    lock.acquire() # thread blocks at this line until it can obtain lock

    # in this section, only one thread can be present at a time.
    print >> f, text, file_size

    lock.release()

def filesize(asset):
    f = open("results.txt", 'a+')
    c = wmi.WMI(asset)
    wql = 'SELECT FileSize,Name FROM CIM_DataFile where (Drive="D:" OR Drive="E:") and Caption like "%file%"'
    for item in c.query(wql):
        write_to_file(f, item.Name.split("\\")[2].strip().upper(), str(item.FileSize))

rawDescription: many threads to write log file at same time python

description: Many threads to write log file at same time python


code:
import collections
result=collections.defaultdict(list)
for n,e in zip(N,E):
    result[n].append(e)

rawDescription: Python: Store the data into two lists and then convert to a dictionary


code:
# Setup
ids = np.array([22, 5, 4, 0, 100])
targets = np.array([5, 0])

sort = np.argsort(ids)
rank = np.searchsorted(ids, targets, sorter=sort)
print(sort[rank])
# array([1, 3])

rawDescription: Find unsorted indices after using numpy.searchsorted


code:
m = np.ma.masked_array(a, mask=(a==value))
np.where(m, m==m.min())

rawDescription: Numpy: Get minimum value indices in array, ignoring specific value


code:
with open("N:\highscores.txt", "r") as scoresfile:
    scores = {name.strip(): score.strip() for line in scoresfile if ':' in line for name, score in (line.split(':'),)}

if name in scores:
    print("You have already entered a score.")
else:
    with open("N:\highscores.txt", "a") as scoresfile:
        file.write('{} : {}\n'.format(name, score))

rawDescription: if(x in y) not working in python file I/O

description: If(x in y) not working in python file I/O


code: subprocess.call("sudo" + " /sbin/iptables -L -n", shell=True)

rawDescription: Call subprocess sudo from uwsgi

description: Call subprocess sudo from uwsgi


rawDescription: basemap: How to remove actual lat/lon lines while keeping the ticks on the axis

description: Basemap: How to remove actual lat/lon lines while keeping the ticks on the axis


code:
def __rmul__(self, scalar):  # self: right operand (Vector)
    v = Vector()
    v.x = self.x * scalar
    v.y = self.y * scalar
    return v

rawDescription: Python - operator overloading in vector math


code: btn.setStyleSheet("background-image: url('image.jpg'); border: none;")

rawDescription: PyQt4: How to make Icon bigger than QPushButton? (Pixmap Buttons)


code:
import urllib2
import json

url = 'http://www.reddit.com/r/python/.json?limit=10'
jsonDownload = urllib2.urlopen(url)
jsonData = json.loads(jsonDownload.read())

rawDescription: How to read top 10 headlines from the front page of Reddit using it's API?

description: Read top 10 headlines from the front page of Reddit using it's API


code:
csrf_protect = CsrfProtect(app)
api = restful.Api(app, decorators=[csrf_protect.exempt])

rawDescription: Flask-Restful POST fails due CSRF protection of Flask-WTF


code:
a= {'bana':3, 'hello':2, 'clue':7, 'an':1,'sad':3}
b=list(a.keys())
x=sorted(list(a.values()), reverse=True)
d=[]
for i in range(len(x)):
    d.append(str(x[i])+b[i])
print(d)

rawDescription: How to remove duplicate from this?

description: Remove duplicate from this


code:
str2='hello: acb cross'
reg = re.compile('hello: (a.*?) cross')

rawDescription: Python regex does not match

description: Python regex does not match


code:
import rdfxml
import json

class Sink(object):
   def __init__(self): self.result = []
   def triple(self, s, p, o): self.result.append((s, p, o))

def rdfToPython(s, base=None):
   sink = Sink()
   return rdfxml.parseRDF(s, base=None, sink=sink).result

s_rdf = someRDFstringhere()
pyth = rdfToPython(s_rdf)
s_jsn = json.dumps(pyth)

rawDescription: RDF/XML format to JSON

description: RDF/XML format to JSON


code:
with open('words.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)

rawDescription: Reading a text file and splitting it into single words in python


code:
import time

nSeconds = 11
t0 = time.clock()
dt = 0
enemyCount = 0

# the following would be in an appropriate
# place in the main game loop
if dt < nSeconds:
    t1 = time.clock()
    dt = t1 - t0
else:
    enemyInstance = Enemy()
    enemyCount += 1
    t0 = time.clock()
    dt = 0

rawDescription: How can instances of classes be automatically generated in python?


code:
for i in xrange(1, 1746):
    file = urllib2.urlopen("http://www.example.com/photos/%04d.jpg" % i)
    ...
    # Write file locally
    ...

rawDescription: I am writing a scraper that downloads all the image files from a multiple pages across the same site and saves them to a specific folder


code:
from bottle import route, run
import scrapper

@route('/scrap')
def scrap():
    return scrapper.main()

rawDescription: How to create a web service who calls a python web scraping script?

description: Create a web service who calls a python web scraping script


code:
char_data1 = {
   "name":"steve",
   "level":1,
    "inventory":["cloak","dagger"],
    "whatever else":"something"
};

char_data2 = {
   "name":"cookie",
   "level":1,
    "inventory":["cigarettes","methamphetamine"],
    "whatever else":"something else"
};
char_data = [char_data1,char_data2]

import json
json.dump(char_data,open("character_data.dat","wb"))

char_data_loaded = json.load(open("character_data.dat"))

rawDescription: How to write my outputs to a file in python 3.3.2

description: Write my outputs to a file in python 3.3.2


code:
def getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""
    """This new implementation should work on all platforms."""
    import subprocess
    pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
    output = "".join(pipe.stdout.readlines())
    sts = pipe.returncode
    if sts is None: sts = 0
    return sts, output

rawDescription: What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python?


code:
class Episode(models.Model):
    episode_num = models.IntegerField()
    def __unicode__(self):
        return 'episode {}'.format(self.episode_num)

Episode.objects.order_by('episode_num')

rawDescription: Sorting by name in django

description: Sorting by name in django


code:
for x in range(0, 10):
    for y in range(x+1, 11):
        for z in range(y+1, 11):
            if condition:
                variable = True
                break
            #...
        if variable:
            break;
        #...

rawDescription: Several nested 'for' loops, continue to next iteration of outer loop if condition inside inner loop is true


code:
df.xs('a', level=0)
df.xs('c', level='group2')

rawDescription: Selecting rows from a Pandas dataframe with a compound (hierarchical) index


rawDescription: R equivlent of python numpy slice: [:, None, :]


code:
image = Image.open("image_file.jpg") #old image object
resized_image = image.resize([100,200],PIL.Image.ANTIALIAS)
resized_image.format = image.format # original image extension

rawDescription: why does resizing image in Pillow-python remove Image.format?

description: Why does resizing image in Pillow-python remove Image.format


rawDescription: Using Google App Enigne's Mail API for django-allauth email


code:
import numpy as np
from scipy.spatial import cKDTree

# inputs
LTU = np.genfromtxt('test.txt', delimiter=',')

coords = ((12.5, 25.5, 137),
          (13.5, 26.5, 141),
          (14.5, 25.5, 144))

# querying and interpolating
xyz = LTU[:, :3]
val = LTU[:, 3]

del LTU # attempt to clean up memory

tree = cKDTree(xyz)
dist, ind = tree.query(coords, k=2)

d1, d2 = dist.T
v1, v2 = val[ind].T
v = (d1)/(d1 + d2)*(v2 - v1) + v1

print(v)
#[ 6758.73909236  6789.16987298  6790.03575996]

rawDescription: Interpolating data from a look up table

description: Interpolating data from a look up table


code:
import logging
# the root logger is created upon the first import of the logging module

# create a file handler to add to the root logger
filehandler = logging.FileHandler(
    filename = 'test.log',
    mode = 'a',
    encoding = None,
    delay = False
)

# set the file handler's level to your desired logging level, e.g. INFO
filehandler.setLevel(logging.INFO)

# create a formatter for the file handler
formatter = logging.Formatter('%(asctime)s.%(msecs)d  [%(name)s](%(process)d): %(levelname)s: %(message)s')

# add filters if you want your handler to only handle events from specific loggers
# e.g. "main.sub.classb" or something like that. I'll leave this commented out.
# filehandler.addFilter(logging.Filter(name='root.child'))

# set the root logger's level to be at most as high as your handler's
if logging.root.level > filehandler.level:
    logging.root.setLevel = filehandler.level

# finally, add the handler to the root. after you do this, the root logger will write
# records to file.
logging.root.addHandler(filehandler)

rawDescription: Python redirecting log

description: Python redirecting log


code:
class Item(models.Model):
    ...
    # blank = True as this is handled by save method
    code = models.CharField(max_length=11, blank=True, unique=True)

    def save(self, *args, **kwargs):
        if not self.code:
            self.code = get_generated_code()
        success = False
        errors = 0
        while not success:
            try:
                super(Item, self).save(*args, **kwargs)
            except IntegrityError:
                errors += 1
                if errors > 3:
                    # tried 3 times, no dice. raise the integrity error and handle elsewhere
                    raise
                else:
                    self.code = get_generated_code()
            else:
                success = True

rawDescription: Django: Override save method to handle unique=True IntegrityError


code:
from turtle import *
startLength = int(input("Please enter the length of first side: "))
decrement = int(input("Please enter the change in length of side: "))
while startLength > decrement:
    forward(startLength)
    left(90)
    startLength = startLength - decrement
forward(startLength)

rawDescription: Side in a Square Spiral In Python (Turtle Graphics)


code:
import csv

with open(filename) as file_object:
    # skip the first two lines
    file_object.next()
    file_object.next()
    list_of_dicts = list(csv.DictReader(file_object, dialect='excel-tab'))

# list_of_dicts now will contain a list of dictionaries extracted from the file

rawDescription: Tab-delimited file into dictionary (python)


code:
import datetime
import time

SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)

def to_dict(model):
    output = {}

    for key, prop in model.properties().iteritems():
        value = getattr(model, key)

        if value is None or isinstance(value, SIMPLE_TYPES):
            output[key] = value
        elif isinstance(value, datetime.date):
            # Convert date/datetime to MILLISECONDS-since-epoch (JS "new Date()").
            ms = time.mktime(value.utctimetuple()) * 1000
            ms += getattr(value, 'microseconds', 0) / 1000
            output[key] = int(ms)
        elif isinstance(value, db.GeoPt):
            output[key] = {'lat': value.lat, 'lon': value.lon}
        elif isinstance(value, db.Model):
            output[key] = to_dict(value)
        else:
            raise ValueError('cannot encode ' + repr(prop))

    return output

rawDescription: JSON serialization of Google App Engine models


code:
def getSheetName(file_name):
    pointSheetObj = []
    import xlrd as xl
    TeamPointWorkbook = xl.open_workbook(file_name)
    pointSheets = TeamPointWorkbook.sheet_names()

    for i in pointSheets:
        pointSheetObj.append(tuple((TeamPointWorkbook.sheet_by_name(i),i)))

rawDescription: How to get excel sheet name in Python using xlrd

description: Get excel sheet name in Python using xlrd


code:
df = pd.read_csv(r'mycsv.csv', nrows=1)
cols = list(df.columns)

rawDescription: Reading Variable names into a list

description: Reading Variable names into a list


code:
def find_two_closest(numbers):
    # most distant points:
    delta = max(numbers), min(numbers)
    for i, element in enumerate(numbers):
        for j, sec_element in enumerate(numbers):
            if i == j:
                continue
            if abs(sec_element - element) < abs(delta[0] - delta[1]):
                delta = sec_element, element
    return delta

rawDescription: Two closest points in list?

description: Two closest points in list


code:
f = open('file.html', 'w')
f.write(div)
f.close()

rawDescription: How to display in browser python output trough javascript?

description: Display in browser python output trough javascript


code:
import os
import psutil

mypid = os.getpid()
for proc in psutil.process_iter():
    if proc.name == 'python' and proc.pid != mypid:
        proc.kill()

rawDescription: using python subprocess.call to kill all running python files

description: Using python subprocess.call to kill all running python files


code:
import pandas as pd
import numpy as np
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# set as 'constant' object shared by all codes in this script
BDAY_US = CustomBusinessDay(calender=USFederalHolidayCalendar())
sample_freq = '5min'
dates = pd.date_range(start='2015-01-01', end='2015-01-31', freq=BDAY_US).date
# exculde the 09:30:00 as it is included in the first time bucket
times = pd.date_range(start='09:30:00', end='16:00:00', freq=sample_freq).time[1:]
time_stamps = [dt.datetime.combine(date, time) for date in dates for time in times]
s = pd.Series(np.random.randn(len(time_stamps)).cumsum() + 100, index=time_stamps)

data_length = len(s)
s.index.name = 'date_time_index'
s.name='stock_price'
s_new = s.reset_index()

ax = s_new.plot(y='stock_price') #plot the data against the new linearised index...

def format_date(x,pos=None):
    thisind = np.clip(int(x+0.5), 0, data_length-1)
    return s_new.date_time_index[thisind].strftime('%Y-%m-%d %H:%M:%S')

ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))

fig = plt.gcf()
fig.autofmt_xdate()

plt.show()

rawDescription: How to build custom pandas.tseries.offsets class?

description: Build custom pandas.tseries.offsets class


code:
import pylab
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import proj3d
fig = pylab.figure()
ax = fig.add_subplot(111, projection = '3d')
x = y = z = [1, 2, 3]
sc = ax.scatter(x,y,z)
# now try to get the display coordinates of the first point

x2, y2, _ = proj3d.proj_transform(1,1,1, ax.get_proj())

label = pylab.annotate(
    "this",
    xy = (x2, y2), xytext = (-20, 20),
    textcoords = 'offset points', ha = 'right', va = 'bottom',
    bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
    arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

def update_position(e):
    x2, y2, _ = proj3d.proj_transform(1,1,1, ax.get_proj())
    label.xy = x2,y2
    label.update_positions(fig.canvas.renderer)
    fig.canvas.draw()
fig.canvas.mpl_connect('button_release_event', update_position)
pylab.show()

rawDescription: Matplotlib: Annotating a 3D scatter plot


code:
"input"[::-1] # from back to the begining. Equivalent to: "input"[len("input")::-1]
"input"[0::-1] # from back to the 0'th (i.e. first) element from back
"input"[1::-1] # from back to the 2ed element from back
"input"[len("input")::-1] # from back to the last element from back (alterantive way)

rawDescription: Extended slice syntax in Python

description: Extended slice syntax in Python


code:
import lxml.etree
fragment = '
text1childtext1text2childtext2text3
'
div = lxml.etree.fromstring(fragment)
div.xpath('./text()')

rawDescription: Getting non-contiguous text with lxml / ElementTree


code:
from django.contrib import messages

class DeleteEventView(DeleteView):
    ...
    def delete(self, request, *args, **kwargs):
        response = super(DeleteEventView, self).delete(request,
                                                       *args, **kwargs)
        deleted_event = self.object
        messages.success(request, 'Event %s deleted.' % deleted_event)
        return response

rawDescription: Where does the function end to add success message/send email - Django/Python


code:
from wtforms.fields import TextAreaField

class MyModelView(ModelView):
    form_overrides = dict(string=TextAreaField)
    def is_accessible(self):
        return current_user.usergroup.name == 'admin'

rawDescription: Customize widget for a form in ModelView in flask-admin


code:
import struct
import mmap

with open('test.bin', 'wb') as f:
    f.truncate(100)

with open('test.bin', 'r+b') as f:
    m = mmap.mmap(f.fileno(), 0)
    mv = memoryview(m)
    for ind in range(25):
        struct.pack_into('>l', mv, ind * 4, ind)

rawDescription: How can I efficiently pack binary data into a file in Python?

description: Efficiently pack binary data into a file in Python


code:
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerLine2D
import numpy as np

line, = plt.plot(range(10), color = 'red')
patch = mpatches.Patch(facecolor='pink', alpha=1.0, linewidth=0)
plt.legend([(patch, line)], ["Theory"], handler_map = {line : HandlerLine2D(marker_pad = 0)} )
plt.show()

rawDescription: Shade legend line in matplotlib

description: Shade legend line in matplotlib


code:
a = table1df[['Name','Phno']].drop_duplicates()
b = table2df[['Name','Phno']].drop_duplicates()
c = table3df[['Name','Phno']].drop_duplicates()
result = pd.concat([a,b,c])

rawDescription: get the distinct column values and union the dataframes

description: Get the distinct column values and union the dataframes


code:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import socket

def _create_sock_pair(port=0):
    """Create socket pair.

    If socket.socketpair isn't available, we emulate it.
    """
    # See if socketpair() is available.
    have_socketpair = hasattr(socket, 'socketpair')
    if have_socketpair:
        client_sock, srv_sock = socket.socketpair()
        return client_sock, srv_sock

    # Create a non-blocking temporary server socket
    temp_srv_sock = socket.socket()
    temp_srv_sock.setblocking(False)
    temp_srv_sock.bind(('', port))
    port = temp_srv_sock.getsockname()[1]
    temp_srv_sock.listen(1)

    # Create non-blocking client socket
    client_sock = socket.socket()
    client_sock.setblocking(False)
    try:
        client_sock.connect(('localhost', port))
    except socket.error as err:
        # Error 10035 (operation would block) is not an error, as we're doing this with a
        # non-blocking socket.
        if err.errno != 10035:
            raise

    # Use select to wait for connect() to succeed.
    import select
    timeout = 1
    readable = select.select([temp_srv_sock], [], [], timeout)[0]
    if temp_srv_sock not in readable:
        raise Exception('Client socket not connected in {} second(s)'.format(timeout))
    srv_sock, _ = temp_srv_sock.accept()

    return client_sock, srv_sock

def can_read():
    print('Server can read')
    app.quit()

def write():
    print('Client writing')
    client_sock.send(b'a')
    client_sock.close()

app = QApplication([])

client_sock, srv_sock = _create_sock_pair()
notifier = QSocketNotifier(srv_sock.fileno(), QSocketNotifier.Read)
notifier.activated.connect(can_read)
write()

w = QMainWindow()
w.show()
app.exec_()
srv_sock.close()

rawDescription: How can I get signaled by QSocketNotifier that a pipe is ready for reading?

description: Get signaled by QSocketNotifier that a pipe is ready for reading


code:
im = Image.new('L', size)
im.putdata([x1, x2, x3, ...])

rawDescription: create a grayscale image

description: Create a grayscale image


code: globals()[option]()

rawDescription: Calling a function from a set variable?

description: Calling a function from a set variable


code:
from xlwings import Sheet
Sheet.add()

rawDescription: Any way to create a new worksheet using xlwings?


rawDescription: Getting index of first occurrence in each row


code:
def func():
    return "foo"

func() # Actually call the function; statement returns the function's return value
func # Reference the function as value; statement returns *the function itself*
var = func # Assign the function value to another variable
var # Now "var" references the same function as "func"...
var() # ...and can also be called as a function

rawDescription: Variable set to call a function

description: Variable set to call a function


code:
bin_directory = r"C:\OSGeo4w\bin"
os.environ['PATH'] += os.path.pathsep + bin_directory

rawDescription: sys.path.append not honored for os.system command?

description: Sys.path.append not honored for os.system command


code:
def logpmf(self, x, n, p):
    """Log of the multinomial probability mass function.
    Parameters
    ----------
    x : array_like
        Quantiles.
    n : int
        Number of trials
    p : array_like, shape (k,)
        Probabilities. These should sum to one. If they do not, then
        ``p[-1]`` is modified to account for the remaining probability so
        that ``sum(p) == 1``.
    Returns
    -------
    logpmf : float
        Log of the probability mass function evaluated at `x`.
    """

    x = np.asarray(x)
    if p.shape[0] != x.shape[-1]:
        raise ValueError("x & p shapes do not match.")

    coef = gammaln(n + 1) - gammaln(x + 1.).sum(axis=-1)
    val = coef + np.sum(xlogy(x, p), axis=-1)

    # insist on that the support is a set of *integers*
    mask = np.logical_and.reduce(np.mod(x, 1) == 0, axis=-1)

    mask &= (x.sum(axis=-1) == n)
    out = np.where(mask, val, -np.inf)
    return out

rawDescription: how to calculate probability mass function for multinomial in scipy?

description: Calculate probability mass function for multinomial in scipy


code:
import io
try:
    file_types = (file, io.IOBase)

except NameError:
    file_types = (io.IOBase,)

with open("README.md", "r") as fin:
    print(isinstance(fin, file_types))

rawDescription: isinstance file python 2.7 and 3.5

description: Isinstance file python 2.7 and 3.5


code:
def get_adjacent_cells( self, x_coord, y_coord ):
    result = {}
    for x,y in [(x_coord+i,y_coord+j) for i in (-1,0,1) for j in (-1,0,1) if i != 0 or j != 0]:
        if (x,y) in grid.cells:
            result[(x,y)] = grid.cells[(x,y)]

rawDescription: Pythonic and efficient way of finding adjacent cells in grid


rawDescription: Selecting specific column in each row from array


code:
import struct

x, y, z = struct.unpack("!iii", receivedData)

rawDescription: Python socket recieve and store data

description: Python socket recieve and store data


code:
for el in chain_views:
    a0, a1, a2, a3, a4, a5 = el.split('|')  # give better names
    if a0 == 'x' and a1 == 'frequency' and a3 == 'y' and a4:
        return True
return False

rawDescription: python regex find match in list

description: Python regex find match in list


code:
class Foo(object):
    def __str__(self):
        return "I am a string for Foo"

'%s' % Foo()

rawDescription: Explicit str() conversion needed for old-style string formatting?


code: instancemethod = type(Anyclass.method)

rawDescription: new.instancemethod convert to python 3.3 in overloading script

description: New.instancemethod convert to python 3.3 in overloading script


code:
from pymongo import MongoClient
from pymongo import database as DB

conn = MongoClient("127.0.0.1", "27017")     # host, port
db = DB.Database(conn, "my_db_name")         # db name
db.authenticate("username", "password")      # username, password

rawDescription: Access monogo db via python

description: Access monogo db via python


code:
def test_message_sending(self):
    data = dict(...)
    response = self.client.post(reverse('my_view'), data)
    messages = self.user.get_and_delete_messages()

    self.assertTrue(messages)
    self.assertEqual('Hey there!', messages[0])

rawDescription: How can I unit test django messages?

description: Unit test django messages


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

def func(x, pos):  # formatter function takes tick label and tick position
    s = str(x)
    ind = s.index('.')
    return s[:ind] + ',' + s[ind+1:]   # change dot to comma

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()

rawDescription: Matplotlib : Comma separated number format for axis


rawDescription: Access array elements by array/list of column indexes


code:
groups = df.groupby((pd.cut(df.age, bins), 'gender'))
output = groups.sum().dropna()

rawDescription: Python Pandas: Aggregate my indexes into a range of ages


code:
from skyfield.api import load, Star
ts = load.timescale()
t = ts.utc(2016, 4, 16, 15, 30)
planets = load('de421.bsp')
earth = planets['earth']
boston = earth.topos(longitude_degrees=(21, 33, 20.4),
                     latitude_degrees=(+43, 8, 24.6))
barnard = Star(ra_hours=(17, 57, 48.49803),
               dec_degrees=(4, 41, 36.2072),
               ra_mas_per_year=-798.71,
               dec_mas_per_year=+10337.77,
               parallax_mas=545.4,
               radial_km_per_s=-110.6)
astrometric = boston.at(t).observe(barnard)
ra, dec, distance = astrometric.radec()
print(ra)
print(dec)
apparent = astrometric.apparent()
ra, dec, distance = apparent.radec()
print(ra)
print(dec)
alt, az, distance = apparent.altaz(temperature_C=25.0,
                                   pressure_mbar=1013.25)
print(alt)
print(az)

rawDescription: Coordinates reduction python

description: Coordinates reduction python


rawDescription: Append some columns to a list of list matrix


code:
# Load configuration with the destination specified.
load_config = {
  'destinationTable': {
    'projectId': PROJECT_ID,
    'datasetId': DATASET_ID,
    'tableId': TABLE_ID
  }
}

load_config['schema'] = {
  'fields': [
    {'name':'string_f', 'type':'STRING'},
    {'name':'boolean_f', 'type':'BOOLEAN'},
    {'name':'integer_f', 'type':'INTEGER'},
    {'name':'float_f', 'type':'FLOAT'},
    {'name':'timestamp_f', 'type':'TIMESTAMP'}
  ]
}
load_config['sourceFormat'] = 'NEWLINE_DELIMITED_JSON'

# This tells it to perform a resumable upload of a local file
# called 'foo.json'
upload = MediaFileUpload('foo.json',
                         mimetype='application/octet-stream',
                         # This enables resumable uploads.
                         resumable=True)

start = time.time()
job_id = 'job_%d' % start
# Create the job.
result = jobs.insert(
  projectId=project_id,
  body={
    'jobReference': {
      'jobId': job_id
    },
    'configuration': {
      'load': load
    }
  },
  media_body=upload).execute()

 # Then you'd also want to wait for the result and check the status. (check out
 # the example at the link for more info).

rawDescription: Loading JSON file in BigQuery using Google BigQuery Client API


code:
lines = [0]
with open("testmat.txt") as f:
    while f.readline():
        lines.append(f.tell())
    # now you can read an arbitrary line:
    f.seek(lines[1235])
    line = f.readline()

rawDescription: Is there a python library for line based file reading?


rawDescription: Pandas: Get duplicated indexes

description: Pandas: Get duplicated indexes


rawDescription: Total Objects based on Value of Another Object


code:
IGNORABLE_404_URLS = (
    re.compile(r'^wp-login$'),
)

rawDescription: Does Django 1.6 support the IGNORABLE_404_URLS setting?


code: list.insert(0, element)

rawDescription: What is opposite of append() function in python?


code: iter(set, None)

rawDescription: Python repeat set generator

description: Python repeat set generator


code:
def split_len(seq, length):
    return [seq[i:i + length] for i in range(0, len(seq), length)]

def encode(key, plaintext):

    order = {
        int(val): num for num, val in enumerate(key)
    }

    ciphertext = ''
    for index in sorted(order.keys()):
        for part in split_len(plaintext, len(key)):
            try:
                ciphertext += part[order[index]]
            except IndexError:
                continue

    return ciphertext

print(encode('3214', 'IHAVETWOCATS'))
#>>> HTAAWTIECVOS

rawDescription: How to Convert a String to 2d array in Python?

description: Convert a String to 2d array in Python


code: [i-j if i>j else j-i for i,j in zip(list1, list2)]

rawDescription: function of difference between value

description: Function of difference between value


code:
def var_change(self):
    self.var.set("world")
    self.root.update_idletasks()  # This forces the window to update
    mb.showinfo("Title", "Hi", parent=None)
    self.var.set("hello")

rawDescription: tkinter, text does not change immediately on mac osx

description: Tkinter, text does not change immediately on mac osx


code:
marmot = Animal.objects(genus='Marmota').first()
photo = marmot.photo.read()
content_type = marmot.photo.content_type

rawDescription: Retrieving an image from mongoengine and display it on a page as http reponse in python


code:
from collections import Counter
lst = [[1, 0, 0, 0], [1, 1, 0, 0], [2, 0, 0, 0], [2, 1, 0, 0], [2, 1, 0, 0], [1, 1, 0, 0], [3, 1, 0, 0], [1, 3, 0, 0], [2, 1, 0, 0], [2, 0, 0, 0]]
list_of_tuples = [tuple(elem) for elem in lst]
dct = dict(Counter(list_of_tuples))
lst = [list(e) for e in dct]
for elem in lst:
    elem[2] = dct[tuple(elem)]

rawDescription: How can I count duplicates in a nested list based on first two elements in python

description: Count duplicates in a nested list based on first two elements in python


code: sorted(..., key=lambda x: (x[0], -x[1]))

rawDescription: How to traverse a list of the following conditions

description: Traverse a list of the following conditions


code:
class MyClass(object):

    def __init__(self):
        self.attributes = []

rawDescription: Python: Iterating over predetermined conditions within conditions


code:
import os.path

file_exists = os.path.isfile(filename)

with open (filename, 'a') as csvfile:
    headers = ['TimeStamp', 'light', 'Proximity']
    writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)

    if not file_exists:
        writer.writeheader()  # file doesn't exist yet, write a header

    writer.writerow({'TimeStamp': dic['ts'], 'light': dic['light'], 'Proximity': dic['prox']})

rawDescription: python csv, writing headers only once

description: Python csv, writing headers only once


code:
numberone = 12

def print(i):
    global numberone
    return print(str(i))

rawDescription: How to use variable from def? in Python

description: Use variable from def? in Python


code:
import matplotlib.pyplot as plt

plt.annotate('Here it is!',xy=(-1,-1),xytext=(0,0),
             arrowprops=dict(lw=1.5, shrink=0.15))

plt.xlim(-10,10)
plt.ylim(-10,10)

plt.show()

rawDescription: Matplotlib - set pad between arrow and text in annotate function


code:
import re
re.findall(r'((Brahui|Han|Yoruba)+\d+)', '10xBrahuiHan50_10xBrahuiYoruba50n4')

rawDescription: Python regular expression search vs match


code:
foo = "http://www.address.com/something#something"
foo = foo.split('#')[0]
foo

rawDescription: How can I remove the fragment identifier from a URL?

description: Remove the fragment identifier from a URL


rawDescription: Mask array based on other array?

description: Mask array based on other array


code:
while True:
    x = input("Enter something: ")
    print("You entered {}".format(x))
    print("That object's type is: {}".format(type(x)))

rawDescription: Python - User input data type

description: Python - User input data type


code:
import sqlite3
import os

filename = ...
with sqlite3.connect(filename) as conn:
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    for tablerow in cursor.fetchall():
        table = tablerow[0]
        cursor.execute("SELECT * FROM {t}".format(t = table))
        for row in cursor:
            for field in row.keys():
                print(table, field, row[field])

rawDescription: Search Sqlite Database - All Tables and Columns


code:
try:
    import pwd
except ImportError:
    import winpwd as pwd

rawDescription: How to shadow python builtin pwd module

description: Shadow python builtin pwd module


rawDescription: Beautiful soup (python) getting value of attribute


code:
import codecs

class StrictUTF8Writer(codecs.StreamWriter):
    '''A StreamWriter for utf8 that requires written objects be unicode'''
    encode = codecs.utf_8_encode

    def write(self, object):
        if not isinstance(object, unicode):
            raise ValueError('write() requires unicode object')
        return codecs.StreamWriter.write(self, object)

rawDescription: How can I make a python StreamWriter REQUIRE unicode input?

description: Make a python StreamWriter REQUIRE unicode input


code:
from itertools import groupby
with open('infile') as f:
    groups = groupby(f, key=str.isspace)
    for k, lines in groups:
        if k:
            continue
        fname = next(lines).strip().lower().replace(' ', '_')+'.txt'
        with open(fname, 'w') as outf:
            outf.writelines(lines)

rawDescription: How can i split a huge txt file with the help of python

description: Split a huge txt file with the help of python


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.canvas = tk.Canvas(self)
        self.start_button = tk.Button(self, text="start", command=self.on_start)
        self.stop_button = tk.Button(self, text="stop", command=self.on_stop)

        self.start_button.pack()
        self.stop_button.pack()
        self.canvas.pack(fill="both", expand=True)

        # call on_stop to initialize the state of the buttons
        self.on_stop()

    def on_start(self):
        """Start the animation"""
        self.canvas.delete("all")
        self.rect_id = self.canvas.create_rectangle(0,0,1,20, fill="blue")

        self.running = True
        self.start_button.configure(state="disabled")
        self.stop_button.configure(state="normal")
        self.draw_one_frame()

    def on_stop(self):
        """Stop the animation"""
        self.start_button.configure(state="normal")
        self.stop_button.configure(state="disabled")
        self.running = False

    def draw_one_frame(self):
        """Draw a single frame of animation"""
        (x0, y0, x1, y1) = self.canvas.coords(self.rect_id)
        if x1 < self.canvas.winfo_width():
            x1 += 1
        else:
            x1 = 1

        self.canvas.coords(self.rect_id, (x0, y0, x1, y1))

        if self.running:
            self.after(10, self.draw_one_frame)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: windows thinks tkinter is not responding

description: Windows thinks tkinter is not responding


code:
currentpath = '/img/default/basicprof.jpg'
newpathandname = '/img/{}.jpg'.format(username)

os.rename(currentpath, newpathandname) #does not keep original file
shutil.copyfile(currentpath, newpathandname) #keeps original file

rawDescription: How to copy an image from server directory to another directory in python

description: Copy an image from server directory to another directory in python


code:
import mymod
import os.path

def chroot_open(filename,*args):
    filename = os.path.join("/home/you/fakeroot",filename)
    return open(filename,*args)

mymod.open = chroot_open

rawDescription: regression test dealing with hard coded path

description: Regression test dealing with hard coded path


code:
class Player(pygame.Sprite):
    def __init__(self):
        self.image = pygame.image.load("player.png").convert_alpha()
        self.rect = self.image.get_rect()
        self.pos = self.rect.x, self.rect.y
        #etc.......

rawDescription: How to use PyGame.sprite

description: Use PyGame.sprite


code: wx.Frame(parent, style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)

rawDescription: wxPython Disable Frame Resizing

description: WxPython Disable Frame Resizing


rawDescription: How to find all ways from up to down in list use python

description: Find all ways from up to down in list use python


code:
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

executable_path = "path_to_webdriver"
os.environ["webdriver.chrome.driver"] = executable_path

chrome_options = Options()
chrome_options.add_extension('path_to_extension')

driver = webdriver.Chrome(executable_path=executable_path, chrome_options=chrome_options)
driver.get("http://stackoverflow.com")
driver.quit()

rawDescription: How to select Chrome extensions to enable when using Selenium

description: Select Chrome extensions to enable when using Selenium


code:
q = (session.query(Table1.id)
     .filter(~exists(
         select([Table2.id])
         .where(Table2.table1_id == Table1.id)
         .where(~exists(
             # changing exists to be implicit enables the 'important' below
             select([Table3.id])
             .where(Table3.contract_id == Table2.contract_id)
             .where(Table3.session_id == Table1.session_id)
             # this is important
             .correlate(Table1)
             .correlate(Table2)
             ))
     )))

rawDescription: sqlalchemy exists() - how to avoid extra From

description: Sqlalchemy exists() - how to avoid extra From


code:
points = []
for line in file:
    x,y = eval(line)
    points.append((x,y))
result = np.array(points)

rawDescription: Fastest way to create a numpy array from text file


code:
# These are not needed in your view method
username = form.clean_username()
email = form.clean_email()
password = form.clean_password2()

rawDescription: Django. Best way to have unique email in User model?


code:
def enterPiece(aBoard, aColour, aPoint):
    c = aBoard
    if 0 < aPoint <= aBoard.size:
        for j in range(aPoint):
            c.removePieceFromPoint(aColour, 0)
            c.addPieceToPoint(aColour, aPoint)
            return True
        else:
            return False

rawDescription: How can I access the integer held in a variable which is defined by a separate definition

description: Access the integer held in a variable which is defined by a separate definition


rawDescription: Centering Static Text WxPython

description: Centering Static Text WxPython


code:
import tkFileDialog
import csv

ENCODING_REGEX_REPLACEMENT_LIST = [(re.compile('\xe2\x80\x99'), "'"),
                                   (re.compile('\xe2\x80\x94'), "--"),
                                   (re.compile('\xe2\x80\x9c'), '"'),
                                   (re.compile('\xe2\x80\x9d'), '"'),
                                   (re.compile('\xe2\x80\xa6'), '...')]

def correct_encoding(csv_row):
    for key in csv_row.keys():
        # if there is a value for the current key
        if csv_row[key]:
            try:
                csv_row[key] = unicode(csv_row[key], errors='strict')
            except ValueError:
                # we have a bad encoding, try iterating through all the known
                # bad encodings in the ENCODING_REGEX_REPLACEMENT and replace
                # everything and then try again
                for (regex, replacement) in ENCODING_REGEX_REPLACEMENT_LIST:
                    csv_row[key] = regex.sub(replacement,csv_row[key])
                print(csv_row)
                csv_row[key] = unicode(csv_row[key])
        # if there is NOT a value for the current key
        else:
            csv_row[key] = unicode('')
    return csv_row

filename = tkFileDialog.askopenfilename()
csv_reader = csv.DictReader(open(filename, "rb"), dialect='excel') # assuming similar dialect
for csv_row in csv_reader:
    csv_row = correct_encoding(csv_row)
    # your application logic here

rawDescription: Python reading csv problem : extra whitespace


code: result = [[name, int(s1), int(s2)] for name, s1, s2 in testscores]

rawDescription: How can I convert list of list with strings to list of list with ints in python?

description: Convert list of list with strings to list of list with ints in python


code:
command = input("> ")
user_input = command.lower().split()
command = user_input[0]
if len(user_input) > 1:
    parameter = user_input[1]
    function_dict[command](parameter)
else:
    function_dict[command]()

rawDescription: Use input as parameters for a function called by a dictionary


code:
def last_feature(line):
    start = line.rfind(' ') + 1
    end = line.rfind(':')
    return int(line[start:end])

with open(...) as file1:
    largest = max(last_feature(line) for line in file1)

rawDescription: Efficient way to check last term of a line in Python file


code:
def split_utf8(s, n):
    """Split UTF-8 s into chunks of maximum length n."""
    while len(s) > n:
        k = n
        while (ord(s[k]) & 0xc0) == 0x80:
            k -= 1
        yield s[:k]
        s = s[k:]
    yield s

rawDescription: Split unicode string into 300 byte chunks without destroying characters


code:
import Image, ImageChops, ImageOps

def transparent_when_gray(x):
    return 255 if x == 127 else 255 - 2 * abs(127 - x)

def mk_badge(img, template):
    templ = template.convert('RGBA')
    r, g, b, alpha = templ.split()
    gray = ImageOps.grayscale(Image.merge('RGB', (r, g, b)))
    amask = gray.point(transparent_when_gray)

    res = ImageChops.composite(img, templ, amask)
    res.putalpha(alpha)
    return res

if __name__ == '__main__':
    image    = Image.open('thumbnail.gif')
    template = Image.open('badge_lighting.png')

    image_cropped = ImageOps.fit(image, template.size)

    badge = mk_badge(image_cropped, template)
    badge.save('badge.png')

rawDescription: Replicating ImageMagicks 'Badge using Lighting Effects' using PIL


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

y = np.array([1,2,3,4,5,6])
z = np.array([2,2,2,2,2,2])

ax1 = plt.subplot2grid((3,3),(0,0), colspan=3, rowspan=2)
ax2 = plt.subplot2grid((3,3),(2,0), colspan=3)

ax1.plot(y)
ax1.plot(z)
ax2.plot(y)
plt.show()

rawDescription: Sizing the subplot differently

description: Sizing the subplot differently


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

# plt.subplots instead of plt.subplot
# create a figure and two subplots side by side, they share the
# x and the y-axis
fig, axes = plt.subplots(ncols=2, sharey=True, sharex=True)
data = np.random.random([10, 2])
# np.r_ instead of lists
colors = np.r_[np.linspace(0.1, 1, 5), np.linspace(0.1, 1, 5)]
mymap = plt.get_cmap("Reds")
# get the colors from the color map
my_colors = mymap(colors)
# here you give floats as color to scatter and a color map
# scatter "translates" this
axes[0].scatter(data[:, 0], data[:, 1], s=40,
                c=colors, edgecolors='None',
                cmap=mymap)
for n in range(5):
    # here you give a color to scatter
    axes[1].scatter(data[n, 0], data[n, 1], s=40,
                    color=my_colors[n], edgecolors='None',
                    label="point %d" %(n))
# by default legend would show multiple scatterpoints (as you would normally
# plot multiple points with scatter)
# I reduce the number to one here
plt.legend(scatterpoints=1)
plt.tight_layout()
plt.show()

rawDescription: how to shade points in scatter based on colormap in matplotlib?

description: Shade points in scatter based on colormap in matplotlib


rawDescription: How to run a shell script without having to press enter/confirm s.th. inbetween

description: Run a shell script without having to press enter/confirm s.th. inbetween


code:
def escape(htmlstring):
    escapes = {'\"': '"',
               '\'': ''',
               '<': '<',
               '>': '>'}
    # This is done first to prevent escaping other escapes.
    htmlstring = htmlstring.replace('&', '&')
    for seq, esc in escapes.iteritems():
        htmlstring = htmlstring.replace(seq, esc)
    return htmlstring

rawDescription: Python sanitizing html from a string

description: Python sanitizing html from a string


rawDescription: Python regex to get string in front of hyphen and plus signs


code:
import subprocess

text = "hello world"
subprocess.Popen(["espeak", "-v", "mb-en1", text])

rawDescription: Operate - espeak -v mb-en1 "hello world" - in Python


code:
def f(x,u,v,z_data):
  C = x[0]
  p = x[1]
  modelled_z = C*u*v**p
  diffs = modelled_z - z_data
  return diffs.flatten() # it expects a 1D array out.
       # it doesn't matter that it's conceptually 2D, provided flatten it consistently

result = scipy.optimize.leastsq(f,[1.0,1.0], # initial guess at starting point
                        args = (u,v,z_data) # alternatively you can do this with closure variables in f if you like
                              )
# result is the best fit point

rawDescription: two dimensional fit with python

description: Two dimensional fit with python


code:
lin="a b c d"
lin.split()

rawDescription: reading a file in python

description: Reading a file in python


code:
from wtforms import Form, TextAreaField, validators

class ReviewForm(Form):
    review = TextAreaField('My Review: ', [validators.DataRequired()])

rawDescription: Line wrapping in HTML forms using Flask

description: Line wrapping in HTML forms using Flask


code:
for seq0, seq1 in itertools.combinations(data['sequence'], 2):
    for a in pairwise2.align.globalxx(seq0, seq1):
        print(format_alignment(*a))

rawDescription: pairwise comparison within a column pandas python Biopython

description: Pairwise comparison within a column pandas python Biopython


code:
service.revisions().update(fileId = newfile['id'], revisionId='head',
    body={'published':True, 'publishAuto': True}).execute()

rawDescription: Set "publish to web" in Google spreadsheet using Drive python API


code:
from datetime import date

def first_week():
    today = date.today()
    return today.weekday() - today.day >= -1

rawDescription: How to determine if we are in the first week of the current month

description: Determine if we are in the first week of the current month


code:
COLORKEY=(127, 127, 0)
TRANSPARENCY=(0, 0, 0, 0)
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
for x in xrange(0, 200, 20):
  pygame.draw.line(screen, (255, 255, 255), (x, 0),(x, 480))

# create red circle using a colorkey
red_circle = pygame.Surface((200, 200))
red_circle.fill(COLORKEY)
red_circle.set_colorkey(COLORKEY)
pygame.draw.circle(red_circle, (255, 0, 0), (100, 100), 25)

#create a green circle using alpha channel (per-pixel transparency)
green_circle = pygame.Surface((100, 100)).convert_alpha()
green_circle.fill(TRANSPARENCY)
pygame.draw.circle(green_circle, (0, 255, 0, 127), (50, 50), 25)

# convert colorkey surface to alpha channel surface before blitting
red_circle = red_circle.convert_alpha()
red_circle.blit(green_circle, (75, 75))

screen.blit(red_circle, (0, 0))

pygame.display.flip()

rawDescription: Stacking different types of transparency in pygame


code: float_prices = [float(p) for p in prices[1:len(prices)]]

rawDescription: Django store csv float items in database


code: [str(u) for u in [(u'one'),(u'one'),(u'three')]]

rawDescription: How to get a string from unicode data returned from sql query (python,sql,wxpython)

description: Get a string from unicode data returned from sql query (python,sql,wxpython)


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

# first data set
X1 = np.linspace(0,1,203)
Y1 = np.sin(X1)

# second data set
X2 = np.linspace(0, 0.5, 1532)
Y2 = np.cos(X2)

# get interpolated values of Y1 evaluated at X2
Y1_interp = np.interp(X2, X1, Y1)

# plot interpolated Y1 vs Y2
plt.plot(Y1_interp, Y2)
plt.show()

rawDescription: Data interpolation in python

description: Data interpolation in python


code:
from PySide.QtGui import QApplication, QMainWindow
from PySide.QtCore import QObject, QTimer, Signal
from PySide.QtGui import QLabel

class MyObject:
    sig = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        QTimer.singleShot(3000, self.alert)
        QTimer.singleShot(5000, self.exit)
    def alert(self):
        self.sig.emit()
    def exit(self):
        print('All done')
        exit(0)

class MyWidget(MyObject, QLabel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.sig.connect(self.update)
    def update(self):
        print(2)

app = QApplication([])

w = MyWidget()
w.show()

app.exec_()

rawDescription: Can we emit signals of a base class in pyside?


code:
x = symbols("x", real=True)
solve(x + 1 < 2, x)

rawDescription: How can I solve x + 1 < 2 in Sympy?

description: Solve x + 1 < 2 in Sympy


code:
FULL_NAV = [
    ['nav1'],
    ['nav1', 'subnav1'],
    ['nav1', 'subnav2'],
    ['nav2'],
    ['nav3'],
    ['nav3', 'subnav1'],
    ['nav3', 'subnav2'],
    ['nav3', 'subnav3'],
    ['nav3', 'subnav3', 'subsubnav1'],
    ['nav3', 'subnav3', 'subsubnav1', 'subsubsubnav'],
    ['nav4'],
    ['nav5'],
    ['nav5', 'subnav1'],
    ['nav5', 'subnav1', 'subsubnav1'],
    ['nav5', 'subnav2'],
    ['nav5', 'subnav3']
]

def get_required_nav(node_path, full_nav):
    return_list = []

    for comparison_node in full_nav:
        cn_len = len(comparison_node)
        np_len = len(node_path)
        if cn_len <= np_len:
            if comparison_node[:cn_len - 1] == node_path[:cn_len - 1]:
                return_list.append(comparison_node)
        else:
            if comparison_node[:-1] == node_path:
                return_list.append(comparison_node)
    return return_list

if __name__ == '__main__':
        from pprint import pprint
        pprint(get_required_nav(
            ['nav3', 'subnav3'], FULL_NAV))

# Output of above example:
# [['nav1'],
#  ['nav2'],
#  ['nav3'],
#  ['nav3', 'subnav1'],
#  ['nav3', 'subnav2'],
#  ['nav3', 'subnav3'],
#  ['nav3', 'subnav3', 'subsubnav1'],
#  ['nav4'],
#  ['nav5']]

rawDescription: Return all items within path, inc siblings at each level traversed


rawDescription: why can't x[:,0] = x[0] for a single row vector?

description: Why can't x[:,0] = x[0] for a single row vector


code:
from __future__ import division, print_function, absolute_import

import numpy as np
import matplotlib.pyplot as plt
import tflearn
import tflearn.data_utils as du

# Data loading and preprocessing
import tflearn.datasets.mnist as mnist
X, Y, testX, testY = mnist.load_data(one_hot=True)

X = X.reshape([-1, 28, 28, 1])
testX = testX.reshape([-1, 28, 28, 1])
X, mean = du.featurewise_zero_center(X)
testX = du.featurewise_zero_center(testX, mean)

# Building the encoder
encoder = tflearn.input_data(shape=[None, 28, 28, 1])
encoder = tflearn.conv_2d(encoder, 16, 3, activation='relu')
encoder = tflearn.max_pool_2d(encoder, 2)
encoder = tflearn.conv_2d(encoder, 8, 3, activation='relu')
decoder = tflearn.upsample_2d(encoder, 2)
decoder = tflearn.conv_2d(encoder, 1, 3, activation='relu')

# Regression, with mean square error
net = tflearn.regression(decoder, optimizer='adam', learning_rate=0.001,
                         loss='mean_square', metric=None)

# Training the auto encoder
model = tflearn.DNN(net, tensorboard_verbose=0)
model.fit(X, X, n_epoch=10, validation_set=(testX, testX),
          run_id="auto_encoder", batch_size=256)

# Encoding X[0] for test
print("\nTest encoding of X[0]:")
# New model, re-using the same session, for weights sharing
encoding_model = tflearn.DNN(encoder, session=model.session)
print(encoding_model.predict([X[0]]))

# Testing the image reconstruction on new data (test set)
print("\nVisualizing results after being encoded and decoded:")
testX = tflearn.data_utils.shuffle(testX)[0]
# Applying encode and decode over test set
encode_decode = model.predict(testX)
# Compare original images with their reconstructions
f, a = plt.subplots(2, 10, figsize=(10, 2))
for i in range(10):
    a[0][i].imshow(np.reshape(testX[i], (28, 28)))
    a[1][i].imshow(np.reshape(encode_decode[i], (28, 28)))
f.show()
plt.draw()
plt.waitforbuttonpress()

rawDescription: TensorFlow/TFLearn: ValueError: Cannot feed value of shape (256, 400, 400) for Tensor u'TargetsData/Y:0', which has shape '(?, 64)'


code:
from cx_Freeze import setup, Executable
import zmq.libzmq

build_exe_options = {
    # zmq.backend.cython seems to be left out by default
    'packages': ['zmq.backend.cython', ],
    # libzmq.pyd is a vital dependency
    'include_files': [zmq.libzmq.__file__, ],
}

setup(
    name='myapp',
    version='0.0.1',
    description='My App',
    options={'build_exe': build_exe_options},
    executables=[Executable('bin/myapp.py')],
)

rawDescription: How do I make pyzmq (14.3.1) and cx_Freeze (4.3.3) work together

description: Make pyzmq (14.3.1) and cx_Freeze (4.3.3) work together


code:
class CarAdmin(admin.ModelAdmin):
    list_display = ('manufacturer', 'model')
    exclude = ('owner',)  # note you need a comma to make this a tuple

    def get_queryset(self, request):
        qs = super(MyModelAdmin, self).get_queryset(request)
        return qs.objects.filter(owner__isnull=False)

rawDescription: Django admin form custom select

description: Django admin form custom select


code:
class MyCustomRenderer(gridlib.PyGridCellRenderer):
    def __init__(self):
        gridlib.PyGridCellRenderer.__init__(self)

    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
        dc.SetBackgroundMode(wx.SOLID)
        dc.SetBrush(wx.Brush(wx.BLACK, wx.SOLID))
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangleRect(rect)

        dc.SetBackgroundMode(wx.TRANSPARENT)
        dc.SetFont(attr.GetFont())

        text = grid.GetCellValue(row, col)
        colors = ["RED", "WHITE", "SKY BLUE"]
        x = rect.x + 1
        y = rect.y + 1

        for ch in text:
            dc.SetTextForeground(random.choice(colors))
            dc.DrawText(ch, x, y)
            w, h = dc.GetTextExtent(ch)
            x = x + w
            if x > rect.right - 5:
                break

rawDescription: How can I highlight individual characters in a cell of a wx.Grid?

description: Highlight individual characters in a cell of a wx.Grid


code:
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import numpy as np

def CustomCmap(from_rgb,to_rgb):

    # from color r,g,b
    r1,g1,b1 = from_rgb

    # to color r,g,b
    r2,g2,b2 = to_rgb

    cdict = {'red': ((0, r1, r1),
                   (1, r2, r2)),
           'green': ((0, g1, g1),
                    (1, g2, g2)),
           'blue': ((0, b1, b1),
                   (1, b2, b2))}

    cmap = LinearSegmentedColormap('custom_cmap', cdict)
    return cmap

fig, ax = plt.subplots(2,2, figsize=(6,6), subplot_kw={'xticks': [],'yticks': []})
fig.subplots_adjust(hspace=.1,wspace=.1)

ax = ax.ravel()

cmap1 = CustomCmap([0.00, 0.00, 0.00], [0.02, 0.75, 1.00]) # from black to +/- 5,192,255
cmap2 = CustomCmap([1.00, 1.00, 1.00], [0.02, 0.75, 1.00]) # from white to +/- 5,192,255
cmap3 = CustomCmap([1.00, 0.42, 0.04], [0.02, 0.75, 1.00]) # from +/- 255,108,10 to +/- 5,192,255
cmap4 = CustomCmap([1.00, 0.42, 0.04], [0.50, 0.50, 0.50]) # from +/- 255,108,10 to grey (128)

ax[0].imshow(np.random.rand(30,30), interpolation='none', cmap=cmap1)
ax[1].imshow(np.random.rand(30,30), interpolation='none', cmap=cmap2)
ax[2].imshow(np.random.rand(30,30), interpolation='none', cmap=cmap3)
ax[3].imshow(np.random.rand(30,30), interpolation='none', cmap=cmap4)

rawDescription: matplotlib: single colored colormap with saturation

description: Matplotlib: single colored colormap with saturation


code:
testfield2 = re.sub(r'([A-Z0-9])\1+', lambda m: m.group(1).upper(), testfield2, flags=re.IGNORECASE)
print(testfield2)

rawDescription: Python regex remove double character from string


code:
from bs4 import BeautifulSoup

def filter(url, data):
    if url == "https://developers.google.com/android/nexus/images":
        soup = BeautifulSoup(data)
        return soup.select("h2#hammerhead ~ table")[0]

rawDescription: Watching part of a page using urlwatch

description: Watching part of a page using urlwatch


code: ', '.join(chassis['name'] for chassis in result.getJSONDATA()['chassis'])

rawDescription: How to convert a single key within a list of dictionaries to a string on the fly

description: Convert a single key within a list of dictionaries to a string on the fly


code:
import subprocess32
subprocess32.call(
    ['java', '-mx1g', '-classpath',
     '/usr/share/stanford-postagger/stanford-postagger.jar',
     'edu.stanford.nlp.tagger.maxent.MaxentTagger', '-props',
     'uyghurtagger.props'])

rawDescription: Training a new Stanford part-of-speech tagger from within the NLTK


code:
import Tkinter as tkinter

root = tkinter.Tk()

canvas = tkinter.Canvas(root)
canvas.pack(fill=tkinter.BOTH, expand=1) # expand

photo = tkinter.PhotoImage(file = 'img1.gif')
root.geometry("450x450")
root.update()

img = canvas.create_image(225,225, image=photo)
#root.after(20000, lambda: canvas.delete(img))

root.mainloop()

rawDescription: Trying to display a whole image in tkinter


code:
import os
os.environ['COMSPEC']
import subprocess
subprocess.call('dir', shell=True)
os.environ['COMSPEC'] = 'C:\\nonexistent.exe'
subprocess.call('dir', shell=True)

rawDescription: Cannot find the file specified when using subprocess.call('dir', shell=True) in Python


code:
#!/usr/bin/env python3
from xml.dom import minidom
import os.path

def new_value(parameter, parameter_value, target_dir, inputfile):
    # Load the XML file and parse it
    dom = minidom.parse(inputfile)

    # Find all <p> elements with the correct name= attribute
    els = [element
           for element in dom.getElementsByTagName('p')
           if element.getAttribute('name') == parameter]

    # Choose the first among these
    chosen_el = els[0]

    # Set its text content
    if chosen_el.hasChildNodes:
        # Assumes that the first child is in fact a text node
        chosen_el.firstChild.nodeValue = parameter_value
    else:
        # If the element is empty, add a child node
        chosen_el.appendChild(dom.createTextNode(parameter_value))

    fullname = os.path.join(target_dir, "test" + str(parameter_value) + ".xml")

    # Opening a file using a "with open" block automatically
    # closes it at the end of the block
    with open(fullname, 'wb') as outFile:
        outFile.write(dom.toxml('utf-8'))

parameter = input("Enter the parameter: ")              # or 'Mango'
target_dir = input("Enter the target directory: ")      # or '.'
input_file = input("Enter the input file: ")            # or 'so_xml.xml'
parameter_value = input("Enter the value to replace: ") # or 'Manstop'
new_value(parameter, parameter_value, target_dir, input_file)

rawDescription: Replacing a text node by another in xml using python


rawDescription: How can I change a list in a tuple?

description: Change a list in a tuple


code:
def AddSingleCard():
    symbols = ['heart', 'diamond', 'club', 'spade']
    newCardNumber = newCardSign = None
    while (newCardNumber not in range(2, 16) or newCardSign not in symbols):
        newCardNumber, newCardSign = raw_input('Enter Number and Symbol with space between:').split()
        try:
            newCardNumber = int(newCardNumber)
        except:
            continue
    newCard = [newCardNumber, newCardSign]
    return newCard

AddSingleCard()

rawDescription: I don't quite understand the while loop in python


code:
from __future__ import absolute_import
import collections  # imports collections that is on sys.path
from . import collections as utils_collections  # now imports utils.collections

rawDescription: controlling order of imports in python without changing sys.path

description: Controlling order of imports in python without changing sys.path


code:
l = [['Yar\\u0131n'], ',', ['Mehmet'], 'ile', 'birlikte', ["Ankara'da", 'ki', 'Nufus', "Mudurlugu'ne"], ',', ['Aziz', 'Y\\u0131ld\\u0131r\\u0131m'], 'ile', 'birlikte', ',', ['Sukru', 'Saracoglu', "Stad\\u0131'na"], 'gidecegiz', '.']
[[item] if not isinstance(item, list) else item for item in l]

rawDescription: Converting str object of list to one list object


code:
results = []
for no in j["response"]["result"]["Potentials"]["row"]:
    data = no["FL"]
    if isinstance(data, list) and len(data) > 1:
        results.append(int(data[1]["content"]))
results

rawDescription: python + json: parse to list

description: Python + json: parse to list


code:
from bokeh.plotting import *
from bokeh.objects import *
import numpy as np

output_notebook()

label = ['United States', 'Russia', 'South Africa', 'Europe (average)', 'Canada', 'Austalia', 'Japan']
number = [1, 2, 3, 4, 5, 6, 7]
value = [700, 530, 400, 150, 125, 125, 75]
yr = Range1d(start=0, end=800)

figure(x_range=label, y_range=yr)
rect(number, [x/2 for x in value] , width=0.5, height=value, color = "#ff1200")
xaxis().major_label_orientation = np.pi/4   # radians, "horizontal", "vertical", "normal"

show()

rawDescription: Bokeh Plot with a nominal or ordinal axis type


code:
res = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest')
for i, cas in enumerate(conf_arr):
    for j, c in enumerate(cas):
        if c>0:
            plt.text(j-.2, i+.2, c, fontsize=14)
cb = fig.colorbar(res)

rawDescription: Confusion Matrix with number of classified/misclassified instances on it (Python/Matplotlib)


code:
class curses_screen:
    def __enter__(self):
        self.stdscr = curses.initscr()
        curses.cbreak()
        curses.noecho()
        self.stdscr.keypad(1)
        SCREEN_HEIGHT, SCREEN_WIDTH = self.stdscr.getmaxyx()
        return self.stdscr
    def __exit__(self,a,b,c):
        curses.nocbreak()
        self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()

with curses_screen() as stdscr:
    """
    Execution code plush getch code here
    """

rawDescription: Python curses - hide user input

description: Python curses - hide user input


code:
import pylab as pl
import numpy as np
import pandas as pd

# prepare some random data
N = 100
np.random.seed(0)
weekday = np.random.randint(0, 7, N)
week = np.random.randint(0, 40, N)
activity = np.random.randint(0, 100, N)

df = pd.DataFrame({"weekday":weekday, "week":week, "activity":activity})
df.drop_duplicates(cols=["weekday", "week"], inplace=True)

# reshape the data and plot it
df2 = df.pivot(columns="week", index="weekday", values="activity")
df2.fillna(0, inplace=True)

Weekday, Week = np.mgrid[:df2.shape[0]+1, :df2.shape[1]+1]
fig, ax = pl.subplots(figsize=(12, 4))
ax.set_aspect("equal")
pl.pcolormesh(Week, Weekday, df2.values, cmap="Greens", edgecolor="w", vmin=-10, vmax=100)
pl.xlim(0, df2.shape[1])

rawDescription: How to create an activity plot from Pandas Dataframe (like the Github contribution plot)

description: Create an activity plot from Pandas Dataframe (like the Github contribution plot)


code:
def button_reload(self, cr, uid, ids, context=None):
    for module_record in self.browse(cr, uid, ids, context=context):
        #Remove any report parsers registered for this module.
        module_path = 'addons/' + module_record.name
        for service_name, service in Service._services.items():
            template = getattr(service, 'tmpl', '')
            if template.startswith(module_path):
                Service.remove(service_name)

        #Remove any model classes registered for this module
        MetaModel.module_to_models[module_record.name] = []

        #Reload all Python modules from the OpenERP module's directory.
        modulename = 'openerp.addons.' + module_record.name
        root = __import__(modulename)
        module = getattr(root.addons, module_record.name)

        reimport(module)
    RegistryManager.delete(cr.dbname)
    RegistryManager.new(cr.dbname)
    return {}

rawDescription: Force python interpreter to reload a code module


rawDescription: Identifying keys by looking at values in a dictionary


code:
import os
if 'GATEWAY_INTERFACE' in os.environ:
    print ('CGI')
else:
    print ('Not CGI. CLI?')

rawDescription: Distinguish from command line and CGI in python


code:
import wx

#===================================================================================================
class UpperPanel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.combo = wx.ComboBox(self, choices=["0", "1", "2", "3", "4"], size=(200, -1))
        self.combo.Bind(wx.EVT_COMBOBOX, self.GetParent().middlePanel.Change)
        self.logo = wx.Button(self, size=(300, 100))

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.combo, 0, wx.EXPAND)
        self.sizer.Add(self.logo, 0, wx.EXPAND)

        self.SetSizerAndFit(self.sizer)

#===================================================================================================
class MiddlePanel(wx.Panel):
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.subs = []
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizerAndFit(self.sizer)

    def Change(self, e):
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        for a in self.subs:
            a.Destroy()

        self.subs = []

        for a in range(int(e.GetString())):
            b = wx.Button(self, size=(-1, 50))
            self.subs.append(b)
            self.sizer.Add(b, 1, wx.EXPAND)

        self.SetSizerAndFit(self.sizer)
        self.GetParent().Fit()

#===================================================================================================
class MainWin(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)

        self.middlePanel = MiddlePanel(self)
        self.upperPanel = UpperPanel(self)
        self.textArea = wx.TextCtrl(self, size=(-1, 300), style=wx.TE_MULTILINE)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.upperPanel, 0, wx.EXPAND)
        self.sizer.Add(self.middlePanel, 0, wx.EXPAND)
        self.sizer.Add(self.textArea, 1, wx.EXPAND)

        self.SetSizerAndFit(self.sizer)

#===================================================================================================
if __name__ == '__main__':
    app = wx.PySimpleApp()
    main_win = MainWin()
    main_win.Show()
    app.MainLoop()

rawDescription: Update/Refresh Dynamically–Created WxPython Widgets


code:
def test_evens():
    for i in range(0, 5):
        yield check_even, i, i*3

def check_even(n, nn):
    assert n % 2 == 0 or nn % 2 == 0

rawDescription: Python's unittest and dynamic creation of test cases


code: x = inputCoordinate()

rawDescription: return key in python

description: Return key in python


code:
def get_max(f, s):
  return max(s, key=f)

rawDescription: more pythonic way of finding element in list that maximizes a function

description: More pythonic way of finding element in list that maximizes a function


code:
def create_deep_dict(value, layers):

    orig_data = {}
    data = orig_data
    last_layer = layers[-1]

    for layer in layers[:-1]:
        data[layer] = {}
        data = data[layer]

    data[last_layer] = value

    return orig_data

def deep_dict_value(data, layers):

    for layer in layers:
        data = data[layer]

    return data

rawDescription: Dynamically set deep python dict

description: Dynamically set deep python dict


code:
import sys

sys.argv = ['programname', '-iq', '-q', directory]
gendeps.gendeps()

rawDescription: Mock command line arguments for Python script with `optparse`?


code:
#coding=utf-8

from cx_Freeze import setup, Executable

includes = ["atexit"]

buildOptions = dict(
    create_shared_zip=False,
    append_script_to_exe=True,
    includes=includes
)

executables = [
    Executable(
        script='main.py',
        targetName='projectname.exe',
        base="Win32GUI" # THIS ONE IS IMPORTANT FOR GUI APPLICATION
    )
]

setup(
    name="ProjectName",
    version="1.0",
    description="",
    options=dict(build_exe=buildOptions),
    executables=executables
)

rawDescription: Converting python files and PyQt into a windows executable?


code:
import re
new_string = re.sub(r'-\d+\.\d+', '0.1', your_string)

rawDescription: python: Detecting a negative number within a string

description: Python: Detecting a negative number within a string


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

def synthimage():
    w,h = 300,200
    im = np.random.randint(0,255,(w,h,3))/255
    xa = np.random.randint(50,w-60)
    xb = xa + np.random.randint(50,90)
    ya = np.random.randint(50,h-60)
    yb = ya + np.random.randint(20,50)
    im[xa:xb,ya] = np.array([1,0,0])
    im[xa:xb,yb] = np.array([1,0,0])
    im[xa,ya:yb] = np.array([1,0,0])
    im[xb,ya:yb] = np.array([1,0,0])
    return im

def getRectPoints(im):
    x,y = [],[]
    for i in range(im.shape[0]):
        for j in range(im.shape[1]):
            if (im[i,j]-np.array([1,0,0])).sum()==0:
                x.append(i)
                y.append(j)
    return np.array(x),np.array(y)

def denoise(x,y):
    nx,ny = [],[]
    for i in range(x.shape[0]):
        d = np.sqrt((x[i]-x)**2+(y[i]-y)**2)
        m = d<2
        if len(m.nonzero()[0])>2:
            nx.append(x[i])
            ny.append(y[i])
    return np.array(nx),np.array(ny)

im = synthimage()
plt.imshow(np.swapaxes(im,0,1),origin='lower',interpolation='nearest')
plt.show()

x,y = getRectPoints(im)
plt.scatter(x,y,c='red')
plt.xlim(0,300)
plt.ylim(0,200)
plt.show()

nx,ny = denoise(x,y)
plt.scatter(nx,ny,c='red')
plt.xlim(0,300)
plt.ylim(0,200)
plt.show()

#Assuming rectangle has no rotation (otherwise check Scipy ConveHull)
xmi = nx.min()
xma = nx.max()
ymi = ny.min()
yma = ny.max()

new = np.ones(im.shape)
new[xmi:xma,ymi:yma] = im[xmi:xma,ymi:yma]
plt.imshow(np.swapaxes(new,0,1),origin='lower',interpolation='nearest')
plt.show()

rawDescription: Crop a pattern-based area of multiple images in python


code:
s = [u'+', u'+', u'o']
col = ['r','r','g']
x = np.array([1,2,3])
y = np.array([4,5,6])

for _s, c, _x, _y in zip(s, col, x, y):
    plt.scatter(_x, _y, marker=_s, c=c)

plt.xlim(0, 4)
plt.ylim(0, 8)

plt.show()

rawDescription: matplotlib scatter plot with different markers and colors

description: Matplotlib scatter plot with different markers and colors


code:
import pkgutil

def module_exists(m):
    for module_loader, name, ispkg in pkgutil.iter_modules():
        if name == m:
            return True
    return False

rawDescription: Determine, is module name already defined, without loading module


code:
example_dict = {"foo": 1, "bar": 2}
map(example_dict.__getitem__, ['foo', 'bar'])

rawDescription: Syntactic sugar for multiple dictionary lookups in one operation


code:
'assesses'.find('sses', 0)    # first look at the start of the string
'assesses'.find('sses', 2)    # now look at previous index + 1
'assesses'.find('sses', 5)    # now look at previous index + 1

rawDescription: Substring Counting in Python and Adding 2 Numbers From One Line of Input


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

x = np.arange(0,10,1)
y = np.arange(0,1,0.2)

xs, ys = np.meshgrid(x, y)
# z = calculate_R(xs, ys)
zs = xs**2 + ys**2

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(xs, ys, zs, rstride=1, cstride=1, cmap='hot')
plt.show()

rawDescription: 3D plot with an 2D array python matplotlib