_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q259900 | NodeBot.relmoveto | validation | def relmoveto(self, x, y):
'''Move relatively to the last point.'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.relmoveto(x, y) | python | {
"resource": ""
} |
q259901 | NodeBot.rellineto | validation | def rellineto(self, x, y):
'''Draw a line using relative coordinates.'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.rellineto(x, y) | python | {
"resource": ""
} |
q259902 | NodeBot.relcurveto | validation | def relcurveto(self, h1x, h1y, h2x, h2y, x, y):
'''Draws a curve relatively to the last point.
'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.relcurveto(h1x, h1y, h2x, h2y, x, y) | python | {
"resource": ""
} |
q259903 | NodeBot.transform | validation | def transform(self, mode=None):
'''
Set the current transform mode.
:param mode: CENTER or CORNER'''
if mode:
self._canvas.mode = mode
return self._canvas.mode | python | {
"resource": ""
} |
q259904 | NodeBot.scale | validation | def scale(self, x=1, y=None):
'''
Set a scale at which to draw objects.
1.0 draws objects at their natural size
:param x: Scale on the horizontal plane
:param y: Scale on the vertical plane
'''
if not y:
y = x
if x == 0:
# Cairo b... | python | {
"resource": ""
} |
q259905 | NodeBot.nostroke | validation | def nostroke(self):
''' Stop applying strokes to new paths.
:return: stroke color before nostroke was called.
'''
c = self._canvas.strokecolor
self._canvas.strokecolor = None
return c | python | {
"resource": ""
} |
q259906 | NodeBot.strokewidth | validation | def strokewidth(self, w=None):
'''Set the stroke width.
:param w: Stroke width.
:return: If no width was specified then current width is returned.
'''
if w is not None:
self._canvas.strokewidth = w
else:
return self._canvas.strokewidth | python | {
"resource": ""
} |
q259907 | NodeBot.font | validation | def font(self, fontpath=None, fontsize=None):
'''Set the font to be used with new text instances.
:param fontpath: path to truetype or opentype font.
:param fontsize: size of font
:return: current current fontpath (if fontpath param not set)
Accepts TrueType and OpenType files.... | python | {
"resource": ""
} |
q259908 | NodeBot.fontsize | validation | def fontsize(self, fontsize=None):
'''
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
'''
if fontsize is not None:
self._canvas.fontsize = fontsize
else:
return self... | python | {
"resource": ""
} |
q259909 | NodeBot.text | validation | def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs):
'''
Draws a string of text according to current font settings.
:param txt: Text to output
:param x: x-coordinate of the top left corner
:param y: y-coordinate of the top left corner
... | python | {
"resource": ""
} |
q259910 | NodeBot.textheight | validation | def textheight(self, txt, width=None):
'''Returns the height of a string of text according to the current
font settings.
:param txt: string to measure
:param width: width of a line of text in a block
'''
w = width
return self.textmetrics(txt, width=w)[1] | python | {
"resource": ""
} |
q259911 | graph_background | validation | def graph_background(s):
""" Graph background color.
"""
if s.background == None:
s._ctx.background(None)
else:
s._ctx.background(s.background)
if s.depth:
try:
clr = colors.color(s.background).darker(0.2)
p = s._ctx.rect(0, 0, s._ctx.WIDTH, s._ct... | python | {
"resource": ""
} |
q259912 | node | validation | def node(s, node, alpha=1.0):
""" Visualization of a default node.
"""
if s.depth:
try: colors.shadow(dx=5, dy=5, blur=10, alpha=0.5*alpha)
except: pass
s._ctx.nofill()
s._ctx.nostroke()
if s.fill:
s._ctx.fill(
s.fill.r,
s.fill.g,
... | python | {
"resource": ""
} |
q259913 | node_label | validation | def node_label(s, node, alpha=1.0):
""" Visualization of a node's id.
"""
if s.text:
#s._ctx.lineheight(1)
s._ctx.font(s.font)
s._ctx.fontsize(s.fontsize)
s._ctx.nostroke()
s._ctx.fill(
s.text.r,
s.text.g,
s.text.b,
... | python | {
"resource": ""
} |
q259914 | edges | validation | def edges(s, edges, alpha=1.0, weighted=False, directed=False):
""" Visualization of the edges in a network.
"""
p = s._ctx.BezierPath()
if directed and s.stroke:
pd = s._ctx.BezierPath()
if weighted and s.fill:
pw = [s._ctx.BezierPath() for i in range(11)... | python | {
"resource": ""
} |
q259915 | edge | validation | def edge(s, path, edge, alpha=1.0):
""" Visualization of a single edge between two nodes.
"""
path.moveto(edge.node1.x, edge.node1.y)
if edge.node2.style == BACK:
path.curveto(
edge.node1.x,
edge.node2.y,
edge.node2.x,
edge.node2.y,
... | python | {
"resource": ""
} |
q259916 | edge_label | validation | def edge_label(s, edge, alpha=1.0):
""" Visualization of the label accompanying an edge.
"""
if s.text and edge.label != "":
s._ctx.nostroke()
s._ctx.fill(
s.text.r,
s.text.g,
s.text.b,
s.text.a * alpha*0.75
)
s._ctx... | python | {
"resource": ""
} |
q259917 | path | validation | def path(s, graph, path):
""" Visualization of a shortest path between two nodes.
"""
def end(n):
r = n.r * 0.35
s._ctx.oval(n.x-r, n.y-r, r*2, r*2)
if path and len(path) > 1 and s.stroke:
s._ctx.nofill()
s._ctx.stroke(
s.stroke.r,
s.stroke.g,
... | python | {
"resource": ""
} |
q259918 | styles.create | validation | def create(self, stylename, **kwargs):
""" Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
"""
if stylename == "default":
self[stylename] = style(stylename, self._ctx, **kwargs)
... | python | {
"resource": ""
} |
q259919 | styles.copy | validation | def copy(self, graph):
""" Returns a copy of all styles and a copy of the styleguide.
"""
s = styles(graph)
s.guide = self.guide.copy(graph)
dict.__init__(s, [(v.name, v.copy()) for v in self.values()])
return s | python | {
"resource": ""
} |
q259920 | styleguide.apply | validation | def apply(self):
""" Check the rules for each node in the graph and apply the style.
"""
sorted = self.order + self.keys()
unique = []; [unique.append(x) for x in sorted if x not in unique]
for node in self.graph.nodes:
for s in unique:
if self.has_key... | python | {
"resource": ""
} |
q259921 | styleguide.copy | validation | def copy(self, graph):
""" Returns a copy of the styleguide for the given graph.
"""
g = styleguide(graph)
g.order = self.order
dict.__init__(g, [(k, v) for k, v in self.iteritems()])
return g | python | {
"resource": ""
} |
q259922 | Tracking.open_socket | validation | def open_socket(self):
"""
Opens the socket and binds to the given host and port. Uses
SO_REUSEADDR to be as robust as possible.
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
se... | python | {
"resource": ""
} |
q259923 | Tracking.load_profiles | validation | def load_profiles(self):
"""
Loads all possible TUIO profiles and returns a dictionary with the
profile addresses as keys and an instance of a profile as the value
"""
_profiles = {}
for name, klass in inspect.getmembers(profiles):
if inspect.isclass(klass) a... | python | {
"resource": ""
} |
q259924 | Tracking.update | validation | def update(self):
"""
Tells the connection manager to receive the next 1024 byte of messages
to analyze.
"""
try:
self.manager.handle(self.socket.recv(1024))
except socket.error:
pass | python | {
"resource": ""
} |
q259925 | Tracking.callback | validation | def callback(self, *incoming):
"""
Gets called by the CallbackManager if a new message was received
"""
message = incoming[0]
if message:
address, command = message[0], message[2]
profile = self.get_profile(address)
if profile is not None:
... | python | {
"resource": ""
} |
q259926 | copytree | validation | def copytree(src, dst, symlinks=False, ignore=None):
"""
copytree that works even if folder already exists
"""
# http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
if not os.path.exists(dst):
os.makedirs(dst)
sh... | python | {
"resource": ""
} |
q259927 | dumps | validation | def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
... | python | {
"resource": ""
} |
q259928 | search | validation | def search(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google web query formatted as a GoogleSearch list object.
"""
service = GOOGLE_SEARCH
return GoogleSearch(q, start, service, "", wait, asynchronous, cached) | python | {
"resource": ""
} |
q259929 | search_images | validation | 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) | python | {
"resource": ""
} |
q259930 | search_news | validation | 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) | python | {
"resource": ""
} |
q259931 | search_blogs | validation | 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) | python | {
"resource": ""
} |
q259932 | Cache.hash | validation | 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) | python | {
"resource": ""
} |
q259933 | Cache.age | validation | 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... | python | {
"resource": ""
} |
q259934 | angle | validation | def angle(x0, y0, x1, y1):
""" Returns the angle between two points.
"""
return degrees(atan2(y1-y0, x1-x0)) | python | {
"resource": ""
} |
q259935 | distance | validation | def distance(x0, y0, x1, y1):
""" Returns the distance between two points.
"""
return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2)) | python | {
"resource": ""
} |
q259936 | line_line_intersection | validation | 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/... | python | {
"resource": ""
} |
q259937 | circle_line_intersection | validation | 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... | python | {
"resource": ""
} |
q259938 | AffineTransform.invert | validation | 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]) / ... | python | {
"resource": ""
} |
q259939 | AffineTransform.transform_path | validation | 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":
... | python | {
"resource": ""
} |
q259940 | Bounds.intersection | validation | 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(... | python | {
"resource": ""
} |
q259941 | Bounds.union | validation | 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) | python | {
"resource": ""
} |
q259942 | error | validation | def error(message):
'''Prints an error message, the help message and quits'''
global parser
print (_("Error: ") + message)
print ()
parser.print_help()
sys.exit() | python | {
"resource": ""
} |
q259943 | DrawBot.textpath | validation | 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 | python | {
"resource": ""
} |
q259944 | draw_cornu_flat | validation | 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 ... | python | {
"resource": ""
} |
q259945 | draw_cornu_bezier | validation | 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... | python | {
"resource": ""
} |
q259946 | search | validation | 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) | python | {
"resource": ""
} |
q259947 | search_images | validation | 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) | python | {
"resource": ""
} |
q259948 | search_news | validation | 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) | python | {
"resource": ""
} |
q259949 | suggest_spelling | validation | 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) | python | {
"resource": ""
} |
q259950 | Canvas.layer | validation | 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... | python | {
"resource": ""
} |
q259951 | Canvas.merge | validation | 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 ... | python | {
"resource": ""
} |
q259952 | Canvas.export | validation | 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 | python | {
"resource": ""
} |
q259953 | Layer.delete | validation | def delete(self):
"""Removes this layer from the canvas.
"""
i = self.index()
if i != None: del self.canvas.layers[i] | python | {
"resource": ""
} |
q259954 | Layer.up | validation | 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) | python | {
"resource": ""
} |
q259955 | Layer.down | validation | 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) | python | {
"resource": ""
} |
q259956 | Layer.duplicate | validation | 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... | python | {
"resource": ""
} |
q259957 | Layer.brightness | validation | 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)
... | python | {
"resource": ""
} |
q259958 | Layer.contrast | validation | 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... | python | {
"resource": ""
} |
q259959 | Layer.desaturate | validation | 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... | python | {
"resource": ""
} |
q259960 | Layer.invert | validation | 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) | python | {
"resource": ""
} |
q259961 | Layer.translate | validation | 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 | python | {
"resource": ""
} |
q259962 | Layer.scale | validation | 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.... | python | {
"resource": ""
} |
q259963 | Layer.rotate | validation | 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.
... | python | {
"resource": ""
} |
q259964 | Layer.flip | validation | 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) | python | {
"resource": ""
} |
q259965 | Layer.sharpen | validation | 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... | python | {
"resource": ""
} |
q259966 | Layer.levels | validation | 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]
... | python | {
"resource": ""
} |
q259967 | Blend.hue | validation | 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... | python | {
"resource": ""
} |
q259968 | Grammar._load_namespace | validation | 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)
... | python | {
"resource": ""
} |
q259969 | Grammar._should_run | validation | 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... | python | {
"resource": ""
} |
q259970 | Grammar._frame_limit | validation | 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... | python | {
"resource": ""
} |
q259971 | Grammar._addvar | validation | 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
... | python | {
"resource": ""
} |
q259972 | hex_to_rgb | validation | 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... | python | {
"resource": ""
} |
q259973 | simple_traceback | validation | 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... | python | {
"resource": ""
} |
q259974 | Database.create | validation | 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... | python | {
"resource": ""
} |
q259975 | Database.create_table | validation | 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 ... | python | {
"resource": ""
} |
q259976 | Database.create_index | validation | 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... | python | {
"resource": ""
} |
q259977 | Database.close | validation | def close(self):
"""Commits any pending transactions and closes the database.
"""
self._con.commit()
self._cur.close()
self._con.close() | python | {
"resource": ""
} |
q259978 | Database.sql | validation | 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 | python | {
"resource": ""
} |
q259979 | Table.edit | validation | 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... | python | {
"resource": ""
} |
q259980 | Table.remove | validation | 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,)) | python | {
"resource": ""
} |
q259981 | next_event | validation | 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 | python | {
"resource": ""
} |
q259982 | publish_event | validation | 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)
... | python | {
"resource": ""
} |
q259983 | Grob._set_mode | validation | 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... | python | {
"resource": ""
} |
q259984 | Grob.inheritFromContext | validation | 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:
... | python | {
"resource": ""
} |
q259985 | LiveExecution.load_edited_source | validation | 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
... | python | {
"resource": ""
} |
q259986 | LiveExecution.reload_functions | validation | 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.... | python | {
"resource": ""
} |
q259987 | LiveExecution.run_tenuous | validation | 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
... | python | {
"resource": ""
} |
q259988 | LiveExecution.run | validation | 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) | python | {
"resource": ""
} |
q259989 | LiveExecution.run_context | validation | def run_context(self):
"""
Context in which the user can run the source in a custom manner.
If no exceptions occur then the source will move from 'tenuous'
to 'known good'.
>>> with run_context() as (known_good, source, ns):
>>> ... exec source in ns
>>> ... n... | python | {
"resource": ""
} |
q259990 | Boid.separation | validation | def separation(self, r=10):
""" Boids keep a small distance from other boids.
Ensures that boids don't collide into each other,
in a smoothly accelerated motion.
"""
vx = vy = vz = 0
for b in self.boids:
if b != self:
... | python | {
"resource": ""
} |
q259991 | Boid.alignment | validation | def alignment(self, d=5):
""" Boids match velocity with other boids.
"""
vx = vy = vz = 0
for b in self.boids:
if b != self:
vx, vy, vz = vx+b.vx, vy+b.vy, vz+b.vz
n = len(self.boids)-1
vx, vy, vz = vx/n, vy/n, vz/n
... | python | {
"resource": ""
} |
q259992 | Boid.limit | validation | def limit(self, max=30):
""" The speed limit for a boid.
Boids can momentarily go very fast,
something that is impossible for real animals.
"""
if abs(self.vx) > max:
self.vx = self.vx/abs(self.vx)*max
if abs(self.vy) > max... | python | {
"resource": ""
} |
q259993 | Boid._angle | validation | def _angle(self):
""" Returns the angle towards which the boid is steering.
"""
from math import atan, pi, degrees
a = degrees(atan(self.vy/self.vx)) + 360
if self.vx < 0: a += 180
return a | python | {
"resource": ""
} |
q259994 | Boid.goal | validation | def goal(self, x, y, z, d=50.0):
""" Tendency towards a particular place.
"""
return (x-self.x)/d, (y-self.y)/d, (z-self.z)/d | python | {
"resource": ""
} |
q259995 | Boids.update | validation | def update(self,
shuffled=True,
cohesion=100,
separation=10,
alignment=5,
goal=20,
limit=30):
""" Calculates the next motion frame for the flock.
"""
# Shuffling the list of boids ens... | python | {
"resource": ""
} |
q259996 | Scanner.iterscan | validation | def iterscan(self, string, idx=0, context=None):
"""
Yield match, end_idx for each match
"""
match = self.scanner.scanner(string, idx).match
actions = self.actions
lastend = idx
end = len(string)
while True:
m = match()
if m is None... | python | {
"resource": ""
} |
q259997 | layout.copy | validation | def copy(self, graph):
""" Returns a copy of the layout for the given graph.
"""
l = self.__class__(graph, self.n)
l.i = 0
return l | python | {
"resource": ""
} |
q259998 | node.can_reach | validation | def can_reach(self, node, traversable=lambda node, edge: True):
""" Returns True if given node can be reached over traversable edges.
To enforce edge direction, use a node==edge.node1 traversable.
"""
if isinstance(node, str):
node = self.graph[node]
... | python | {
"resource": ""
} |
q259999 | graph.clear | validation | def clear(self):
""" Remove nodes and edges and reset the layout.
"""
dict.clear(self)
self.nodes = []
self.edges = []
self.root = None
self.layout.i = 0
self.alpha = 0 | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.