INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Draws list markup with indentation in NodeBox. | def draw_list(markup, x, y, w, padding=5, callback=None):
""" Draws list markup with indentation in NodeBox.
Draw list markup at x, y coordinates
using indented bullets or numbers.
The callback is a command that takes a str and an int.
"""
try: from web import _ctx
except: pa... |
This is a very poor algorithm to draw Wikipedia tables in NodeBox. | def draw_table(table, x, y, w, padding=5):
""" This is a very poor algorithm to draw Wikipedia tables in NodeBox.
"""
try: from web import _ctx
except: pass
f = _ctx.fill()
_ctx.stroke(f)
h = _ctx.textheight(" ") + padding*2
row_y = y
if table.title != "":
... |
Parses data from Wikipedia page markup. | def parse(self, light=False):
""" Parses data from Wikipedia page markup.
The markup comes from Wikipedia's edit page.
We parse it here into objects containing plain text.
The light version parses only links to other articles, it's faster than a full parse.
"""
... |
Strips Wikipedia markup from given text. This creates a plain version of the markup stripping images and references and the like. Does some commonsense maintenance as well like collapsing multiple spaces. If you specified full_strip = False for WikipediaPage instance some markup is preserved as HTML ( links bold italic... | def plain(self, markup):
""" Strips Wikipedia markup from given text.
This creates a "plain" version of the markup,
stripping images and references and the like.
Does some commonsense maintenance as well,
like collapsing multiple spaces.
If you specified... |
Substitutes <pre > to Wikipedia markup by adding a space at the start of a line. | def convert_pre(self, markup):
""" Substitutes <pre> to Wikipedia markup by adding a space at the start of a line.
"""
for m in re.findall(self.re["preformatted"], markup):
markup = markup.replace(m, m.replace("\n", "\n "))
markup = re.sub("<pre.*?>\n{0,... |
Subtitutes <li > content to Wikipedia markup. | def convert_li(self, markup):
""" Subtitutes <li> content to Wikipedia markup.
"""
for li in re.findall("<li;*?>", markup):
markup = re.sub(li, "\n* ", markup)
markup = markup.replace("</li>", "")
return markup |
Subtitutes <table > content to Wikipedia markup. | def convert_table(self, markup):
""" Subtitutes <table> content to Wikipedia markup.
"""
for table in re.findall(self.re["html-table"], markup):
wiki = table
wiki = re.sub(r"<table(.*?)>", "{|\\1", wiki)
wiki = re.sub(r"<tr(.*?)>", "|-\\1", w... |
Returns a list of internal Wikipedia links in the markup. | def parse_links(self, markup):
""" Returns a list of internal Wikipedia links in the markup.
# A Wikipedia link looks like:
# [[List of operating systems#Embedded | List of embedded operating systems]]
# It does not contain a colon, this indicates images, users, languages, etc.... |
Returns a list of images found in the markup. An image has a pathname a description in plain text and a list of properties Wikipedia uses to size and place images. | def parse_images(self, markup, treshold=6):
""" Returns a list of images found in the markup.
An image has a pathname, a description in plain text
and a list of properties Wikipedia uses to size and place images.
# A Wikipedia image looks like:
# [[Image:Columb... |
Corrects Wikipedia image markup. | def parse_balanced_image(self, markup):
""" Corrects Wikipedia image markup.
Images have a description inside their link markup that
can contain link markup itself, make sure the outer "[" and "]" brackets
delimiting the image are balanced correctly (e.g. no [[ ]] ]]).
... |
Parses images from the <gallery > </ gallery > section. Images inside <gallery > tags do not have outer [[ brackets. Add these and then parse again. | def parse_gallery_images(self, markup):
""" Parses images from the <gallery></gallery> section.
Images inside <gallery> tags do not have outer "[[" brackets.
Add these and then parse again.
"""
gallery = re.search(self.re["gallery"], markup)
... |
Creates a list from lines of text in a paragraph. Each line of text is a new item in the list except lists and preformatted chunks ( <li > and <pre > ) these are kept together as a single chunk. Lists are formatted using parse_paragraph_list (). Empty lines are stripped from the output. Indentation ( i. e. lines starti... | def parse_paragraph(self, markup):
""" Creates a list from lines of text in a paragraph.
Each line of text is a new item in the list,
except lists and preformatted chunks (<li> and <pre>),
these are kept together as a single chunk.
Lists are formatted u... |
Formats bullets and numbering of Wikipedia lists. List items are marked by * # or ; at the start of a line. We treat ; the same as * and replace # with real numbering ( e. g. 2. ). Sublists ( e. g. *** and ### ) get indented by tabs. Called from parse_paragraphs () method. | def parse_paragraph_list(self, markup, indent="\t"):
""" Formats bullets and numbering of Wikipedia lists.
List items are marked by "*", "#" or ";" at the start of a line.
We treat ";" the same as "*",
and replace "#" with real numbering (e.g. "2.").
Sublists (e... |
Create parent/ child links to other paragraphs. The paragraphs parameters is a list of all the paragraphs parsed up till now. The parent is the previous paragraph whose depth is less. The parent s children include this paragraph. Called from parse_paragraphs () method. | def connect_paragraph(self, paragraph, paragraphs):
""" Create parent/child links to other paragraphs.
The paragraphs parameters is a list of all the paragraphs
parsed up till now.
The parent is the previous paragraph whose depth is less.
The parent's c... |
Updates references with content from specific paragraphs. The references notes external links paragraphs are double - checked for references. Not all items in the list might have been referenced inside the article or the item might contain more info than we initially parsed from it. Called from parse_paragraphs () meth... | def parse_paragraph_references(self, markup):
""" Updates references with content from specific paragraphs.
The "references", "notes", "external links" paragraphs
are double-checked for references. Not all items in the list
might have been referenced inside the article... |
Returns a list of paragraphs in the markup. A paragraph has a title and multiple lines of plain text. A paragraph might have parent and child paragraphs denoting subtitles or bigger chapters. A paragraph might have links to additional articles. Formats numbered lists by replacing # by 1. Formats bulleted sublists like ... | def parse_paragraphs(self, markup):
""" Returns a list of paragraphs in the markup.
A paragraph has a title and multiple lines of plain text.
A paragraph might have parent and child paragraphs,
denoting subtitles or bigger chapters.
A paragraph might ha... |
Parses a row of cells in a Wikipedia table. Cells in the row are separated by ||. A ! indicates a row of heading columns. Each cell can contain properties before a | # e. g. align = right | Cell 2 ( right aligned ). | def parse_table_row(self, markup, row):
""" Parses a row of cells in a Wikipedia table.
Cells in the row are separated by "||".
A "!" indicates a row of heading columns.
Each cell can contain properties before a "|",
# e.g. align="right" | Cell 2 (right aligned). ... |
Creates a link from the table to paragraph and vice versa. Finds the first heading above the table in the markup. This is the title of the paragraph the table belongs to. | def connect_table(self, table, chunk, markup):
""" Creates a link from the table to paragraph and vice versa.
Finds the first heading above the table in the markup.
This is the title of the paragraph the table belongs to.
"""
k = markup.find(chunk)
i =... |
Returns a list of tables in the markup. | def parse_tables(self, markup):
""" Returns a list of tables in the markup.
A Wikipedia table looks like:
{| border="1"
|-
|Cell 1 (no modifier - not aligned)
|-
|align="right" |Cell 2 (right aligned)
|-
|}
"""
tables = ... |
Returns a list of references found in the markup. References appear inline as <ref > footnotes http:// external links or {{ cite }} citations. We replace it with ( 1 ) - style footnotes. Additional references data is gathered in parse_paragraph_references () when we parse paragraphs. References can also appear in image... | def parse_references(self, markup):
""" Returns a list of references found in the markup.
References appear inline as <ref> footnotes,
http:// external links, or {{cite}} citations.
We replace it with (1)-style footnotes.
Additional references data is gathered in
... |
Returns a list of categories the page belongs to. | def parse_categories(self, markup):
""" Returns a list of categories the page belongs to.
# A Wikipedia category link looks like:
# [[Category:Computing]]
# This indicates the page is included in the given category.
# If "Category" is preceded by ":" this indicates a li... |
Returns a dictionary of translations for the page title. A Wikipedia language link looks like: [[ af: Rekenaar ]]. The parser will also fetch links like user: and media: but these are stripped against the dictionary of Wikipedia languages. You can get a translated page by searching Wikipedia with the appropriate langua... | def parse_translations(self, markup):
""" Returns a dictionary of translations for the page title.
A Wikipedia language link looks like: [[af:Rekenaar]].
The parser will also fetch links like "user:" and "media:"
but these are stripped against the dictionary of
... |
Gets the Wikipedia disambiguation page for this article. A Wikipedia disambiguation link refers to other pages with the same title but of smaller significance e. g. {{ dablink|For the IEEE magazine see [[ Computer ( magazine ) ]]. }} | def parse_disambiguation(self, markup):
""" Gets the Wikipedia disambiguation page for this article.
A Wikipedia disambiguation link refers to other pages
with the same title but of smaller significance,
e.g. {{dablink|For the IEEE magazine see [[Computer (magazine)]].}... |
Returns a list of words that appear in bold in the article. Things like table titles are not added to the list these are probably bold because it makes the layout nice not necessarily because they are important. | def parse_important(self, markup):
""" Returns a list of words that appear in bold in the article.
Things like table titles are not added to the list,
these are probably bold because it makes the layout nice,
not necessarily because they are important.
... |
Given a Variable and a value cleans it out | def sanitize(self, val):
"""Given a Variable and a value, cleans it out"""
if self.type == NUMBER:
try:
return clamp(self.min, self.max, float(val))
except ValueError:
return 0.0
elif self.type == TEXT:
try:
retu... |
Return whether I am compatible with the given var: - Type should be the same - My value should be inside the given vars min/ max range. | def compliesTo(self, v):
"""Return whether I am compatible with the given var:
- Type should be the same
- My value should be inside the given vars' min/max range.
"""
if self.type == v.type:
if self.type == NUMBER:
if self.value < self.min o... |
Convenience method that works with all 2. x versions of Python to determine whether or not something is listlike. | def isList(l):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is listlike."""
return hasattr(l, '__iter__') \
or (type(l) in (types.ListType, types.TupleType)) |
Convenience method that works with all 2. x versions of Python to determine whether or not something is stringlike. | def isString(s):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is stringlike."""
try:
return isinstance(s, unicode) or isinstance(s, basestring)
except NameError:
return isinstance(s, str) |
Turns a list of maps lists or scalars into a single map. Used to build the SELF_CLOSING_TAGS NESTABLE_TAGS and NESTING_RESET_TAGS maps out of lists and partial maps. | def buildTagMap(default, *args):
"""Turns a list of maps, lists, or scalars into a single map.
Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
NESTING_RESET_TAGS maps out of lists and partial maps."""
built = {}
for portion in args:
if hasattr(portion, 'items'):
#It's a m... |
Sets up the initial relations between this element and other elements. | def setup(self, parent=None, previous=None):
"""Sets up the initial relations between this element and
other elements."""
self.parent = parent
self.previous = previous
self.next = None
self.previousSibling = None
self.nextSibling = None
if self.parent and ... |
Destructively rips this element out of the tree. | def extract(self):
"""Destructively rips this element out of the tree."""
if self.parent:
try:
self.parent.contents.remove(self)
except ValueError:
pass
#Find the two elements that would be next to each other if
#this element (and ... |
Finds the last element beneath this object to be parsed. | def _lastRecursiveChild(self):
"Finds the last element beneath this object to be parsed."
lastChild = self
while hasattr(lastChild, 'contents') and lastChild.contents:
lastChild = lastChild.contents[-1]
return lastChild |
Returns the first item that matches the given criteria and appears after this Tag in the document. | def findNext(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears after this Tag in the document."""
return self._findOne(self.findAllNext, name, attrs, text, **kwargs) |
Returns all items that match the given criteria and appear after this Tag in the document. | def findAllNext(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
after this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.nextGenerator,
**kwar... |
Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document. | def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears after this Tag in the document."""
return self._findOne(self.findNextSiblings, name, attrs, text,
**kwargs) |
Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document. | def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document."""
return self._findAll(name, attrs, text, limit,
s... |
Returns the first item that matches the given criteria and appears before this Tag in the document. | def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears before this Tag in the document."""
return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) |
Returns all items that match the given criteria and appear before this Tag in the document. | def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
before this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.previousGenerator,
... |
Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document. | def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document."""
return self._findOne(self.findPreviousSiblings, name, attrs, text,
**kw... |
Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document. | def findPreviousSiblings(self, name=None, attrs={}, text=None,
limit=None, **kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear before this Tag in the document."""
return self._findAll(name, attrs, text, limit,
... |
Returns the closest parent of this Tag that matches the given criteria. | def findParent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _findOne because findParents takes a different
# set of arguments.
r = None
l = self.findParents(name, attrs, 1)
... |
Returns the parents of this Tag that match the given criteria. | def findParents(self, name=None, attrs={}, limit=None, **kwargs):
"""Returns the parents of this Tag that match the given
criteria."""
return self._findAll(name, attrs, None, limit, self.parentGenerator,
**kwargs) |
Iterates over a generator looking for things that match. | def _findAll(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
else:
# Build a SoupStrainer
strainer = SoupStrainer(name, attrs, text, **kwargs)
... |
Encodes an object to a string in some encoding or to Unicode.. | def toEncoding(self, s, encoding=None):
"""Encodes an object to a string in some encoding, or to Unicode.
."""
if isinstance(s, unicode):
if encoding:
s = s.encode(encoding)
elif isinstance(s, str):
if encoding:
s = s.encode(encodin... |
Cheap function to invert a hash. | def _invert(h):
"Cheap function to invert a hash."
i = {}
for k,v in h.items():
i[v] = k
return i |
Used in a call to re. sub to replace HTML XML and numeric entities with the appropriate Unicode characters. If HTML entities are being converted any unrecognized entities are escaped. | def _convertEntities(self, match):
"""Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped."""
x = match.group(1)
if self.convertHTMLEntitie... |
Recursively destroys the contents of this tree. | def decompose(self):
"""Recursively destroys the contents of this tree."""
contents = [i for i in self.contents]
for i in contents:
if isinstance(i, Tag):
i.decompose()
else:
i.extract()
self.extract() |
Renders the contents of this tag as a string in the given encoding. If encoding is None returns a Unicode string.. | def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Renders the contents of this tag as a string in the given
encoding. If encoding is None, returns a Unicode string.."""
s=[]
for c in self:
text = None
... |
Return only the first child of this Tag matching the given criteria. | def find(self, name=None, attrs={}, recursive=True, text=None,
**kwargs):
"""Return only the first child of this Tag matching the given
criteria."""
r = None
l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r |
Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. | def findAll(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in th... |
Initializes a map representation of this tag s attributes if not already initialized. | def _getAttrMap(self):
"""Initializes a map representation of this tag's attributes,
if not already initialized."""
if not getattr(self, 'attrMap'):
self.attrMap = {}
for (key, value) in self.attrs:
self.attrMap[key] = value
return self.attrMap |
This method fixes a bug in Python s SGMLParser. | def convert_charref(self, name):
"""This method fixes a bug in Python's SGMLParser."""
try:
n = int(name)
except ValueError:
return
if not 0 <= n <= 127 : # ASCII ends at 127, not 255
return
return self.convert_codepoint(n) |
Returns true iff the given string is the name of a self - closing tag according to this parser. | def isSelfClosingTag(self, name):
"""Returns true iff the given string is the name of a
self-closing tag according to this parser."""
return self.SELF_CLOSING_TAGS.has_key(name) \
or self.instanceSelfClosingTags.has_key(name) |
Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false pops the tag stack up to but * not * including the most recent instqance of the given tag. | def _popToTag(self, name, inclusivePop=True):
"""Pops the tag stack up to and including the most recent
instance of the given tag. If inclusivePop is false, pops the tag
stack up to but *not* including the most recent instqance of
the given tag."""
#print "Popping to %s" % name
... |
Adds a certain piece of text to the tree as a NavigableString subclass. | def _toStringSubclass(self, text, subclass):
"""Adds a certain piece of text to the tree as a NavigableString
subclass."""
self.endData()
self.handle_data(text)
self.endData(subclass) |
Handle a processing instruction as a ProcessingInstruction object possibly one with a %SOUP - ENCODING% slot into which an encoding will be plugged later. | def handle_pi(self, text):
"""Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later."""
if text[:3] == "xml":
text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
self... |
Handle character references as data. | def handle_charref(self, ref):
"Handle character references as data."
if self.convertEntities:
data = unichr(int(ref))
else:
data = '&#%s;' % ref
self.handle_data(data) |
Handle entity references as data possibly converting known HTML and/ or XML entity references to the corresponding Unicode characters. | def handle_entityref(self, ref):
"""Handle entity references as data, possibly converting known
HTML and/or XML entity references to the corresponding Unicode
characters."""
data = None
if self.convertHTMLEntities:
try:
data = unichr(name2codepoint[ref... |
Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object. | def parse_declaration(self, i):
"""Treat a bogus SGML declaration as raw data. Treat a CDATA
declaration as a CData object."""
j = None
if self.rawdata[i:i+9] == '<![CDATA[':
k = self.rawdata.find(']]>', i)
if k == -1:
k = len(self.rawdata)
... |
Beautiful Soup can detect a charset included in a META tag try to convert the document to that charset and re - parse the document from the beginning. | def start_meta(self, attrs):
"""Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning."""
httpEquiv = None
contentType = None
contentTypeIndex = None
tagNeedsEncodingSu... |
Changes a MS smart quote character to an XML or HTML entity. | def _subMSChar(self, orig):
"""Changes a MS smart quote character to an XML or HTML
entity."""
sub = self.MS_CHARS.get(orig)
if type(sub) == types.TupleType:
if self.smartQuotesTo == 'xml':
sub = '&#x%s;' % sub[1]
else:
sub = '&%s;'... |
Given a string and its encoding decodes the string into Unicode. %encoding is a string recognized by encodings. aliases | def _toUnicode(self, data, encoding):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') \
and (data[2:4] != '\... |
Given a document tries to detect its XML encoding. | def _detectEncoding(self, xml_data, isHTML=False):
"""Given a document, tries to detect its XML encoding."""
xml_encoding = sniffed_xml_encoding = None
try:
if xml_data[:4] == '\x4c\x6f\xa7\x94':
# EBCDIC
xml_data = self._ebcdic_to_ascii(xml_data)
... |
Decorator to run some code in a bot instance. | def shoebot_example(**shoebot_kwargs):
"""
Decorator to run some code in a bot instance.
"""
def decorator(f):
def run():
from shoebot import ShoebotInstallError # https://github.com/shoebot/shoebot/issues/206
print(" Shoebot - %s:" % f.__name__.replace("_", " "))
... |
Returns the center point of the path disregarding transforms. | def _get_center(self):
'''Returns the center point of the path, disregarding transforms.
'''
x = (self.x + self.width / 2)
y = (self.y + self.height / 2)
return (x, y) |
Scale context based on difference between bot size and widget | def scale_context_and_center(self, cr):
"""
Scale context based on difference between bot size and widget
"""
bot_width, bot_height = self.bot_size
if self.width != bot_width or self.height != bot_height:
# Scale up by largest dimension
if self.width < sel... |
Draw just the exposed part of the backing store scaled to fit | def draw(self, widget, cr):
'''
Draw just the exposed part of the backing store, scaled to fit
'''
if self.bot_size is None:
# No bot to draw yet.
self.draw_default_image(cr)
return
cr = driver.ensure_pycairo_context(cr)
surfa... |
Creates a recording surface for the bot to draw on | def create_rcontext(self, size, frame):
'''
Creates a recording surface for the bot to draw on
:param size: The width and height of bot
'''
self.frame = frame
width, height = size
meta_surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, (0, 0, width, heig... |
Update the backing store from a cairo context and schedule a redraw ( expose event ) | def do_drawing(self, size, frame, cairo_ctx):
'''
Update the backing store from a cairo context and
schedule a redraw (expose event)
:param size: width, height in pixels of bot
:param frame: frame # thar was drawn
:param cairo_ctx: cairo context the bot was drawn on
... |
Return a JSON string representation of a Python data structure. | def encode(self, o):
"""
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks.
if isinstance(o, basestring):
... |
Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder (). iterencode ( bigobject ): mysocket. write ( chunk ) | def iterencode(self, o):
"""
Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
... |
Return a dict in the form of | def get_key_map(self):
'''
Return a dict in the form of
SHOEBOT_KEY_NAME, GTK_VALUE
Shoebot key names look like KEY_LEFT, whereas Gdk uses KEY_Left
- Shoebot key names are derived from Nodebox 1, which was a mac
app.
'''
kdict = {}
for gdk_name... |
Recurse through the system. When a segment is drawn the LSsytem. segment () method will be called. You can customize this method to create your own visualizations. It takes an optional time parameter. If you divide this parameter by LSsytem. duration () you get a number between 0. 0 and 1. 0 you can use as an alpha val... | def _grow(self, generation, rule, angle, length, time=maxint, draw=True):
""" Recurse through the system.
When a segment is drawn, the LSsytem.segment() method will be called.
You can customize this method to create your own visualizations.
It takes an optional time parameter. ... |
If filename was used output a filename along with multifile numbered filenames will be used. | def _output_file(self, frame):
"""
If filename was used output a filename, along with multifile
numbered filenames will be used.
If buff was specified it is returned.
:return: Output buff or filename.
"""
if self.buff:
return self.buff
elif s... |
Called when CairoCanvas needs a cairo context to draw on | def create_rcontext(self, size, frame):
"""
Called when CairoCanvas needs a cairo context to draw on
"""
if self.format == 'pdf':
surface = cairo.PDFSurface(self._output_file(frame), *size)
elif self.format in ('ps', 'eps'):
surface = cairo.PSSurface(self.... |
Called when CairoCanvas has rendered a bot | def rendering_finished(self, size, frame, cairo_ctx):
"""
Called when CairoCanvas has rendered a bot
"""
surface = cairo_ctx.get_target()
if self.format == 'png':
surface.write_to_png(self._output_file(frame))
surface.finish()
surface.flush() |
Function to output to a cairo surface | def output_closure(self, target, file_number=None):
'''
Function to output to a cairo surface
target is a cairo Context or filename
if file_number is set, then files will be numbered
(this is usually set to the current frame number)
'''
def output_context(ctx):
... |
Strips links from the definition and gathers them in a links property. | def _parse(self):
""" Strips links from the definition and gathers them in a links property.
"""
p1 = "\[.*?\](.*?)\[\/.*?\]"
p2 = "\[(.*?)\]"
self.links = []
for p in (p1,p2):
for link in re.findall(p, self.description):
self... |
Create canvas and sink for attachment to a bot | def create_canvas(src, format=None, outputfile=None, multifile=False, buff=None, window=False, title=None,
fullscreen=None, show_vars=False):
"""
Create canvas and sink for attachment to a bot
canvas is what draws images, 'sink' is the final consumer of the images
:param src: Default... |
Create a canvas and a bot with the same canvas attached to it | def create_bot(src=None, grammar=NODEBOX, format=None, outputfile=None, iterations=1, buff=None, window=False,
title=None, fullscreen=None, server=False, port=7777, show_vars=False, vars=None, namespace=None):
"""
Create a canvas and a bot with the same canvas attached to it
bot parameters
... |
Create and run a bot the arguments all correspond to sanitized commandline options. | def run(src,
grammar=NODEBOX,
format=None,
outputfile=None,
iterations=1,
buff=None,
window=True,
title=None,
fullscreen=None,
close_window=False,
server=False,
port=7777,
show_vars=False,
vars=None,
namespac... |
Return True if the buffer was saved | def save_as(self):
"""
Return True if the buffer was saved
"""
chooser = ShoebotFileChooserDialog(_('Save File'), None, Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT,
Gtk.STOCK_C... |
Add all widgets to specified vbox: param container:: return: | def add_variables(self):
"""
Add all widgets to specified vbox
:param container:
:return:
"""
for k, v in self.bot._vars.items():
if not hasattr(v, 'type'):
raise AttributeError(
'%s is not a Shoebot Variable - see https://s... |
: return: success err_msg_if_failed | def update_var(self, name, value):
"""
:return: success, err_msg_if_failed
"""
widget = self.widgets.get(name)
if widget is None:
return False, 'No widget found matching, {}'.format(name)
try:
if isinstance(widget, Gtk.CheckButton):
... |
Called when a slider is adjusted. | def widget_changed(self, widget, v):
''' Called when a slider is adjusted. '''
# set the appropriate bot var
if v.type is NUMBER:
self.bot._namespace[v.name] = widget.get_value()
self.bot._vars[v.name].value = widget.get_value() ## Not sure if this is how to do this - st... |
var was added in the bot while it ran possibly by livecoding | def var_added(self, v):
"""
var was added in the bot while it ran, possibly
by livecoding
:param v:
:return:
"""
self.add_variable(v)
self.window.set_size_request(400, 35 * len(self.widgets.keys()))
self.window.show_all() |
var was added in the bot | def var_deleted(self, v):
"""
var was added in the bot
:param v:
:return:
"""
widget = self.widgets[v.name]
# widgets are all in a single container ..
parent = widget.get_parent()
self.container.remove(parent)
del self.widgets[v.name]
... |
Returns cached copies unless otherwise specified. | def parse(svg, cached=False, _copy=True):
""" Returns cached copies unless otherwise specified.
"""
if not cached:
dom = parser.parseString(svg)
paths = parse_node(dom, [])
else:
id = _cache.id(svg)
if not _cache.has_key(id):
dom = parser.parseString... |
Returns XML element s attribute or default if none. | def get_attribute(element, attribute, default=0):
""" Returns XML element's attribute, or default if none.
"""
a = element.getAttribute(attribute)
if a == "":
return default
return a |
Recurse the node tree and find drawable tags. Recures all the children in the node. If a child is something we can draw a line rect oval or path parse it to a PathElement drawable with drawpath () | def parse_node(node, paths=[], ignore=["pattern"]):
""" Recurse the node tree and find drawable tags.
Recures all the children in the node.
If a child is something we can draw,
a line, rect, oval or path,
parse it to a PathElement drawable with drawpath()
"""
# Ignore pat... |
Transform the path according to a defined matrix. Attempts to extract a transform = matrix () |translate () attribute. Transforms the path accordingly. | def parse_transform(e, path):
""" Transform the path according to a defined matrix.
Attempts to extract a transform="matrix()|translate()" attribute.
Transforms the path accordingly.
"""
t = get_attribute(e, "transform", default="")
for mode in ("matrix", "translate"):
... |
Expand the path with color information. Attempts to extract fill and stroke colors from the element and adds it to path attributes. | def add_color_info(e, path):
""" Expand the path with color information.
Attempts to extract fill and stroke colors
from the element and adds it to path attributes.
"""
_ctx.colormode(RGB, 1.0)
def _color(hex, alpha=1.0):
if hex == "none": return None
n =... |
Downloads this image to cache. Calling the download () method instantiates an asynchronous URLAccumulator. Once it is done downloading this image will have its path property set to an image file in the cache. | def download(self, size=SIZE_LARGE, thumbnail=False, wait=60, asynchronous=False):
""" Downloads this image to cache.
Calling the download() method instantiates an asynchronous URLAccumulator.
Once it is done downloading, this image will have its path property
set to an... |
Returns a copy of the event handler remembering the last node clicked. | def copy(self, graph):
""" Returns a copy of the event handler, remembering the last node clicked.
"""
e = events(graph, self._ctx)
e.clicked = self.clicked
return e |
Interacts with the graph by clicking or dragging nodes. Hovering a node fires the callback function events. hover (). Clicking a node fires the callback function events. click (). | def update(self):
""" Interacts with the graph by clicking or dragging nodes.
Hovering a node fires the callback function events.hover().
Clicking a node fires the callback function events.click().
"""
if self.mousedown:
# When not pressing or dragg... |
Drags given node to mouse location. | def drag(self, node):
""" Drags given node to mouse location.
"""
dx = self.mouse.x - self.graph.x
dy = self.mouse.y - self.graph.y
# A dashed line indicates the drag vector.
s = self.graph.styles.default
self._ctx.nofill()
self._ctx.nostroke()
... |
Displays a popup when hovering over a node. | def hover(self, node):
""" Displays a popup when hovering over a node.
"""
if self.popup == False: return
if self.popup == True or self.popup.node != node:
if self.popup_text.has_key(node.id):
texts = self.popup_text[node.id]
else... |
Returns a cached textpath of the given text in queue. | def textpath(self, i):
""" Returns a cached textpath of the given text in queue.
"""
if len(self._textpaths) == i:
self._ctx.font(self.font, self.fontsize)
txt = self.q[i]
if len(self.q) > 1:
# Indicate current text (e.g. 5/13... |
Rotates the queued texts and determines display time. | def update(self):
""" Rotates the queued texts and determines display time.
"""
if self.delay > 0:
# It takes a while for the popup to appear.
self.delay -= 1; return
if self.fi == 0:
# Only one text in queue, displayed i... |
Draws a popup rectangle with a rotating text queue. | def draw(self):
""" Draws a popup rectangle with a rotating text queue.
"""
if len(self.q) > 0:
self.update()
if self.delay == 0:
# Rounded rectangle in the given background color.
p,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.