INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns the name of the nearest named hue. | def nearest_hue(self, primary=False):
""" Returns the name of the nearest named hue.
For example,
if you supply an indigo color (a color between blue and violet),
the return value is "violet". If primary is set to True,
the return value is "purple".
Primary colors lea... |
Returns a mix of two colors. | def blend(self, clr, factor=0.5):
"""
Returns a mix of two colors.
"""
r = self.r * (1 - factor) + clr.r * factor
g = self.g * (1 - factor) + clr.g * factor
b = self.b * (1 - factor) + clr.b * factor
a = self.a * (1 - factor) + clr.a * factor
return Color(... |
Returns the Euclidean distance between two colors ( 0. 0 - 1. 0 ). | def distance(self, clr):
"""
Returns the Euclidean distance between two colors (0.0-1.0).
Consider colors arranged on the color wheel:
- hue is the angle of a color along the center
- saturation is the distance of a color from the center
- brightness is the elevation of ... |
Rectangle swatch for this color. | def swatch(self, x, y, w=35, h=35, roundness=0):
"""
Rectangle swatch for this color.
"""
_ctx.fill(self)
_ctx.rect(x, y, w, h, roundness) |
Returns a list of colors based on pixel values in the image. | def image_to_rgb(self, path, n=10):
"""
Returns a list of colors based on pixel values in the image.
The Core Image library must be present to determine pixel colors.
F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05
"""
from PIL import Image
... |
Returns the colors that have the given word in their context. | def context_to_rgb(self, str):
""" Returns the colors that have the given word in their context.
For example, the word "anger" appears
in black, orange and red contexts,
so the list will contain those three colors.
"""
matches = []
for clr in context:
... |
Returns the intersection of each color s context. | def _context(self):
"""
Returns the intersection of each color's context.
Get the nearest named hue of each color,
and finds overlapping tags in each hue's colors.
For example, a list containing yellow, deeppink and olive
yields: femininity, friendship, happiness, joy.
... |
Returns a deep copy of the list. | def copy(self):
""" Returns a deep copy of the list.
"""
return ColorList(
[color(clr.r, clr.g, clr.b, clr.a, mode="rgb") for clr in self],
name=self.name,
tags=self.tags
) |
Returns the darkest color from the list. | def _darkest(self):
"""
Returns the darkest color from the list.
Knowing the contrast between a light and a dark swatch
can help us decide how to display readable typography.
"""
min, n = (1.0, 1.0, 1.0), 3.0
for clr in self:
if clr.r + clr.g + clr.b... |
Returns one average color for the colors in the list. | def _average(self):
"""
Returns one average color for the colors in the list.
"""
r, g, b, a = 0, 0, 0, 0
for clr in self:
r += clr.r
g += clr.g
b += clr.b
a += clr.alpha
r /= len(self)
g /= len(self)
b /= l... |
Returns a list with the smallest distance between two neighboring colors. The algorithm has a factorial complexity so it may run slow. | def sort_by_distance(self, reversed=False):
"""
Returns a list with the smallest distance between two neighboring colors.
The algorithm has a factorial complexity so it may run slow.
"""
if len(self) == 0: return ColorList()
# Find the darkest color in the list.
... |
Returns a sorted copy with the colors arranged according to the given comparison. | def _sorted_copy(self, comparison, reversed=False):
"""
Returns a sorted copy with the colors arranged according to the given comparison.
"""
sorted = self.copy()
_list.sort(sorted, comparison)
if reversed:
_list.reverse(sorted)
return sorted |
Sorts the list by cmp1 then cuts it into n pieces which are sorted by cmp2. | def cluster_sort(self, cmp1="hue", cmp2="brightness", reversed=False, n=12):
"""
Sorts the list by cmp1, then cuts it into n pieces which are sorted by cmp2.
If you want to cluster by hue, use n=12 (since there are 12 primary/secondary hues).
The resulting list will not contain n even s... |
Returns a reversed copy of the list. | def reverse(self):
"""
Returns a reversed copy of the list.
"""
colors = ColorList.copy(self)
_list.reverse(colors)
return colors |
Returns a list that is a repetition of the given list. | def repeat(self, n=2, oscillate=False, callback=None):
"""
Returns a list that is a repetition of the given list.
When oscillate is True,
moves from the end back to the beginning,
and then from the beginning to the end, and so on.
"""
colorlist = ColorList()
... |
Rectangle swatches for all the colors in the list. | def swatch(self, x, y, w=35, h=35, padding=0, roundness=0):
"""
Rectangle swatches for all the colors in the list.
"""
for clr in self:
clr.swatch(x, y, w, h, roundness)
y += h + padding |
Fancy random ovals for all the colors in the list. | def swarm(self, x, y, r=100):
"""
Fancy random ovals for all the colors in the list.
"""
sc = _ctx.stroke(0, 0, 0, 0)
sw = _ctx.strokewidth(0)
_ctx.push()
_ctx.transform(_ctx.CORNER)
_ctx.translate(x, y)
for i in _range(r * 3):
clr = ... |
Returns intermediary colors for given list of colors. | def _interpolate(self, colors, n=100):
""" Returns intermediary colors for given list of colors.
"""
gradient = []
for i in _range(n):
l = len(colors) - 1
x = int(1.0 * i / n * l)
x = min(x + 0, l)
y = min(x + 1, l)
base = 1.... |
Populates the list with a number of gradient colors. | def _cache(self):
"""
Populates the list with a number of gradient colors.
The list has Gradient.steps colors that interpolate between
the fixed base Gradient.colors.
The spread parameter controls the midpoint of the gradient,
you can shift it right and left. A separate... |
Returns a copy of the range. | def copy(self, clr=None, d=0.0):
"""
Returns a copy of the range.
Optionally, supply a color to get a range copy
limited to the hue of that color.
"""
cr = ColorRange()
cr.name = self.name
cr.h = deepcopy(self.h)
cr.s = deepcopy(self.s)
c... |
Returns a color with random values in the defined h s b a ranges. | def color(self, clr=None, d=0.035):
"""
Returns a color with random values in the defined h, s b, a ranges.
If a color is given, use that color's hue and alpha,
and generate its saturation and brightness from the shade.
The hue is varied with the given d.
In this way yo... |
Returns True if the given color is part of this color range. | def contains(self, clr):
"""
Returns True if the given color is part of this color range.
Check whether each h, s, b, a component of the color
falls within the defined range for that component.
If the given color is grayscale,
checks against the definitions for black an... |
Returns a list of ( hue ranges total weight normalized total weight ) - tuples. | def _weight_by_hue(self):
"""
Returns a list of (hue, ranges, total weight, normalized total weight)-tuples.
ColorTheme is made up out of (color, range, weight) tuples.
For consistency with XML-output in the old Prism format
(i.e. <color>s made up of <shade>s) we need a group
... |
Returns the color information as XML. | def _xml(self):
"""
Returns the color information as XML.
The XML has the following structure:
<colors query="">
<color name="" weight="" />
<rgb r="" g="" b="" />
<shade name="" weight="" />
</color>
</colors>
Not... |
Saves the color information in the cache as XML. | def _save(self):
"""
Saves the color information in the cache as XML.
"""
if not os.path.exists(self.cache):
os.makedirs(self.cache)
path = os.path.join(self.cache, self.name + ".xml")
f = open(path, "w")
f.write(self.xml)
f.close() |
Loads a theme from aggregated web data. | def _load(self, top=5, blue="blue", archive=None, member=None):
"""
Loads a theme from aggregated web data.
The data must be old-style Prism XML: <color>s consisting of <shade>s.
Colors named "blue" will be overridden with the blue parameter.
archive can be a file like object (... |
Returns a random color within the theme. | def color(self, d=0.035):
"""
Returns a random color within the theme.
Fetches a random range (the weight is taken into account,
so ranges with a bigger weight have a higher chance of propagating)
and hues it with the associated color.
"""
s = sum([w for clr, rng... |
Returns a number of random colors from the theme. | def colors(self, n=10, d=0.035):
"""
Returns a number of random colors from the theme.
"""
s = sum([w for clr, rng, w in self.ranges])
colors = colorlist()
for i in _range(n):
r = random()
for clr, rng, weight in self.ranges:
if wei... |
Genetic recombination of two themes using cut and splice technique. | def recombine(self, other, d=0.7):
"""
Genetic recombination of two themes using cut and splice technique.
"""
a, b = self, other
d1 = max(0, min(d, 1))
d2 = d1
c = ColorTheme(
name=a.name[:int(len(a.name) * d1)] +
b.name[int(len(b.na... |
Draws a weighted swatch with approximately n columns and rows. | def swatch(self, x, y, w=35, h=35, padding=4, roundness=0, n=12, d=0.035, grouped=None):
"""
Draws a weighted swatch with approximately n columns and rows.
When the grouped parameter is True, colors are grouped in blocks of the same hue
(also see the _weight_by_hue() method).
""... |
fseq messages associate a unique frame id with a set of set and alive messages | def fseq(self, client, message):
"""
fseq messages associate a unique frame id with a set of set
and alive messages
"""
client.last_frame = client.current_frame
client.current_frame = message[3] |
Returns a generator list of tracked objects which are recognized with this profile and are in the current session. | def objs(self):
"""
Returns a generator list of tracked objects which are recognized with
this profile and are in the current session.
"""
for obj in self.objects.itervalues():
if obj.sessionid in self.sessions:
yield obj |
Append a render function and the parameters to pass an equivilent PathElement or the PathElement itself. | def _append_element(self, render_func, pe):
'''
Append a render function and the parameters to pass
an equivilent PathElement, or the PathElement itself.
'''
self._render_funcs.append(render_func)
self._elements.append(pe) |
Return cached bounds of this Grob. If bounds are not cached render to a meta surface and keep the meta surface and bounds cached. | def _get_bounds(self):
'''
Return cached bounds of this Grob.
If bounds are not cached, render to a meta surface, and
keep the meta surface and bounds cached.
'''
if self._bounds:
return self._bounds
record_surface = cairo.RecordingSurface(cairo.CONTE... |
Return cached bounds of this Grob. If bounds are not cached render to a meta surface and keep the meta surface and bounds cached. | def contains(self, x, y):
'''
Return cached bounds of this Grob.
If bounds are not cached, render to a meta surface, and
keep the meta surface and bounds cached.
'''
if self._bounds:
return self._bounds
record_surface = cairo.RecordingSurface(cairo.CO... |
Return cached bounds of this Grob. If bounds are not cached render to a meta surface and keep the meta surface and bounds cached. | def _get_center(self):
'''
Return cached bounds of this Grob.
If bounds are not cached, render to a meta surface, and
keep the meta surface and bounds cached.
'''
if self._center:
return self._center
# get the center point
(x1, y1, x2, y2) = s... |
Use a closure so that draw attributes can be saved | def _render_closure(self):
'''Use a closure so that draw attributes can be saved'''
fillcolor = self.fill
strokecolor = self.stroke
strokewidth = self.strokewidth
def _render(cairo_ctx):
'''
At the moment this is based on cairo.
TODO: Need to... |
Returns a list of contours in the path as BezierPath objects. A contour is a sequence of lines and curves separated from the next contour by a MOVETO. For example the glyph o has two contours: the inner circle and the outer circle. | def _get_contours(self):
"""
Returns a list of contours in the path, as BezierPath objects.
A contour is a sequence of lines and curves separated from the next contour by a MOVETO.
For example, the glyph "o" has two contours: the inner circle and the outer circle.
"""
# O... |
Locates t on a specific segment in the path. Returns ( index t PathElement ) A path is a combination of lines and curves ( segments ). The returned index indicates the start of the segment that contains point t. The returned t is the absolute time on that segment in contrast to the relative t on the whole of the path. ... | def _locate(self, t, segments=None):
""" Locates t on a specific segment in the path.
Returns (index, t, PathElement)
A path is a combination of lines and curves (segments).
The returned index indicates the start of the segment that contains point t.
The returned ... |
Returns the PathElement at time t ( 0. 0 - 1. 0 ) on the path. | def point(self, t, segments=None):
"""
Returns the PathElement at time t (0.0-1.0) on the path.
Returns coordinates for point at t on the path.
Gets the length of the path, based on the length of each curve and line in the path.
Determines in what segment t falls... |
Returns an iterator with a list of calculated points for the path. To omit the last point on closed paths: end = 1 - 1. 0/ amount | def points(self, amount=100, start=0.0, end=1.0, segments=None):
""" Returns an iterator with a list of calculated points for the path.
To omit the last point on closed paths: end=1-1.0/amount
"""
# Originally from nodebox-gl
if len(self._elements) == 0:
raise Pat... |
Returns coordinates for point at t on the line. Calculates the coordinates of x and y for a point at t on a straight line. The t parameter is a number between 0. 0 and 1. 0 x0 and y0 define the starting point of the line x1 and y1 the ending point of the line. | def _linepoint(self, t, x0, y0, x1, y1):
""" Returns coordinates for point at t on the line.
Calculates the coordinates of x and y for a point at t on a straight line.
The t parameter is a number between 0.0 and 1.0,
x0 and y0 define the starting point of the line,
... |
Returns the length of the line. | def _linelength(self, x0, y0, x1, y1):
""" Returns the length of the line.
"""
# Originally from nodebox-gl
a = pow(abs(x0 - x1), 2)
b = pow(abs(y0 - y1), 2)
return sqrt(a + b) |
Returns coordinates for point at t on the spline. Calculates the coordinates of x and y for a point at t on the cubic bezier spline and its control points based on the de Casteljau interpolation algorithm. The t parameter is a number between 0. 0 and 1. 0 x0 and y0 define the starting point of the spline x1 and y1 its ... | def _curvepoint(self, t, x0, y0, x1, y1, x2, y2, x3, y3, handles=False):
""" Returns coordinates for point at t on the spline.
Calculates the coordinates of x and y for a point at t on the cubic bezier spline,
and its control points, based on the de Casteljau interpolation algorithm.
... |
Returns the length of the spline. Integrates the estimated length of the cubic bezier spline defined by x0 y0... x3 y3 by adding the lengths of lineair lines between points at t. The number of points is defined by n ( n = 10 would add the lengths of lines between 0. 0 and 0. 1 between 0. 1 and 0. 2 and so on ). The def... | def _curvelength(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
""" Returns the length of the spline.
Integrates the estimated length of the cubic bezier spline defined by x0, y0, ... x3, y3,
by adding the lengths of lineair lines between points at t.
The number of points is de... |
Returns a list with the lengths of each segment in the path. | def _segment_lengths(self, relative=False, n=20):
""" Returns a list with the lengths of each segment in the path.
"""
# From nodebox_gl
lengths = []
first = True
for el in self._get_elements():
if first is True:
close_x, close_y = el.x, el.y
... |
Returns the length of the path. Calculates the length of each spline in the path using n as a number of points to measure. When segmented is True returns a list containing the individual length of each spline as values between 0. 0 and 1. 0 defining the relative length of each spline in relation to the total path lengt... | def _get_length(self, segmented=False, precision=10):
""" Returns the length of the path.
Calculates the length of each spline in the path, using n as a number of points to measure.
When segmented is True, returns a list containing the individual length of each spline
as valu... |
Yields all elements as PathElements | def _get_elements(self):
'''
Yields all elements as PathElements
'''
for index, el in enumerate(self._elements):
if isinstance(el, tuple):
el = PathElement(*el)
self._elements[index] = el
yield el |
Simple multi - purpose depth - first search. Visits all the nodes connected to the root depth - first. The visit function is called on each node. Recursion will stop if it returns True and ubsequently dfs () will return True. The traversable function takes the current node and edge and returns True if we are allowed to... | def depth_first_search(root, visit=lambda node: False, traversable=lambda node, edge: True):
""" Simple, multi-purpose depth-first search.
Visits all the nodes connected to the root, depth-first.
The visit function is called on each node.
Recursion will stop if it returns True, and ubsequently dfs... |
An edge weight map indexed by node id s. A dictionary indexed by node id1 s in which each value is a dictionary of connected node id2 s linking to the edge weight. If directed edges go from id1 to id2 but not the other way. If stochastic all the weights for the neighbors of a given node sum to 1. A heuristic can be a f... | def adjacency(graph, directed=False, reversed=False, stochastic=False, heuristic=None):
""" An edge weight map indexed by node id's.
A dictionary indexed by node id1's in which each value is a
dictionary of connected node id2's linking to the edge weight.
If directed, edges go from id1 to id2,... |
Betweenness centrality for nodes in the graph. Betweenness centrality is a measure of the number of shortests paths that pass through a node. Nodes in high - density areas will get a good score. The algorithm is Brandes betweenness centrality from NetworkX 0. 35. 1: Aric Hagberg Dan Schult and Pieter Swart based on Dij... | def brandes_betweenness_centrality(graph, normalized=True):
""" Betweenness centrality for nodes in the graph.
Betweenness centrality is a measure of the number of shortests paths that pass through a node.
Nodes in high-density areas will get a good score.
The algorithm is Brandes' betweennes... |
Eigenvector centrality for nodes in the graph ( like Google s PageRank ). Eigenvector centrality is a measure of the importance of a node in a directed network. It rewards nodes with a high potential of ( indirectly ) connecting to high - scoring nodes. Nodes with no incoming connections have a score of zero. If you wa... | def eigenvector_centrality(graph, normalized=True, reversed=True, rating={},
start=None, iterations=100, tolerance=0.0001):
""" Eigenvector centrality for nodes in the graph (like Google's PageRank).
Eigenvector centrality is a measure of the importance of a node in a directed n... |
: return: xml for menu [ ( bot_action label )... ] [ ( menu_action label )... ] | def examples_menu(root_dir=None, depth=0):
"""
:return: xml for menu, [(bot_action, label), ...], [(menu_action, label), ...]
"""
# pre 3.12 menus
examples_dir = ide_utils.get_example_dir()
if not examples_dir:
return "", [], []
root_dir = root_dir or examples_dir
file_tmpl = '... |
: return: base_item rel_paths | def mk_examples_menu(text, root_dir=None, depth=0):
"""
:return: base_item, rel_paths
"""
# 3.12+ menus
examples_dir = ide_utils.get_example_dir()
if not examples_dir:
return None, []
root_dir = root_dir or examples_dir
file_actions = []
menu = Gio.Menu.new()
b... |
Iterate through a gtk container parent and return the widget with the name name. | def get_child_by_name(parent, name):
"""
Iterate through a gtk container, `parent`,
and return the widget with the name `name`.
"""
# http://stackoverflow.com/questions/2072976/access-to-widget-in-gtk
def iterate_children(widget, name):
if widget.get_name() == name:
return wi... |
: param script: script to look for in bin folder | def venv_has_script(script):
"""
:param script: script to look for in bin folder
"""
def f(venv):
path=os.path.join(venv, 'bin', script)
if os.path.isfile(path):
return True
return f |
: param directory: base directory of python environment | def is_venv(directory, executable='python'):
"""
:param directory: base directory of python environment
"""
path=os.path.join(directory, 'bin', executable)
return os.path.isfile(path) |
: return: python environments in ~/. virtualenvs | def vw_envs(filter=None):
"""
:return: python environments in ~/.virtualenvs
:param filter: if this returns False the venv will be ignored
>>> vw_envs(filter=venv_has_script('pip'))
"""
vw_root=os.path.abspath(os.path.expanduser(os.path.expandvars('~/.virtualenvs')))
venvs=[]
for direc... |
Find shoebot executable | def sbot_executable():
"""
Find shoebot executable
"""
gsettings=load_gsettings()
venv = gsettings.get_string('current-virtualenv')
if venv == 'Default':
sbot = which('sbot')
elif venv == 'System':
# find system python
env_venv = os.environ.get('VIRTUAL_ENV')
... |
Returns the meta description in the page. | def _description(self):
""" Returns the meta description in the page.
"""
meta = self.find("meta", {"name":"description"})
if isinstance(meta, dict) and \
meta.has_key("content"):
return meta["content"]
else:
return u"" |
Returns the meta keywords in the page. | def _keywords(self):
""" Returns the meta keywords in the page.
"""
meta = self.find("meta", {"name":"keywords"})
if isinstance(meta, dict) and \
meta.has_key("content"):
keywords = [k.strip() for k in meta["content"].split(",")]
else:
... |
Retrieves links in the page. Returns a list of URL s. By default only external URL s are returned. External URL s starts with http:// and point to another domain than the domain the page is on. | def links(self, external=True):
""" Retrieves links in the page.
Returns a list of URL's.
By default, only external URL's are returned.
External URL's starts with http:// and point to another
domain than the domain the page is on.
"""
... |
Returns a sorted copy of the list. | def sorted(list, cmp=None, reversed=False):
""" Returns a sorted copy of the list.
"""
list = [x for x in list]
list.sort(cmp)
if reversed: list.reverse()
return list |
Returns a copy of the list without duplicates. | def unique(list):
""" Returns a copy of the list without duplicates.
"""
unique = []; [unique.append(x) for x in list if x not in unique]
return unique |
Recursively lists the node and its links. Distance of 0 will return the given [ node ]. Distance of 1 will return a list of the node and all its links. Distance of 2 will also include the linked nodes links etc. | def flatten(node, distance=1):
""" Recursively lists the node and its links.
Distance of 0 will return the given [node].
Distance of 1 will return a list of the node and all its links.
Distance of 2 will also include the linked nodes' links, etc.
"""
# When you pass a graph i... |
Creates the subgraph of the flattened node with given id ( or list of id s ). Finds all the edges between the nodes that make up the subgraph. | def subgraph(graph, id, distance=1):
""" Creates the subgraph of the flattened node with given id (or list of id's).
Finds all the edges between the nodes that make up the subgraph.
"""
g = graph.copy(empty=True)
if isinstance(id, (FunctionType, LambdaType)):
# id can also be ... |
Returns the largest possible clique for the node with given id. | def clique(graph, id):
""" Returns the largest possible clique for the node with given id.
"""
clique = [id]
for n in graph.nodes:
friend = True
for id in clique:
if n.id == id or graph.edge(n.id, id) == None:
friend = False
break
... |
Returns all the cliques in the graph of at least the given size. | def cliques(graph, threshold=3):
""" Returns all the cliques in the graph of at least the given size.
"""
cliques = []
for n in graph.nodes:
c = clique(graph, n.id)
if len(c) >= threshold:
c.sort()
if c not in cliques:
cliques.append(c)
... |
Splits unconnected subgraphs. For each node in the graph make a list of its id and all directly connected id s. If one of the nodes in this list intersects with a subgraph they are all part of that subgraph. Otherwise this list is part of a new subgraph. Return a list of subgraphs sorted by size ( biggest - first ). | def partition(graph):
""" Splits unconnected subgraphs.
For each node in the graph, make a list of its id and all directly connected id's.
If one of the nodes in this list intersects with a subgraph,
they are all part of that subgraph.
Otherwise, this list is part of a new subgraph.
Re... |
Calls implmentation to get a render context passes it to the drawqueues render function then calls self. rendering_finished | def render(self, size, frame, drawqueue):
'''
Calls implmentation to get a render context,
passes it to the drawqueues render function
then calls self.rendering_finished
'''
r_context = self.create_rcontext(size, frame)
drawqueue.render(r_context)
self.ren... |
Context manager to only update listeners at the end in the meantime it doesn t matter what intermediate state the vars are in ( they can be added and removed ) | def batch(vars, oldvars, ns):
"""
Context manager to only update listeners
at the end, in the meantime it doesn't
matter what intermediate state the vars
are in (they can be added and removed)
>>> with VarListener.batch()
... pass
"""
snapshot... |
Useful utility ; prints the string in hexadecimal | def hexDump(bytes):
"""Useful utility; prints the string in hexadecimal"""
for i in range(len(bytes)):
sys.stdout.write("%2x " % (ord(bytes[i])))
if (i+1) % 8 == 0:
print repr(bytes[i-7:i+1])
if(len(bytes) % 8 != 0):
print string.rjust("", 11), repr(bytes[i-len(bytes)%8:... |
Tries to interpret the next 8 bytes of the data as a 64 - bit signed integer. | def readLong(data):
"""Tries to interpret the next 8 bytes of the data
as a 64-bit signed integer."""
high, low = struct.unpack(">ll", data[0:8])
big = (long(high) << 32) + low
rest = data[8:]
return (big, rest) |
Convert a string into an OSC Blob returning a ( typetag data ) tuple. | def OSCBlob(next):
"""Convert a string into an OSC Blob,
returning a (typetag, data) tuple."""
if type(next) == type(""):
length = len(next)
padded = math.ceil((len(next)) / 4.0) * 4
binary = struct.pack(">i%ds" % (padded), length, next)
tag = 'b'
else:
tag ... |
Convert some Python types to their OSC binary representations returning a ( typetag data ) tuple. | def OSCArgument(next):
"""Convert some Python types to their
OSC binary representations, returning a
(typetag, data) tuple."""
if type(next) == type(""):
OSCstringLength = math.ceil((len(next)+1) / 4.0) * 4
binary = struct.pack(">%ds" % (OSCstringLength), next)
tag = "s"
el... |
Given a list of strings produces a list where those strings have been parsed ( where possible ) as floats or integers. | def parseArgs(args):
"""Given a list of strings, produces a list
where those strings have been parsed (where
possible) as floats or integers."""
parsed = []
for arg in args:
print arg
arg = arg.strip()
interpretation = None
try:
interpretation = float(arg)... |
Converts a typetagged OSC message to a Python list. | def decodeOSC(data):
"""Converts a typetagged OSC message to a Python list."""
table = {"i":readInt, "f":readFloat, "s":readString, "b":readBlob}
decoded = []
address, rest = readString(data)
typetags = ""
if address == "#bundle":
time, rest = readLong(rest)
# decoded.append(addr... |
Appends data to the message updating the typetags based on the argument s type. If the argument is a blob ( counted string ) pass in b as typehint. | def append(self, argument, typehint = None):
"""Appends data to the message,
updating the typetags based on
the argument's type.
If the argument is a blob (counted string)
pass in 'b' as typehint."""
if typehint == 'b':
binary = OSCBlob(argument)
else... |
Returns the binary message ( so far ) with typetags. | def getBinary(self):
"""Returns the binary message (so far) with typetags."""
address = OSCArgument(self.address)[1]
typetags = OSCArgument(self.typetags)[1]
return address + typetags + self.message |
Given OSC data tries to call the callback with the right address. | def handle(self, data, source = None):
"""Given OSC data, tries to call the callback with the
right address."""
decoded = decodeOSC(data)
self.dispatch(decoded, source) |
Sends decoded OSC data to an appropriate calback | def dispatch(self, message, source = None):
"""Sends decoded OSC data to an appropriate calback"""
msgtype = ""
try:
if type(message[0]) == str:
# got a single message
address = message[0]
self.callbacks[address](message)
el... |
Adds a callback to our set of callbacks or removes the callback with name if callback is None. | def add(self, callback, name):
"""Adds a callback to our set of callbacks,
or removes the callback with name if callback
is None."""
if callback == None:
del self.callbacks[name]
else:
self.callbacks[name] = callback |
Find examples dir.. a little bit ugly.. | def find_example_dir():
"""
Find examples dir .. a little bit ugly..
"""
# Replace %s with directory to check for shoebot menus.
code_stub = textwrap.dedent("""
from pkg_resources import resource_filename, Requirement, DistributionNotFound
try:
print(resource_filename(Requirement.par... |
The body of the tread: read lines and put them on the queue. | def run(self):
"""
The body of the tread: read lines and put them on the queue.
"""
try:
for line in iter(self._fd.readline, False):
if line is not None:
if self._althandler:
if self._althandler(line):
... |
Check whether there is no more content to expect. | def eof(self):
"""
Check whether there is no more content to expect.
"""
return (not self.is_alive()) and self._queue.empty() or self._fd.closed |
Send new source code to the bot | def live_source_load(self, source):
"""
Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return:
"""
source = source.rstrip('\n... |
: param cmd:: param args:: return: | def send_command(self, cmd, *args):
"""
:param cmd:
:param args:
:return:
"""
# Test in python 2 and 3 before modifying (gedit2 + 3)
if True:
# Create a CommandResponse using a cookie as a unique id
cookie = str(uuid.uuid4())
re... |
Close outputs of process. | def close(self):
"""
Close outputs of process.
"""
self.process.stdout.close()
self.process.stderr.close()
self.running = False |
: yield: stdout_line stderr_line running | def get_output(self):
"""
:yield: stdout_line, stderr_line, running
Generator that outputs lines captured from stdout and stderr
These can be consumed to output on a widget in an IDE
"""
if self.process.poll() is not None:
self.close()
yield Non... |
Get responses to commands sent | def get_command_responses(self):
"""
Get responses to commands sent
"""
if not self.response_queue.empty():
yield None
while not self.response_queue.empty():
line = self.response_queue.get()
if line is not None:
yield line |
: param options: List of options: param prefer: Prefered options: return: | def sort_by_preference(options, prefer):
"""
:param options: List of options
:param prefer: Prefered options
:return:
Pass in a list of options, return options in 'prefer' first
>>> sort_by_preference(["cairo", "cairocffi"], ["cairocffi"])
["cairocffi", "cairo"]
"""
if not prefer:
... |
Interpret env var as key = value: return: | def get_driver_options():
"""
Interpret env var as key=value
:return:
"""
options = os.environ.get("SHOEBOT_GRAPHICS")
if not options:
return {}
try:
return dict([kv.split('=') for kv in options.split()])
except ValueError:
sys.stderr.write("Bad option format.\n"... |
Loop through module_names add has_.... booleans to class set... _impl to first successful import | def import_libs(self, module_names, impl_name):
"""
Loop through module_names,
add has_.... booleans to class
set ..._impl to first successful import
:param module_names: list of module names to try importing
:param impl_name: used in error output if no modules succeed... |
If ctx is a cairocffi Context convert it to a PyCairo Context otherwise return the original context | def ensure_pycairo_context(self, ctx):
"""
If ctx is a cairocffi Context convert it to a PyCairo Context
otherwise return the original context
:param ctx:
:return:
"""
if self.cairocffi and isinstance(ctx, self.cairocffi.Context):
from shoebot.util.ca... |
If python - gi - cairo is not installed using PangoCairo. create_context dies with an unhelpful KeyError check for that and output somethig useful. | def pangocairo_create_context(cr):
"""
If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful.
"""
# TODO move this to core.backend
try:
return PangoCairo.create_context(cr)
except KeyError a... |
Returns the center point of the path disregarding transforms. | def _get_center(self):
'''Returns the center point of the path, disregarding transforms.
'''
w, h = self.layout.get_pixel_size()
x = (self.x + w / 2)
y = (self.y + h / 2)
return x, y |
Determines if an item in a paragraph is a list. | def is_list(str):
""" Determines if an item in a paragraph is a list.
If all of the lines in the markup start with a "*" or "1."
this indicates a list as parsed by parse_paragraphs().
It can be drawn with draw_list().
"""
for chunk in str.split("\n"):
chunk = chunk.replace... |
Determines if an item in a paragraph is a LaTeX math equation. Math equations are wrapped in <math > </ math > tags. They can be drawn as an image using draw_math (). | def is_math(str):
""" Determines if an item in a paragraph is a LaTeX math equation.
Math equations are wrapped in <math></math> tags.
They can be drawn as an image using draw_math().
"""
str = str.strip()
if str.startswith("<math>") and str.endswith("</math>"):
retur... |
Uses mimetex to generate a GIF - image from the LaTeX equation. | def draw_math(str, x, y, alpha=1.0):
""" Uses mimetex to generate a GIF-image from the LaTeX equation.
"""
try: from web import _ctx
except: pass
str = re.sub("</{0,1}math>", "", str.strip())
img = mimetex.gif(str)
w, h = _ctx.imagesize(img)
_ctx.image(img, x, y, alpha=alp... |
textwidth () reports incorrectly when lineheight () is smaller than 1. 0 | def textwidth(str):
"""textwidth() reports incorrectly when lineheight() is smaller than 1.0
"""
try: from web import _ctx
except: pass
l = _ctx.lineheight()
_ctx.lineheight(1)
w = _ctx.textwidth(str)
_ctx.lineheight(l)
return w |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.