Search is not available for this dataset
text stringlengths 75 104k |
|---|
def search_images(q, start=0, size="", wait=10, asynchronous=False, cached=False):
""" Returns a Google images query formatted as a GoogleSearch list object.
"""
service = GOOGLE_IMAGES
return GoogleSearch(q, start, service, size, wait, asynchronous, cached) |
def search_news(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google news query formatted as a GoogleSearch list object.
"""
service = GOOGLE_NEWS
return GoogleSearch(q, start, service, "", wait, asynchronous, cached) |
def search_blogs(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google blogs query formatted as a GoogleSearch list object.
"""
service = GOOGLE_BLOGS
return GoogleSearch(q, start, service, "", wait, asynchronous, cached) |
def _parse(self, str):
""" Parses the text data from an XML element defined by tag.
"""
str = replace_entities(str)
str = strip_tags(str)
str = collapse_spaces(str)
return str |
def hash(self, id):
""" Creates a unique filename in the cache for the id.
"""
h = md5(id).hexdigest()
return os.path.join(self.path, h+self.type) |
def age(self, id):
""" Returns the age of the cache entry, in days.
"""
path = self.hash(id)
if os.path.exists(path):
modified = datetime.datetime.fromtimestamp(os.stat(path)[8])
age = datetime.datetime.today() - modified
return age.days
else... |
def angle(x0, y0, x1, y1):
""" Returns the angle between two points.
"""
return degrees(atan2(y1-y0, x1-x0)) |
def distance(x0, y0, x1, y1):
""" Returns the distance between two points.
"""
return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2)) |
def coordinates(x0, y0, distance, angle):
""" Returns the location of a point by rotating around origin (x0,y0).
"""
return (x0 + cos(radians(angle)) * distance,
y0 + sin(radians(angle)) * distance) |
def rotate(x, y, x0, y0, angle):
""" Returns the coordinates of (x,y) rotated around origin (x0,y0).
"""
x, y = x - x0, y - y0
a, b = cos(radians(angle)), sin(radians(angle))
return (x * a - y * b + x0,
y * a + x * b + y0) |
def reflect(x, y, x0, y0, d=1.0, a=180):
""" Returns the reflection of a point through origin (x0,y0).
"""
return coordinates(x0, y0, d * distance(x0, y0, x, y),
a + angle(x0, y0, x, y)) |
def lerp(a, b, t):
""" Returns the linear interpolation between a and b for time t between 0.0-1.0.
For example: lerp(100, 200, 0.5) => 150.
"""
if t < 0.0:
return a
if t > 1.0:
return b
return a + (b - a) * t |
def smoothstep(a, b, x):
""" Returns a smooth transition between 0.0 and 1.0 using Hermite interpolation (cubic spline),
where x is a number between a and b. The return value will ease (slow down) as x nears a or b.
For x smaller than a, returns 0.0. For x bigger than b, returns 1.0.
"""
... |
def line_line_intersection(x1, y1, x2, y2, x3, y3, x4, y4, infinite=False):
""" Determines the intersection point of two lines, or two finite line segments if infinite=False.
When the lines do not intersect, returns an empty list.
"""
# Based on: P. Bourke, http://local.wasp.uwa.edu.au/~pbourke/... |
def circle_line_intersection(cx, cy, radius, x1, y1, x2, y2, infinite=False):
""" Returns a list of points where the circle and the line intersect.
Returns an empty list when the circle and the line do not intersect.
"""
# Based on: http://www.vb-helper.com/howto_net_line_circle_intersection... |
def point_in_polygon(points, x, y):
""" Ray casting algorithm.
Determines how many times a horizontal ray starting from the point
intersects with the sides of the polygon.
If it is an even number of times, the point is outside, if odd, inside.
The algorithm does not always repor... |
def _mmult(self, a, b):
""" Returns the 3x3 matrix multiplication of A and B.
Note that scale(), translate(), rotate() work with premultiplication,
e.g. the matrix A followed by B = BA and not AB.
"""
# No need to optimize (C version is just as fast).
return... |
def invert(self):
""" Multiplying a matrix by its inverse produces the identity matrix.
"""
m = self.matrix
d = m[0] * m[4] - m[1] * m[3]
self.matrix = [
m[4] / d, -m[1] / d, 0,
-m[3] / d, m[0] / d, 0,
(m[3] * m[7] - m[4] * m[6]) / ... |
def transform_point(self, x, y):
""" Returns the new coordinates of (x,y) after transformation.
"""
m = self.matrix
return (x*m[0]+y*m[3]+m[6], x*m[1]+y*m[4]+m[7]) |
def transform_path(self, path):
""" Returns a BezierPath object with the transformation applied.
"""
p = path.__class__() # Create a new BezierPath.
for pt in path:
if pt.cmd == "close":
p.closepath()
elif pt.cmd == "moveto":
... |
def intersects(self, b):
""" Return True if a part of the two bounds overlaps.
"""
return max(self.x, b.x) < min(self.x+self.width, b.x+b.width) \
and max(self.y, b.y) < min(self.y+self.height, b.y+b.height) |
def intersection(self, b):
""" Returns bounds that encompass the intersection of the two.
If there is no overlap between the two, None is returned.
"""
if not self.intersects(b):
return None
mx, my = max(self.x, b.x), max(self.y, b.y)
return Bounds(... |
def union(self, b):
""" Returns bounds that encompass the union of the two.
"""
mx, my = min(self.x, b.x), min(self.y, b.y)
return Bounds(mx, my,
max(self.x+self.width, b.x+b.width) - mx,
max(self.y+self.height, b.y+b.height) - my) |
def contains(self, *a):
""" Returns True if the given point or rectangle falls within the bounds.
"""
if len(a) == 2: a = [Point(a[0], a[1])]
if len(a) == 1:
a = a[0]
if isinstance(a, Point):
return a.x >= self.x and a.x <= self.x+self.width... |
def error(message):
'''Prints an error message, the help message and quits'''
global parser
print (_("Error: ") + message)
print ()
parser.print_help()
sys.exit() |
def ellipse(self, x, y, width, height, draw=True, **kwargs):
'''Draws an ellipse starting from (x,y)'''
path = self.BezierPath(**kwargs)
path.ellipse(x,y,width,height)
if draw:
path.draw()
return path |
def line(self, x1, y1, x2, y2, draw=True):
'''Draws a line from (x1,y1) to (x2,y2)'''
p = self._path
self.newpath()
self.moveto(x1,y1)
self.lineto(x2,y2)
self.endpath(draw=draw)
self._path = p
return p |
def colormode(self, mode=None, crange=None):
'''Sets the current colormode (can be RGB or HSB) and eventually
the color range.
If called without arguments, it returns the current colormode.
'''
if mode is not None:
if mode == "rgb":
self.color_mode = ... |
def fill(self,*args):
'''Sets a fill color, applying it to new paths.'''
self._fillcolor = self.color(*args)
return self._fillcolor |
def stroke(self,*args):
'''Set a stroke color, applying it to new paths.'''
self._strokecolor = self.color(*args)
return self._strokecolor |
def textpath(self, txt, x, y, width=None, height=1000000, enableRendering=False, **kwargs):
'''
Draws an outlined path of the input text
'''
txt = self.Text(txt, x, y, width, height, **kwargs)
path = txt.path
if draw:
path.draw()
return path |
def textmetrics(self, txt, width=None, height=None, **kwargs):
'''Returns the width and height of a string of text as a tuple
(according to current font settings).
'''
# for now only returns width and height (as per Nodebox behaviour)
# but maybe we could use the other data from ... |
def draw_cornu_flat(x0, y0, t0, t1, s0, c0, flip, cs, ss, cmd):
""" Raph Levien's code draws fast LINETO segments.
"""
for j in range(0, 100):
t = j * .01
s, c = eval_cornu(t0 + t * (t1 - t0))
s *= flip
s -= s0
c -= c0
#print '%', c, s
x = c ... |
def draw_cornu_bezier(x0, y0, t0, t1, s0, c0, flip, cs, ss, cmd, scale, rot):
""" Mark Meyer's code draws elegant CURVETO segments.
"""
s = None
for j in range(0, 5):
# travel along the function two points at a time (at time t and t2)
# the first time through we'll need to get both poi... |
def search(q, start=1, count=10, context=None, wait=10, asynchronous=False, cached=False):
""" Returns a Yahoo web query formatted as a YahooSearch list object.
"""
service = YAHOO_SEARCH
return YahooSearch(q, start, count, service, context, wait, asynchronous, cached) |
def search_images(q, start=1, count=10, wait=10, asynchronous=False, cached=False):
""" Returns a Yahoo images query formatted as a YahooSearch list object.
"""
service = YAHOO_IMAGES
return YahooSearch(q, start, count, service, None, wait, asynchronous, cached) |
def search_news(q, start=1, count=10, wait=10, asynchronous=False, cached=False):
""" Returns a Yahoo news query formatted as a YahooSearch list object.
"""
service = YAHOO_NEWS
return YahooSearch(q, start, count, service, None, wait, asynchronous, cached) |
def suggest_spelling(q, wait=10, asynchronous=False, cached=False):
""" Returns list of suggested spelling corrections for the given query.
"""
return YahooSpelling(q, wait, asynchronous, cached) |
def sort(words, context="", strict=True, relative=True, service=YAHOO_SEARCH,
wait=10, asynchronous=False, cached=False):
"""Performs a Yahoo sort on the given list.
Sorts the items in the list according to
the result count Yahoo yields on an item.
Setting a context sorts the it... |
def _parse(self, e, tag):
""" Parses the text data from an XML element defined by tag.
"""
tags = e.getElementsByTagName(tag)
children = tags[0].childNodes
if len(children) != 1: return None
assert children[0].nodeType == xml.dom.minidom.Element.TEXT_NOD... |
def layer(self, img, x=0, y=0, name=""):
"""Creates a new layer from file, Layer, PIL Image.
If img is an image file or PIL Image object,
Creates a new layer with the given image file.
The image is positioned on the canvas at x, y.
If img is a Layer,
us... |
def fill(self, rgb, x=0, y=0, w=None, h=None, name=""):
"""Creates a new fill layer.
Creates a new layer filled with the given rgb color.
For example, fill((255,0,0)) creates a red fill.
The layers fills the entire canvas by default.
"""
if w == None:... |
def gradient(self, style=LINEAR, w=1.0, h=1.0, name=""):
"""Creates a gradient layer.
Creates a gradient layer, that is usually used
together with the mask() function.
All the image functions work on gradients,
so they can easily be flipped, rotated, scaled, invert... |
def merge(self, layers):
"""Flattens the given layers on the canvas.
Merges the given layers with the indices in the list
on the bottom layer in the list.
The other layers are discarded.
"""
layers.sort()
if layers[0] == 0: del ... |
def flatten(self, layers=[]):
"""Flattens all layers according to their blend modes.
Merges all layers to the canvas,
using the blend mode and opacity defined for each layer.
Once flattened, the stack of layers is emptied except
for the transparent background (bottom la... |
def export(self, filename):
"""Exports the flattened canvas.
Flattens the canvas.
PNG retains the alpha channel information.
Other possibilities are JPEG and GIF.
"""
self.flatten()
self.layers[1].img.save(filename)
return filename |
def draw(self, x, y):
"""Places the flattened canvas in NodeBox.
Exports to a temporary PNG file.
Draws the PNG in NodeBox using the image() command.
Removes the temporary file.
"""
try:
from time import time
imp... |
def index(self):
"""Returns this layer's index in the canvas.layers[].
Searches the position of this layer in the canvas'
layers list, return None when not found.
"""
for i in range(len(self.canvas.layers)):
if self.canvas.layers[i]... |
def copy(self):
"""Returns a copy of the layer.
This is different from the duplicate() method,
which duplicates the layer as a new layer on the canvas.
The copy() method returns a copy of the layer
that can be added to a different canvas.
"""
... |
def delete(self):
"""Removes this layer from the canvas.
"""
i = self.index()
if i != None: del self.canvas.layers[i] |
def up(self):
"""Moves the layer up in the stacking order.
"""
i = self.index()
if i != None:
del self.canvas.layers[i]
i = min(len(self.canvas.layers), i+1)
self.canvas.layers.insert(i, self) |
def down(self):
"""Moves the layer down in the stacking order.
"""
i = self.index()
if i != None:
del self.canvas.layers[i]
i = max(0, i-1)
self.canvas.layers.insert(i, self) |
def select(self, path, feather=True):
"""Applies the polygonal lasso tool on a layer.
The path paramater is a list of points,
either [x1, y1, x2, y2, x3, y3, ...]
or [(x1,y1), (x2,y2), (x3,y3), ...]
The parts of the layer that fall outside
this polygonal ar... |
def mask(self):
"""Masks the layer below with this layer.
Commits the current layer to the alpha channel of
the previous layer. Primarily, mask() is useful when
using gradient layers as masks on images below.
For example:
canvas.layer("image.jpg")
... |
def duplicate(self):
"""Creates a copy of the current layer.
This copy becomes the top layer on the canvas.
"""
i = self.canvas.layer(self.img.copy(), self.x, self.y, self.name)
clone = self.canvas.layers[i]
clone.alpha = self.alpha
clone.blend... |
def brightness(self, value=1.0):
"""Increases or decreases the brightness in the layer.
The given value is a percentage to increase
or decrease the image brightness,
for example 0.8 means brightness at 80%.
"""
b = ImageEnhance.Brightness(self.img)
... |
def contrast(self, value=1.0):
"""Increases or decreases the contrast in the layer.
The given value is a percentage to increase
or decrease the image contrast,
for example 1.2 means contrast at 120%.
"""
c = ImageEnhance.Contrast(self.img)
self.im... |
def desaturate(self):
"""Desaturates the layer, making it grayscale.
Instantly removes all color information from the layer,
while maintaing its alpha channel.
"""
alpha = self.img.split()[3]
self.img = self.img.convert("L")
self.img = self.img... |
def invert(self):
"""Inverts the layer.
"""
alpha = self.img.split()[3]
self.img = self.img.convert("RGB")
self.img = ImageOps.invert(self.img)
self.img = self.img.convert("RGBA")
self.img.putalpha(alpha) |
def translate(self, x, y):
"""Positions the layer at the given coordinates.
The x and y parameters define where to position
the top left corner of the layer,
measured from the top left of the canvas.
"""
self.x = x
self.y = y |
def scale(self, w=1.0, h=1.0):
"""Resizes the layer to the given width and height.
When width w or height h is a floating-point number,
scales percentual,
otherwise scales to the given size in pixels.
"""
from types import FloatType
w0, h0 = self.... |
def distort(self, x1=0,y1=0, x2=0,y2=0, x3=0,y3=0, x4=0,y4=0):
"""Distorts the layer.
Distorts the layer by translating
the four corners of its bounding box to the given coordinates:
upper left (x1,y1), upper right(x2,y2),
lower right (x3,y3) and lower left (x4,y4)... |
def rotate(self, angle):
"""Rotates the layer.
Rotates the layer by given angle.
Positive numbers rotate counter-clockwise,
negative numbers rotate clockwise.
Rotate commands are executed instantly,
so many subsequent rotates will distort the image.
... |
def flip(self, axis=HORIZONTAL):
"""Flips the layer, either HORIZONTAL or VERTICAL.
"""
if axis == HORIZONTAL:
self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)
if axis == VERTICAL:
self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM) |
def sharpen(self, value=1.0):
"""Increases or decreases the sharpness in the layer.
The given value is a percentage to increase
or decrease the image sharpness,
for example 0.8 means sharpness at 80%.
"""
s = ImageEnhance.Sharpness(self.img)
self... |
def levels(self):
"""Returns a histogram for each RGBA channel.
Returns a 4-tuple of lists, r, g, b, and a.
Each list has 255 items, a count for each pixel value.
"""
h = self.img.histogram()
r = h[0:255]
g = h[256:511]
... |
def overlay(self, img1, img2):
"""Applies the overlay blend mode.
Overlays image img2 on image img1.
The overlay pixel combines multiply and screen:
it multiplies dark pixels values and screen light values.
Returns a composite image with the alpha channel retained.
... |
def hue(self, img1, img2):
"""Applies the hue blend mode.
Hues image img1 with image img2.
The hue filter replaces the hues of pixels in img1
with the hues of pixels in img2.
Returns a composite image with the alpha channel retained.
"""
import col... |
def convolute(self, kernel, scale=None, offset=0):
"""A (3,3) or (5,5) convolution kernel.
The kernel argument is a list with either 9 or 25 elements,
the weight for each surrounding pixels to convolute.
"""
if len(kernel) == 9: size = (3,3)... |
def _load_namespace(self, namespace, filename=None):
"""
Initialise bot namespace with info in shoebot.data
:param filename: Will be set to __file__ in the namespace
"""
from shoebot import data
for name in dir(data):
namespace[name] = getattr(data, name)
... |
def _should_run(self, iteration, max_iterations):
''' Return False if bot should quit '''
if iteration == 0:
# First frame always runs
return True
if max_iterations:
if iteration < max_iterations:
return True
elif max_iterations is None... |
def _frame_limit(self, start_time):
"""
Limit to framerate, should be called after
rendering has completed
:param start_time: When execution started
"""
if self._speed:
completion_time = time()
exc_time = completion_time - start_time
s... |
def _run_frame(self, executor, limit=False, iteration=0):
""" Run single frame of the bot
:param source_or_code: path to code to run, or actual code.
:param limit: Time a frame should take to run (float - seconds)
"""
#
# Gets a bit complex here...
#
# No... |
def run(self, inputcode, iterations=None, run_forever=False, frame_limiter=False, verbose=False,
break_on_error=False):
'''
Executes the contents of a Nodebox/Shoebot script
in current surface's context.
:param inputcode: Path to shoebot source or string containing source
... |
def _addvar(self, v):
''' Sets a new accessible variable.
:param v: Variable.
'''
oldvar = self._oldvars.get(v.name)
if oldvar is not None:
if isinstance(oldvar, Variable):
if oldvar.compliesTo(v):
v.value = oldvar.value
... |
def parse_color(v, color_range=1):
'''Receives a colour definition and returns a (r,g,b,a) tuple.
Accepts:
- v
- (v)
- (v,a)
- (r,g,b)
- (r,g,b,a)
- #RRGGBB
- RRGGBB
- #RRGGBBAA
- RRGGBBAA
Returns a (red, green, blue, alpha) tuple, with values ranging from
0 to 1.
... |
def hex_to_rgb(hex):
""" Returns RGB values for a hex color string.
"""
hex = hex.lstrip("#")
if len(hex) < 6:
hex += hex[-1] * (6 - len(hex))
if len(hex) == 6:
r, g, b = hex[0:2], hex[2:4], hex[4:]
r, g, b = [int(n, 16) / 255.0 for n in (r, g, b)]
a = 1.0
elif le... |
def cmyk_to_rgb(c, m, y, k):
""" Cyan, magenta, yellow, black to red, green, blue.
ReportLab, http://www.koders.com/python/fid5C006F554616848C01AC7CB96C21426B69D2E5A9.aspx
Results will differ from the way NSColor converts color spaces.
"""
r = 1.0 - min(1.0, c + k)
g = 1.0 - min(1.0, m + k)
... |
def hsv_to_rgb(h, s, v):
""" Hue, saturation, brightness to red, green, blue.
http://www.koders.com/python/fidB2FE963F658FE74D9BF74EB93EFD44DCAE45E10E.aspx
Results will differ from the way NSColor converts color spaces.
"""
if s == 0: return v, v, v
h = h / (60.0 / 360)
i = floor(h)
f ... |
def simple_traceback(ex, source):
"""
Format traceback, showing line number and surrounding source.
"""
exc_type, exc_value, exc_tb = sys.exc_info()
exc = traceback.format_exception(exc_type, exc_value, exc_tb)
source_arr = source.splitlines()
# Defaults...
exc_location = exc[-2]
f... |
def connect(self, name):
"""Generic database.
Opens the SQLite database with the given name.
The .db extension is automatically appended to the name.
For each table in the database an attribute is created,
and assigned a Table object.
You can do... |
def create(self, name, overwrite=True):
"""Creates an SQLite database file.
Creates an SQLite database with the given name.
The .box file extension is added automatically.
Overwrites any existing database by default.
"""
self._name = na... |
def create_table(self, name, fields=[], key="id"):
"""Creates a new table.
Creates a table with the given name,
containing the list of given fields.
Since SQLite uses manifest typing, no data type need be supplied.
The primary key is "id" by default,
an ... |
def create_index(self, table, field, unique=False, ascending=True):
"""Creates a table index.
Creates an index on the given table,
on the given field with unique values enforced or not,
in ascending or descending order.
"""
if unique: u... |
def close(self):
"""Commits any pending transactions and closes the database.
"""
self._con.commit()
self._cur.close()
self._con.close() |
def sql(self, sql):
""" Executes a raw SQL statement on the database.
"""
self._cur.execute(sql)
if sql.lower().find("select") >= 0:
matches = []
for r in self._cur: matches.append(r)
return matches |
def find(self, q, operator="=", fields="*", key=None):
"""A simple SQL SELECT query.
Retrieves all rows from the table
where the given query value is found in the given column (primary key if None).
A different comparison operator (e.g. >, <, like) can be set.
... |
def append(self, *args, **kw):
"""Adds a new row to a table.
Adds a row to the given table.
The column names and their corresponding values
must either be supplied as a dictionary of {fields:values},
or a series of keyword arguments of field=value style.
... |
def edit(self, id, *args, **kw):
""" Edits the row with given id.
"""
if args and kw:
return
if args and type(args[0]) == dict:
fields = [k for k in args[0]]
v = [args[0][k] for k in args[0]]
if kw:
fields = [k fo... |
def remove(self, id, operator="=", key=None):
""" Deletes the row with given id.
"""
if key == None: key = self._key
try: id = unicode(id)
except: pass
sql = "delete from "+self._name+" where "+key+" "+operator+" ?"
self._db._cur.execute(sql, (id,)) |
def next_event(block=False, timeout=None):
"""
Get the next available event or None
:param block:
:param timeout:
:return: None or (event, data)
"""
try:
return channel.listen(block=block, timeout=timeout).next()['data']
except StopIteration:
return None |
def publish_event(event_t, data=None, extra_channels=None, wait=None):
"""
Publish an event ot any subscribers.
:param event_t: event type
:param data: event data
:param extra_channels:
:param wait:
:return:
"""
event = Event(event_t, data)
pubsub.publish("shoebot", event)
... |
def _set_mode(self, mode):
'''
Sets call_transform_mode to point to the
center_transform or corner_transform
'''
if mode == CENTER:
self._call_transform_mode = self._center_transform
elif mode == CORNER:
self._call_transform_mode = self._corner_tra... |
def _center_transform(self, transform):
''''
Works like setupTransform of a version of java nodebox
http://dev.nodebox.net/browser/nodebox-java/branches/rewrite/src/java/net/nodebox/graphics/Grob.java
'''
dx, dy = self._get_center()
t = cairo.Matrix()
t.translate(... |
def inheritFromContext(self, ignore=()):
"""
Doesn't store exactly the same items as Nodebox for ease of implementation,
it has enough to get the Nodebox Dentrite example working.
"""
for canvas_attr, grob_attr in STATES.items():
if canvas_attr in ignore:
... |
def load_edited_source(self, source, good_cb=None, bad_cb=None, filename=None):
"""
Load changed code into the execution environment.
Until the code is executed correctly, it will be
in the 'tenuous' state.
"""
with LiveExecution.lock:
self.good_cb = good_cb
... |
def reload_functions(self):
"""
Replace functions in namespace with functions from edited_source.
"""
with LiveExecution.lock:
if self.edited_source:
tree = ast.parse(self.edited_source)
for f in [n for n in ast.walk(tree) if isinstance(n, ast.... |
def run_tenuous(self):
"""
Run edited source, if no exceptions occur then it
graduates to known good.
"""
with LiveExecution.lock:
ns_snapshot = copy.copy(self.ns)
try:
source = self.edited_source
self.edited_source = None
... |
def run(self):
"""
Attempt to known good or tenuous source.
"""
with LiveExecution.lock:
if self.edited_source:
success, ex = self.run_tenuous()
if success:
return
self.do_exec(self.known_good, self.ns) |
def call_bad_cb(self, tb):
"""
If bad_cb returns True then keep it
:param tb: traceback that caused exception
:return:
"""
with LiveExecution.lock:
if self.bad_cb and not self.bad_cb(tb):
self.bad_cb = None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.