partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
search_images
Returns a Google images query formatted as a GoogleSearch list object.
lib/web/google.py
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_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)
[ "Returns", "a", "Google", "images", "query", "formatted", "as", "a", "GoogleSearch", "list", "object", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L220-L226
[ "def", "search_images", "(", "q", ",", "start", "=", "0", ",", "size", "=", "\"\"", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "GOOGLE_IMAGES", "return", "GoogleSearch", "(", "q", ",", "start", ",", "service", ",", "size", ",", "wait", ",", "asynchronous", ",", "cached", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
search_news
Returns a Google news query formatted as a GoogleSearch list object.
lib/web/google.py
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_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)
[ "Returns", "a", "Google", "news", "query", "formatted", "as", "a", "GoogleSearch", "list", "object", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L228-L234
[ "def", "search_news", "(", "q", ",", "start", "=", "0", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "GOOGLE_NEWS", "return", "GoogleSearch", "(", "q", ",", "start", ",", "service", ",", "\"\"", ",", "wait", ",", "asynchronous", ",", "cached", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
search_blogs
Returns a Google blogs query formatted as a GoogleSearch list object.
lib/web/google.py
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 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)
[ "Returns", "a", "Google", "blogs", "query", "formatted", "as", "a", "GoogleSearch", "list", "object", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L236-L242
[ "def", "search_blogs", "(", "q", ",", "start", "=", "0", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "GOOGLE_BLOGS", "return", "GoogleSearch", "(", "q", ",", "start", ",", "service", ",", "\"\"", ",", "wait", ",", "asynchronous", ",", "cached", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
GoogleResults._parse
Parses the text data from an XML element defined by tag.
lib/web/google.py
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 _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
[ "Parses", "the", "text", "data", "from", "an", "XML", "element", "defined", "by", "tag", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L138-L146
[ "def", "_parse", "(", "self", ",", "str", ")", ":", "str", "=", "replace_entities", "(", "str", ")", "str", "=", "strip_tags", "(", "str", ")", "str", "=", "collapse_spaces", "(", "str", ")", "return", "str" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Cache.hash
Creates a unique filename in the cache for the id.
lib/web/cache.py
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 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)
[ "Creates", "a", "unique", "filename", "in", "the", "cache", "for", "the", "id", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/cache.py#L48-L54
[ "def", "hash", "(", "self", ",", "id", ")", ":", "h", "=", "md5", "(", "id", ")", ".", "hexdigest", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "h", "+", "self", ".", "type", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Cache.age
Returns the age of the cache entry, in days.
lib/web/cache.py
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: return 0
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: return 0
[ "Returns", "the", "age", "of", "the", "cache", "entry", "in", "days", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/cache.py#L78-L89
[ "def", "age", "(", "self", ",", "id", ")", ":", "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", ":", "return", "0" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
angle
Returns the angle between two points.
shoebot/data/geometry.py
def angle(x0, y0, x1, y1): """ Returns the angle between two points. """ return degrees(atan2(y1-y0, x1-x0))
def angle(x0, y0, x1, y1): """ Returns the angle between two points. """ return degrees(atan2(y1-y0, x1-x0))
[ "Returns", "the", "angle", "between", "two", "points", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L20-L23
[ "def", "angle", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "return", "degrees", "(", "atan2", "(", "y1", "-", "y0", ",", "x1", "-", "x0", ")", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
distance
Returns the distance between two points.
shoebot/data/geometry.py
def distance(x0, y0, x1, y1): """ Returns the distance between two points. """ return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2))
def distance(x0, y0, x1, y1): """ Returns the distance between two points. """ return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2))
[ "Returns", "the", "distance", "between", "two", "points", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L26-L29
[ "def", "distance", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "return", "sqrt", "(", "pow", "(", "x1", "-", "x0", ",", "2", ")", "+", "pow", "(", "y1", "-", "y0", ",", "2", ")", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
coordinates
Returns the location of a point by rotating around origin (x0,y0).
shoebot/data/geometry.py
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 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)
[ "Returns", "the", "location", "of", "a", "point", "by", "rotating", "around", "origin", "(", "x0", "y0", ")", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L32-L36
[ "def", "coordinates", "(", "x0", ",", "y0", ",", "distance", ",", "angle", ")", ":", "return", "(", "x0", "+", "cos", "(", "radians", "(", "angle", ")", ")", "*", "distance", ",", "y0", "+", "sin", "(", "radians", "(", "angle", ")", ")", "*", "distance", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
rotate
Returns the coordinates of (x,y) rotated around origin (x0,y0).
shoebot/data/geometry.py
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 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)
[ "Returns", "the", "coordinates", "of", "(", "x", "y", ")", "rotated", "around", "origin", "(", "x0", "y0", ")", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L39-L45
[ "def", "rotate", "(", "x", ",", "y", ",", "x0", ",", "y0", ",", "angle", ")", ":", "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", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
reflect
Returns the reflection of a point through origin (x0,y0).
shoebot/data/geometry.py
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 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))
[ "Returns", "the", "reflection", "of", "a", "point", "through", "origin", "(", "x0", "y0", ")", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L48-L52
[ "def", "reflect", "(", "x", ",", "y", ",", "x0", ",", "y0", ",", "d", "=", "1.0", ",", "a", "=", "180", ")", ":", "return", "coordinates", "(", "x0", ",", "y0", ",", "d", "*", "distance", "(", "x0", ",", "y0", ",", "x", ",", "y", ")", ",", "a", "+", "angle", "(", "x0", ",", "y0", ",", "x", ",", "y", ")", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
lerp
Returns the linear interpolation between a and b for time t between 0.0-1.0. For example: lerp(100, 200, 0.5) => 150.
shoebot/data/geometry.py
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 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
[ "Returns", "the", "linear", "interpolation", "between", "a", "and", "b", "for", "time", "t", "between", "0", ".", "0", "-", "1", ".", "0", ".", "For", "example", ":", "lerp", "(", "100", "200", "0", ".", "5", ")", "=", ">", "150", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L64-L72
[ "def", "lerp", "(", "a", ",", "b", ",", "t", ")", ":", "if", "t", "<", "0.0", ":", "return", "a", "if", "t", ">", "1.0", ":", "return", "b", "return", "a", "+", "(", "b", "-", "a", ")", "*", "t" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
smoothstep
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.
shoebot/data/geometry.py
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. """ if x < a: return 0.0 if x >= b: return 1.0 x = float(x - a) / (b - a) return x * x * (3 - 2 * x)
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. """ if x < a: return 0.0 if x >= b: return 1.0 x = float(x - a) / (b - a) return x * x * (3 - 2 * 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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L75-L85
[ "def", "smoothstep", "(", "a", ",", "b", ",", "x", ")", ":", "if", "x", "<", "a", ":", "return", "0.0", "if", "x", ">=", "b", ":", "return", "1.0", "x", "=", "float", "(", "x", "-", "a", ")", "/", "(", "b", "-", "a", ")", "return", "x", "*", "x", "*", "(", "3", "-", "2", "*", "x", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
line_line_intersection
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.
shoebot/data/geometry.py
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/geometry/lineline2d/ ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3) ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3) d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1) if d == 0: if ua == ub == 0: # The lines are coincident return [] else: # The lines are parallel. return [] ua /= float(d) ub /= float(d) if not infinite and not (0 <= ua <= 1 and 0 <= ub <= 1): # Intersection point is not within both line segments. return None, None return [(x1 + ua * (x2 - x1), y1 + ua * (y2 - y1))]
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/geometry/lineline2d/ ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3) ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3) d = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1) if d == 0: if ua == ub == 0: # The lines are coincident return [] else: # The lines are parallel. return [] ua /= float(d) ub /= float(d) if not infinite and not (0 <= ua <= 1 and 0 <= ub <= 1): # Intersection point is not within both line segments. return None, None return [(x1 + ua * (x2 - x1), y1 + ua * (y2 - y1))]
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L94-L115
[ "def", "line_line_intersection", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ",", "x4", ",", "y4", ",", "infinite", "=", "False", ")", ":", "# Based on: P. Bourke, http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/\r", "ua", "=", "(", "x4", "-", "x3", ")", "*", "(", "y1", "-", "y3", ")", "-", "(", "y4", "-", "y3", ")", "*", "(", "x1", "-", "x3", ")", "ub", "=", "(", "x2", "-", "x1", ")", "*", "(", "y1", "-", "y3", ")", "-", "(", "y2", "-", "y1", ")", "*", "(", "x1", "-", "x3", ")", "d", "=", "(", "y4", "-", "y3", ")", "*", "(", "x2", "-", "x1", ")", "-", "(", "x4", "-", "x3", ")", "*", "(", "y2", "-", "y1", ")", "if", "d", "==", "0", ":", "if", "ua", "==", "ub", "==", "0", ":", "# The lines are coincident\r", "return", "[", "]", "else", ":", "# The lines are parallel.\r", "return", "[", "]", "ua", "/=", "float", "(", "d", ")", "ub", "/=", "float", "(", "d", ")", "if", "not", "infinite", "and", "not", "(", "0", "<=", "ua", "<=", "1", "and", "0", "<=", "ub", "<=", "1", ")", ":", "# Intersection point is not within both line segments.\r", "return", "None", ",", "None", "return", "[", "(", "x1", "+", "ua", "*", "(", "x2", "-", "x1", ")", ",", "y1", "+", "ua", "*", "(", "y2", "-", "y1", ")", ")", "]" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
circle_line_intersection
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.
shoebot/data/geometry.py
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_intersections.html dx = x2 - x1 dy = y2 - y1 A = dx * dx + dy * dy B = 2 * (dx * (x1 - cx) + dy * (y1 - cy)) C = pow(x1 - cx, 2) + pow(y1 - cy, 2) - radius * radius det = B * B - 4 * A * C if A <= 0.0000001 or det < 0: return [] elif det == 0: # One point of intersection. t = -B / (2 * A) return [(x1 + t * dx, y1 + t * dy)] else: # Two points of intersection. # A point of intersection lies on the line segment if 0 <= t <= 1, # and on an extension of the segment otherwise. points = [] det2 = sqrt(det) t1 = (-B + det2) / (2 * A) t2 = (-B - det2) / (2 * A) if infinite or 0 <= t1 <= 1: points.append((x1 + t1 * dx, y1 + t1 * dy)) if infinite or 0 <= t2 <= 1: points.append((x1 + t2 * dx, y1 + t2 * dy)) return points
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_intersections.html dx = x2 - x1 dy = y2 - y1 A = dx * dx + dy * dy B = 2 * (dx * (x1 - cx) + dy * (y1 - cy)) C = pow(x1 - cx, 2) + pow(y1 - cy, 2) - radius * radius det = B * B - 4 * A * C if A <= 0.0000001 or det < 0: return [] elif det == 0: # One point of intersection. t = -B / (2 * A) return [(x1 + t * dx, y1 + t * dy)] else: # Two points of intersection. # A point of intersection lies on the line segment if 0 <= t <= 1, # and on an extension of the segment otherwise. points = [] det2 = sqrt(det) t1 = (-B + det2) / (2 * A) t2 = (-B - det2) / (2 * A) if infinite or 0 <= t1 <= 1: points.append((x1 + t1 * dx, y1 + t1 * dy)) if infinite or 0 <= t2 <= 1: points.append((x1 + t2 * dx, y1 + t2 * dy)) return points
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L118-L147
[ "def", "circle_line_intersection", "(", "cx", ",", "cy", ",", "radius", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "infinite", "=", "False", ")", ":", "# Based on: http://www.vb-helper.com/howto_net_line_circle_intersections.html\r", "dx", "=", "x2", "-", "x1", "dy", "=", "y2", "-", "y1", "A", "=", "dx", "*", "dx", "+", "dy", "*", "dy", "B", "=", "2", "*", "(", "dx", "*", "(", "x1", "-", "cx", ")", "+", "dy", "*", "(", "y1", "-", "cy", ")", ")", "C", "=", "pow", "(", "x1", "-", "cx", ",", "2", ")", "+", "pow", "(", "y1", "-", "cy", ",", "2", ")", "-", "radius", "*", "radius", "det", "=", "B", "*", "B", "-", "4", "*", "A", "*", "C", "if", "A", "<=", "0.0000001", "or", "det", "<", "0", ":", "return", "[", "]", "elif", "det", "==", "0", ":", "# One point of intersection.\r", "t", "=", "-", "B", "/", "(", "2", "*", "A", ")", "return", "[", "(", "x1", "+", "t", "*", "dx", ",", "y1", "+", "t", "*", "dy", ")", "]", "else", ":", "# Two points of intersection.\r", "# A point of intersection lies on the line segment if 0 <= t <= 1,\r", "# and on an extension of the segment otherwise.\r", "points", "=", "[", "]", "det2", "=", "sqrt", "(", "det", ")", "t1", "=", "(", "-", "B", "+", "det2", ")", "/", "(", "2", "*", "A", ")", "t2", "=", "(", "-", "B", "-", "det2", ")", "/", "(", "2", "*", "A", ")", "if", "infinite", "or", "0", "<=", "t1", "<=", "1", ":", "points", ".", "append", "(", "(", "x1", "+", "t1", "*", "dx", ",", "y1", "+", "t1", "*", "dy", ")", ")", "if", "infinite", "or", "0", "<=", "t2", "<=", "1", ":", "points", ".", "append", "(", "(", "x1", "+", "t2", "*", "dx", ",", "y1", "+", "t2", "*", "dy", ")", ")", "return", "points" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
point_in_polygon
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 report correctly when the point is very close to the boundary. The polygon is passed as a list of (x,y)-tuples.
shoebot/data/geometry.py
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 report correctly when the point is very close to the boundary. The polygon is passed as a list of (x,y)-tuples. """ odd = False n = len(points) for i in range(n): j = i < n - 1 and i + 1 or 0 x0, y0 = points[i][0], points[i][1] x1, y1 = points[j][0], points[j][1] if (y0 < y and y1 >= y) or (y1 < y and y0 >= y): if x0 + (y - y0) / (y1 - y0) * (x1 - x0) < x: odd = not odd return odd
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 report correctly when the point is very close to the boundary. The polygon is passed as a list of (x,y)-tuples. """ odd = False n = len(points) for i in range(n): j = i < n - 1 and i + 1 or 0 x0, y0 = points[i][0], points[i][1] x1, y1 = points[j][0], points[j][1] if (y0 < y and y1 >= y) or (y1 < y and y0 >= y): if x0 + (y - y0) / (y1 - y0) * (x1 - x0) < x: odd = not odd return odd
[ "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", "report", "correctly", "when", "the", "point", "is", "very", "close", "to", "the", "boundary", ".", "The", "polygon", "is", "passed", "as", "a", "list", "of", "(", "x", "y", ")", "-", "tuples", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L157-L174
[ "def", "point_in_polygon", "(", "points", ",", "x", ",", "y", ")", ":", "odd", "=", "False", "n", "=", "len", "(", "points", ")", "for", "i", "in", "range", "(", "n", ")", ":", "j", "=", "i", "<", "n", "-", "1", "and", "i", "+", "1", "or", "0", "x0", ",", "y0", "=", "points", "[", "i", "]", "[", "0", "]", ",", "points", "[", "i", "]", "[", "1", "]", "x1", ",", "y1", "=", "points", "[", "j", "]", "[", "0", "]", ",", "points", "[", "j", "]", "[", "1", "]", "if", "(", "y0", "<", "y", "and", "y1", ">=", "y", ")", "or", "(", "y1", "<", "y", "and", "y0", ">=", "y", ")", ":", "if", "x0", "+", "(", "y", "-", "y0", ")", "/", "(", "y1", "-", "y0", ")", "*", "(", "x1", "-", "x0", ")", "<", "x", ":", "odd", "=", "not", "odd", "return", "odd" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
AffineTransform._mmult
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.
shoebot/data/geometry.py
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 [ a[0] * b[0] + a[1] * b[3], a[0] * b[1] + a[1] * b[4], 0, a[3] * b[0] + a[4] * b[3], a[3] * b[1] + a[4] * b[4], 0, a[6] * b[0] + a[7] * b[3] + b[6], a[6] * b[1] + a[7] * b[4] + b[7], 1 ]
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 [ a[0] * b[0] + a[1] * b[3], a[0] * b[1] + a[1] * b[4], 0, a[3] * b[0] + a[4] * b[3], a[3] * b[1] + a[4] * b[4], 0, a[6] * b[0] + a[7] * b[3] + b[6], a[6] * b[1] + a[7] * b[4] + b[7], 1 ]
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L205-L221
[ "def", "_mmult", "(", "self", ",", "a", ",", "b", ")", ":", "# No need to optimize (C version is just as fast).\r", "return", "[", "a", "[", "0", "]", "*", "b", "[", "0", "]", "+", "a", "[", "1", "]", "*", "b", "[", "3", "]", ",", "a", "[", "0", "]", "*", "b", "[", "1", "]", "+", "a", "[", "1", "]", "*", "b", "[", "4", "]", ",", "0", ",", "a", "[", "3", "]", "*", "b", "[", "0", "]", "+", "a", "[", "4", "]", "*", "b", "[", "3", "]", ",", "a", "[", "3", "]", "*", "b", "[", "1", "]", "+", "a", "[", "4", "]", "*", "b", "[", "4", "]", ",", "0", ",", "a", "[", "6", "]", "*", "b", "[", "0", "]", "+", "a", "[", "7", "]", "*", "b", "[", "3", "]", "+", "b", "[", "6", "]", ",", "a", "[", "6", "]", "*", "b", "[", "1", "]", "+", "a", "[", "7", "]", "*", "b", "[", "4", "]", "+", "b", "[", "7", "]", ",", "1", "]" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
AffineTransform.invert
Multiplying a matrix by its inverse produces the identity matrix.
shoebot/data/geometry.py
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]) / d, -(m[0] * m[7] - m[1] * m[6]) / d, 1 ]
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]) / d, -(m[0] * m[7] - m[1] * m[6]) / d, 1 ]
[ "Multiplying", "a", "matrix", "by", "its", "inverse", "produces", "the", "identity", "matrix", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L223-L234
[ "def", "invert", "(", "self", ")", ":", "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", "]", ")", "/", "d", ",", "-", "(", "m", "[", "0", "]", "*", "m", "[", "7", "]", "-", "m", "[", "1", "]", "*", "m", "[", "6", "]", ")", "/", "d", ",", "1", "]" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
AffineTransform.transform_point
Returns the new coordinates of (x,y) after transformation.
shoebot/data/geometry.py
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_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])
[ "Returns", "the", "new", "coordinates", "of", "(", "x", "y", ")", "after", "transformation", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L257-L261
[ "def", "transform_point", "(", "self", ",", "x", ",", "y", ")", ":", "m", "=", "self", ".", "matrix", "return", "(", "x", "*", "m", "[", "0", "]", "+", "y", "*", "m", "[", "3", "]", "+", "m", "[", "6", "]", ",", "x", "*", "m", "[", "1", "]", "+", "y", "*", "m", "[", "4", "]", "+", "m", "[", "7", "]", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
AffineTransform.transform_path
Returns a BezierPath object with the transformation applied.
shoebot/data/geometry.py
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": p.moveto(*self.apply(pt.x, pt.y)) elif pt.cmd == "lineto": p.lineto(*self.apply(pt.x, pt.y)) elif pt.cmd == "curveto": vx1, vy1 = self.apply(pt.ctrl1.x, pt.ctrl1.y) vx2, vy2 = self.apply(pt.ctrl2.x, pt.ctrl2.y) x, y = self.apply(pt.x, pt.y) p.curveto(vx1, vy1, vx2, vy2, x, y) return p
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": p.moveto(*self.apply(pt.x, pt.y)) elif pt.cmd == "lineto": p.lineto(*self.apply(pt.x, pt.y)) elif pt.cmd == "curveto": vx1, vy1 = self.apply(pt.ctrl1.x, pt.ctrl1.y) vx2, vy2 = self.apply(pt.ctrl2.x, pt.ctrl2.y) x, y = self.apply(pt.x, pt.y) p.curveto(vx1, vy1, vx2, vy2, x, y) return p
[ "Returns", "a", "BezierPath", "object", "with", "the", "transformation", "applied", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L265-L281
[ "def", "transform_path", "(", "self", ",", "path", ")", ":", "p", "=", "path", ".", "__class__", "(", ")", "# Create a new BezierPath.\r", "for", "pt", "in", "path", ":", "if", "pt", ".", "cmd", "==", "\"close\"", ":", "p", ".", "closepath", "(", ")", "elif", "pt", ".", "cmd", "==", "\"moveto\"", ":", "p", ".", "moveto", "(", "*", "self", ".", "apply", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", ")", "elif", "pt", ".", "cmd", "==", "\"lineto\"", ":", "p", ".", "lineto", "(", "*", "self", ".", "apply", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", ")", "elif", "pt", ".", "cmd", "==", "\"curveto\"", ":", "vx1", ",", "vy1", "=", "self", ".", "apply", "(", "pt", ".", "ctrl1", ".", "x", ",", "pt", ".", "ctrl1", ".", "y", ")", "vx2", ",", "vy2", "=", "self", ".", "apply", "(", "pt", ".", "ctrl2", ".", "x", ",", "pt", ".", "ctrl2", ".", "y", ")", "x", ",", "y", "=", "self", ".", "apply", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", "p", ".", "curveto", "(", "vx1", ",", "vy1", ",", "vx2", ",", "vy2", ",", "x", ",", "y", ")", "return", "p" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Bounds.intersects
Return True if a part of the two bounds overlaps.
shoebot/data/geometry.py
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 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)
[ "Return", "True", "if", "a", "part", "of", "the", "two", "bounds", "overlaps", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L349-L353
[ "def", "intersects", "(", "self", ",", "b", ")", ":", "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", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Bounds.intersection
Returns bounds that encompass the intersection of the two. If there is no overlap between the two, None is returned.
shoebot/data/geometry.py
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(mx, my, min(self.x+self.width, b.x+b.width) - mx, min(self.y+self.height, b.y+b.height) - my)
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(mx, my, min(self.x+self.width, b.x+b.width) - mx, min(self.y+self.height, b.y+b.height) - my)
[ "Returns", "bounds", "that", "encompass", "the", "intersection", "of", "the", "two", ".", "If", "there", "is", "no", "overlap", "between", "the", "two", "None", "is", "returned", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L355-L364
[ "def", "intersection", "(", "self", ",", "b", ")", ":", "if", "not", "self", ".", "intersects", "(", "b", ")", ":", "return", "None", "mx", ",", "my", "=", "max", "(", "self", ".", "x", ",", "b", ".", "x", ")", ",", "max", "(", "self", ".", "y", ",", "b", ".", "y", ")", "return", "Bounds", "(", "mx", ",", "my", ",", "min", "(", "self", ".", "x", "+", "self", ".", "width", ",", "b", ".", "x", "+", "b", ".", "width", ")", "-", "mx", ",", "min", "(", "self", ".", "y", "+", "self", ".", "height", ",", "b", ".", "y", "+", "b", ".", "height", ")", "-", "my", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Bounds.union
Returns bounds that encompass the union of the two.
shoebot/data/geometry.py
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 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)
[ "Returns", "bounds", "that", "encompass", "the", "union", "of", "the", "two", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L366-L372
[ "def", "union", "(", "self", ",", "b", ")", ":", "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", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Bounds.contains
Returns True if the given point or rectangle falls within the bounds.
shoebot/data/geometry.py
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 \ and a.y >= self.y and a.y <= self.y+self.height if isinstance(a, Bounds): return a.x >= self.x and a.x+a.width <= self.x+self.width \ and a.y >= self.y and a.y+a.height <= self.y+self.height
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 \ and a.y >= self.y and a.y <= self.y+self.height if isinstance(a, Bounds): return a.x >= self.x and a.x+a.width <= self.x+self.width \ and a.y >= self.y and a.y+a.height <= self.y+self.height
[ "Returns", "True", "if", "the", "given", "point", "or", "rectangle", "falls", "within", "the", "bounds", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L374-L385
[ "def", "contains", "(", "self", ",", "*", "a", ")", ":", "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", "and", "a", ".", "y", ">=", "self", ".", "y", "and", "a", ".", "y", "<=", "self", ".", "y", "+", "self", ".", "height", "if", "isinstance", "(", "a", ",", "Bounds", ")", ":", "return", "a", ".", "x", ">=", "self", ".", "x", "and", "a", ".", "x", "+", "a", ".", "width", "<=", "self", ".", "x", "+", "self", ".", "width", "and", "a", ".", "y", ">=", "self", ".", "y", "and", "a", ".", "y", "+", "a", ".", "height", "<=", "self", ".", "y", "+", "self", ".", "height" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
error
Prints an error message, the help message and quits
shoebot/run.py
def error(message): '''Prints an error message, the help message and quits''' global parser print (_("Error: ") + message) print () parser.print_help() sys.exit()
def error(message): '''Prints an error message, the help message and quits''' global parser print (_("Error: ") + message) print () parser.print_help() sys.exit()
[ "Prints", "an", "error", "message", "the", "help", "message", "and", "quits" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/run.py#L63-L69
[ "def", "error", "(", "message", ")", ":", "global", "parser", "print", "(", "_", "(", "\"Error: \"", ")", "+", "message", ")", "print", "(", ")", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
DrawBot.ellipse
Draws an ellipse starting from (x,y)
shoebot/grammar/drawbot.py
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 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
[ "Draws", "an", "ellipse", "starting", "from", "(", "x", "y", ")" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L64-L70
[ "def", "ellipse", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "draw", "=", "True", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "BezierPath", "(", "*", "*", "kwargs", ")", "path", ".", "ellipse", "(", "x", ",", "y", ",", "width", ",", "height", ")", "if", "draw", ":", "path", ".", "draw", "(", ")", "return", "path" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
DrawBot.line
Draws a line from (x1,y1) to (x2,y2)
shoebot/grammar/drawbot.py
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 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
[ "Draws", "a", "line", "from", "(", "x1", "y1", ")", "to", "(", "x2", "y2", ")" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L75-L83
[ "def", "line", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "draw", "=", "True", ")", ":", "p", "=", "self", ".", "_path", "self", ".", "newpath", "(", ")", "self", ".", "moveto", "(", "x1", ",", "y1", ")", "self", ".", "lineto", "(", "x2", ",", "y2", ")", "self", ".", "endpath", "(", "draw", "=", "draw", ")", "self", ".", "_path", "=", "p", "return", "p" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
DrawBot.colormode
Sets the current colormode (can be RGB or HSB) and eventually the color range. If called without arguments, it returns the current colormode.
shoebot/grammar/drawbot.py
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 = Bot.RGB elif mode == "hsb": self.color_mode = Bot.HSB else: raise NameError, _("Only RGB and HSB colormodes are supported.") if crange is not None: self.color_range = crange return self.color_mode
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 = Bot.RGB elif mode == "hsb": self.color_mode = Bot.HSB else: raise NameError, _("Only RGB and HSB colormodes are supported.") if crange is not None: self.color_range = crange return self.color_mode
[ "Sets", "the", "current", "colormode", "(", "can", "be", "RGB", "or", "HSB", ")", "and", "eventually", "the", "color", "range", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L230-L245
[ "def", "colormode", "(", "self", ",", "mode", "=", "None", ",", "crange", "=", "None", ")", ":", "if", "mode", "is", "not", "None", ":", "if", "mode", "==", "\"rgb\"", ":", "self", ".", "color_mode", "=", "Bot", ".", "RGB", "elif", "mode", "==", "\"hsb\"", ":", "self", ".", "color_mode", "=", "Bot", ".", "HSB", "else", ":", "raise", "NameError", ",", "_", "(", "\"Only RGB and HSB colormodes are supported.\"", ")", "if", "crange", "is", "not", "None", ":", "self", ".", "color_range", "=", "crange", "return", "self", ".", "color_mode" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
DrawBot.fill
Sets a fill color, applying it to new paths.
shoebot/grammar/drawbot.py
def fill(self,*args): '''Sets a fill color, applying it to new paths.''' self._fillcolor = self.color(*args) return self._fillcolor
def fill(self,*args): '''Sets a fill color, applying it to new paths.''' self._fillcolor = self.color(*args) return self._fillcolor
[ "Sets", "a", "fill", "color", "applying", "it", "to", "new", "paths", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L250-L253
[ "def", "fill", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_fillcolor", "=", "self", ".", "color", "(", "*", "args", ")", "return", "self", ".", "_fillcolor" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
DrawBot.stroke
Set a stroke color, applying it to new paths.
shoebot/grammar/drawbot.py
def stroke(self,*args): '''Set a stroke color, applying it to new paths.''' self._strokecolor = self.color(*args) return self._strokecolor
def stroke(self,*args): '''Set a stroke color, applying it to new paths.''' self._strokecolor = self.color(*args) return self._strokecolor
[ "Set", "a", "stroke", "color", "applying", "it", "to", "new", "paths", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L259-L262
[ "def", "stroke", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_strokecolor", "=", "self", ".", "color", "(", "*", "args", ")", "return", "self", ".", "_strokecolor" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
DrawBot.textpath
Draws an outlined path of the input text
shoebot/grammar/drawbot.py
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 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
[ "Draws", "an", "outlined", "path", "of", "the", "input", "text" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L311-L319
[ "def", "textpath", "(", "self", ",", "txt", ",", "x", ",", "y", ",", "width", "=", "None", ",", "height", "=", "1000000", ",", "enableRendering", "=", "False", ",", "*", "*", "kwargs", ")", ":", "txt", "=", "self", ".", "Text", "(", "txt", ",", "x", ",", "y", ",", "width", ",", "height", ",", "*", "*", "kwargs", ")", "path", "=", "txt", ".", "path", "if", "draw", ":", "path", ".", "draw", "(", ")", "return", "path" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
DrawBot.textmetrics
Returns the width and height of a string of text as a tuple (according to current font settings).
shoebot/grammar/drawbot.py
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 cairo # we send doRender=False to prevent the actual rendering process, only the path generation is enabled # not the most efficient way, but it generates accurate results txt = self.Text(txt, 0, 0, width, height, enableRendering=False, **kwargs) return txt.metrics
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 cairo # we send doRender=False to prevent the actual rendering process, only the path generation is enabled # not the most efficient way, but it generates accurate results txt = self.Text(txt, 0, 0, width, height, enableRendering=False, **kwargs) return txt.metrics
[ "Returns", "the", "width", "and", "height", "of", "a", "string", "of", "text", "as", "a", "tuple", "(", "according", "to", "current", "font", "settings", ")", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/drawbot.py#L321-L331
[ "def", "textmetrics", "(", "self", ",", "txt", ",", "width", "=", "None", ",", "height", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# for now only returns width and height (as per Nodebox behaviour)", "# but maybe we could use the other data from cairo", "# we send doRender=False to prevent the actual rendering process, only the path generation is enabled", "# not the most efficient way, but it generates accurate results", "txt", "=", "self", ".", "Text", "(", "txt", ",", "0", ",", "0", ",", "width", ",", "height", ",", "enableRendering", "=", "False", ",", "*", "*", "kwargs", ")", "return", "txt", ".", "metrics" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
draw_cornu_flat
Raph Levien's code draws fast LINETO segments.
lib/cornu/__init__.py
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 * cs - s * ss y = s * cs + c * ss print_pt(x0 + x, y0 + y, cmd) cmd = 'lineto' return cmd
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 * cs - s * ss y = s * cs + c * ss print_pt(x0 + x, y0 + y, cmd) cmd = 'lineto' return cmd
[ "Raph", "Levien", "s", "code", "draws", "fast", "LINETO", "segments", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/cornu/__init__.py#L272-L288
[ "def", "draw_cornu_flat", "(", "x0", ",", "y0", ",", "t0", ",", "t1", ",", "s0", ",", "c0", ",", "flip", ",", "cs", ",", "ss", ",", "cmd", ")", ":", "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", "*", "cs", "-", "s", "*", "ss", "y", "=", "s", "*", "cs", "+", "c", "*", "ss", "print_pt", "(", "x0", "+", "x", ",", "y0", "+", "y", ",", "cmd", ")", "cmd", "=", "'lineto'", "return", "cmd" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
draw_cornu_bezier
Mark Meyer's code draws elegant CURVETO segments.
lib/cornu/__init__.py
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 points # after that we only need the second point because the old second point # becomes the new first point t = j * .2 t2 = t+ .2 curvetime = t0 + t * (t1 - t0) curvetime2 = t0 + t2 * (t1 - t0) Dt = (curvetime2 - curvetime) * scale if not s: # get first point # avoid calling this again: the next time though x,y will equal x3, y3 s, c = eval_cornu(curvetime) s *= flip s -= s0 c -= c0 # calculate derivative of fresnel function at point to get tangent slope # just take the integrand of the fresnel function dx1 = cos(pow(curvetime, 2) + (flip * rot)) dy1 = flip * sin(pow(curvetime, 2) + (flip *rot)) # x,y = first point on function x = ((c * cs - s * ss) +x0) y = ((s * cs + c * ss) + y0) #evaluate the fresnel further along the function to look ahead to the next point s2,c2 = eval_cornu(curvetime2) s2 *= flip s2 -= s0 c2 -= c0 dx2 = cos(pow(curvetime2, 2) + (flip * rot)) dy2 = flip * sin(pow(curvetime2, 2) + (flip * rot)) # x3, y3 = second point on function x3 = ((c2 * cs - s2 * ss)+x0) y3 = ((s2 * cs + c2 * ss)+y0) # calculate control points x1 = (x + ((Dt/3.0) * dx1)) y1 = (y + ((Dt/3.0) * dy1)) x2 = (x3 - ((Dt/3.0) * dx2)) y2 = (y3 - ((Dt/3.0) * dy2)) if cmd == 'moveto': print_pt(x, y, cmd) cmd = 'curveto' print_crv(x1, y1, x2, y2, x3, y3) dx1, dy1 = dx2, dy2 x,y = x3, y3 return cmd
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 points # after that we only need the second point because the old second point # becomes the new first point t = j * .2 t2 = t+ .2 curvetime = t0 + t * (t1 - t0) curvetime2 = t0 + t2 * (t1 - t0) Dt = (curvetime2 - curvetime) * scale if not s: # get first point # avoid calling this again: the next time though x,y will equal x3, y3 s, c = eval_cornu(curvetime) s *= flip s -= s0 c -= c0 # calculate derivative of fresnel function at point to get tangent slope # just take the integrand of the fresnel function dx1 = cos(pow(curvetime, 2) + (flip * rot)) dy1 = flip * sin(pow(curvetime, 2) + (flip *rot)) # x,y = first point on function x = ((c * cs - s * ss) +x0) y = ((s * cs + c * ss) + y0) #evaluate the fresnel further along the function to look ahead to the next point s2,c2 = eval_cornu(curvetime2) s2 *= flip s2 -= s0 c2 -= c0 dx2 = cos(pow(curvetime2, 2) + (flip * rot)) dy2 = flip * sin(pow(curvetime2, 2) + (flip * rot)) # x3, y3 = second point on function x3 = ((c2 * cs - s2 * ss)+x0) y3 = ((s2 * cs + c2 * ss)+y0) # calculate control points x1 = (x + ((Dt/3.0) * dx1)) y1 = (y + ((Dt/3.0) * dy1)) x2 = (x3 - ((Dt/3.0) * dx2)) y2 = (y3 - ((Dt/3.0) * dy2)) if cmd == 'moveto': print_pt(x, y, cmd) cmd = 'curveto' print_crv(x1, y1, x2, y2, x3, y3) dx1, dy1 = dx2, dy2 x,y = x3, y3 return cmd
[ "Mark", "Meyer", "s", "code", "draws", "elegant", "CURVETO", "segments", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/cornu/__init__.py#L290-L349
[ "def", "draw_cornu_bezier", "(", "x0", ",", "y0", ",", "t0", ",", "t1", ",", "s0", ",", "c0", ",", "flip", ",", "cs", ",", "ss", ",", "cmd", ",", "scale", ",", "rot", ")", ":", "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 points", "# after that we only need the second point because the old second point", "# becomes the new first point", "t", "=", "j", "*", ".2", "t2", "=", "t", "+", ".2", "curvetime", "=", "t0", "+", "t", "*", "(", "t1", "-", "t0", ")", "curvetime2", "=", "t0", "+", "t2", "*", "(", "t1", "-", "t0", ")", "Dt", "=", "(", "curvetime2", "-", "curvetime", ")", "*", "scale", "if", "not", "s", ":", "# get first point", "# avoid calling this again: the next time though x,y will equal x3, y3", "s", ",", "c", "=", "eval_cornu", "(", "curvetime", ")", "s", "*=", "flip", "s", "-=", "s0", "c", "-=", "c0", "# calculate derivative of fresnel function at point to get tangent slope", "# just take the integrand of the fresnel function", "dx1", "=", "cos", "(", "pow", "(", "curvetime", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "dy1", "=", "flip", "*", "sin", "(", "pow", "(", "curvetime", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "# x,y = first point on function", "x", "=", "(", "(", "c", "*", "cs", "-", "s", "*", "ss", ")", "+", "x0", ")", "y", "=", "(", "(", "s", "*", "cs", "+", "c", "*", "ss", ")", "+", "y0", ")", "#evaluate the fresnel further along the function to look ahead to the next point", "s2", ",", "c2", "=", "eval_cornu", "(", "curvetime2", ")", "s2", "*=", "flip", "s2", "-=", "s0", "c2", "-=", "c0", "dx2", "=", "cos", "(", "pow", "(", "curvetime2", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "dy2", "=", "flip", "*", "sin", "(", "pow", "(", "curvetime2", ",", "2", ")", "+", "(", "flip", "*", "rot", ")", ")", "# x3, y3 = second point on function", "x3", "=", "(", "(", "c2", "*", "cs", "-", "s2", "*", "ss", ")", "+", "x0", ")", "y3", "=", "(", "(", "s2", "*", "cs", "+", "c2", "*", "ss", ")", "+", "y0", ")", "# calculate control points", "x1", "=", "(", "x", "+", "(", "(", "Dt", "/", "3.0", ")", "*", "dx1", ")", ")", "y1", "=", "(", "y", "+", "(", "(", "Dt", "/", "3.0", ")", "*", "dy1", ")", ")", "x2", "=", "(", "x3", "-", "(", "(", "Dt", "/", "3.0", ")", "*", "dx2", ")", ")", "y2", "=", "(", "y3", "-", "(", "(", "Dt", "/", "3.0", ")", "*", "dy2", ")", ")", "if", "cmd", "==", "'moveto'", ":", "print_pt", "(", "x", ",", "y", ",", "cmd", ")", "cmd", "=", "'curveto'", "print_crv", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ")", "dx1", ",", "dy1", "=", "dx2", ",", "dy2", "x", ",", "y", "=", "x3", ",", "y3", "return", "cmd" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
search
Returns a Yahoo web query formatted as a YahooSearch list object.
lib/web/yahoo.py
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(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)
[ "Returns", "a", "Yahoo", "web", "query", "formatted", "as", "a", "YahooSearch", "list", "object", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L201-L207
[ "def", "search", "(", "q", ",", "start", "=", "1", ",", "count", "=", "10", ",", "context", "=", "None", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "YAHOO_SEARCH", "return", "YahooSearch", "(", "q", ",", "start", ",", "count", ",", "service", ",", "context", ",", "wait", ",", "asynchronous", ",", "cached", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
search_images
Returns a Yahoo images query formatted as a YahooSearch list object.
lib/web/yahoo.py
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_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)
[ "Returns", "a", "Yahoo", "images", "query", "formatted", "as", "a", "YahooSearch", "list", "object", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L209-L215
[ "def", "search_images", "(", "q", ",", "start", "=", "1", ",", "count", "=", "10", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "YAHOO_IMAGES", "return", "YahooSearch", "(", "q", ",", "start", ",", "count", ",", "service", ",", "None", ",", "wait", ",", "asynchronous", ",", "cached", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
search_news
Returns a Yahoo news query formatted as a YahooSearch list object.
lib/web/yahoo.py
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 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)
[ "Returns", "a", "Yahoo", "news", "query", "formatted", "as", "a", "YahooSearch", "list", "object", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L217-L223
[ "def", "search_news", "(", "q", ",", "start", "=", "1", ",", "count", "=", "10", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "service", "=", "YAHOO_NEWS", "return", "YahooSearch", "(", "q", ",", "start", ",", "count", ",", "service", ",", "None", ",", "wait", ",", "asynchronous", ",", "cached", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
suggest_spelling
Returns list of suggested spelling corrections for the given query.
lib/web/yahoo.py
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 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)
[ "Returns", "list", "of", "suggested", "spelling", "corrections", "for", "the", "given", "query", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L247-L252
[ "def", "suggest_spelling", "(", "q", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "return", "YahooSpelling", "(", "q", ",", "wait", ",", "asynchronous", ",", "cached", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
sort
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 items according to their relation to this context; for example sorting [red, green, blue] by "love" yields red as the highest results, likely because red is the color commonly associated with love.
lib/web/yahoo.py
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 items according to their relation to this context; for example sorting [red, green, blue] by "love" yields red as the highest results, likely because red is the color commonly associated with love. """ results = [] for word in words: q = word + " " + context q.strip() if strict: q = "\""+q+"\"" r = YahooSearch(q, 1, 1, service, context, wait, asynchronous, cached) results.append(r) results.sort(YahooResults.__cmp__) results.reverse() if relative and len(results) > 0: sum = 0.000000000000000001 for r in results: sum += r.total for r in results: r.total /= float(sum) results = [(r.query, r.total) for r in results] return results
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 items according to their relation to this context; for example sorting [red, green, blue] by "love" yields red as the highest results, likely because red is the color commonly associated with love. """ results = [] for word in words: q = word + " " + context q.strip() if strict: q = "\""+q+"\"" r = YahooSearch(q, 1, 1, service, context, wait, asynchronous, cached) results.append(r) results.sort(YahooResults.__cmp__) results.reverse() if relative and len(results) > 0: sum = 0.000000000000000001 for r in results: sum += r.total for r in results: r.total /= float(sum) results = [(r.query, r.total) for r in results] return results
[ "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", "items", "according", "to", "their", "relation", "to", "this", "context", ";", "for", "example", "sorting", "[", "red", "green", "blue", "]", "by", "love", "yields", "red", "as", "the", "highest", "results", "likely", "because", "red", "is", "the", "color", "commonly", "associated", "with", "love", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L256-L289
[ "def", "sort", "(", "words", ",", "context", "=", "\"\"", ",", "strict", "=", "True", ",", "relative", "=", "True", ",", "service", "=", "YAHOO_SEARCH", ",", "wait", "=", "10", ",", "asynchronous", "=", "False", ",", "cached", "=", "False", ")", ":", "results", "=", "[", "]", "for", "word", "in", "words", ":", "q", "=", "word", "+", "\" \"", "+", "context", "q", ".", "strip", "(", ")", "if", "strict", ":", "q", "=", "\"\\\"\"", "+", "q", "+", "\"\\\"\"", "r", "=", "YahooSearch", "(", "q", ",", "1", ",", "1", ",", "service", ",", "context", ",", "wait", ",", "asynchronous", ",", "cached", ")", "results", ".", "append", "(", "r", ")", "results", ".", "sort", "(", "YahooResults", ".", "__cmp__", ")", "results", ".", "reverse", "(", ")", "if", "relative", "and", "len", "(", "results", ")", ">", "0", ":", "sum", "=", "0.000000000000000001", "for", "r", "in", "results", ":", "sum", "+=", "r", ".", "total", "for", "r", "in", "results", ":", "r", ".", "total", "/=", "float", "(", "sum", ")", "results", "=", "[", "(", "r", ".", "query", ",", "r", ".", "total", ")", "for", "r", "in", "results", "]", "return", "results" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
YahooResults._parse
Parses the text data from an XML element defined by tag.
lib/web/yahoo.py
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_NODE s = children[0].nodeValue s = format_data(s) s = replace_entities(s) return s
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_NODE s = children[0].nodeValue s = format_data(s) s = replace_entities(s) return s
[ "Parses", "the", "text", "data", "from", "an", "XML", "element", "defined", "by", "tag", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/yahoo.py#L123-L137
[ "def", "_parse", "(", "self", ",", "e", ",", "tag", ")", ":", "tags", "=", "e", ".", "getElementsByTagName", "(", "tag", ")", "children", "=", "tags", "[", "0", "]", ".", "childNodes", "if", "len", "(", "children", ")", "!=", "1", ":", "return", "None", "assert", "children", "[", "0", "]", ".", "nodeType", "==", "xml", ".", "dom", ".", "minidom", ".", "Element", ".", "TEXT_NODE", "s", "=", "children", "[", "0", "]", ".", "nodeValue", "s", "=", "format_data", "(", "s", ")", "s", "=", "replace_entities", "(", "s", ")", "return", "s" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Canvas.layer
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, uses that layer's x and y position and name.
lib/photobot/__init__.py
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, uses that layer's x and y position and name. """ from types import StringType if isinstance(img, Image.Image): img = img.convert("RGBA") self.layers.append(Layer(self, img, x, y, name)) return len(self.layers)-1 if isinstance(img, Layer): img.canvas = self self.layers.append(img) return len(self.layers)-1 if type(img) == StringType: img = Image.open(img) img = img.convert("RGBA") self.layers.append(Layer(self, img, x, y, name)) return len(self.layers)-1
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, uses that layer's x and y position and name. """ from types import StringType if isinstance(img, Image.Image): img = img.convert("RGBA") self.layers.append(Layer(self, img, x, y, name)) return len(self.layers)-1 if isinstance(img, Layer): img.canvas = self self.layers.append(img) return len(self.layers)-1 if type(img) == StringType: img = Image.open(img) img = img.convert("RGBA") self.layers.append(Layer(self, img, x, y, name)) return len(self.layers)-1
[ "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", "uses", "that", "layer", "s", "x", "and", "y", "position", "and", "name", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L57-L83
[ "def", "layer", "(", "self", ",", "img", ",", "x", "=", "0", ",", "y", "=", "0", ",", "name", "=", "\"\"", ")", ":", "from", "types", "import", "StringType", "if", "isinstance", "(", "img", ",", "Image", ".", "Image", ")", ":", "img", "=", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "layers", ".", "append", "(", "Layer", "(", "self", ",", "img", ",", "x", ",", "y", ",", "name", ")", ")", "return", "len", "(", "self", ".", "layers", ")", "-", "1", "if", "isinstance", "(", "img", ",", "Layer", ")", ":", "img", ".", "canvas", "=", "self", "self", ".", "layers", ".", "append", "(", "img", ")", "return", "len", "(", "self", ".", "layers", ")", "-", "1", "if", "type", "(", "img", ")", "==", "StringType", ":", "img", "=", "Image", ".", "open", "(", "img", ")", "img", "=", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "layers", ".", "append", "(", "Layer", "(", "self", ",", "img", ",", "x", ",", "y", ",", "name", ")", ")", "return", "len", "(", "self", ".", "layers", ")", "-", "1" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Canvas.fill
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.
lib/photobot/__init__.py
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: w = self.w - x if h == None: h = self.h - y img = Image.new("RGBA", (w,h), rgb) self.layer(img, x, y, name)
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: w = self.w - x if h == None: h = self.h - y img = Image.new("RGBA", (w,h), rgb) self.layer(img, x, y, 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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L85-L98
[ "def", "fill", "(", "self", ",", "rgb", ",", "x", "=", "0", ",", "y", "=", "0", ",", "w", "=", "None", ",", "h", "=", "None", ",", "name", "=", "\"\"", ")", ":", "if", "w", "==", "None", ":", "w", "=", "self", ".", "w", "-", "x", "if", "h", "==", "None", ":", "h", "=", "self", ".", "h", "-", "y", "img", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "(", "w", ",", "h", ")", ",", "rgb", ")", "self", ".", "layer", "(", "img", ",", "x", ",", "y", ",", "name", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Canvas.gradient
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, inverted, made brighter or darker, ... Styles for gradients are LINEAR, RADIAL and DIAMOND.
lib/photobot/__init__.py
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, inverted, made brighter or darker, ... Styles for gradients are LINEAR, RADIAL and DIAMOND. """ from types import FloatType w0 = self.w h0 = self.h if type(w) == FloatType: w *= w0 if type(h) == FloatType: h *= h0 img = Image.new("L", (int(w),int(h)), 255) draw = ImageDraw.Draw(img) if style == LINEAR: for i in range(int(w)): k = 255.0 * i/w draw.rectangle((i, 0, i, h), fill=int(k)) if style == RADIAL: r = min(w,h)/2 for i in range(int(r)): k = 255 - 255.0 * i/r draw.ellipse((w/2-r+i, h/2-r+i, w/2+r-i, h/2+r-i), fill=int(k)) if style == DIAMOND: r = max(w,h) for i in range(int(r)): x = int(i*w/r*0.5) y = int(i*h/r*0.5) k = 255.0 * i/r draw.rectangle((x, y, w-x, h-y), outline=int(k)) img = img.convert("RGBA") self.layer(img, 0, 0, name="")
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, inverted, made brighter or darker, ... Styles for gradients are LINEAR, RADIAL and DIAMOND. """ from types import FloatType w0 = self.w h0 = self.h if type(w) == FloatType: w *= w0 if type(h) == FloatType: h *= h0 img = Image.new("L", (int(w),int(h)), 255) draw = ImageDraw.Draw(img) if style == LINEAR: for i in range(int(w)): k = 255.0 * i/w draw.rectangle((i, 0, i, h), fill=int(k)) if style == RADIAL: r = min(w,h)/2 for i in range(int(r)): k = 255 - 255.0 * i/r draw.ellipse((w/2-r+i, h/2-r+i, w/2+r-i, h/2+r-i), fill=int(k)) if style == DIAMOND: r = max(w,h) for i in range(int(r)): x = int(i*w/r*0.5) y = int(i*h/r*0.5) k = 255.0 * i/r draw.rectangle((x, y, w-x, h-y), outline=int(k)) img = img.convert("RGBA") self.layer(img, 0, 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", "inverted", "made", "brighter", "or", "darker", "...", "Styles", "for", "gradients", "are", "LINEAR", "RADIAL", "and", "DIAMOND", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L100-L144
[ "def", "gradient", "(", "self", ",", "style", "=", "LINEAR", ",", "w", "=", "1.0", ",", "h", "=", "1.0", ",", "name", "=", "\"\"", ")", ":", "from", "types", "import", "FloatType", "w0", "=", "self", ".", "w", "h0", "=", "self", ".", "h", "if", "type", "(", "w", ")", "==", "FloatType", ":", "w", "*=", "w0", "if", "type", "(", "h", ")", "==", "FloatType", ":", "h", "*=", "h0", "img", "=", "Image", ".", "new", "(", "\"L\"", ",", "(", "int", "(", "w", ")", ",", "int", "(", "h", ")", ")", ",", "255", ")", "draw", "=", "ImageDraw", ".", "Draw", "(", "img", ")", "if", "style", "==", "LINEAR", ":", "for", "i", "in", "range", "(", "int", "(", "w", ")", ")", ":", "k", "=", "255.0", "*", "i", "/", "w", "draw", ".", "rectangle", "(", "(", "i", ",", "0", ",", "i", ",", "h", ")", ",", "fill", "=", "int", "(", "k", ")", ")", "if", "style", "==", "RADIAL", ":", "r", "=", "min", "(", "w", ",", "h", ")", "/", "2", "for", "i", "in", "range", "(", "int", "(", "r", ")", ")", ":", "k", "=", "255", "-", "255.0", "*", "i", "/", "r", "draw", ".", "ellipse", "(", "(", "w", "/", "2", "-", "r", "+", "i", ",", "h", "/", "2", "-", "r", "+", "i", ",", "w", "/", "2", "+", "r", "-", "i", ",", "h", "/", "2", "+", "r", "-", "i", ")", ",", "fill", "=", "int", "(", "k", ")", ")", "if", "style", "==", "DIAMOND", ":", "r", "=", "max", "(", "w", ",", "h", ")", "for", "i", "in", "range", "(", "int", "(", "r", ")", ")", ":", "x", "=", "int", "(", "i", "*", "w", "/", "r", "*", "0.5", ")", "y", "=", "int", "(", "i", "*", "h", "/", "r", "*", "0.5", ")", "k", "=", "255.0", "*", "i", "/", "r", "draw", ".", "rectangle", "(", "(", "x", ",", "y", ",", "w", "-", "x", ",", "h", "-", "y", ")", ",", "outline", "=", "int", "(", "k", ")", ")", "img", "=", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "layer", "(", "img", ",", "0", ",", "0", ",", "name", "=", "\"\"", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Canvas.merge
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.
lib/photobot/__init__.py
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 layers[0] self.flatten(layers)
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 layers[0] self.flatten(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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L146-L158
[ "def", "merge", "(", "self", ",", "layers", ")", ":", "layers", ".", "sort", "(", ")", "if", "layers", "[", "0", "]", "==", "0", ":", "del", "layers", "[", "0", "]", "self", ".", "flatten", "(", "layers", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Canvas.flatten
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 layer).
lib/photobot/__init__.py
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 layer). """ #When the layers argument is omitted, #flattens all the layers on the canvas. #When given, merges the indexed layers. #Layers that fall outside of the canvas are cropped: #this should be fixed by merging to a transparent background #large enough to hold all the given layers' data #(=time consuming). if layers == []: layers = range(1, len(self.layers)) background = self.layers._get_bg() background.name = "Background" for i in layers: layer = self.layers[i] #Determine which portion of the canvas #needs to be updated with the overlaying layer. x = max(0, layer.x) y = max(0, layer.y) w = min(background.w, layer.x+layer.w) h = min(background.h, layer.y+layer.h) base = background.img.crop((x, y, w, h)) #Determine which piece of the layer #falls within the canvas. x = max(0, -layer.x) y = max(0, -layer.y) w -= layer.x h -= layer.y blend = layer.img.crop((x, y, w, h)) #Buffer layer blend modes: #the base below is a flattened version #of all the layers below this one, #on which to merge this blended layer. if layer.blend == NORMAL: buffer = blend if layer.blend == MULTIPLY: buffer = ImageChops.multiply(base, blend) if layer.blend == SCREEN: buffer = ImageChops.screen(base, blend) if layer.blend == OVERLAY: buffer = Blend().overlay(base, blend) if layer.blend == HUE: buffer = Blend().hue(base, blend) if layer.blend == COLOR: buffer = Blend().color(base, blend) #Buffer a merge between the base and blend #according to the blend's alpha channel: #the base shines through where the blend is less opaque. #Merging the first layer to the transparent canvas #works slightly different than the other layers. alpha = buffer.split()[3] if i == 1: buffer = Image.composite(base, buffer, base.split()[3]) else: buffer = Image.composite(buffer, base, alpha) #The alpha channel becomes a composite of #this layer and the base: #the base's (optional) tranparent background #is retained in arrays where the blend layer #is transparent as well. alpha = ImageChops.lighter(alpha, base.split()[3]) buffer.putalpha(alpha) #Apply the layer's opacity, #merging the buffer to the base with #the given layer opacity. base = Image.blend(base, buffer, layer.alpha) #Merge the base to the flattened canvas. x = max(0, layer.x) y = max(0, layer.y) background.img.paste(base, (x,y)) layers.reverse() for i in layers: del self.layers[i] img = Image.new("RGBA", (self.w,self.h), (255,255,255,0)) self.layers._set_bg(Layer(self, img, 0, 0, name="_bg")) if len(self.layers) == 1: self.layers.append(background) else: self.layers.insert(layers[-1], background)
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 layer). """ #When the layers argument is omitted, #flattens all the layers on the canvas. #When given, merges the indexed layers. #Layers that fall outside of the canvas are cropped: #this should be fixed by merging to a transparent background #large enough to hold all the given layers' data #(=time consuming). if layers == []: layers = range(1, len(self.layers)) background = self.layers._get_bg() background.name = "Background" for i in layers: layer = self.layers[i] #Determine which portion of the canvas #needs to be updated with the overlaying layer. x = max(0, layer.x) y = max(0, layer.y) w = min(background.w, layer.x+layer.w) h = min(background.h, layer.y+layer.h) base = background.img.crop((x, y, w, h)) #Determine which piece of the layer #falls within the canvas. x = max(0, -layer.x) y = max(0, -layer.y) w -= layer.x h -= layer.y blend = layer.img.crop((x, y, w, h)) #Buffer layer blend modes: #the base below is a flattened version #of all the layers below this one, #on which to merge this blended layer. if layer.blend == NORMAL: buffer = blend if layer.blend == MULTIPLY: buffer = ImageChops.multiply(base, blend) if layer.blend == SCREEN: buffer = ImageChops.screen(base, blend) if layer.blend == OVERLAY: buffer = Blend().overlay(base, blend) if layer.blend == HUE: buffer = Blend().hue(base, blend) if layer.blend == COLOR: buffer = Blend().color(base, blend) #Buffer a merge between the base and blend #according to the blend's alpha channel: #the base shines through where the blend is less opaque. #Merging the first layer to the transparent canvas #works slightly different than the other layers. alpha = buffer.split()[3] if i == 1: buffer = Image.composite(base, buffer, base.split()[3]) else: buffer = Image.composite(buffer, base, alpha) #The alpha channel becomes a composite of #this layer and the base: #the base's (optional) tranparent background #is retained in arrays where the blend layer #is transparent as well. alpha = ImageChops.lighter(alpha, base.split()[3]) buffer.putalpha(alpha) #Apply the layer's opacity, #merging the buffer to the base with #the given layer opacity. base = Image.blend(base, buffer, layer.alpha) #Merge the base to the flattened canvas. x = max(0, layer.x) y = max(0, layer.y) background.img.paste(base, (x,y)) layers.reverse() for i in layers: del self.layers[i] img = Image.new("RGBA", (self.w,self.h), (255,255,255,0)) self.layers._set_bg(Layer(self, img, 0, 0, name="_bg")) if len(self.layers) == 1: self.layers.append(background) else: self.layers.insert(layers[-1], background)
[ "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", "layer", ")", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L160-L270
[ "def", "flatten", "(", "self", ",", "layers", "=", "[", "]", ")", ":", "#When the layers argument is omitted,", "#flattens all the layers on the canvas.", "#When given, merges the indexed layers.", "#Layers that fall outside of the canvas are cropped:", "#this should be fixed by merging to a transparent background", "#large enough to hold all the given layers' data", "#(=time consuming).", "if", "layers", "==", "[", "]", ":", "layers", "=", "range", "(", "1", ",", "len", "(", "self", ".", "layers", ")", ")", "background", "=", "self", ".", "layers", ".", "_get_bg", "(", ")", "background", ".", "name", "=", "\"Background\"", "for", "i", "in", "layers", ":", "layer", "=", "self", ".", "layers", "[", "i", "]", "#Determine which portion of the canvas", "#needs to be updated with the overlaying layer.", "x", "=", "max", "(", "0", ",", "layer", ".", "x", ")", "y", "=", "max", "(", "0", ",", "layer", ".", "y", ")", "w", "=", "min", "(", "background", ".", "w", ",", "layer", ".", "x", "+", "layer", ".", "w", ")", "h", "=", "min", "(", "background", ".", "h", ",", "layer", ".", "y", "+", "layer", ".", "h", ")", "base", "=", "background", ".", "img", ".", "crop", "(", "(", "x", ",", "y", ",", "w", ",", "h", ")", ")", "#Determine which piece of the layer", "#falls within the canvas.", "x", "=", "max", "(", "0", ",", "-", "layer", ".", "x", ")", "y", "=", "max", "(", "0", ",", "-", "layer", ".", "y", ")", "w", "-=", "layer", ".", "x", "h", "-=", "layer", ".", "y", "blend", "=", "layer", ".", "img", ".", "crop", "(", "(", "x", ",", "y", ",", "w", ",", "h", ")", ")", "#Buffer layer blend modes:", "#the base below is a flattened version", "#of all the layers below this one,", "#on which to merge this blended layer.", "if", "layer", ".", "blend", "==", "NORMAL", ":", "buffer", "=", "blend", "if", "layer", ".", "blend", "==", "MULTIPLY", ":", "buffer", "=", "ImageChops", ".", "multiply", "(", "base", ",", "blend", ")", "if", "layer", ".", "blend", "==", "SCREEN", ":", "buffer", "=", "ImageChops", ".", "screen", "(", "base", ",", "blend", ")", "if", "layer", ".", "blend", "==", "OVERLAY", ":", "buffer", "=", "Blend", "(", ")", ".", "overlay", "(", "base", ",", "blend", ")", "if", "layer", ".", "blend", "==", "HUE", ":", "buffer", "=", "Blend", "(", ")", ".", "hue", "(", "base", ",", "blend", ")", "if", "layer", ".", "blend", "==", "COLOR", ":", "buffer", "=", "Blend", "(", ")", ".", "color", "(", "base", ",", "blend", ")", "#Buffer a merge between the base and blend", "#according to the blend's alpha channel:", "#the base shines through where the blend is less opaque.", "#Merging the first layer to the transparent canvas", "#works slightly different than the other layers.", "alpha", "=", "buffer", ".", "split", "(", ")", "[", "3", "]", "if", "i", "==", "1", ":", "buffer", "=", "Image", ".", "composite", "(", "base", ",", "buffer", ",", "base", ".", "split", "(", ")", "[", "3", "]", ")", "else", ":", "buffer", "=", "Image", ".", "composite", "(", "buffer", ",", "base", ",", "alpha", ")", "#The alpha channel becomes a composite of", "#this layer and the base:", "#the base's (optional) tranparent background", "#is retained in arrays where the blend layer", "#is transparent as well.", "alpha", "=", "ImageChops", ".", "lighter", "(", "alpha", ",", "base", ".", "split", "(", ")", "[", "3", "]", ")", "buffer", ".", "putalpha", "(", "alpha", ")", "#Apply the layer's opacity,", "#merging the buffer to the base with", "#the given layer opacity.", "base", "=", "Image", ".", "blend", "(", "base", ",", "buffer", ",", "layer", ".", "alpha", ")", "#Merge the base to the flattened canvas.", "x", "=", "max", "(", "0", ",", "layer", ".", "x", ")", "y", "=", "max", "(", "0", ",", "layer", ".", "y", ")", "background", ".", "img", ".", "paste", "(", "base", ",", "(", "x", ",", "y", ")", ")", "layers", ".", "reverse", "(", ")", "for", "i", "in", "layers", ":", "del", "self", ".", "layers", "[", "i", "]", "img", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "(", "self", ".", "w", ",", "self", ".", "h", ")", ",", "(", "255", ",", "255", ",", "255", ",", "0", ")", ")", "self", ".", "layers", ".", "_set_bg", "(", "Layer", "(", "self", ",", "img", ",", "0", ",", "0", ",", "name", "=", "\"_bg\"", ")", ")", "if", "len", "(", "self", ".", "layers", ")", "==", "1", ":", "self", ".", "layers", ".", "append", "(", "background", ")", "else", ":", "self", ".", "layers", ".", "insert", "(", "layers", "[", "-", "1", "]", ",", "background", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Canvas.export
Exports the flattened canvas. Flattens the canvas. PNG retains the alpha channel information. Other possibilities are JPEG and GIF.
lib/photobot/__init__.py
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 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
[ "Exports", "the", "flattened", "canvas", ".", "Flattens", "the", "canvas", ".", "PNG", "retains", "the", "alpha", "channel", "information", ".", "Other", "possibilities", "are", "JPEG", "and", "GIF", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L272-L284
[ "def", "export", "(", "self", ",", "filename", ")", ":", "self", ".", "flatten", "(", ")", "self", ".", "layers", "[", "1", "]", ".", "img", ".", "save", "(", "filename", ")", "return", "filename" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Canvas.draw
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.
lib/photobot/__init__.py
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 import md5 from os import unlink m = md5.new() m.update(str(time())) filename = "photobot" + str(m.hexdigest()) + ".png" self.export(filename) _ctx.image(filename, x, y) unlink(filename) except: pass
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 import md5 from os import unlink m = md5.new() m.update(str(time())) filename = "photobot" + str(m.hexdigest()) + ".png" self.export(filename) _ctx.image(filename, x, y) unlink(filename) except: pass
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L286-L308
[ "def", "draw", "(", "self", ",", "x", ",", "y", ")", ":", "try", ":", "from", "time", "import", "time", "import", "md5", "from", "os", "import", "unlink", "m", "=", "md5", ".", "new", "(", ")", "m", ".", "update", "(", "str", "(", "time", "(", ")", ")", ")", "filename", "=", "\"photobot\"", "+", "str", "(", "m", ".", "hexdigest", "(", ")", ")", "+", "\".png\"", "self", ".", "export", "(", "filename", ")", "_ctx", ".", "image", "(", "filename", ",", "x", ",", "y", ")", "unlink", "(", "filename", ")", "except", ":", "pass" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.index
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.
lib/photobot/__init__.py
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] == self: break if self.canvas.layers[i] == self: return i else: return None
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] == self: break if self.canvas.layers[i] == self: return i else: return None
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L377-L391
[ "def", "index", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "canvas", ".", "layers", ")", ")", ":", "if", "self", ".", "canvas", ".", "layers", "[", "i", "]", "==", "self", ":", "break", "if", "self", ".", "canvas", ".", "layers", "[", "i", "]", "==", "self", ":", "return", "i", "else", ":", "return", "None" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.copy
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.
lib/photobot/__init__.py
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. """ layer = Layer(None, self.img.copy(), self.x, self.y, self.name) layer.w = self.w layer.h = self.h layer.alpha = self.alpha layer.blend = self.blend return layer
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. """ layer = Layer(None, self.img.copy(), self.x, self.y, self.name) layer.w = self.w layer.h = self.h layer.alpha = self.alpha layer.blend = self.blend return layer
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L393-L410
[ "def", "copy", "(", "self", ")", ":", "layer", "=", "Layer", "(", "None", ",", "self", ".", "img", ".", "copy", "(", ")", ",", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "name", ")", "layer", ".", "w", "=", "self", ".", "w", "layer", ".", "h", "=", "self", ".", "h", "layer", ".", "alpha", "=", "self", ".", "alpha", "layer", ".", "blend", "=", "self", ".", "blend", "return", "layer" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.delete
Removes this layer from the canvas.
lib/photobot/__init__.py
def delete(self): """Removes this layer from the canvas. """ i = self.index() if i != None: del self.canvas.layers[i]
def delete(self): """Removes this layer from the canvas. """ i = self.index() if i != None: del self.canvas.layers[i]
[ "Removes", "this", "layer", "from", "the", "canvas", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L412-L419
[ "def", "delete", "(", "self", ")", ":", "i", "=", "self", ".", "index", "(", ")", "if", "i", "!=", "None", ":", "del", "self", ".", "canvas", ".", "layers", "[", "i", "]" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.up
Moves the layer up in the stacking order.
lib/photobot/__init__.py
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 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)
[ "Moves", "the", "layer", "up", "in", "the", "stacking", "order", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L421-L431
[ "def", "up", "(", "self", ")", ":", "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", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.down
Moves the layer down in the stacking order.
lib/photobot/__init__.py
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 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)
[ "Moves", "the", "layer", "down", "in", "the", "stacking", "order", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L433-L443
[ "def", "down", "(", "self", ")", ":", "i", "=", "self", ".", "index", "(", ")", "if", "i", "!=", "None", ":", "del", "self", ".", "canvas", ".", "layers", "[", "i", "]", "i", "=", "max", "(", "0", ",", "i", "-", "1", ")", "self", ".", "canvas", ".", "layers", ".", "insert", "(", "i", ",", "self", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.select
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 area are cut. The selection is not anti-aliased, but the feather parameter creates soft edges.
lib/photobot/__init__.py
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 area are cut. The selection is not anti-aliased, but the feather parameter creates soft edges. """ w, h = self.img.size mask = Image.new("L", (w,h), 0) draw = ImageDraw.Draw(mask) draw = ImageDraw.Draw(mask) draw.polygon(path, fill=255) if feather: mask = mask.filter(ImageFilter.SMOOTH_MORE) mask = mask.filter(ImageFilter.SMOOTH_MORE) mask = ImageChops.darker(mask, self.img.split()[3]) self.img.putalpha(mask)
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 area are cut. The selection is not anti-aliased, but the feather parameter creates soft edges. """ w, h = self.img.size mask = Image.new("L", (w,h), 0) draw = ImageDraw.Draw(mask) draw = ImageDraw.Draw(mask) draw.polygon(path, fill=255) if feather: mask = mask.filter(ImageFilter.SMOOTH_MORE) mask = mask.filter(ImageFilter.SMOOTH_MORE) mask = ImageChops.darker(mask, self.img.split()[3]) self.img.putalpha(mask)
[ "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", "area", "are", "cut", ".", "The", "selection", "is", "not", "anti", "-", "aliased", "but", "the", "feather", "parameter", "creates", "soft", "edges", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L456-L484
[ "def", "select", "(", "self", ",", "path", ",", "feather", "=", "True", ")", ":", "w", ",", "h", "=", "self", ".", "img", ".", "size", "mask", "=", "Image", ".", "new", "(", "\"L\"", ",", "(", "w", ",", "h", ")", ",", "0", ")", "draw", "=", "ImageDraw", ".", "Draw", "(", "mask", ")", "draw", "=", "ImageDraw", ".", "Draw", "(", "mask", ")", "draw", ".", "polygon", "(", "path", ",", "fill", "=", "255", ")", "if", "feather", ":", "mask", "=", "mask", ".", "filter", "(", "ImageFilter", ".", "SMOOTH_MORE", ")", "mask", "=", "mask", ".", "filter", "(", "ImageFilter", ".", "SMOOTH_MORE", ")", "mask", "=", "ImageChops", ".", "darker", "(", "mask", ",", "self", ".", "img", ".", "split", "(", ")", "[", "3", "]", ")", "self", ".", "img", ".", "putalpha", "(", "mask", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.mask
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") canvas.gradient() canvas.layer(2).flip() canvas.layer(2).mask() Adds a white-to-black linear gradient to the alpha channel of image.jpg, making it evolve from opaque on the left to transparent on the right.
lib/photobot/__init__.py
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") canvas.gradient() canvas.layer(2).flip() canvas.layer(2).mask() Adds a white-to-black linear gradient to the alpha channel of image.jpg, making it evolve from opaque on the left to transparent on the right. """ if len(self.canvas.layers) < 2: return i = self.index() if i == 0: return layer = self.canvas.layers[i-1] alpha = Image.new("L", layer.img.size, 0) #Make a composite of the mask layer in grayscale #and its own alpha channel. mask = self.canvas.layers[i] flat = ImageChops.darker(mask.img.convert("L"), mask.img.split()[3]) alpha.paste(flat, (mask.x,mask.y)) alpha = ImageChops.darker(alpha, layer.img.split()[3]) layer.img.putalpha(alpha) self.delete()
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") canvas.gradient() canvas.layer(2).flip() canvas.layer(2).mask() Adds a white-to-black linear gradient to the alpha channel of image.jpg, making it evolve from opaque on the left to transparent on the right. """ if len(self.canvas.layers) < 2: return i = self.index() if i == 0: return layer = self.canvas.layers[i-1] alpha = Image.new("L", layer.img.size, 0) #Make a composite of the mask layer in grayscale #and its own alpha channel. mask = self.canvas.layers[i] flat = ImageChops.darker(mask.img.convert("L"), mask.img.split()[3]) alpha.paste(flat, (mask.x,mask.y)) alpha = ImageChops.darker(alpha, layer.img.split()[3]) layer.img.putalpha(alpha) self.delete()
[ "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", ")", "canvas", ".", "gradient", "()", "canvas", ".", "layer", "(", "2", ")", ".", "flip", "()", "canvas", ".", "layer", "(", "2", ")", ".", "mask", "()", "Adds", "a", "white", "-", "to", "-", "black", "linear", "gradient", "to", "the", "alpha", "channel", "of", "image", ".", "jpg", "making", "it", "evolve", "from", "opaque", "on", "the", "left", "to", "transparent", "on", "the", "right", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L486-L524
[ "def", "mask", "(", "self", ")", ":", "if", "len", "(", "self", ".", "canvas", ".", "layers", ")", "<", "2", ":", "return", "i", "=", "self", ".", "index", "(", ")", "if", "i", "==", "0", ":", "return", "layer", "=", "self", ".", "canvas", ".", "layers", "[", "i", "-", "1", "]", "alpha", "=", "Image", ".", "new", "(", "\"L\"", ",", "layer", ".", "img", ".", "size", ",", "0", ")", "#Make a composite of the mask layer in grayscale", "#and its own alpha channel.", "mask", "=", "self", ".", "canvas", ".", "layers", "[", "i", "]", "flat", "=", "ImageChops", ".", "darker", "(", "mask", ".", "img", ".", "convert", "(", "\"L\"", ")", ",", "mask", ".", "img", ".", "split", "(", ")", "[", "3", "]", ")", "alpha", ".", "paste", "(", "flat", ",", "(", "mask", ".", "x", ",", "mask", ".", "y", ")", ")", "alpha", "=", "ImageChops", ".", "darker", "(", "alpha", ",", "layer", ".", "img", ".", "split", "(", ")", "[", "3", "]", ")", "layer", ".", "img", ".", "putalpha", "(", "alpha", ")", "self", ".", "delete", "(", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.duplicate
Creates a copy of the current layer. This copy becomes the top layer on the canvas.
lib/photobot/__init__.py
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 = self.blend
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 = self.blend
[ "Creates", "a", "copy", "of", "the", "current", "layer", ".", "This", "copy", "becomes", "the", "top", "layer", "on", "the", "canvas", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L526-L537
[ "def", "duplicate", "(", "self", ")", ":", "i", "=", "self", ".", "canvas", ".", "layer", "(", "self", ".", "img", ".", "copy", "(", ")", ",", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "name", ")", "clone", "=", "self", ".", "canvas", ".", "layers", "[", "i", "]", "clone", ".", "alpha", "=", "self", ".", "alpha", "clone", ".", "blend", "=", "self", ".", "blend" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.brightness
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%.
lib/photobot/__init__.py
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) self.img = b.enhance(value)
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) self.img = b.enhance(value)
[ "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%", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L563-L574
[ "def", "brightness", "(", "self", ",", "value", "=", "1.0", ")", ":", "b", "=", "ImageEnhance", ".", "Brightness", "(", "self", ".", "img", ")", "self", ".", "img", "=", "b", ".", "enhance", "(", "value", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.contrast
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%.
lib/photobot/__init__.py
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.img = c.enhance(value)
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.img = c.enhance(value)
[ "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%", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L576-L587
[ "def", "contrast", "(", "self", ",", "value", "=", "1.0", ")", ":", "c", "=", "ImageEnhance", ".", "Contrast", "(", "self", ".", "img", ")", "self", ".", "img", "=", "c", ".", "enhance", "(", "value", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.desaturate
Desaturates the layer, making it grayscale. Instantly removes all color information from the layer, while maintaing its alpha channel.
lib/photobot/__init__.py
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.convert("RGBA") self.img.putalpha(alpha)
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.convert("RGBA") self.img.putalpha(alpha)
[ "Desaturates", "the", "layer", "making", "it", "grayscale", ".", "Instantly", "removes", "all", "color", "information", "from", "the", "layer", "while", "maintaing", "its", "alpha", "channel", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L589-L601
[ "def", "desaturate", "(", "self", ")", ":", "alpha", "=", "self", ".", "img", ".", "split", "(", ")", "[", "3", "]", "self", ".", "img", "=", "self", ".", "img", ".", "convert", "(", "\"L\"", ")", "self", ".", "img", "=", "self", ".", "img", ".", "convert", "(", "\"RGBA\"", ")", "self", ".", "img", ".", "putalpha", "(", "alpha", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.invert
Inverts the layer.
lib/photobot/__init__.py
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 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)
[ "Inverts", "the", "layer", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L603-L613
[ "def", "invert", "(", "self", ")", ":", "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", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.translate
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.
lib/photobot/__init__.py
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 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
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L615-L626
[ "def", "translate", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "x", "=", "x", "self", ".", "y", "=", "y" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.scale
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.
lib/photobot/__init__.py
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.img.size if type(w) == FloatType: w = int(w*w0) if type(h) == FloatType: h = int(h*h0) self.img = self.img.resize((w,h), INTERPOLATION) self.w = w self.h = h
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.img.size if type(w) == FloatType: w = int(w*w0) if type(h) == FloatType: h = int(h*h0) self.img = self.img.resize((w,h), INTERPOLATION) self.w = w self.h = h
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L628-L645
[ "def", "scale", "(", "self", ",", "w", "=", "1.0", ",", "h", "=", "1.0", ")", ":", "from", "types", "import", "FloatType", "w0", ",", "h0", "=", "self", ".", "img", ".", "size", "if", "type", "(", "w", ")", "==", "FloatType", ":", "w", "=", "int", "(", "w", "*", "w0", ")", "if", "type", "(", "h", ")", "==", "FloatType", ":", "h", "=", "int", "(", "h", "*", "h0", ")", "self", ".", "img", "=", "self", ".", "img", ".", "resize", "(", "(", "w", ",", "h", ")", ",", "INTERPOLATION", ")", "self", ".", "w", "=", "w", "self", ".", "h", "=", "h" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.distort
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).
lib/photobot/__init__.py
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). """ w, h = self.img.size quad = (-x1,-y1, -x4,h-y4, w-x3,w-y3, w-x2,-y2) self.img = self.img.transform(self.img.size, Image.QUAD, quad, INTERPOLATION)
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). """ w, h = self.img.size quad = (-x1,-y1, -x4,h-y4, w-x3,w-y3, w-x2,-y2) self.img = self.img.transform(self.img.size, Image.QUAD, quad, INTERPOLATION)
[ "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", ")", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L647-L660
[ "def", "distort", "(", "self", ",", "x1", "=", "0", ",", "y1", "=", "0", ",", "x2", "=", "0", ",", "y2", "=", "0", ",", "x3", "=", "0", ",", "y3", "=", "0", ",", "x4", "=", "0", ",", "y4", "=", "0", ")", ":", "w", ",", "h", "=", "self", ".", "img", ".", "size", "quad", "=", "(", "-", "x1", ",", "-", "y1", ",", "-", "x4", ",", "h", "-", "y4", ",", "w", "-", "x3", ",", "w", "-", "y3", ",", "w", "-", "x2", ",", "-", "y2", ")", "self", ".", "img", "=", "self", ".", "img", ".", "transform", "(", "self", ".", "img", ".", "size", ",", "Image", ".", "QUAD", ",", "quad", ",", "INTERPOLATION", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.rotate
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.
lib/photobot/__init__.py
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. """ #When a layer rotates, its corners will fall outside #of its defined width and height. #Thus, its bounding box needs to be expanded. #Calculate the diagonal width, and angle from the layer center. #This way we can use the layers's corners #to calculate the bounding box. from math import sqrt, pow, sin, cos, degrees, radians, asin w0, h0 = self.img.size d = sqrt(pow(w0,2) + pow(h0,2)) d_angle = degrees(asin((w0*0.5) / (d*0.5))) angle = angle % 360 if angle > 90 and angle <= 270: d_angle += 180 w = sin(radians(d_angle + angle)) * d w = max(w, sin(radians(d_angle - angle)) * d) w = int(abs(w)) h = cos(radians(d_angle + angle)) * d h = max(h, cos(radians(d_angle - angle)) * d) h = int(abs(h)) dx = int((w-w0) / 2) dy = int((h-h0) / 2) d = int(d) #The rotation box's background color #is the mean pixel value of the rotating image. #This is the best option to avoid borders around #the rotated image. bg = ImageStat.Stat(self.img).mean bg = (int(bg[0]), int(bg[1]), int(bg[2]), 0) box = Image.new("RGBA", (d,d), bg) box.paste(self.img, ((d-w0)/2, (d-h0)/2)) box = box.rotate(angle, INTERPOLATION) box = box.crop(((d-w)/2+2, (d-h)/2, d-(d-w)/2, d-(d-h)/2)) self.img = box #Since rotate changes the bounding box size, #update the layers' width, height, and position, #so it rotates from the center. self.x += (self.w-w)/2 self.y += (self.h-h)/2 self.w = w self.h = h
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. """ #When a layer rotates, its corners will fall outside #of its defined width and height. #Thus, its bounding box needs to be expanded. #Calculate the diagonal width, and angle from the layer center. #This way we can use the layers's corners #to calculate the bounding box. from math import sqrt, pow, sin, cos, degrees, radians, asin w0, h0 = self.img.size d = sqrt(pow(w0,2) + pow(h0,2)) d_angle = degrees(asin((w0*0.5) / (d*0.5))) angle = angle % 360 if angle > 90 and angle <= 270: d_angle += 180 w = sin(radians(d_angle + angle)) * d w = max(w, sin(radians(d_angle - angle)) * d) w = int(abs(w)) h = cos(radians(d_angle + angle)) * d h = max(h, cos(radians(d_angle - angle)) * d) h = int(abs(h)) dx = int((w-w0) / 2) dy = int((h-h0) / 2) d = int(d) #The rotation box's background color #is the mean pixel value of the rotating image. #This is the best option to avoid borders around #the rotated image. bg = ImageStat.Stat(self.img).mean bg = (int(bg[0]), int(bg[1]), int(bg[2]), 0) box = Image.new("RGBA", (d,d), bg) box.paste(self.img, ((d-w0)/2, (d-h0)/2)) box = box.rotate(angle, INTERPOLATION) box = box.crop(((d-w)/2+2, (d-h)/2, d-(d-w)/2, d-(d-h)/2)) self.img = box #Since rotate changes the bounding box size, #update the layers' width, height, and position, #so it rotates from the center. self.x += (self.w-w)/2 self.y += (self.h-h)/2 self.w = w self.h = h
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L662-L724
[ "def", "rotate", "(", "self", ",", "angle", ")", ":", "#When a layer rotates, its corners will fall outside", "#of its defined width and height.", "#Thus, its bounding box needs to be expanded.", "#Calculate the diagonal width, and angle from the layer center.", "#This way we can use the layers's corners ", "#to calculate the bounding box.", "from", "math", "import", "sqrt", ",", "pow", ",", "sin", ",", "cos", ",", "degrees", ",", "radians", ",", "asin", "w0", ",", "h0", "=", "self", ".", "img", ".", "size", "d", "=", "sqrt", "(", "pow", "(", "w0", ",", "2", ")", "+", "pow", "(", "h0", ",", "2", ")", ")", "d_angle", "=", "degrees", "(", "asin", "(", "(", "w0", "*", "0.5", ")", "/", "(", "d", "*", "0.5", ")", ")", ")", "angle", "=", "angle", "%", "360", "if", "angle", ">", "90", "and", "angle", "<=", "270", ":", "d_angle", "+=", "180", "w", "=", "sin", "(", "radians", "(", "d_angle", "+", "angle", ")", ")", "*", "d", "w", "=", "max", "(", "w", ",", "sin", "(", "radians", "(", "d_angle", "-", "angle", ")", ")", "*", "d", ")", "w", "=", "int", "(", "abs", "(", "w", ")", ")", "h", "=", "cos", "(", "radians", "(", "d_angle", "+", "angle", ")", ")", "*", "d", "h", "=", "max", "(", "h", ",", "cos", "(", "radians", "(", "d_angle", "-", "angle", ")", ")", "*", "d", ")", "h", "=", "int", "(", "abs", "(", "h", ")", ")", "dx", "=", "int", "(", "(", "w", "-", "w0", ")", "/", "2", ")", "dy", "=", "int", "(", "(", "h", "-", "h0", ")", "/", "2", ")", "d", "=", "int", "(", "d", ")", "#The rotation box's background color", "#is the mean pixel value of the rotating image.", "#This is the best option to avoid borders around", "#the rotated image.", "bg", "=", "ImageStat", ".", "Stat", "(", "self", ".", "img", ")", ".", "mean", "bg", "=", "(", "int", "(", "bg", "[", "0", "]", ")", ",", "int", "(", "bg", "[", "1", "]", ")", ",", "int", "(", "bg", "[", "2", "]", ")", ",", "0", ")", "box", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "(", "d", ",", "d", ")", ",", "bg", ")", "box", ".", "paste", "(", "self", ".", "img", ",", "(", "(", "d", "-", "w0", ")", "/", "2", ",", "(", "d", "-", "h0", ")", "/", "2", ")", ")", "box", "=", "box", ".", "rotate", "(", "angle", ",", "INTERPOLATION", ")", "box", "=", "box", ".", "crop", "(", "(", "(", "d", "-", "w", ")", "/", "2", "+", "2", ",", "(", "d", "-", "h", ")", "/", "2", ",", "d", "-", "(", "d", "-", "w", ")", "/", "2", ",", "d", "-", "(", "d", "-", "h", ")", "/", "2", ")", ")", "self", ".", "img", "=", "box", "#Since rotate changes the bounding box size,", "#update the layers' width, height, and position,", "#so it rotates from the center.", "self", ".", "x", "+=", "(", "self", ".", "w", "-", "w", ")", "/", "2", "self", ".", "y", "+=", "(", "self", ".", "h", "-", "h", ")", "/", "2", "self", ".", "w", "=", "w", "self", ".", "h", "=", "h" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.flip
Flips the layer, either HORIZONTAL or VERTICAL.
lib/photobot/__init__.py
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 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)
[ "Flips", "the", "layer", "either", "HORIZONTAL", "or", "VERTICAL", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L726-L735
[ "def", "flip", "(", "self", ",", "axis", "=", "HORIZONTAL", ")", ":", "if", "axis", "==", "HORIZONTAL", ":", "self", ".", "img", "=", "self", ".", "img", ".", "transpose", "(", "Image", ".", "FLIP_LEFT_RIGHT", ")", "if", "axis", "==", "VERTICAL", ":", "self", ".", "img", "=", "self", ".", "img", ".", "transpose", "(", "Image", ".", "FLIP_TOP_BOTTOM", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.sharpen
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%.
lib/photobot/__init__.py
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.img = s.enhance(value)
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.img = s.enhance(value)
[ "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%", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L745-L756
[ "def", "sharpen", "(", "self", ",", "value", "=", "1.0", ")", ":", "s", "=", "ImageEnhance", ".", "Sharpness", "(", "self", ".", "img", ")", "self", ".", "img", "=", "s", ".", "enhance", "(", "value", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Layer.levels
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.
lib/photobot/__init__.py
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] b = h[512:767] a = h[768:1024] return r, g, b, a
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] b = h[512:767] a = h[768:1024] return r, g, b, a
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L762-L777
[ "def", "levels", "(", "self", ")", ":", "h", "=", "self", ".", "img", ".", "histogram", "(", ")", "r", "=", "h", "[", "0", ":", "255", "]", "g", "=", "h", "[", "256", ":", "511", "]", "b", "=", "h", "[", "512", ":", "767", "]", "a", "=", "h", "[", "768", ":", "1024", "]", "return", "r", ",", "g", ",", "b", ",", "a" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Blend.overlay
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.
lib/photobot/__init__.py
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. """ p1 = list(img1.getdata()) p2 = list(img2.getdata()) for i in range(len(p1)): p3 = () for j in range(len(p1[i])): a = p1[i][j] / 255.0 b = p2[i][j] / 255.0 #When overlaying the alpha channels, #take the alpha of the most transparent layer. if j == 3: #d = (a+b)*0.5 #d = a d = min(a,b) elif a > 0.5: d = 2*(a+b-a*b)-1 else: d = 2*a*b p3 += (int(d*255),) p1[i] = p3 img = Image.new("RGBA", img1.size, 255) img.putdata(p1) return img
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. """ p1 = list(img1.getdata()) p2 = list(img2.getdata()) for i in range(len(p1)): p3 = () for j in range(len(p1[i])): a = p1[i][j] / 255.0 b = p2[i][j] / 255.0 #When overlaying the alpha channels, #take the alpha of the most transparent layer. if j == 3: #d = (a+b)*0.5 #d = a d = min(a,b) elif a > 0.5: d = 2*(a+b-a*b)-1 else: d = 2*a*b p3 += (int(d*255),) p1[i] = p3 img = Image.new("RGBA", img1.size, 255) img.putdata(p1) return img
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L793-L832
[ "def", "overlay", "(", "self", ",", "img1", ",", "img2", ")", ":", "p1", "=", "list", "(", "img1", ".", "getdata", "(", ")", ")", "p2", "=", "list", "(", "img2", ".", "getdata", "(", ")", ")", "for", "i", "in", "range", "(", "len", "(", "p1", ")", ")", ":", "p3", "=", "(", ")", "for", "j", "in", "range", "(", "len", "(", "p1", "[", "i", "]", ")", ")", ":", "a", "=", "p1", "[", "i", "]", "[", "j", "]", "/", "255.0", "b", "=", "p2", "[", "i", "]", "[", "j", "]", "/", "255.0", "#When overlaying the alpha channels,", "#take the alpha of the most transparent layer.", "if", "j", "==", "3", ":", "#d = (a+b)*0.5", "#d = a", "d", "=", "min", "(", "a", ",", "b", ")", "elif", "a", ">", "0.5", ":", "d", "=", "2", "*", "(", "a", "+", "b", "-", "a", "*", "b", ")", "-", "1", "else", ":", "d", "=", "2", "*", "a", "*", "b", "p3", "+=", "(", "int", "(", "d", "*", "255", ")", ",", ")", "p1", "[", "i", "]", "=", "p3", "img", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "img1", ".", "size", ",", "255", ")", "img", ".", "putdata", "(", "p1", ")", "return", "img" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Blend.hue
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.
lib/photobot/__init__.py
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 colorsys p1 = list(img1.getdata()) p2 = list(img2.getdata()) for i in range(len(p1)): r1, g1, b1, a1 = p1[i] r1 = r1 / 255.0 g1 = g1 / 255.0 b1 = b1 / 255.0 h1, s1, v1 = colorsys.rgb_to_hsv(r1, g1, b1) r2, g2, b2, a2 = p2[i] r2 = r2 / 255.0 g2 = g2 / 255.0 b2 = b2 / 255.0 h2, s2, v2 = colorsys.rgb_to_hsv(r2, g2, b2) r3, g3, b3 = colorsys.hsv_to_rgb(h2, s1, v1) r3 = int(r3*255) g3 = int(g3*255) b3 = int(b3*255) p1[i] = (r3, g3, b3, a1) img = Image.new("RGBA", img1.size, 255) img.putdata(p1) return img
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 colorsys p1 = list(img1.getdata()) p2 = list(img2.getdata()) for i in range(len(p1)): r1, g1, b1, a1 = p1[i] r1 = r1 / 255.0 g1 = g1 / 255.0 b1 = b1 / 255.0 h1, s1, v1 = colorsys.rgb_to_hsv(r1, g1, b1) r2, g2, b2, a2 = p2[i] r2 = r2 / 255.0 g2 = g2 / 255.0 b2 = b2 / 255.0 h2, s2, v2 = colorsys.rgb_to_hsv(r2, g2, b2) r3, g3, b3 = colorsys.hsv_to_rgb(h2, s1, v1) r3 = int(r3*255) g3 = int(g3*255) b3 = int(b3*255) p1[i] = (r3, g3, b3, a1) img = Image.new("RGBA", img1.size, 255) img.putdata(p1) return img
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L834-L873
[ "def", "hue", "(", "self", ",", "img1", ",", "img2", ")", ":", "import", "colorsys", "p1", "=", "list", "(", "img1", ".", "getdata", "(", ")", ")", "p2", "=", "list", "(", "img2", ".", "getdata", "(", ")", ")", "for", "i", "in", "range", "(", "len", "(", "p1", ")", ")", ":", "r1", ",", "g1", ",", "b1", ",", "a1", "=", "p1", "[", "i", "]", "r1", "=", "r1", "/", "255.0", "g1", "=", "g1", "/", "255.0", "b1", "=", "b1", "/", "255.0", "h1", ",", "s1", ",", "v1", "=", "colorsys", ".", "rgb_to_hsv", "(", "r1", ",", "g1", ",", "b1", ")", "r2", ",", "g2", ",", "b2", ",", "a2", "=", "p2", "[", "i", "]", "r2", "=", "r2", "/", "255.0", "g2", "=", "g2", "/", "255.0", "b2", "=", "b2", "/", "255.0", "h2", ",", "s2", ",", "v2", "=", "colorsys", ".", "rgb_to_hsv", "(", "r2", ",", "g2", ",", "b2", ")", "r3", ",", "g3", ",", "b3", "=", "colorsys", ".", "hsv_to_rgb", "(", "h2", ",", "s1", ",", "v1", ")", "r3", "=", "int", "(", "r3", "*", "255", ")", "g3", "=", "int", "(", "g3", "*", "255", ")", "b3", "=", "int", "(", "b3", "*", "255", ")", "p1", "[", "i", "]", "=", "(", "r3", ",", "g3", ",", "b3", ",", "a1", ")", "img", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "img1", ".", "size", ",", "255", ")", "img", ".", "putdata", "(", "p1", ")", "return", "img" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Pixels.convolute
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.
lib/photobot/__init__.py
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) elif len(kernel) == 25: size = (5,5) else: return if scale == None: scale = 0 for x in kernel: scale += x if scale == 0: scale = 1 f = ImageFilter.BuiltinFilter() f.filterargs = size, scale, offset, kernel self.layer.img = self.layer.img.filter(f)
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) elif len(kernel) == 25: size = (5,5) else: return if scale == None: scale = 0 for x in kernel: scale += x if scale == 0: scale = 1 f = ImageFilter.BuiltinFilter() f.filterargs = size, scale, offset, kernel self.layer.img = self.layer.img.filter(f)
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L969-L989
[ "def", "convolute", "(", "self", ",", "kernel", ",", "scale", "=", "None", ",", "offset", "=", "0", ")", ":", "if", "len", "(", "kernel", ")", "==", "9", ":", "size", "=", "(", "3", ",", "3", ")", "elif", "len", "(", "kernel", ")", "==", "25", ":", "size", "=", "(", "5", ",", "5", ")", "else", ":", "return", "if", "scale", "==", "None", ":", "scale", "=", "0", "for", "x", "in", "kernel", ":", "scale", "+=", "x", "if", "scale", "==", "0", ":", "scale", "=", "1", "f", "=", "ImageFilter", ".", "BuiltinFilter", "(", ")", "f", ".", "filterargs", "=", "size", ",", "scale", ",", "offset", ",", "kernel", "self", ".", "layer", ".", "img", "=", "self", ".", "layer", ".", "img", ".", "filter", "(", "f", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grammar._load_namespace
Initialise bot namespace with info in shoebot.data :param filename: Will be set to __file__ in the namespace
shoebot/grammar/grammar.py
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) for name in dir(self): if name[0] != '_': namespace[name] = getattr(self, name) namespace['_ctx'] = self # Used in older nodebox scripts. namespace['__file__'] = filename
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) for name in dir(self): if name[0] != '_': namespace[name] = getattr(self, name) namespace['_ctx'] = self # Used in older nodebox scripts. namespace['__file__'] = filename
[ "Initialise", "bot", "namespace", "with", "info", "in", "shoebot", ".", "data" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L47-L62
[ "def", "_load_namespace", "(", "self", ",", "namespace", ",", "filename", "=", "None", ")", ":", "from", "shoebot", "import", "data", "for", "name", "in", "dir", "(", "data", ")", ":", "namespace", "[", "name", "]", "=", "getattr", "(", "data", ",", "name", ")", "for", "name", "in", "dir", "(", "self", ")", ":", "if", "name", "[", "0", "]", "!=", "'_'", ":", "namespace", "[", "name", "]", "=", "getattr", "(", "self", ",", "name", ")", "namespace", "[", "'_ctx'", "]", "=", "self", "# Used in older nodebox scripts.", "namespace", "[", "'__file__'", "]", "=", "filename" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grammar._should_run
Return False if bot should quit
shoebot/grammar/grammar.py
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: if self._dynamic: return True else: return False return True if not self._dynamic: return False return False
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: if self._dynamic: return True else: return False return True if not self._dynamic: return False return False
[ "Return", "False", "if", "bot", "should", "quit" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L66-L83
[ "def", "_should_run", "(", "self", ",", "iteration", ",", "max_iterations", ")", ":", "if", "iteration", "==", "0", ":", "# First frame always runs", "return", "True", "if", "max_iterations", ":", "if", "iteration", "<", "max_iterations", ":", "return", "True", "elif", "max_iterations", "is", "None", ":", "if", "self", ".", "_dynamic", ":", "return", "True", "else", ":", "return", "False", "return", "True", "if", "not", "self", ".", "_dynamic", ":", "return", "False", "return", "False" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grammar._frame_limit
Limit to framerate, should be called after rendering has completed :param start_time: When execution started
shoebot/grammar/grammar.py
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 sleep_for = (1.0 / abs(self._speed)) - exc_time if sleep_for > 0: sleep(sleep_for)
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 sleep_for = (1.0 / abs(self._speed)) - exc_time if sleep_for > 0: sleep(sleep_for)
[ "Limit", "to", "framerate", "should", "be", "called", "after", "rendering", "has", "completed" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L85-L97
[ "def", "_frame_limit", "(", "self", ",", "start_time", ")", ":", "if", "self", ".", "_speed", ":", "completion_time", "=", "time", "(", ")", "exc_time", "=", "completion_time", "-", "start_time", "sleep_for", "=", "(", "1.0", "/", "abs", "(", "self", ".", "_speed", ")", ")", "-", "exc_time", "if", "sleep_for", ">", "0", ":", "sleep", "(", "sleep_for", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grammar._run_frame
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)
shoebot/grammar/grammar.py
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... # # Nodebox (which we are trying to be compatible with) supports two # kinds of bot 'dynamic' which has a 'draw' function and non dynamic # which doesn't have one. # # Dynamic bots: # # First run: # run body and 'setup' if it exists, then 'draw' # # Later runs: # run 'draw' # # Non Dynamic bots: # # Just have a 'body' and run once... # # UNLESS... a 'var' is changed, then run it again. # # # Livecoding: # # Code can be 'known_good' or 'tenous' (when it has been edited). # # If code is tenous and an exception occurs, attempt to roll # everything back. # # Livecoding and vars # # If vars are added / removed or renamed then attempt to update # the GUI start_time = time() if iteration != 0 and self._speed != 0: self._canvas.reset_canvas() self._set_dynamic_vars() if iteration == 0: # First frame executor.run() # run setup and draw # (assume user hasn't live edited already) executor.ns['setup']() executor.ns['draw']() self._canvas.flush(self._frame) else: # Subsequent frames if self._dynamic: if self._speed != 0: # speed 0 is paused, so do nothing with executor.run_context() as (known_good, source, ns): # Code in main block may redefine 'draw' if not known_good: executor.reload_functions() with VarListener.batch(self._vars, self._oldvars, ns): self._oldvars.clear() # Re-run the function body - ideally this would only # happen if the body had actually changed # - Or perhaps if the line included a variable declaration exec source in ns ns['draw']() self._canvas.flush(self._frame) else: # Non "dynamic" bots # # TODO - This part is overly complex, before live-coding it # was just exec source in ns ... have to see if it # can be simplified again. # with executor.run_context() as (known_good, source, ns): if not known_good: executor.reload_functions() with VarListener.batch(self._vars, self._oldvars, ns): self._oldvars.clear() # Re-run the function body - ideally this would only # happen if the body had actually changed # - Or perhaps if the line included a variable declaration exec source in ns else: exec source in ns self._canvas.flush(self._frame) if limit: self._frame_limit(start_time) # Can set speed to go backwards using the shell if you really want # or pause by setting speed == 0 if self._speed > 0: self._frame += 1 elif self._speed < 0: self._frame -= 1
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... # # Nodebox (which we are trying to be compatible with) supports two # kinds of bot 'dynamic' which has a 'draw' function and non dynamic # which doesn't have one. # # Dynamic bots: # # First run: # run body and 'setup' if it exists, then 'draw' # # Later runs: # run 'draw' # # Non Dynamic bots: # # Just have a 'body' and run once... # # UNLESS... a 'var' is changed, then run it again. # # # Livecoding: # # Code can be 'known_good' or 'tenous' (when it has been edited). # # If code is tenous and an exception occurs, attempt to roll # everything back. # # Livecoding and vars # # If vars are added / removed or renamed then attempt to update # the GUI start_time = time() if iteration != 0 and self._speed != 0: self._canvas.reset_canvas() self._set_dynamic_vars() if iteration == 0: # First frame executor.run() # run setup and draw # (assume user hasn't live edited already) executor.ns['setup']() executor.ns['draw']() self._canvas.flush(self._frame) else: # Subsequent frames if self._dynamic: if self._speed != 0: # speed 0 is paused, so do nothing with executor.run_context() as (known_good, source, ns): # Code in main block may redefine 'draw' if not known_good: executor.reload_functions() with VarListener.batch(self._vars, self._oldvars, ns): self._oldvars.clear() # Re-run the function body - ideally this would only # happen if the body had actually changed # - Or perhaps if the line included a variable declaration exec source in ns ns['draw']() self._canvas.flush(self._frame) else: # Non "dynamic" bots # # TODO - This part is overly complex, before live-coding it # was just exec source in ns ... have to see if it # can be simplified again. # with executor.run_context() as (known_good, source, ns): if not known_good: executor.reload_functions() with VarListener.batch(self._vars, self._oldvars, ns): self._oldvars.clear() # Re-run the function body - ideally this would only # happen if the body had actually changed # - Or perhaps if the line included a variable declaration exec source in ns else: exec source in ns self._canvas.flush(self._frame) if limit: self._frame_limit(start_time) # Can set speed to go backwards using the shell if you really want # or pause by setting speed == 0 if self._speed > 0: self._frame += 1 elif self._speed < 0: self._frame -= 1
[ "Run", "single", "frame", "of", "the", "bot" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L101-L200
[ "def", "_run_frame", "(", "self", ",", "executor", ",", "limit", "=", "False", ",", "iteration", "=", "0", ")", ":", "#", "# Gets a bit complex here...", "#", "# Nodebox (which we are trying to be compatible with) supports two", "# kinds of bot 'dynamic' which has a 'draw' function and non dynamic", "# which doesn't have one.", "#", "# Dynamic bots:", "#", "# First run:", "# run body and 'setup' if it exists, then 'draw'", "#", "# Later runs:", "# run 'draw'", "#", "# Non Dynamic bots:", "#", "# Just have a 'body' and run once...", "#", "# UNLESS... a 'var' is changed, then run it again.", "#", "#", "# Livecoding:", "#", "# Code can be 'known_good' or 'tenous' (when it has been edited).", "#", "# If code is tenous and an exception occurs, attempt to roll", "# everything back.", "#", "# Livecoding and vars", "#", "# If vars are added / removed or renamed then attempt to update", "# the GUI", "start_time", "=", "time", "(", ")", "if", "iteration", "!=", "0", "and", "self", ".", "_speed", "!=", "0", ":", "self", ".", "_canvas", ".", "reset_canvas", "(", ")", "self", ".", "_set_dynamic_vars", "(", ")", "if", "iteration", "==", "0", ":", "# First frame", "executor", ".", "run", "(", ")", "# run setup and draw", "# (assume user hasn't live edited already)", "executor", ".", "ns", "[", "'setup'", "]", "(", ")", "executor", ".", "ns", "[", "'draw'", "]", "(", ")", "self", ".", "_canvas", ".", "flush", "(", "self", ".", "_frame", ")", "else", ":", "# Subsequent frames", "if", "self", ".", "_dynamic", ":", "if", "self", ".", "_speed", "!=", "0", ":", "# speed 0 is paused, so do nothing", "with", "executor", ".", "run_context", "(", ")", "as", "(", "known_good", ",", "source", ",", "ns", ")", ":", "# Code in main block may redefine 'draw'", "if", "not", "known_good", ":", "executor", ".", "reload_functions", "(", ")", "with", "VarListener", ".", "batch", "(", "self", ".", "_vars", ",", "self", ".", "_oldvars", ",", "ns", ")", ":", "self", ".", "_oldvars", ".", "clear", "(", ")", "# Re-run the function body - ideally this would only", "# happen if the body had actually changed", "# - Or perhaps if the line included a variable declaration", "exec", "source", "in", "ns", "ns", "[", "'draw'", "]", "(", ")", "self", ".", "_canvas", ".", "flush", "(", "self", ".", "_frame", ")", "else", ":", "# Non \"dynamic\" bots", "#", "# TODO - This part is overly complex, before live-coding it", "# was just exec source in ns ... have to see if it", "# can be simplified again.", "#", "with", "executor", ".", "run_context", "(", ")", "as", "(", "known_good", ",", "source", ",", "ns", ")", ":", "if", "not", "known_good", ":", "executor", ".", "reload_functions", "(", ")", "with", "VarListener", ".", "batch", "(", "self", ".", "_vars", ",", "self", ".", "_oldvars", ",", "ns", ")", ":", "self", ".", "_oldvars", ".", "clear", "(", ")", "# Re-run the function body - ideally this would only", "# happen if the body had actually changed", "# - Or perhaps if the line included a variable declaration", "exec", "source", "in", "ns", "else", ":", "exec", "source", "in", "ns", "self", ".", "_canvas", ".", "flush", "(", "self", ".", "_frame", ")", "if", "limit", ":", "self", ".", "_frame_limit", "(", "start_time", ")", "# Can set speed to go backwards using the shell if you really want", "# or pause by setting speed == 0", "if", "self", ".", "_speed", ">", "0", ":", "self", ".", "_frame", "+=", "1", "elif", "self", ".", "_speed", "<", "0", ":", "self", ".", "_frame", "-=", "1" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grammar.run
Executes the contents of a Nodebox/Shoebot script in current surface's context. :param inputcode: Path to shoebot source or string containing source :param iterations: None or Maximum amount of frames to run :param run_forever: If True then run until user quits the bot :param frame_limiter: If True then sleep between frames to respect speed() command.
shoebot/grammar/grammar.py
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 :param iterations: None or Maximum amount of frames to run :param run_forever: If True then run until user quits the bot :param frame_limiter: If True then sleep between frames to respect speed() command. ''' source = None filename = None if os.path.isfile(inputcode): source = open(inputcode).read() filename = inputcode elif isinstance(inputcode, basestring): filename = 'shoebot_code' source = inputcode self._load_namespace(self._namespace, filename) self._executor = executor = LiveExecution(source, ns=self._namespace, filename=filename) try: if not iterations: if run_forever: iterations = None else: iterations = 1 iteration = 0 event = None while iteration != iterations and not event_is(event, QUIT_EVENT): # do the magic # First iteration self._run_frame(executor, limit=frame_limiter, iteration=iteration) if iteration == 0: self._initial_namespace = copy.copy(self._namespace) # Stored so script can be rewound iteration += 1 # Subsequent iterations while self._should_run(iteration, iterations) and event is None: iteration += 1 self._run_frame(executor, limit=frame_limiter, iteration=iteration) event = next_event() if not event: self._canvas.sink.main_iteration() # update GUI, may generate events.. while run_forever: # # Running in GUI, bot has finished # Either - # receive quit event and quit # receive any other event and loop (e.g. if var changed or source edited) # while event is None: self._canvas.sink.main_iteration() event = next_event(block=True, timeout=0.05) if not event: self._canvas.sink.main_iteration() # update GUI, may generate events.. if event.type == QUIT_EVENT: break elif event.type == SOURCE_CHANGED_EVENT: # Debounce SOURCE_CHANGED events - # gedit generates two events for changing a single character - # delete and then add while event and event.type == SOURCE_CHANGED_EVENT: event = next_event(block=True, timeout=0.001) elif event.type == SET_WINDOW_TITLE: self._canvas.sink.set_title(event.data) event = None # this loop is a bit weird... break except Exception as e: # this makes KeyboardInterrupts still work # if something goes wrong, print verbose system output # maybe this is too verbose, but okay for now import sys if verbose: errmsg = traceback.format_exc() else: errmsg = simple_traceback(e, executor.known_good or '') print >> sys.stderr, errmsg if break_on_error: raise
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 :param iterations: None or Maximum amount of frames to run :param run_forever: If True then run until user quits the bot :param frame_limiter: If True then sleep between frames to respect speed() command. ''' source = None filename = None if os.path.isfile(inputcode): source = open(inputcode).read() filename = inputcode elif isinstance(inputcode, basestring): filename = 'shoebot_code' source = inputcode self._load_namespace(self._namespace, filename) self._executor = executor = LiveExecution(source, ns=self._namespace, filename=filename) try: if not iterations: if run_forever: iterations = None else: iterations = 1 iteration = 0 event = None while iteration != iterations and not event_is(event, QUIT_EVENT): # do the magic # First iteration self._run_frame(executor, limit=frame_limiter, iteration=iteration) if iteration == 0: self._initial_namespace = copy.copy(self._namespace) # Stored so script can be rewound iteration += 1 # Subsequent iterations while self._should_run(iteration, iterations) and event is None: iteration += 1 self._run_frame(executor, limit=frame_limiter, iteration=iteration) event = next_event() if not event: self._canvas.sink.main_iteration() # update GUI, may generate events.. while run_forever: # # Running in GUI, bot has finished # Either - # receive quit event and quit # receive any other event and loop (e.g. if var changed or source edited) # while event is None: self._canvas.sink.main_iteration() event = next_event(block=True, timeout=0.05) if not event: self._canvas.sink.main_iteration() # update GUI, may generate events.. if event.type == QUIT_EVENT: break elif event.type == SOURCE_CHANGED_EVENT: # Debounce SOURCE_CHANGED events - # gedit generates two events for changing a single character - # delete and then add while event and event.type == SOURCE_CHANGED_EVENT: event = next_event(block=True, timeout=0.001) elif event.type == SET_WINDOW_TITLE: self._canvas.sink.set_title(event.data) event = None # this loop is a bit weird... break except Exception as e: # this makes KeyboardInterrupts still work # if something goes wrong, print verbose system output # maybe this is too verbose, but okay for now import sys if verbose: errmsg = traceback.format_exc() else: errmsg = simple_traceback(e, executor.known_good or '') print >> sys.stderr, errmsg if break_on_error: raise
[ "Executes", "the", "contents", "of", "a", "Nodebox", "/", "Shoebot", "script", "in", "current", "surface", "s", "context", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L202-L292
[ "def", "run", "(", "self", ",", "inputcode", ",", "iterations", "=", "None", ",", "run_forever", "=", "False", ",", "frame_limiter", "=", "False", ",", "verbose", "=", "False", ",", "break_on_error", "=", "False", ")", ":", "source", "=", "None", "filename", "=", "None", "if", "os", ".", "path", ".", "isfile", "(", "inputcode", ")", ":", "source", "=", "open", "(", "inputcode", ")", ".", "read", "(", ")", "filename", "=", "inputcode", "elif", "isinstance", "(", "inputcode", ",", "basestring", ")", ":", "filename", "=", "'shoebot_code'", "source", "=", "inputcode", "self", ".", "_load_namespace", "(", "self", ".", "_namespace", ",", "filename", ")", "self", ".", "_executor", "=", "executor", "=", "LiveExecution", "(", "source", ",", "ns", "=", "self", ".", "_namespace", ",", "filename", "=", "filename", ")", "try", ":", "if", "not", "iterations", ":", "if", "run_forever", ":", "iterations", "=", "None", "else", ":", "iterations", "=", "1", "iteration", "=", "0", "event", "=", "None", "while", "iteration", "!=", "iterations", "and", "not", "event_is", "(", "event", ",", "QUIT_EVENT", ")", ":", "# do the magic", "# First iteration", "self", ".", "_run_frame", "(", "executor", ",", "limit", "=", "frame_limiter", ",", "iteration", "=", "iteration", ")", "if", "iteration", "==", "0", ":", "self", ".", "_initial_namespace", "=", "copy", ".", "copy", "(", "self", ".", "_namespace", ")", "# Stored so script can be rewound", "iteration", "+=", "1", "# Subsequent iterations", "while", "self", ".", "_should_run", "(", "iteration", ",", "iterations", ")", "and", "event", "is", "None", ":", "iteration", "+=", "1", "self", ".", "_run_frame", "(", "executor", ",", "limit", "=", "frame_limiter", ",", "iteration", "=", "iteration", ")", "event", "=", "next_event", "(", ")", "if", "not", "event", ":", "self", ".", "_canvas", ".", "sink", ".", "main_iteration", "(", ")", "# update GUI, may generate events..", "while", "run_forever", ":", "#", "# Running in GUI, bot has finished", "# Either -", "# receive quit event and quit", "# receive any other event and loop (e.g. if var changed or source edited)", "#", "while", "event", "is", "None", ":", "self", ".", "_canvas", ".", "sink", ".", "main_iteration", "(", ")", "event", "=", "next_event", "(", "block", "=", "True", ",", "timeout", "=", "0.05", ")", "if", "not", "event", ":", "self", ".", "_canvas", ".", "sink", ".", "main_iteration", "(", ")", "# update GUI, may generate events..", "if", "event", ".", "type", "==", "QUIT_EVENT", ":", "break", "elif", "event", ".", "type", "==", "SOURCE_CHANGED_EVENT", ":", "# Debounce SOURCE_CHANGED events -", "# gedit generates two events for changing a single character -", "# delete and then add", "while", "event", "and", "event", ".", "type", "==", "SOURCE_CHANGED_EVENT", ":", "event", "=", "next_event", "(", "block", "=", "True", ",", "timeout", "=", "0.001", ")", "elif", "event", ".", "type", "==", "SET_WINDOW_TITLE", ":", "self", ".", "_canvas", ".", "sink", ".", "set_title", "(", "event", ".", "data", ")", "event", "=", "None", "# this loop is a bit weird...", "break", "except", "Exception", "as", "e", ":", "# this makes KeyboardInterrupts still work", "# if something goes wrong, print verbose system output", "# maybe this is too verbose, but okay for now", "import", "sys", "if", "verbose", ":", "errmsg", "=", "traceback", ".", "format_exc", "(", ")", "else", ":", "errmsg", "=", "simple_traceback", "(", "e", ",", "executor", ".", "known_good", "or", "''", ")", "print", ">>", "sys", ".", "stderr", ",", "errmsg", "if", "break_on_error", ":", "raise" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grammar._addvar
Sets a new accessible variable. :param v: Variable.
shoebot/grammar/grammar.py
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 else: # Set from commandline v.value = v.sanitize(oldvar) else: for listener in VarListener.listeners: listener.var_added(v) self._vars[v.name] = v self._namespace[v.name] = v.value self._oldvars[v.name] = v return v
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 else: # Set from commandline v.value = v.sanitize(oldvar) else: for listener in VarListener.listeners: listener.var_added(v) self._vars[v.name] = v self._namespace[v.name] = v.value self._oldvars[v.name] = v return v
[ "Sets", "a", "new", "accessible", "variable", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/grammar.py#L301-L320
[ "def", "_addvar", "(", "self", ",", "v", ")", ":", "oldvar", "=", "self", ".", "_oldvars", ".", "get", "(", "v", ".", "name", ")", "if", "oldvar", "is", "not", "None", ":", "if", "isinstance", "(", "oldvar", ",", "Variable", ")", ":", "if", "oldvar", ".", "compliesTo", "(", "v", ")", ":", "v", ".", "value", "=", "oldvar", ".", "value", "else", ":", "# Set from commandline", "v", ".", "value", "=", "v", ".", "sanitize", "(", "oldvar", ")", "else", ":", "for", "listener", "in", "VarListener", ".", "listeners", ":", "listener", ".", "var_added", "(", "v", ")", "self", ".", "_vars", "[", "v", ".", "name", "]", "=", "v", "self", ".", "_namespace", "[", "v", ".", "name", "]", "=", "v", ".", "value", "self", ".", "_oldvars", "[", "v", ".", "name", "]", "=", "v", "return", "v" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
parse_color
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. The 'color_range' parameter sets the colour range in which the colour data values are specified (except in hexstrings).
shoebot/data/basecolor.py
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. The 'color_range' parameter sets the colour range in which the colour data values are specified (except in hexstrings). ''' # unpack one-element tuples, they show up sometimes while isinstance(v, (tuple, list)) and len(v) == 1: v = v[0] if isinstance(v, (int, float)): red = green = blue = v / color_range alpha = 1. elif isinstance(v, data.Color): red, green, blue, alpha = v elif isinstance(v, (tuple, list)): # normalise values according to the supplied colour range # for this we make a list with the normalised data color = [] for index in range(0, len(v)): color.append(v[index] / color_range) if len(color) == 1: red = green = blue = alpha = color[0] elif len(color) == 2: red = green = blue = color[0] alpha = color[1] elif len(color) == 3: red = color[0] green = color[1] blue = color[2] alpha = 1. elif len(color) == 4: red = color[0] green = color[1] blue = color[2] alpha = color[3] elif isinstance(v, basestring): # got a hexstring: first remove hash character, if any v = v.strip('#') if len(data) == 6: # RRGGBB red = hex2dec(v[0:2]) / 255. green = hex2dec(v[2:4]) / 255. blue = hex2dec(v[4:6]) / 255. alpha = 1. elif len(v) == 8: red = hex2dec(v[0:2]) / 255. green = hex2dec(v[2:4]) / 255. blue = hex2dec(v[4:6]) / 255. alpha = hex2dec(v[6:8]) / 255. return red, green, blue, alpha
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. The 'color_range' parameter sets the colour range in which the colour data values are specified (except in hexstrings). ''' # unpack one-element tuples, they show up sometimes while isinstance(v, (tuple, list)) and len(v) == 1: v = v[0] if isinstance(v, (int, float)): red = green = blue = v / color_range alpha = 1. elif isinstance(v, data.Color): red, green, blue, alpha = v elif isinstance(v, (tuple, list)): # normalise values according to the supplied colour range # for this we make a list with the normalised data color = [] for index in range(0, len(v)): color.append(v[index] / color_range) if len(color) == 1: red = green = blue = alpha = color[0] elif len(color) == 2: red = green = blue = color[0] alpha = color[1] elif len(color) == 3: red = color[0] green = color[1] blue = color[2] alpha = 1. elif len(color) == 4: red = color[0] green = color[1] blue = color[2] alpha = color[3] elif isinstance(v, basestring): # got a hexstring: first remove hash character, if any v = v.strip('#') if len(data) == 6: # RRGGBB red = hex2dec(v[0:2]) / 255. green = hex2dec(v[2:4]) / 255. blue = hex2dec(v[4:6]) / 255. alpha = 1. elif len(v) == 8: red = hex2dec(v[0:2]) / 255. green = hex2dec(v[2:4]) / 255. blue = hex2dec(v[4:6]) / 255. alpha = hex2dec(v[6:8]) / 255. return red, green, blue, alpha
[ "Receives", "a", "colour", "definition", "and", "returns", "a", "(", "r", "g", "b", "a", ")", "tuple", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/basecolor.py#L306-L376
[ "def", "parse_color", "(", "v", ",", "color_range", "=", "1", ")", ":", "# unpack one-element tuples, they show up sometimes", "while", "isinstance", "(", "v", ",", "(", "tuple", ",", "list", ")", ")", "and", "len", "(", "v", ")", "==", "1", ":", "v", "=", "v", "[", "0", "]", "if", "isinstance", "(", "v", ",", "(", "int", ",", "float", ")", ")", ":", "red", "=", "green", "=", "blue", "=", "v", "/", "color_range", "alpha", "=", "1.", "elif", "isinstance", "(", "v", ",", "data", ".", "Color", ")", ":", "red", ",", "green", ",", "blue", ",", "alpha", "=", "v", "elif", "isinstance", "(", "v", ",", "(", "tuple", ",", "list", ")", ")", ":", "# normalise values according to the supplied colour range", "# for this we make a list with the normalised data", "color", "=", "[", "]", "for", "index", "in", "range", "(", "0", ",", "len", "(", "v", ")", ")", ":", "color", ".", "append", "(", "v", "[", "index", "]", "/", "color_range", ")", "if", "len", "(", "color", ")", "==", "1", ":", "red", "=", "green", "=", "blue", "=", "alpha", "=", "color", "[", "0", "]", "elif", "len", "(", "color", ")", "==", "2", ":", "red", "=", "green", "=", "blue", "=", "color", "[", "0", "]", "alpha", "=", "color", "[", "1", "]", "elif", "len", "(", "color", ")", "==", "3", ":", "red", "=", "color", "[", "0", "]", "green", "=", "color", "[", "1", "]", "blue", "=", "color", "[", "2", "]", "alpha", "=", "1.", "elif", "len", "(", "color", ")", "==", "4", ":", "red", "=", "color", "[", "0", "]", "green", "=", "color", "[", "1", "]", "blue", "=", "color", "[", "2", "]", "alpha", "=", "color", "[", "3", "]", "elif", "isinstance", "(", "v", ",", "basestring", ")", ":", "# got a hexstring: first remove hash character, if any", "v", "=", "v", ".", "strip", "(", "'#'", ")", "if", "len", "(", "data", ")", "==", "6", ":", "# RRGGBB", "red", "=", "hex2dec", "(", "v", "[", "0", ":", "2", "]", ")", "/", "255.", "green", "=", "hex2dec", "(", "v", "[", "2", ":", "4", "]", ")", "/", "255.", "blue", "=", "hex2dec", "(", "v", "[", "4", ":", "6", "]", ")", "/", "255.", "alpha", "=", "1.", "elif", "len", "(", "v", ")", "==", "8", ":", "red", "=", "hex2dec", "(", "v", "[", "0", ":", "2", "]", ")", "/", "255.", "green", "=", "hex2dec", "(", "v", "[", "2", ":", "4", "]", ")", "/", "255.", "blue", "=", "hex2dec", "(", "v", "[", "4", ":", "6", "]", ")", "/", "255.", "alpha", "=", "hex2dec", "(", "v", "[", "6", ":", "8", "]", ")", "/", "255.", "return", "red", ",", "green", ",", "blue", ",", "alpha" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
hex_to_rgb
Returns RGB values for a hex color string.
shoebot/data/basecolor.py
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 len(hex) == 8: r, g, b, a = hex[0:2], hex[2:4], hex[4:6], hex[6:] r, g, b, a = [int(n, 16) / 255.0 for n in (r, g, b, a)] return r, g, b, a
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 len(hex) == 8: r, g, b, a = hex[0:2], hex[2:4], hex[4:6], hex[6:] r, g, b, a = [int(n, 16) / 255.0 for n in (r, g, b, a)] return r, g, b, a
[ "Returns", "RGB", "values", "for", "a", "hex", "color", "string", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/basecolor.py#L381-L394
[ "def", "hex_to_rgb", "(", "hex", ")", ":", "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", "len", "(", "hex", ")", "==", "8", ":", "r", ",", "g", ",", "b", ",", "a", "=", "hex", "[", "0", ":", "2", "]", ",", "hex", "[", "2", ":", "4", "]", ",", "hex", "[", "4", ":", "6", "]", ",", "hex", "[", "6", ":", "]", "r", ",", "g", ",", "b", ",", "a", "=", "[", "int", "(", "n", ",", "16", ")", "/", "255.0", "for", "n", "in", "(", "r", ",", "g", ",", "b", ",", "a", ")", "]", "return", "r", ",", "g", ",", "b", ",", "a" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
cmyk_to_rgb
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.
shoebot/data/basecolor.py
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) b = 1.0 - min(1.0, y + k) return r, g, b
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) b = 1.0 - min(1.0, y + k) return r, g, b
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/basecolor.py#L444-L454
[ "def", "cmyk_to_rgb", "(", "c", ",", "m", ",", "y", ",", "k", ")", ":", "r", "=", "1.0", "-", "min", "(", "1.0", ",", "c", "+", "k", ")", "g", "=", "1.0", "-", "min", "(", "1.0", ",", "m", "+", "k", ")", "b", "=", "1.0", "-", "min", "(", "1.0", ",", "y", "+", "k", ")", "return", "r", ",", "g", ",", "b" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
hsv_to_rgb
Hue, saturation, brightness to red, green, blue. http://www.koders.com/python/fidB2FE963F658FE74D9BF74EB93EFD44DCAE45E10E.aspx Results will differ from the way NSColor converts color spaces.
shoebot/data/basecolor.py
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 = h - i p = v * (1 - s) q = v * (1 - s * f) t = v * (1 - s * (1 - f)) if i == 0: r, g, b = v, t, p elif i == 1: r, g, b = q, v, p elif i == 2: r, g, b = p, v, t elif i == 3: r, g, b = p, q, v elif i == 4: r, g, b = t, p, v else: r, g, b = v, p, q return r, g, b
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 = h - i p = v * (1 - s) q = v * (1 - s * f) t = v * (1 - s * (1 - f)) if i == 0: r, g, b = v, t, p elif i == 1: r, g, b = q, v, p elif i == 2: r, g, b = p, v, t elif i == 3: r, g, b = p, q, v elif i == 4: r, g, b = t, p, v else: r, g, b = v, p, q return r, g, b
[ "Hue", "saturation", "brightness", "to", "red", "green", "blue", ".", "http", ":", "//", "www", ".", "koders", ".", "com", "/", "python", "/", "fidB2FE963F658FE74D9BF74EB93EFD44DCAE45E10E", ".", "aspx", "Results", "will", "differ", "from", "the", "way", "NSColor", "converts", "color", "spaces", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/basecolor.py#L476-L504
[ "def", "hsv_to_rgb", "(", "h", ",", "s", ",", "v", ")", ":", "if", "s", "==", "0", ":", "return", "v", ",", "v", ",", "v", "h", "=", "h", "/", "(", "60.0", "/", "360", ")", "i", "=", "floor", "(", "h", ")", "f", "=", "h", "-", "i", "p", "=", "v", "*", "(", "1", "-", "s", ")", "q", "=", "v", "*", "(", "1", "-", "s", "*", "f", ")", "t", "=", "v", "*", "(", "1", "-", "s", "*", "(", "1", "-", "f", ")", ")", "if", "i", "==", "0", ":", "r", ",", "g", ",", "b", "=", "v", ",", "t", ",", "p", "elif", "i", "==", "1", ":", "r", ",", "g", ",", "b", "=", "q", ",", "v", ",", "p", "elif", "i", "==", "2", ":", "r", ",", "g", ",", "b", "=", "p", ",", "v", ",", "t", "elif", "i", "==", "3", ":", "r", ",", "g", ",", "b", "=", "p", ",", "q", ",", "v", "elif", "i", "==", "4", ":", "r", ",", "g", ",", "b", "=", "t", ",", "p", ",", "v", "else", ":", "r", ",", "g", ",", "b", "=", "v", ",", "p", ",", "q", "return", "r", ",", "g", ",", "b" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
simple_traceback
Format traceback, showing line number and surrounding source.
shoebot/grammar/format_traceback.py
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] for i, err in enumerate(exc): if 'exec source in ns' in err: exc_location = exc[i + 1] break # extract line number from traceback fn = exc_location.split(',')[0][8:-1] line_number = int(exc_location.split(',')[1].replace('line', '').strip()) # Build error messages err_msgs = [] # code around the error err_where = ' '.join(exc[i - 1].split(',')[1:]).strip() # 'line 37 in blah" err_msgs.append('Error in the Shoebot script at %s:' % err_where) for i in xrange(max(0, line_number - 5), line_number): if fn == "<string>": line = source_arr[i] else: line = linecache.getline(fn, i + 1) err_msgs.append('%s: %s' % (i + 1, line.rstrip())) err_msgs.append(' %s^ %s' % (len(str(i)) * ' ', exc[-1].rstrip())) err_msgs.append('') # traceback err_msgs.append(exc[0].rstrip()) for err in exc[3:]: err_msgs.append(err.rstrip()) return '\n'.join(err_msgs)
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] for i, err in enumerate(exc): if 'exec source in ns' in err: exc_location = exc[i + 1] break # extract line number from traceback fn = exc_location.split(',')[0][8:-1] line_number = int(exc_location.split(',')[1].replace('line', '').strip()) # Build error messages err_msgs = [] # code around the error err_where = ' '.join(exc[i - 1].split(',')[1:]).strip() # 'line 37 in blah" err_msgs.append('Error in the Shoebot script at %s:' % err_where) for i in xrange(max(0, line_number - 5), line_number): if fn == "<string>": line = source_arr[i] else: line = linecache.getline(fn, i + 1) err_msgs.append('%s: %s' % (i + 1, line.rstrip())) err_msgs.append(' %s^ %s' % (len(str(i)) * ' ', exc[-1].rstrip())) err_msgs.append('') # traceback err_msgs.append(exc[0].rstrip()) for err in exc[3:]: err_msgs.append(err.rstrip()) return '\n'.join(err_msgs)
[ "Format", "traceback", "showing", "line", "number", "and", "surrounding", "source", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/format_traceback.py#L6-L47
[ "def", "simple_traceback", "(", "ex", ",", "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", "]", "for", "i", ",", "err", "in", "enumerate", "(", "exc", ")", ":", "if", "'exec source in ns'", "in", "err", ":", "exc_location", "=", "exc", "[", "i", "+", "1", "]", "break", "# extract line number from traceback", "fn", "=", "exc_location", ".", "split", "(", "','", ")", "[", "0", "]", "[", "8", ":", "-", "1", "]", "line_number", "=", "int", "(", "exc_location", ".", "split", "(", "','", ")", "[", "1", "]", ".", "replace", "(", "'line'", ",", "''", ")", ".", "strip", "(", ")", ")", "# Build error messages", "err_msgs", "=", "[", "]", "# code around the error", "err_where", "=", "' '", ".", "join", "(", "exc", "[", "i", "-", "1", "]", ".", "split", "(", "','", ")", "[", "1", ":", "]", ")", ".", "strip", "(", ")", "# 'line 37 in blah\"", "err_msgs", ".", "append", "(", "'Error in the Shoebot script at %s:'", "%", "err_where", ")", "for", "i", "in", "xrange", "(", "max", "(", "0", ",", "line_number", "-", "5", ")", ",", "line_number", ")", ":", "if", "fn", "==", "\"<string>\"", ":", "line", "=", "source_arr", "[", "i", "]", "else", ":", "line", "=", "linecache", ".", "getline", "(", "fn", ",", "i", "+", "1", ")", "err_msgs", ".", "append", "(", "'%s: %s'", "%", "(", "i", "+", "1", ",", "line", ".", "rstrip", "(", ")", ")", ")", "err_msgs", ".", "append", "(", "' %s^ %s'", "%", "(", "len", "(", "str", "(", "i", ")", ")", "*", "' '", ",", "exc", "[", "-", "1", "]", ".", "rstrip", "(", ")", ")", ")", "err_msgs", ".", "append", "(", "''", ")", "# traceback", "err_msgs", ".", "append", "(", "exc", "[", "0", "]", ".", "rstrip", "(", ")", ")", "for", "err", "in", "exc", "[", "3", ":", "]", ":", "err_msgs", ".", "append", "(", "err", ".", "rstrip", "(", ")", ")", "return", "'\\n'", ".", "join", "(", "err_msgs", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Database.connect
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: database.table or database[table].
lib/database/__init__.py
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: database.table or database[table]. """ self._name = name.rstrip(".db") self._con = sqlite.connect(self._name + ".db") self._cur = self._con.cursor() self._tables = [] self._cur.execute("select name from sqlite_master where type='table'") for r in self._cur: self._tables.append(r[0]) self._indices = [] self._cur.execute("select name from sqlite_master where type='index'") for r in self._cur: self._indices.append(r[0]) for t in self._tables: self._cur.execute("pragma table_info("+t+")") fields = [] key = "" for r in self._cur: fields.append(r[1]) if r[2] == "integer": key = r[1] setattr(self, t, Table(self, t, key, fields))
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: database.table or database[table]. """ self._name = name.rstrip(".db") self._con = sqlite.connect(self._name + ".db") self._cur = self._con.cursor() self._tables = [] self._cur.execute("select name from sqlite_master where type='table'") for r in self._cur: self._tables.append(r[0]) self._indices = [] self._cur.execute("select name from sqlite_master where type='index'") for r in self._cur: self._indices.append(r[0]) for t in self._tables: self._cur.execute("pragma table_info("+t+")") fields = [] key = "" for r in self._cur: fields.append(r[1]) if r[2] == "integer": key = r[1] setattr(self, t, Table(self, t, key, fields))
[ "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", ":", "database", ".", "table", "or", "database", "[", "table", "]", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L31-L63
[ "def", "connect", "(", "self", ",", "name", ")", ":", "self", ".", "_name", "=", "name", ".", "rstrip", "(", "\".db\"", ")", "self", ".", "_con", "=", "sqlite", ".", "connect", "(", "self", ".", "_name", "+", "\".db\"", ")", "self", ".", "_cur", "=", "self", ".", "_con", ".", "cursor", "(", ")", "self", ".", "_tables", "=", "[", "]", "self", ".", "_cur", ".", "execute", "(", "\"select name from sqlite_master where type='table'\"", ")", "for", "r", "in", "self", ".", "_cur", ":", "self", ".", "_tables", ".", "append", "(", "r", "[", "0", "]", ")", "self", ".", "_indices", "=", "[", "]", "self", ".", "_cur", ".", "execute", "(", "\"select name from sqlite_master where type='index'\"", ")", "for", "r", "in", "self", ".", "_cur", ":", "self", ".", "_indices", ".", "append", "(", "r", "[", "0", "]", ")", "for", "t", "in", "self", ".", "_tables", ":", "self", ".", "_cur", ".", "execute", "(", "\"pragma table_info(\"", "+", "t", "+", "\")\"", ")", "fields", "=", "[", "]", "key", "=", "\"\"", "for", "r", "in", "self", ".", "_cur", ":", "fields", ".", "append", "(", "r", "[", "1", "]", ")", "if", "r", "[", "2", "]", "==", "\"integer\"", ":", "key", "=", "r", "[", "1", "]", "setattr", "(", "self", ",", "t", ",", "Table", "(", "self", ",", "t", ",", "key", ",", "fields", ")", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Database.create
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.
lib/database/__init__.py
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 = name.rstrip(".db") from os import unlink if overwrite: try: unlink(self._name + ".db") except: pass self._con = sqlite.connect(self._name + ".db") self._cur = self._con.cursor()
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 = name.rstrip(".db") from os import unlink if overwrite: try: unlink(self._name + ".db") except: pass self._con = sqlite.connect(self._name + ".db") self._cur = self._con.cursor()
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L65-L81
[ "def", "create", "(", "self", ",", "name", ",", "overwrite", "=", "True", ")", ":", "self", ".", "_name", "=", "name", ".", "rstrip", "(", "\".db\"", ")", "from", "os", "import", "unlink", "if", "overwrite", ":", "try", ":", "unlink", "(", "self", ".", "_name", "+", "\".db\"", ")", "except", ":", "pass", "self", ".", "_con", "=", "sqlite", ".", "connect", "(", "self", ".", "_name", "+", "\".db\"", ")", "self", ".", "_cur", "=", "self", ".", "_con", ".", "cursor", "(", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Database.create_table
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 integer that can be set or otherwise autoincrements.
lib/database/__init__.py
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 integer that can be set or otherwise autoincrements. """ for f in fields: if f == key: fields.remove(key) sql = "create table "+name+" " sql += "("+key+" integer primary key" for f in fields: sql += ", "+f+" varchar(255)" sql += ")" self._cur.execute(sql) self._con.commit() self.index(name, key, unique=True) self.connect(self._name)
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 integer that can be set or otherwise autoincrements. """ for f in fields: if f == key: fields.remove(key) sql = "create table "+name+" " sql += "("+key+" integer primary key" for f in fields: sql += ", "+f+" varchar(255)" sql += ")" self._cur.execute(sql) self._con.commit() self.index(name, key, unique=True) self.connect(self._name)
[ "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", "integer", "that", "can", "be", "set", "or", "otherwise", "autoincrements", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L94-L115
[ "def", "create_table", "(", "self", ",", "name", ",", "fields", "=", "[", "]", ",", "key", "=", "\"id\"", ")", ":", "for", "f", "in", "fields", ":", "if", "f", "==", "key", ":", "fields", ".", "remove", "(", "key", ")", "sql", "=", "\"create table \"", "+", "name", "+", "\" \"", "sql", "+=", "\"(\"", "+", "key", "+", "\" integer primary key\"", "for", "f", "in", "fields", ":", "sql", "+=", "\", \"", "+", "f", "+", "\" varchar(255)\"", "sql", "+=", "\")\"", "self", ".", "_cur", ".", "execute", "(", "sql", ")", "self", ".", "_con", ".", "commit", "(", ")", "self", ".", "index", "(", "name", ",", "key", ",", "unique", "=", "True", ")", "self", ".", "connect", "(", "self", ".", "_name", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Database.create_index
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.
lib/database/__init__.py
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 = "unique " else: u = "" if ascending: a = "asc" else: a = "desc" sql = "create "+u+"index index_"+table+"_"+field+" " sql += "on "+table+"("+field+" "+a+")" self._cur.execute(sql) self._con.commit()
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 = "unique " else: u = "" if ascending: a = "asc" else: a = "desc" sql = "create "+u+"index index_"+table+"_"+field+" " sql += "on "+table+"("+field+" "+a+")" self._cur.execute(sql) self._con.commit()
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L120-L137
[ "def", "create_index", "(", "self", ",", "table", ",", "field", ",", "unique", "=", "False", ",", "ascending", "=", "True", ")", ":", "if", "unique", ":", "u", "=", "\"unique \"", "else", ":", "u", "=", "\"\"", "if", "ascending", ":", "a", "=", "\"asc\"", "else", ":", "a", "=", "\"desc\"", "sql", "=", "\"create \"", "+", "u", "+", "\"index index_\"", "+", "table", "+", "\"_\"", "+", "field", "+", "\" \"", "sql", "+=", "\"on \"", "+", "table", "+", "\"(\"", "+", "field", "+", "\" \"", "+", "a", "+", "\")\"", "self", ".", "_cur", ".", "execute", "(", "sql", ")", "self", ".", "_con", ".", "commit", "(", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Database.close
Commits any pending transactions and closes the database.
lib/database/__init__.py
def close(self): """Commits any pending transactions and closes the database. """ self._con.commit() self._cur.close() self._con.close()
def close(self): """Commits any pending transactions and closes the database. """ self._con.commit() self._cur.close() self._con.close()
[ "Commits", "any", "pending", "transactions", "and", "closes", "the", "database", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L157-L164
[ "def", "close", "(", "self", ")", ":", "self", ".", "_con", ".", "commit", "(", ")", "self", ".", "_cur", ".", "close", "(", ")", "self", ".", "_con", ".", "close", "(", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Database.sql
Executes a raw SQL statement on the database.
lib/database/__init__.py
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 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
[ "Executes", "a", "raw", "SQL", "statement", "on", "the", "database", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L166-L175
[ "def", "sql", "(", "self", ",", "sql", ")", ":", "self", ".", "_cur", ".", "execute", "(", "sql", ")", "if", "sql", ".", "lower", "(", ")", ".", "find", "(", "\"select\"", ")", ">=", "0", ":", "matches", "=", "[", "]", "for", "r", "in", "self", ".", "_cur", ":", "matches", ".", "append", "(", "r", ")", "return", "matches" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Table.find
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. The wildcard character is * and automatically sets the operator to "like". Optionally, the fields argument can be a list of column names to select. Returns a list of row tuples containing fields.
lib/database/__init__.py
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. The wildcard character is * and automatically sets the operator to "like". Optionally, the fields argument can be a list of column names to select. Returns a list of row tuples containing fields. """ if key == None: key = self._key if fields != "*": fields = ", ".join(fields) try: q = unicode(q) except: pass if q != "*" and (q[0] == "*" or q[-1] == "*"): if q[0] == "*": q = "%"+q.lstrip("*") if q[-1] == "*": q = q.rstrip("*")+"%" operator = "like" if q != "*": sql = "select "+fields+" from "+self._name+" where "+key+" "+operator+" ?" self._db._cur.execute(sql, (q,)) else: sql = "select "+fields+" from "+self._name self._db._cur.execute(sql) # You need to watch out here when bad unicode data # has entered the database: pysqlite will throw an OperationalError. # http://lists.initd.org/pipermail/pysqlite/2006-April/000488.html matches = [] for r in self._db._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. The wildcard character is * and automatically sets the operator to "like". Optionally, the fields argument can be a list of column names to select. Returns a list of row tuples containing fields. """ if key == None: key = self._key if fields != "*": fields = ", ".join(fields) try: q = unicode(q) except: pass if q != "*" and (q[0] == "*" or q[-1] == "*"): if q[0] == "*": q = "%"+q.lstrip("*") if q[-1] == "*": q = q.rstrip("*")+"%" operator = "like" if q != "*": sql = "select "+fields+" from "+self._name+" where "+key+" "+operator+" ?" self._db._cur.execute(sql, (q,)) else: sql = "select "+fields+" from "+self._name self._db._cur.execute(sql) # You need to watch out here when bad unicode data # has entered the database: pysqlite will throw an OperationalError. # http://lists.initd.org/pipermail/pysqlite/2006-April/000488.html matches = [] for r in self._db._cur: matches.append(r) return matches
[ "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", ".", "The", "wildcard", "character", "is", "*", "and", "automatically", "sets", "the", "operator", "to", "like", ".", "Optionally", "the", "fields", "argument", "can", "be", "a", "list", "of", "column", "names", "to", "select", ".", "Returns", "a", "list", "of", "row", "tuples", "containing", "fields", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L259-L293
[ "def", "find", "(", "self", ",", "q", ",", "operator", "=", "\"=\"", ",", "fields", "=", "\"*\"", ",", "key", "=", "None", ")", ":", "if", "key", "==", "None", ":", "key", "=", "self", ".", "_key", "if", "fields", "!=", "\"*\"", ":", "fields", "=", "\", \"", ".", "join", "(", "fields", ")", "try", ":", "q", "=", "unicode", "(", "q", ")", "except", ":", "pass", "if", "q", "!=", "\"*\"", "and", "(", "q", "[", "0", "]", "==", "\"*\"", "or", "q", "[", "-", "1", "]", "==", "\"*\"", ")", ":", "if", "q", "[", "0", "]", "==", "\"*\"", ":", "q", "=", "\"%\"", "+", "q", ".", "lstrip", "(", "\"*\"", ")", "if", "q", "[", "-", "1", "]", "==", "\"*\"", ":", "q", "=", "q", ".", "rstrip", "(", "\"*\"", ")", "+", "\"%\"", "operator", "=", "\"like\"", "if", "q", "!=", "\"*\"", ":", "sql", "=", "\"select \"", "+", "fields", "+", "\" from \"", "+", "self", ".", "_name", "+", "\" where \"", "+", "key", "+", "\" \"", "+", "operator", "+", "\" ?\"", "self", ".", "_db", ".", "_cur", ".", "execute", "(", "sql", ",", "(", "q", ",", ")", ")", "else", ":", "sql", "=", "\"select \"", "+", "fields", "+", "\" from \"", "+", "self", ".", "_name", "self", ".", "_db", ".", "_cur", ".", "execute", "(", "sql", ")", "# You need to watch out here when bad unicode data ", "# has entered the database: pysqlite will throw an OperationalError.", "# http://lists.initd.org/pipermail/pysqlite/2006-April/000488.html", "matches", "=", "[", "]", "for", "r", "in", "self", ".", "_db", ".", "_cur", ":", "matches", ".", "append", "(", "r", ")", "return", "matches" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Table.append
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.
lib/database/__init__.py
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. """ 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 for k in kw] v = [kw[k] for k in kw] q = ", ".join(["?" for x in fields]) sql = "insert into "+self._name+" ("+", ".join(fields)+") " sql += "values ("+q+")" self._db._cur.execute(sql, v) self._db._i += 1 if self._db._i >= self._db._commit: self._db._i = 0 self._db._con.commit()
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. """ 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 for k in kw] v = [kw[k] for k in kw] q = ", ".join(["?" for x in fields]) sql = "insert into "+self._name+" ("+", ".join(fields)+") " sql += "values ("+q+")" self._db._cur.execute(sql, v) self._db._i += 1 if self._db._i >= self._db._commit: self._db._i = 0 self._db._con.commit()
[ "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", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L313-L340
[ "def", "append", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "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", "for", "k", "in", "kw", "]", "v", "=", "[", "kw", "[", "k", "]", "for", "k", "in", "kw", "]", "q", "=", "\", \"", ".", "join", "(", "[", "\"?\"", "for", "x", "in", "fields", "]", ")", "sql", "=", "\"insert into \"", "+", "self", ".", "_name", "+", "\" (\"", "+", "\", \"", ".", "join", "(", "fields", ")", "+", "\") \"", "sql", "+=", "\"values (\"", "+", "q", "+", "\")\"", "self", ".", "_db", ".", "_cur", ".", "execute", "(", "sql", ",", "v", ")", "self", ".", "_db", ".", "_i", "+=", "1", "if", "self", ".", "_db", ".", "_i", ">=", "self", ".", "_db", ".", "_commit", ":", "self", ".", "_db", ".", "_i", "=", "0", "self", ".", "_db", ".", "_con", ".", "commit", "(", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Table.edit
Edits the row with given id.
lib/database/__init__.py
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 for k in kw] v = [kw[k] for k in kw] sql = "update "+self._name+" set "+"=?, ".join(fields)+"=? where "+self._key+"="+unicode(id) self._db._cur.execute(sql, v) self._db._i += 1 if self._db._i >= self._db._commit: self._db._i = 0 self._db._con.commit()
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 for k in kw] v = [kw[k] for k in kw] sql = "update "+self._name+" set "+"=?, ".join(fields)+"=? where "+self._key+"="+unicode(id) self._db._cur.execute(sql, v) self._db._i += 1 if self._db._i >= self._db._commit: self._db._i = 0 self._db._con.commit()
[ "Edits", "the", "row", "with", "given", "id", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L342-L361
[ "def", "edit", "(", "self", ",", "id", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "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", "for", "k", "in", "kw", "]", "v", "=", "[", "kw", "[", "k", "]", "for", "k", "in", "kw", "]", "sql", "=", "\"update \"", "+", "self", ".", "_name", "+", "\" set \"", "+", "\"=?, \"", ".", "join", "(", "fields", ")", "+", "\"=? where \"", "+", "self", ".", "_key", "+", "\"=\"", "+", "unicode", "(", "id", ")", "self", ".", "_db", ".", "_cur", ".", "execute", "(", "sql", ",", "v", ")", "self", ".", "_db", ".", "_i", "+=", "1", "if", "self", ".", "_db", ".", "_i", ">=", "self", ".", "_db", ".", "_commit", ":", "self", ".", "_db", ".", "_i", "=", "0", "self", ".", "_db", ".", "_con", ".", "commit", "(", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Table.remove
Deletes the row with given id.
lib/database/__init__.py
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 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,))
[ "Deletes", "the", "row", "with", "given", "id", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L363-L372
[ "def", "remove", "(", "self", ",", "id", ",", "operator", "=", "\"=\"", ",", "key", "=", "None", ")", ":", "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", ",", ")", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
next_event
Get the next available event or None :param block: :param timeout: :return: None or (event, data)
shoebot/core/events.py
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 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
[ "Get", "the", "next", "available", "event", "or", "None" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/events.py#L33-L44
[ "def", "next_event", "(", "block", "=", "False", ",", "timeout", "=", "None", ")", ":", "try", ":", "return", "channel", ".", "listen", "(", "block", "=", "block", ",", "timeout", "=", "timeout", ")", ".", "next", "(", ")", "[", "'data'", "]", "except", "StopIteration", ":", "return", "None" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
publish_event
Publish an event ot any subscribers. :param event_t: event type :param data: event data :param extra_channels: :param wait: :return:
shoebot/core/events.py
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) for channel_name in extra_channels or []: pubsub.publish(channel_name, event) if wait is not None: channel = pubsub.subscribe(wait) channel.listen(wait)
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) for channel_name in extra_channels or []: pubsub.publish(channel_name, event) if wait is not None: channel = pubsub.subscribe(wait) channel.listen(wait)
[ "Publish", "an", "event", "ot", "any", "subscribers", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/core/events.py#L57-L73
[ "def", "publish_event", "(", "event_t", ",", "data", "=", "None", ",", "extra_channels", "=", "None", ",", "wait", "=", "None", ")", ":", "event", "=", "Event", "(", "event_t", ",", "data", ")", "pubsub", ".", "publish", "(", "\"shoebot\"", ",", "event", ")", "for", "channel_name", "in", "extra_channels", "or", "[", "]", ":", "pubsub", ".", "publish", "(", "channel_name", ",", "event", ")", "if", "wait", "is", "not", "None", ":", "channel", "=", "pubsub", ".", "subscribe", "(", "wait", ")", "channel", ".", "listen", "(", "wait", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grob._set_mode
Sets call_transform_mode to point to the center_transform or corner_transform
shoebot/data/grob.py
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_transform else: raise ValueError('mode must be CENTER or CORNER')
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_transform else: raise ValueError('mode must be CENTER or CORNER')
[ "Sets", "call_transform_mode", "to", "point", "to", "the", "center_transform", "or", "corner_transform" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/grob.py#L28-L38
[ "def", "_set_mode", "(", "self", ",", "mode", ")", ":", "if", "mode", "==", "CENTER", ":", "self", ".", "_call_transform_mode", "=", "self", ".", "_center_transform", "elif", "mode", "==", "CORNER", ":", "self", ".", "_call_transform_mode", "=", "self", ".", "_corner_transform", "else", ":", "raise", "ValueError", "(", "'mode must be CENTER or CORNER'", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grob._center_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
shoebot/data/grob.py
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(dx, dy) t = transform * t t.translate(-dx, -dy) return t
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(dx, dy) t = transform * t t.translate(-dx, -dy) return t
[ "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" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/grob.py#L60-L70
[ "def", "_center_transform", "(", "self", ",", "transform", ")", ":", "dx", ",", "dy", "=", "self", ".", "_get_center", "(", ")", "t", "=", "cairo", ".", "Matrix", "(", ")", "t", ".", "translate", "(", "dx", ",", "dy", ")", "t", "=", "transform", "*", "t", "t", ".", "translate", "(", "-", "dx", ",", "-", "dy", ")", "return", "t" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
Grob.inheritFromContext
Doesn't store exactly the same items as Nodebox for ease of implementation, it has enough to get the Nodebox Dentrite example working.
shoebot/data/grob.py
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: continue setattr(self, grob_attr, getattr(self._bot._canvas, canvas_attr))
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: continue setattr(self, grob_attr, getattr(self._bot._canvas, canvas_attr))
[ "Doesn", "t", "store", "exactly", "the", "same", "items", "as", "Nodebox", "for", "ease", "of", "implementation", "it", "has", "enough", "to", "get", "the", "Nodebox", "Dentrite", "example", "working", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/grob.py#L89-L97
[ "def", "inheritFromContext", "(", "self", ",", "ignore", "=", "(", ")", ")", ":", "for", "canvas_attr", ",", "grob_attr", "in", "STATES", ".", "items", "(", ")", ":", "if", "canvas_attr", "in", "ignore", ":", "continue", "setattr", "(", "self", ",", "grob_attr", ",", "getattr", "(", "self", ".", "_bot", ".", "_canvas", ",", "canvas_attr", ")", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
LiveExecution.load_edited_source
Load changed code into the execution environment. Until the code is executed correctly, it will be in the 'tenuous' state.
shoebot/grammar/livecode.py
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 self.bad_cb = bad_cb try: # text compile compile(source + '\n\n', filename or self.filename, "exec") self.edited_source = source except Exception as e: if bad_cb: self.edited_source = None tb = traceback.format_exc() self.call_bad_cb(tb) return if filename is not None: self.filename = filename
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 self.bad_cb = bad_cb try: # text compile compile(source + '\n\n', filename or self.filename, "exec") self.edited_source = source except Exception as e: if bad_cb: self.edited_source = None tb = traceback.format_exc() self.call_bad_cb(tb) return if filename is not None: self.filename = filename
[ "Load", "changed", "code", "into", "the", "execution", "environment", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L43-L64
[ "def", "load_edited_source", "(", "self", ",", "source", ",", "good_cb", "=", "None", ",", "bad_cb", "=", "None", ",", "filename", "=", "None", ")", ":", "with", "LiveExecution", ".", "lock", ":", "self", ".", "good_cb", "=", "good_cb", "self", ".", "bad_cb", "=", "bad_cb", "try", ":", "# text compile", "compile", "(", "source", "+", "'\\n\\n'", ",", "filename", "or", "self", ".", "filename", ",", "\"exec\"", ")", "self", ".", "edited_source", "=", "source", "except", "Exception", "as", "e", ":", "if", "bad_cb", ":", "self", ".", "edited_source", "=", "None", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "call_bad_cb", "(", "tb", ")", "return", "if", "filename", "is", "not", "None", ":", "self", ".", "filename", "=", "filename" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
LiveExecution.reload_functions
Replace functions in namespace with functions from edited_source.
shoebot/grammar/livecode.py
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.FunctionDef)]: self.ns[f.name].__code__ = meta.decompiler.compile_func(f, self.filename, self.ns).__code__
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.FunctionDef)]: self.ns[f.name].__code__ = meta.decompiler.compile_func(f, self.filename, self.ns).__code__
[ "Replace", "functions", "in", "namespace", "with", "functions", "from", "edited_source", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L66-L74
[ "def", "reload_functions", "(", "self", ")", ":", "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", ".", "FunctionDef", ")", "]", ":", "self", ".", "ns", "[", "f", ".", "name", "]", ".", "__code__", "=", "meta", ".", "decompiler", ".", "compile_func", "(", "f", ",", "self", ".", "filename", ",", "self", ".", "ns", ")", ".", "__code__" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
LiveExecution.run_tenuous
Run edited source, if no exceptions occur then it graduates to known good.
shoebot/grammar/livecode.py
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 self.do_exec(source, ns_snapshot) self.known_good = source self.call_good_cb() return True, None except Exception as ex: tb = traceback.format_exc() self.call_bad_cb(tb) self.ns.clear() self.ns.update(ns_snapshot) return False, ex
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 self.do_exec(source, ns_snapshot) self.known_good = source self.call_good_cb() return True, None except Exception as ex: tb = traceback.format_exc() self.call_bad_cb(tb) self.ns.clear() self.ns.update(ns_snapshot) return False, ex
[ "Run", "edited", "source", "if", "no", "exceptions", "occur", "then", "it", "graduates", "to", "known", "good", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L84-L103
[ "def", "run_tenuous", "(", "self", ")", ":", "with", "LiveExecution", ".", "lock", ":", "ns_snapshot", "=", "copy", ".", "copy", "(", "self", ".", "ns", ")", "try", ":", "source", "=", "self", ".", "edited_source", "self", ".", "edited_source", "=", "None", "self", ".", "do_exec", "(", "source", ",", "ns_snapshot", ")", "self", ".", "known_good", "=", "source", "self", ".", "call_good_cb", "(", ")", "return", "True", ",", "None", "except", "Exception", "as", "ex", ":", "tb", "=", "traceback", ".", "format_exc", "(", ")", "self", ".", "call_bad_cb", "(", "tb", ")", "self", ".", "ns", ".", "clear", "(", ")", "self", ".", "ns", ".", "update", "(", "ns_snapshot", ")", "return", "False", ",", "ex" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
LiveExecution.run
Attempt to known good or tenuous source.
shoebot/grammar/livecode.py
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 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)
[ "Attempt", "to", "known", "good", "or", "tenuous", "source", "." ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L105-L115
[ "def", "run", "(", "self", ")", ":", "with", "LiveExecution", ".", "lock", ":", "if", "self", ".", "edited_source", ":", "success", ",", "ex", "=", "self", ".", "run_tenuous", "(", ")", "if", "success", ":", "return", "self", ".", "do_exec", "(", "self", ".", "known_good", ",", "self", ".", "ns", ")" ]
d554c1765c1899fa25727c9fc6805d221585562b
valid
LiveExecution.call_bad_cb
If bad_cb returns True then keep it :param tb: traceback that caused exception :return:
shoebot/grammar/livecode.py
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
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
[ "If", "bad_cb", "returns", "True", "then", "keep", "it", ":", "param", "tb", ":", "traceback", "that", "caused", "exception", ":", "return", ":" ]
shoebot/shoebot
python
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/livecode.py#L125-L133
[ "def", "call_bad_cb", "(", "self", ",", "tb", ")", ":", "with", "LiveExecution", ".", "lock", ":", "if", "self", ".", "bad_cb", "and", "not", "self", ".", "bad_cb", "(", "tb", ")", ":", "self", ".", "bad_cb", "=", "None" ]
d554c1765c1899fa25727c9fc6805d221585562b