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
test
unsign
Remove RECORD.jws from a wheel by truncating the zip file. RECORD.jws must be at the end of the archive. The zip file must be an ordinary archive, with the compressed files and the directory in the same order, and without any non-zip content after the truncation point.
capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py
def unsign(wheelfile): """ Remove RECORD.jws from a wheel by truncating the zip file. RECORD.jws must be at the end of the archive. The zip file must be an ordinary archive, with the compressed files and the directory in the same order, and without any non-zip content after the truncation point. """ import wheel.install vzf = wheel.install.VerifyingZipFile(wheelfile, "a") info = vzf.infolist() if not (len(info) and info[-1].filename.endswith('/RECORD.jws')): raise WheelError("RECORD.jws not found at end of archive.") vzf.pop() vzf.close()
def unsign(wheelfile): """ Remove RECORD.jws from a wheel by truncating the zip file. RECORD.jws must be at the end of the archive. The zip file must be an ordinary archive, with the compressed files and the directory in the same order, and without any non-zip content after the truncation point. """ import wheel.install vzf = wheel.install.VerifyingZipFile(wheelfile, "a") info = vzf.infolist() if not (len(info) and info[-1].filename.endswith('/RECORD.jws')): raise WheelError("RECORD.jws not found at end of archive.") vzf.pop() vzf.close()
[ "Remove", "RECORD", ".", "jws", "from", "a", "wheel", "by", "truncating", "the", "zip", "file", ".", "RECORD", ".", "jws", "must", "be", "at", "the", "end", "of", "the", "archive", ".", "The", "zip", "file", "must", "be", "an", "ordinary", "archive", "with", "the", "compressed", "files", "and", "the", "directory", "in", "the", "same", "order", "and", "without", "any", "non", "-", "zip", "content", "after", "the", "truncation", "point", "." ]
AkihikoITOH/capybara
python
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py#L94-L108
[ "def", "unsign", "(", "wheelfile", ")", ":", "import", "wheel", ".", "install", "vzf", "=", "wheel", ".", "install", ".", "VerifyingZipFile", "(", "wheelfile", ",", "\"a\"", ")", "info", "=", "vzf", ".", "infolist", "(", ")", "if", "not", "(", "len", "(", "info", ")", "and", "info", "[", "-", "1", "]", ".", "filename", ".", "endswith", "(", "'/RECORD.jws'", ")", ")", ":", "raise", "WheelError", "(", "\"RECORD.jws not found at end of archive.\"", ")", "vzf", ".", "pop", "(", ")", "vzf", ".", "close", "(", ")" ]
e86c2173ea386654f4ae061148e8fbe3f25e715c
test
verify
Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents.
capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py
def verify(wheelfile): """Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents. """ wf = WheelFile(wheelfile) sig_name = wf.distinfo_name + '/RECORD.jws' sig = json.loads(native(wf.zipfile.open(sig_name).read())) verified = signatures.verify(sig) sys.stderr.write("Signatures are internally consistent.\n") sys.stdout.write(json.dumps(verified, indent=2)) sys.stdout.write('\n')
def verify(wheelfile): """Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents. """ wf = WheelFile(wheelfile) sig_name = wf.distinfo_name + '/RECORD.jws' sig = json.loads(native(wf.zipfile.open(sig_name).read())) verified = signatures.verify(sig) sys.stderr.write("Signatures are internally consistent.\n") sys.stdout.write(json.dumps(verified, indent=2)) sys.stdout.write('\n')
[ "Verify", "a", "wheel", ".", "The", "signature", "will", "be", "verified", "for", "internal", "consistency", "ONLY", "and", "printed", ".", "Wheel", "s", "own", "unpack", "/", "install", "commands", "verify", "the", "manifest", "against", "the", "signature", "and", "file", "contents", "." ]
AkihikoITOH/capybara
python
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py#L110-L123
[ "def", "verify", "(", "wheelfile", ")", ":", "wf", "=", "WheelFile", "(", "wheelfile", ")", "sig_name", "=", "wf", ".", "distinfo_name", "+", "'/RECORD.jws'", "sig", "=", "json", ".", "loads", "(", "native", "(", "wf", ".", "zipfile", ".", "open", "(", "sig_name", ")", ".", "read", "(", ")", ")", ")", "verified", "=", "signatures", ".", "verify", "(", "sig", ")", "sys", ".", "stderr", ".", "write", "(", "\"Signatures are internally consistent.\\n\"", ")", "sys", ".", "stdout", ".", "write", "(", "json", ".", "dumps", "(", "verified", ",", "indent", "=", "2", ")", ")", "sys", ".", "stdout", ".", "write", "(", "'\\n'", ")" ]
e86c2173ea386654f4ae061148e8fbe3f25e715c
test
unpack
Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory).
capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py
def unpack(wheelfile, dest='.'): """Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory). """ wf = WheelFile(wheelfile) namever = wf.parsed_filename.group('namever') destination = os.path.join(dest, namever) sys.stderr.write("Unpacking to: %s\n" % (destination)) wf.zipfile.extractall(destination) wf.zipfile.close()
def unpack(wheelfile, dest='.'): """Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory). """ wf = WheelFile(wheelfile) namever = wf.parsed_filename.group('namever') destination = os.path.join(dest, namever) sys.stderr.write("Unpacking to: %s\n" % (destination)) wf.zipfile.extractall(destination) wf.zipfile.close()
[ "Unpack", "a", "wheel", "." ]
AkihikoITOH/capybara
python
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py#L125-L139
[ "def", "unpack", "(", "wheelfile", ",", "dest", "=", "'.'", ")", ":", "wf", "=", "WheelFile", "(", "wheelfile", ")", "namever", "=", "wf", ".", "parsed_filename", ".", "group", "(", "'namever'", ")", "destination", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "namever", ")", "sys", ".", "stderr", ".", "write", "(", "\"Unpacking to: %s\\n\"", "%", "(", "destination", ")", ")", "wf", ".", "zipfile", ".", "extractall", "(", "destination", ")", "wf", ".", "zipfile", ".", "close", "(", ")" ]
e86c2173ea386654f4ae061148e8fbe3f25e715c
test
install
Install wheels. :param requirements: A list of requirements or wheel files to install. :param requirements_file: A file containing requirements to install. :param wheel_dirs: A list of directories to search for wheels. :param force: Install a wheel file even if it is not compatible. :param list_files: Only list the files to install, don't install them. :param dry_run: Do everything but the actual install.
capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py
def install(requirements, requirements_file=None, wheel_dirs=None, force=False, list_files=False, dry_run=False): """Install wheels. :param requirements: A list of requirements or wheel files to install. :param requirements_file: A file containing requirements to install. :param wheel_dirs: A list of directories to search for wheels. :param force: Install a wheel file even if it is not compatible. :param list_files: Only list the files to install, don't install them. :param dry_run: Do everything but the actual install. """ # If no wheel directories specified, use the WHEELPATH environment # variable, or the current directory if that is not set. if not wheel_dirs: wheelpath = os.getenv("WHEELPATH") if wheelpath: wheel_dirs = wheelpath.split(os.pathsep) else: wheel_dirs = [ os.path.curdir ] # Get a list of all valid wheels in wheel_dirs all_wheels = [] for d in wheel_dirs: for w in os.listdir(d): if w.endswith('.whl'): wf = WheelFile(os.path.join(d, w)) if wf.compatible: all_wheels.append(wf) # If there is a requirements file, add it to the list of requirements if requirements_file: # If the file doesn't exist, search for it in wheel_dirs # This allows standard requirements files to be stored with the # wheels. if not os.path.exists(requirements_file): for d in wheel_dirs: name = os.path.join(d, requirements_file) if os.path.exists(name): requirements_file = name break with open(requirements_file) as fd: requirements.extend(fd) to_install = [] for req in requirements: if req.endswith('.whl'): # Explicitly specified wheel filename if os.path.exists(req): wf = WheelFile(req) if wf.compatible or force: to_install.append(wf) else: msg = ("{0} is not compatible with this Python. " "--force to install anyway.".format(req)) raise WheelError(msg) else: # We could search on wheel_dirs, but it's probably OK to # assume the user has made an error. raise WheelError("No such wheel file: {}".format(req)) continue # We have a requirement spec # If we don't have pkg_resources, this will raise an exception matches = matches_requirement(req, all_wheels) if not matches: raise WheelError("No match for requirement {}".format(req)) to_install.append(max(matches)) # We now have a list of wheels to install if list_files: sys.stdout.write("Installing:\n") if dry_run: return for wf in to_install: if list_files: sys.stdout.write(" {0}\n".format(wf.filename)) continue wf.install(force=force) wf.zipfile.close()
def install(requirements, requirements_file=None, wheel_dirs=None, force=False, list_files=False, dry_run=False): """Install wheels. :param requirements: A list of requirements or wheel files to install. :param requirements_file: A file containing requirements to install. :param wheel_dirs: A list of directories to search for wheels. :param force: Install a wheel file even if it is not compatible. :param list_files: Only list the files to install, don't install them. :param dry_run: Do everything but the actual install. """ # If no wheel directories specified, use the WHEELPATH environment # variable, or the current directory if that is not set. if not wheel_dirs: wheelpath = os.getenv("WHEELPATH") if wheelpath: wheel_dirs = wheelpath.split(os.pathsep) else: wheel_dirs = [ os.path.curdir ] # Get a list of all valid wheels in wheel_dirs all_wheels = [] for d in wheel_dirs: for w in os.listdir(d): if w.endswith('.whl'): wf = WheelFile(os.path.join(d, w)) if wf.compatible: all_wheels.append(wf) # If there is a requirements file, add it to the list of requirements if requirements_file: # If the file doesn't exist, search for it in wheel_dirs # This allows standard requirements files to be stored with the # wheels. if not os.path.exists(requirements_file): for d in wheel_dirs: name = os.path.join(d, requirements_file) if os.path.exists(name): requirements_file = name break with open(requirements_file) as fd: requirements.extend(fd) to_install = [] for req in requirements: if req.endswith('.whl'): # Explicitly specified wheel filename if os.path.exists(req): wf = WheelFile(req) if wf.compatible or force: to_install.append(wf) else: msg = ("{0} is not compatible with this Python. " "--force to install anyway.".format(req)) raise WheelError(msg) else: # We could search on wheel_dirs, but it's probably OK to # assume the user has made an error. raise WheelError("No such wheel file: {}".format(req)) continue # We have a requirement spec # If we don't have pkg_resources, this will raise an exception matches = matches_requirement(req, all_wheels) if not matches: raise WheelError("No match for requirement {}".format(req)) to_install.append(max(matches)) # We now have a list of wheels to install if list_files: sys.stdout.write("Installing:\n") if dry_run: return for wf in to_install: if list_files: sys.stdout.write(" {0}\n".format(wf.filename)) continue wf.install(force=force) wf.zipfile.close()
[ "Install", "wheels", ".", ":", "param", "requirements", ":", "A", "list", "of", "requirements", "or", "wheel", "files", "to", "install", ".", ":", "param", "requirements_file", ":", "A", "file", "containing", "requirements", "to", "install", ".", ":", "param", "wheel_dirs", ":", "A", "list", "of", "directories", "to", "search", "for", "wheels", ".", ":", "param", "force", ":", "Install", "a", "wheel", "file", "even", "if", "it", "is", "not", "compatible", ".", ":", "param", "list_files", ":", "Only", "list", "the", "files", "to", "install", "don", "t", "install", "them", ".", ":", "param", "dry_run", ":", "Do", "everything", "but", "the", "actual", "install", "." ]
AkihikoITOH/capybara
python
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py#L141-L224
[ "def", "install", "(", "requirements", ",", "requirements_file", "=", "None", ",", "wheel_dirs", "=", "None", ",", "force", "=", "False", ",", "list_files", "=", "False", ",", "dry_run", "=", "False", ")", ":", "# If no wheel directories specified, use the WHEELPATH environment", "# variable, or the current directory if that is not set.", "if", "not", "wheel_dirs", ":", "wheelpath", "=", "os", ".", "getenv", "(", "\"WHEELPATH\"", ")", "if", "wheelpath", ":", "wheel_dirs", "=", "wheelpath", ".", "split", "(", "os", ".", "pathsep", ")", "else", ":", "wheel_dirs", "=", "[", "os", ".", "path", ".", "curdir", "]", "# Get a list of all valid wheels in wheel_dirs", "all_wheels", "=", "[", "]", "for", "d", "in", "wheel_dirs", ":", "for", "w", "in", "os", ".", "listdir", "(", "d", ")", ":", "if", "w", ".", "endswith", "(", "'.whl'", ")", ":", "wf", "=", "WheelFile", "(", "os", ".", "path", ".", "join", "(", "d", ",", "w", ")", ")", "if", "wf", ".", "compatible", ":", "all_wheels", ".", "append", "(", "wf", ")", "# If there is a requirements file, add it to the list of requirements", "if", "requirements_file", ":", "# If the file doesn't exist, search for it in wheel_dirs", "# This allows standard requirements files to be stored with the", "# wheels.", "if", "not", "os", ".", "path", ".", "exists", "(", "requirements_file", ")", ":", "for", "d", "in", "wheel_dirs", ":", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "requirements_file", ")", "if", "os", ".", "path", ".", "exists", "(", "name", ")", ":", "requirements_file", "=", "name", "break", "with", "open", "(", "requirements_file", ")", "as", "fd", ":", "requirements", ".", "extend", "(", "fd", ")", "to_install", "=", "[", "]", "for", "req", "in", "requirements", ":", "if", "req", ".", "endswith", "(", "'.whl'", ")", ":", "# Explicitly specified wheel filename", "if", "os", ".", "path", ".", "exists", "(", "req", ")", ":", "wf", "=", "WheelFile", "(", "req", ")", "if", "wf", ".", "compatible", "or", "force", ":", "to_install", ".", "append", "(", "wf", ")", "else", ":", "msg", "=", "(", "\"{0} is not compatible with this Python. \"", "\"--force to install anyway.\"", ".", "format", "(", "req", ")", ")", "raise", "WheelError", "(", "msg", ")", "else", ":", "# We could search on wheel_dirs, but it's probably OK to", "# assume the user has made an error.", "raise", "WheelError", "(", "\"No such wheel file: {}\"", ".", "format", "(", "req", ")", ")", "continue", "# We have a requirement spec", "# If we don't have pkg_resources, this will raise an exception", "matches", "=", "matches_requirement", "(", "req", ",", "all_wheels", ")", "if", "not", "matches", ":", "raise", "WheelError", "(", "\"No match for requirement {}\"", ".", "format", "(", "req", ")", ")", "to_install", ".", "append", "(", "max", "(", "matches", ")", ")", "# We now have a list of wheels to install", "if", "list_files", ":", "sys", ".", "stdout", ".", "write", "(", "\"Installing:\\n\"", ")", "if", "dry_run", ":", "return", "for", "wf", "in", "to_install", ":", "if", "list_files", ":", "sys", ".", "stdout", ".", "write", "(", "\" {0}\\n\"", ".", "format", "(", "wf", ".", "filename", ")", ")", "continue", "wf", ".", "install", "(", "force", "=", "force", ")", "wf", ".", "zipfile", ".", "close", "(", ")" ]
e86c2173ea386654f4ae061148e8fbe3f25e715c
test
install_scripts
Regenerate the entry_points console_scripts for the named distribution.
capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py
def install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") for dist in distributions: pkg_resources_dist = pkg_resources.get_distribution(dist) install = wheel.paths.get_install_command(dist) command = easy_install.easy_install(install.distribution) command.args = ['wheel'] # dummy argument command.finalize_options() command.install_egg_scripts(pkg_resources_dist)
def install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") for dist in distributions: pkg_resources_dist = pkg_resources.get_distribution(dist) install = wheel.paths.get_install_command(dist) command = easy_install.easy_install(install.distribution) command.args = ['wheel'] # dummy argument command.finalize_options() command.install_egg_scripts(pkg_resources_dist)
[ "Regenerate", "the", "entry_points", "console_scripts", "for", "the", "named", "distribution", "." ]
AkihikoITOH/capybara
python
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py#L226-L242
[ "def", "install_scripts", "(", "distributions", ")", ":", "try", ":", "from", "setuptools", ".", "command", "import", "easy_install", "import", "pkg_resources", "except", "ImportError", ":", "raise", "RuntimeError", "(", "\"'wheel install_scripts' needs setuptools.\"", ")", "for", "dist", "in", "distributions", ":", "pkg_resources_dist", "=", "pkg_resources", ".", "get_distribution", "(", "dist", ")", "install", "=", "wheel", ".", "paths", ".", "get_install_command", "(", "dist", ")", "command", "=", "easy_install", ".", "easy_install", "(", "install", ".", "distribution", ")", "command", ".", "args", "=", "[", "'wheel'", "]", "# dummy argument", "command", ".", "finalize_options", "(", ")", "command", ".", "install_egg_scripts", "(", "pkg_resources_dist", ")" ]
e86c2173ea386654f4ae061148e8fbe3f25e715c
test
Graph.arrange_all
Sets for the _draw_ and _ldraw_ attributes for each of the graph sub-elements by processing the xdot format of the graph.
godot/graph.py
def arrange_all(self): """ Sets for the _draw_ and _ldraw_ attributes for each of the graph sub-elements by processing the xdot format of the graph. """ import godot.dot_data_parser parser = godot.dot_data_parser.GodotDataParser() xdot_data = self.create( format = "xdot" ) # print "GRAPH DOT:\n", str( self ) # print "XDOT DATA:\n", xdot_data parser.dotparser.parseWithTabs() ndata = xdot_data.replace( "\\\n", "" ) tokens = parser.dotparser.parseString( ndata )[0] parser.build_graph( graph=self, tokens=tokens[3] ) self.redraw_canvas()
def arrange_all(self): """ Sets for the _draw_ and _ldraw_ attributes for each of the graph sub-elements by processing the xdot format of the graph. """ import godot.dot_data_parser parser = godot.dot_data_parser.GodotDataParser() xdot_data = self.create( format = "xdot" ) # print "GRAPH DOT:\n", str( self ) # print "XDOT DATA:\n", xdot_data parser.dotparser.parseWithTabs() ndata = xdot_data.replace( "\\\n", "" ) tokens = parser.dotparser.parseString( ndata )[0] parser.build_graph( graph=self, tokens=tokens[3] ) self.redraw_canvas()
[ "Sets", "for", "the", "_draw_", "and", "_ldraw_", "attributes", "for", "each", "of", "the", "graph", "sub", "-", "elements", "by", "processing", "the", "xdot", "format", "of", "the", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L886-L903
[ "def", "arrange_all", "(", "self", ")", ":", "import", "godot", ".", "dot_data_parser", "parser", "=", "godot", ".", "dot_data_parser", ".", "GodotDataParser", "(", ")", "xdot_data", "=", "self", ".", "create", "(", "format", "=", "\"xdot\"", ")", "# print \"GRAPH DOT:\\n\", str( self )", "# print \"XDOT DATA:\\n\", xdot_data", "parser", ".", "dotparser", ".", "parseWithTabs", "(", ")", "ndata", "=", "xdot_data", ".", "replace", "(", "\"\\\\\\n\"", ",", "\"\"", ")", "tokens", "=", "parser", ".", "dotparser", ".", "parseString", "(", "ndata", ")", "[", "0", "]", "parser", ".", "build_graph", "(", "graph", "=", "self", ",", "tokens", "=", "tokens", "[", "3", "]", ")", "self", ".", "redraw_canvas", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Graph.redraw_canvas
Parses the Xdot attributes of all graph components and adds the components to a new canvas.
godot/graph.py
def redraw_canvas(self): """ Parses the Xdot attributes of all graph components and adds the components to a new canvas. """ from xdot_parser import XdotAttrParser xdot_parser = XdotAttrParser() canvas = self._component_default() for node in self.nodes: components = xdot_parser.parse_xdot_data( node._draw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( node._ldraw_ ) canvas.add( *components ) for edge in self.edges: components = xdot_parser.parse_xdot_data( edge._draw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._ldraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._hdraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._tdraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._hldraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._tldraw_ ) canvas.add( *components ) self.component = canvas self.vp.request_redraw()
def redraw_canvas(self): """ Parses the Xdot attributes of all graph components and adds the components to a new canvas. """ from xdot_parser import XdotAttrParser xdot_parser = XdotAttrParser() canvas = self._component_default() for node in self.nodes: components = xdot_parser.parse_xdot_data( node._draw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( node._ldraw_ ) canvas.add( *components ) for edge in self.edges: components = xdot_parser.parse_xdot_data( edge._draw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._ldraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._hdraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._tdraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._hldraw_ ) canvas.add( *components ) components = xdot_parser.parse_xdot_data( edge._tldraw_ ) canvas.add( *components ) self.component = canvas self.vp.request_redraw()
[ "Parses", "the", "Xdot", "attributes", "of", "all", "graph", "components", "and", "adds", "the", "components", "to", "a", "new", "canvas", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L907-L938
[ "def", "redraw_canvas", "(", "self", ")", ":", "from", "xdot_parser", "import", "XdotAttrParser", "xdot_parser", "=", "XdotAttrParser", "(", ")", "canvas", "=", "self", ".", "_component_default", "(", ")", "for", "node", "in", "self", ".", "nodes", ":", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "node", ".", "_draw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "node", ".", "_ldraw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "for", "edge", "in", "self", ".", "edges", ":", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "edge", ".", "_draw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "edge", ".", "_ldraw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "edge", ".", "_hdraw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "edge", ".", "_tdraw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "edge", ".", "_hldraw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "components", "=", "xdot_parser", ".", "parse_xdot_data", "(", "edge", ".", "_tldraw_", ")", "canvas", ".", "add", "(", "*", "components", ")", "self", ".", "component", "=", "canvas", "self", ".", "vp", ".", "request_redraw", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Graph.get_node
Returns a node given an ID or None if no such node exists.
godot/graph.py
def get_node(self, ID): """ Returns a node given an ID or None if no such node exists. """ node = super(Graph, self).get_node(ID) if node is not None: return node for graph in self.all_graphs: for each_node in graph.nodes: if each_node.ID == ID: return each_node else: return None
def get_node(self, ID): """ Returns a node given an ID or None if no such node exists. """ node = super(Graph, self).get_node(ID) if node is not None: return node for graph in self.all_graphs: for each_node in graph.nodes: if each_node.ID == ID: return each_node else: return None
[ "Returns", "a", "node", "given", "an", "ID", "or", "None", "if", "no", "such", "node", "exists", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L941-L953
[ "def", "get_node", "(", "self", ",", "ID", ")", ":", "node", "=", "super", "(", "Graph", ",", "self", ")", ".", "get_node", "(", "ID", ")", "if", "node", "is", "not", "None", ":", "return", "node", "for", "graph", "in", "self", ".", "all_graphs", ":", "for", "each_node", "in", "graph", ".", "nodes", ":", "if", "each_node", ".", "ID", "==", "ID", ":", "return", "each_node", "else", ":", "return", "None" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Graph._maxiter_default
Trait initialiser.
godot/graph.py
def _maxiter_default(self): """ Trait initialiser. """ mode = self.mode if mode == "KK": return 100 * len(self.nodes) elif mode == "major": return 200 else: return 600
def _maxiter_default(self): """ Trait initialiser. """ mode = self.mode if mode == "KK": return 100 * len(self.nodes) elif mode == "major": return 200 else: return 600
[ "Trait", "initialiser", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L1012-L1021
[ "def", "_maxiter_default", "(", "self", ")", ":", "mode", "=", "self", ".", "mode", "if", "mode", "==", "\"KK\"", ":", "return", "100", "*", "len", "(", "self", ".", "nodes", ")", "elif", "mode", "==", "\"major\"", ":", "return", "200", "else", ":", "return", "600" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Graph._get_all_graphs
Property getter.
godot/graph.py
def _get_all_graphs(self): """ Property getter. """ top_graph = self def get_subgraphs(graph): assert isinstance(graph, BaseGraph) subgraphs = graph.subgraphs[:] for subgraph in graph.subgraphs: subsubgraphs = get_subgraphs(subgraph) subgraphs.extend(subsubgraphs) return subgraphs subgraphs = get_subgraphs(top_graph) return [top_graph] + subgraphs
def _get_all_graphs(self): """ Property getter. """ top_graph = self def get_subgraphs(graph): assert isinstance(graph, BaseGraph) subgraphs = graph.subgraphs[:] for subgraph in graph.subgraphs: subsubgraphs = get_subgraphs(subgraph) subgraphs.extend(subsubgraphs) return subgraphs subgraphs = get_subgraphs(top_graph) return [top_graph] + subgraphs
[ "Property", "getter", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L1027-L1041
[ "def", "_get_all_graphs", "(", "self", ")", ":", "top_graph", "=", "self", "def", "get_subgraphs", "(", "graph", ")", ":", "assert", "isinstance", "(", "graph", ",", "BaseGraph", ")", "subgraphs", "=", "graph", ".", "subgraphs", "[", ":", "]", "for", "subgraph", "in", "graph", ".", "subgraphs", ":", "subsubgraphs", "=", "get_subgraphs", "(", "subgraph", ")", "subgraphs", ".", "extend", "(", "subsubgraphs", ")", "return", "subgraphs", "subgraphs", "=", "get_subgraphs", "(", "top_graph", ")", "return", "[", "top_graph", "]", "+", "subgraphs" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Graph._directed_changed
Sets the connection string for all edges.
godot/graph.py
def _directed_changed(self, new): """ Sets the connection string for all edges. """ if new: conn = "->" else: conn = "--" for edge in [e for g in self.all_graphs for e in g.edges]: edge.conn = conn
def _directed_changed(self, new): """ Sets the connection string for all edges. """ if new: conn = "->" else: conn = "--" for edge in [e for g in self.all_graphs for e in g.edges]: edge.conn = conn
[ "Sets", "the", "connection", "string", "for", "all", "edges", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L1047-L1056
[ "def", "_directed_changed", "(", "self", ",", "new", ")", ":", "if", "new", ":", "conn", "=", "\"->\"", "else", ":", "conn", "=", "\"--\"", "for", "edge", "in", "[", "e", "for", "g", "in", "self", ".", "all_graphs", "for", "e", "in", "g", ".", "edges", "]", ":", "edge", ".", "conn", "=", "conn" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Graph._on_nodes
Maintains each branch's list of available nodes in order that they may move themselves (InstanceEditor values).
godot/graph.py
def _on_nodes(self): """ Maintains each branch's list of available nodes in order that they may move themselves (InstanceEditor values). """ all_graphs = self.all_graphs all_nodes = [n for g in all_graphs for n in g.nodes] for graph in all_graphs: for edge in graph.edges: edge._nodes = all_nodes
def _on_nodes(self): """ Maintains each branch's list of available nodes in order that they may move themselves (InstanceEditor values). """ all_graphs = self.all_graphs all_nodes = [n for g in all_graphs for n in g.nodes] for graph in all_graphs: for edge in graph.edges: edge._nodes = all_nodes
[ "Maintains", "each", "branch", "s", "list", "of", "available", "nodes", "in", "order", "that", "they", "may", "move", "themselves", "(", "InstanceEditor", "values", ")", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L1059-L1068
[ "def", "_on_nodes", "(", "self", ")", ":", "all_graphs", "=", "self", ".", "all_graphs", "all_nodes", "=", "[", "n", "for", "g", "in", "all_graphs", "for", "n", "in", "g", ".", "nodes", "]", "for", "graph", "in", "all_graphs", ":", "for", "edge", "in", "graph", ".", "edges", ":", "edge", ".", "_nodes", "=", "all_nodes" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Graph._on_edges
Handles the list of edges for any graph changing.
godot/graph.py
def _on_edges(self, object, name, old, new): """ Handles the list of edges for any graph changing. """ if name == "edges_items": edges = new.added elif name == "edges": edges = new else: edges = [] all_nodes = [n for g in self.all_graphs for n in g.nodes] for each_edge in edges: # Ensure the edge's nodes exist in the graph. if each_edge.tail_node not in all_nodes: object.nodes.append( each_edge.tail_node ) if each_edge.head_node not in all_nodes: object.nodes.append( each_edge.head_node ) # Initialise the edge's list of available nodes. each_edge._nodes = all_nodes
def _on_edges(self, object, name, old, new): """ Handles the list of edges for any graph changing. """ if name == "edges_items": edges = new.added elif name == "edges": edges = new else: edges = [] all_nodes = [n for g in self.all_graphs for n in g.nodes] for each_edge in edges: # Ensure the edge's nodes exist in the graph. if each_edge.tail_node not in all_nodes: object.nodes.append( each_edge.tail_node ) if each_edge.head_node not in all_nodes: object.nodes.append( each_edge.head_node ) # Initialise the edge's list of available nodes. each_edge._nodes = all_nodes
[ "Handles", "the", "list", "of", "edges", "for", "any", "graph", "changing", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/graph.py#L1071-L1092
[ "def", "_on_edges", "(", "self", ",", "object", ",", "name", ",", "old", ",", "new", ")", ":", "if", "name", "==", "\"edges_items\"", ":", "edges", "=", "new", ".", "added", "elif", "name", "==", "\"edges\"", ":", "edges", "=", "new", "else", ":", "edges", "=", "[", "]", "all_nodes", "=", "[", "n", "for", "g", "in", "self", ".", "all_graphs", "for", "n", "in", "g", ".", "nodes", "]", "for", "each_edge", "in", "edges", ":", "# Ensure the edge's nodes exist in the graph.", "if", "each_edge", ".", "tail_node", "not", "in", "all_nodes", ":", "object", ".", "nodes", ".", "append", "(", "each_edge", ".", "tail_node", ")", "if", "each_edge", ".", "head_node", "not", "in", "all_nodes", ":", "object", ".", "nodes", ".", "append", "(", "each_edge", ".", "head_node", ")", "# Initialise the edge's list of available nodes.", "each_edge", ".", "_nodes", "=", "all_nodes" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
MarkdownExtension._support
Helper callback.
combine/jinja_extensions/markdown.py
def _support(self, caller): """Helper callback.""" markdown_content = caller() html_content = markdown.markdown( markdown_content, extensions=[ "markdown.extensions.fenced_code", CodeHiliteExtension(css_class="highlight"), "markdown.extensions.tables", ], ) return html_content
def _support(self, caller): """Helper callback.""" markdown_content = caller() html_content = markdown.markdown( markdown_content, extensions=[ "markdown.extensions.fenced_code", CodeHiliteExtension(css_class="highlight"), "markdown.extensions.tables", ], ) return html_content
[ "Helper", "callback", "." ]
dropseed/combine
python
https://github.com/dropseed/combine/blob/b0d622d09fcb121bc12e65f6044cb3a940b6b052/combine/jinja_extensions/markdown.py#L21-L32
[ "def", "_support", "(", "self", ",", "caller", ")", ":", "markdown_content", "=", "caller", "(", ")", "html_content", "=", "markdown", ".", "markdown", "(", "markdown_content", ",", "extensions", "=", "[", "\"markdown.extensions.fenced_code\"", ",", "CodeHiliteExtension", "(", "css_class", "=", "\"highlight\"", ")", ",", "\"markdown.extensions.tables\"", ",", "]", ",", ")", "return", "html_content" ]
b0d622d09fcb121bc12e65f6044cb3a940b6b052
test
ComponentViewer._viewport_default
Trait initialiser
godot/component/component_viewer.py
def _viewport_default(self): """ Trait initialiser """ viewport = Viewport(component=self.canvas, enable_zoom=True) viewport.tools.append(ViewportPanTool(viewport)) return viewport
def _viewport_default(self): """ Trait initialiser """ viewport = Viewport(component=self.canvas, enable_zoom=True) viewport.tools.append(ViewportPanTool(viewport)) return viewport
[ "Trait", "initialiser" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/component_viewer.py#L67-L72
[ "def", "_viewport_default", "(", "self", ")", ":", "viewport", "=", "Viewport", "(", "component", "=", "self", ".", "canvas", ",", "enable_zoom", "=", "True", ")", "viewport", ".", "tools", ".", "append", "(", "ViewportPanTool", "(", "viewport", ")", ")", "return", "viewport" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
ComponentViewer._component_changed
Handles the component being changed.
godot/component/component_viewer.py
def _component_changed(self, old, new): """ Handles the component being changed. """ canvas = self.canvas if old is not None: canvas.remove(old) if new is not None: canvas.add(new)
def _component_changed(self, old, new): """ Handles the component being changed. """ canvas = self.canvas if old is not None: canvas.remove(old) if new is not None: canvas.add(new)
[ "Handles", "the", "component", "being", "changed", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/component_viewer.py#L74-L81
[ "def", "_component_changed", "(", "self", ",", "old", ",", "new", ")", ":", "canvas", "=", "self", ".", "canvas", "if", "old", "is", "not", "None", ":", "canvas", ".", "remove", "(", "old", ")", "if", "new", "is", "not", "None", ":", "canvas", ".", "add", "(", "new", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
CodeHighlightExtension._code_support
Helper callback.
combine/jinja_extensions/code.py
def _code_support(self, language, caller): """Helper callback.""" code = caller() # remove the leading whitespace so the whole block can be indented more easily with flow of page lines = code.splitlines() first_nonempty_line_index = 0 while not lines[first_nonempty_line_index]: first_nonempty_line_index += 1 len_to_trim = len(lines[first_nonempty_line_index]) - len( lines[first_nonempty_line_index].lstrip() ) lines = [x[len_to_trim:] for x in lines] code = "\n".join(lines) if language: lexer = get_lexer_by_name(language, stripall=True) else: lexer = guess_lexer(code) highlighted = highlight(code, lexer, HtmlFormatter()) return highlighted
def _code_support(self, language, caller): """Helper callback.""" code = caller() # remove the leading whitespace so the whole block can be indented more easily with flow of page lines = code.splitlines() first_nonempty_line_index = 0 while not lines[first_nonempty_line_index]: first_nonempty_line_index += 1 len_to_trim = len(lines[first_nonempty_line_index]) - len( lines[first_nonempty_line_index].lstrip() ) lines = [x[len_to_trim:] for x in lines] code = "\n".join(lines) if language: lexer = get_lexer_by_name(language, stripall=True) else: lexer = guess_lexer(code) highlighted = highlight(code, lexer, HtmlFormatter()) return highlighted
[ "Helper", "callback", "." ]
dropseed/combine
python
https://github.com/dropseed/combine/blob/b0d622d09fcb121bc12e65f6044cb3a940b6b052/combine/jinja_extensions/code.py#L23-L47
[ "def", "_code_support", "(", "self", ",", "language", ",", "caller", ")", ":", "code", "=", "caller", "(", ")", "# remove the leading whitespace so the whole block can be indented more easily with flow of page", "lines", "=", "code", ".", "splitlines", "(", ")", "first_nonempty_line_index", "=", "0", "while", "not", "lines", "[", "first_nonempty_line_index", "]", ":", "first_nonempty_line_index", "+=", "1", "len_to_trim", "=", "len", "(", "lines", "[", "first_nonempty_line_index", "]", ")", "-", "len", "(", "lines", "[", "first_nonempty_line_index", "]", ".", "lstrip", "(", ")", ")", "lines", "=", "[", "x", "[", "len_to_trim", ":", "]", "for", "x", "in", "lines", "]", "code", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "if", "language", ":", "lexer", "=", "get_lexer_by_name", "(", "language", ",", "stripall", "=", "True", ")", "else", ":", "lexer", "=", "guess_lexer", "(", "code", ")", "highlighted", "=", "highlight", "(", "code", ",", "lexer", ",", "HtmlFormatter", "(", ")", ")", "return", "highlighted" ]
b0d622d09fcb121bc12e65f6044cb3a940b6b052
test
ElementTool.normal_left_dclick
Handles the left mouse button being double-clicked when the tool is in the 'normal' state. If the event occurred on this tool's component (or any contained component of that component), the method opens a Traits UI view on the object referenced by the 'element' trait of the component that was double-clicked, setting the tool as the active tool for the duration of the view.
godot/tool/element_tool.py
def normal_left_dclick(self, event): """ Handles the left mouse button being double-clicked when the tool is in the 'normal' state. If the event occurred on this tool's component (or any contained component of that component), the method opens a Traits UI view on the object referenced by the 'element' trait of the component that was double-clicked, setting the tool as the active tool for the duration of the view. """ x = event.x y = event.y # First determine what component or components we are going to hittest # on. If our component is a container, then we add its non-container # components to the list of candidates. # candidates = [] component = self.component # if isinstance(component, Container): # candidates = get_nested_components(self.component) # else: # # We don't support clicking on unrecognized components # return # # # Hittest against all the candidate and take the first one # item = None # for candidate, offset in candidates: # if candidate.is_in(x-offset[0], y-offset[1]): # item = candidate # break if hasattr(component, "element"): if component.element is not None: component.active_tool = self component.element.edit_traits(kind="livemodal") event.handled = True component.active_tool = None component.request_redraw() return
def normal_left_dclick(self, event): """ Handles the left mouse button being double-clicked when the tool is in the 'normal' state. If the event occurred on this tool's component (or any contained component of that component), the method opens a Traits UI view on the object referenced by the 'element' trait of the component that was double-clicked, setting the tool as the active tool for the duration of the view. """ x = event.x y = event.y # First determine what component or components we are going to hittest # on. If our component is a container, then we add its non-container # components to the list of candidates. # candidates = [] component = self.component # if isinstance(component, Container): # candidates = get_nested_components(self.component) # else: # # We don't support clicking on unrecognized components # return # # # Hittest against all the candidate and take the first one # item = None # for candidate, offset in candidates: # if candidate.is_in(x-offset[0], y-offset[1]): # item = candidate # break if hasattr(component, "element"): if component.element is not None: component.active_tool = self component.element.edit_traits(kind="livemodal") event.handled = True component.active_tool = None component.request_redraw() return
[ "Handles", "the", "left", "mouse", "button", "being", "double", "-", "clicked", "when", "the", "tool", "is", "in", "the", "normal", "state", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/tool/element_tool.py#L17-L56
[ "def", "normal_left_dclick", "(", "self", ",", "event", ")", ":", "x", "=", "event", ".", "x", "y", "=", "event", ".", "y", "# First determine what component or components we are going to hittest", "# on. If our component is a container, then we add its non-container", "# components to the list of candidates.", "# candidates = []", "component", "=", "self", ".", "component", "# if isinstance(component, Container):", "# candidates = get_nested_components(self.component)", "# else:", "# # We don't support clicking on unrecognized components", "# return", "#", "# # Hittest against all the candidate and take the first one", "# item = None", "# for candidate, offset in candidates:", "# if candidate.is_in(x-offset[0], y-offset[1]):", "# item = candidate", "# break", "if", "hasattr", "(", "component", ",", "\"element\"", ")", ":", "if", "component", ".", "element", "is", "not", "None", ":", "component", ".", "active_tool", "=", "self", "component", ".", "element", ".", "edit_traits", "(", "kind", "=", "\"livemodal\"", ")", "event", ".", "handled", "=", "True", "component", ".", "active_tool", "=", "None", "component", ".", "request_redraw", "(", ")", "return" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
CanvasMapping._diagram_canvas_default
Trait initialiser
godot/mapping.py
def _diagram_canvas_default(self): """ Trait initialiser """ canvas = Canvas() for tool in self.tools: canvas.tools.append(tool(canvas)) return canvas
def _diagram_canvas_default(self): """ Trait initialiser """ canvas = Canvas() for tool in self.tools: canvas.tools.append(tool(canvas)) return canvas
[ "Trait", "initialiser" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L74-L82
[ "def", "_diagram_canvas_default", "(", "self", ")", ":", "canvas", "=", "Canvas", "(", ")", "for", "tool", "in", "self", ".", "tools", ":", "canvas", ".", "tools", ".", "append", "(", "tool", "(", "canvas", ")", ")", "return", "canvas" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
CanvasMapping._viewport_default
Trait initialiser
godot/mapping.py
def _viewport_default(self): """ Trait initialiser """ vp = Viewport(component=self.diagram_canvas, enable_zoom=True) vp.view_position = [0,0] vp.tools.append(ViewportPanTool(vp)) return vp
def _viewport_default(self): """ Trait initialiser """ vp = Viewport(component=self.diagram_canvas, enable_zoom=True) vp.view_position = [0,0] vp.tools.append(ViewportPanTool(vp)) return vp
[ "Trait", "initialiser" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L85-L91
[ "def", "_viewport_default", "(", "self", ")", ":", "vp", "=", "Viewport", "(", "component", "=", "self", ".", "diagram_canvas", ",", "enable_zoom", "=", "True", ")", "vp", ".", "view_position", "=", "[", "0", ",", "0", "]", "vp", ".", "tools", ".", "append", "(", "ViewportPanTool", "(", "vp", ")", ")", "return", "vp" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
CanvasMapping._diagram_canvas_changed
Handles the diagram canvas being set
godot/mapping.py
def _diagram_canvas_changed(self, new): """ Handles the diagram canvas being set """ logger.debug("Diagram canvas changed!") canvas = self.diagram_canvas for tool in self.tools: if canvas is not None: print "Adding tool: %s" % tool canvas.tools.append(tool(canvas))
def _diagram_canvas_changed(self, new): """ Handles the diagram canvas being set """ logger.debug("Diagram canvas changed!") canvas = self.diagram_canvas for tool in self.tools: if canvas is not None: print "Adding tool: %s" % tool canvas.tools.append(tool(canvas))
[ "Handles", "the", "diagram", "canvas", "being", "set" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L95-L104
[ "def", "_diagram_canvas_changed", "(", "self", ",", "new", ")", ":", "logger", ".", "debug", "(", "\"Diagram canvas changed!\"", ")", "canvas", "=", "self", ".", "diagram_canvas", "for", "tool", "in", "self", ".", "tools", ":", "if", "canvas", "is", "not", "None", ":", "print", "\"Adding tool: %s\"", "%", "tool", "canvas", ".", "tools", ".", "append", "(", "tool", "(", "canvas", ")", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
CanvasMapping.clear_canvas
Removes all components from the canvas
godot/mapping.py
def clear_canvas(self): """ Removes all components from the canvas """ logger.debug("Clearing the diagram canvas!") old_canvas = self.diagram_canvas # logger.debug("Canvas components: %s" % canvas.components) # for component in canvas.components: # canvas.remove(component) # logger.debug("Canvas components: %s" % canvas.components) # for component in canvas.components: # canvas.remove(component) # logger.debug("Canvas components: %s" % canvas.components) # canvas.request_redraw() new_canvas = Canvas() new_canvas.copy_traits(old_canvas, ["bgcolor", "draw_axes"]) self.diagram_canvas = new_canvas self.viewport.component=new_canvas self.viewport.request_redraw() return
def clear_canvas(self): """ Removes all components from the canvas """ logger.debug("Clearing the diagram canvas!") old_canvas = self.diagram_canvas # logger.debug("Canvas components: %s" % canvas.components) # for component in canvas.components: # canvas.remove(component) # logger.debug("Canvas components: %s" % canvas.components) # for component in canvas.components: # canvas.remove(component) # logger.debug("Canvas components: %s" % canvas.components) # canvas.request_redraw() new_canvas = Canvas() new_canvas.copy_traits(old_canvas, ["bgcolor", "draw_axes"]) self.diagram_canvas = new_canvas self.viewport.component=new_canvas self.viewport.request_redraw() return
[ "Removes", "all", "components", "from", "the", "canvas" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L113-L135
[ "def", "clear_canvas", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Clearing the diagram canvas!\"", ")", "old_canvas", "=", "self", ".", "diagram_canvas", "# logger.debug(\"Canvas components: %s\" % canvas.components)", "# for component in canvas.components:", "# canvas.remove(component)", "# logger.debug(\"Canvas components: %s\" % canvas.components)", "# for component in canvas.components:", "# canvas.remove(component)", "# logger.debug(\"Canvas components: %s\" % canvas.components)", "# canvas.request_redraw()", "new_canvas", "=", "Canvas", "(", ")", "new_canvas", ".", "copy_traits", "(", "old_canvas", ",", "[", "\"bgcolor\"", ",", "\"draw_axes\"", "]", ")", "self", ".", "diagram_canvas", "=", "new_canvas", "self", ".", "viewport", ".", "component", "=", "new_canvas", "self", ".", "viewport", ".", "request_redraw", "(", ")", "return" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Mapping._domain_model_changed_for_diagram
Handles the domain model changing
godot/mapping.py
def _domain_model_changed_for_diagram(self, obj, name, old, new): """ Handles the domain model changing """ if old is not None: self.unmap_model(old) if new is not None: self.map_model(new)
def _domain_model_changed_for_diagram(self, obj, name, old, new): """ Handles the domain model changing """ if old is not None: self.unmap_model(old) if new is not None: self.map_model(new)
[ "Handles", "the", "domain", "model", "changing" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L210-L216
[ "def", "_domain_model_changed_for_diagram", "(", "self", ",", "obj", ",", "name", ",", "old", ",", "new", ")", ":", "if", "old", "is", "not", "None", ":", "self", ".", "unmap_model", "(", "old", ")", "if", "new", "is", "not", "None", ":", "self", ".", "map_model", "(", "new", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Mapping.map_model
Maps a domain model to the diagram
godot/mapping.py
def map_model(self, new): """ Maps a domain model to the diagram """ logger.debug("Mapping the domain model!") dot = Dot() self.diagram.clear_canvas() for node_mapping in self.nodes: ct = node_mapping.containment_trait logger.debug("Mapping elements contained by the '%s' trait" % ct) if hasattr(new, ct): elements = getattr(new, ct) logger.debug("%d element(s) found" % len(elements)) for element in elements: pydot_node = Node(str(id(element))) dot_attrs = node_mapping.dot_node if dot_attrs is not None: self._style_node(pydot_node, dot_attrs) dot.add_node(pydot_node) new.on_trait_change(self.map_element, ct+"_items") logger.debug("Retrieving xdot data and forming pydot graph!") xdot = graph_from_dot_data(dot.create(self.program, "xdot")) parser = XDotParser() for node in xdot.get_node_list(): diagram_node = parser.parse_node(node) logger.debug( "Parsed node [%s] and received diagram node [%s]" % (node, diagram_node) ) if diagram_node is not None: for node_mapping in self.nodes: # FIXME: slow ct = node_mapping.containment_trait for element in getattr(new, ct): if str(id(element)) == diagram_node.dot_node.get_name(): logger.debug( "Referencing element [%s] from diagram node [%s]" % (element, diagram_node) ) diagram_node.element = element break # Tools if isinstance(diagram_node.element, node_mapping.element): for tool in node_mapping.tools: logger.debug( "Adding tool [%s] to diagram node [%s]" % (tool, diagram_node) ) diagram_node.tools.append(tool(diagram_node)) else: if diagram_node.element is None: logger.warning("Diagram node not referenced to element") self.diagram.diagram_canvas.add(diagram_node) del parser
def map_model(self, new): """ Maps a domain model to the diagram """ logger.debug("Mapping the domain model!") dot = Dot() self.diagram.clear_canvas() for node_mapping in self.nodes: ct = node_mapping.containment_trait logger.debug("Mapping elements contained by the '%s' trait" % ct) if hasattr(new, ct): elements = getattr(new, ct) logger.debug("%d element(s) found" % len(elements)) for element in elements: pydot_node = Node(str(id(element))) dot_attrs = node_mapping.dot_node if dot_attrs is not None: self._style_node(pydot_node, dot_attrs) dot.add_node(pydot_node) new.on_trait_change(self.map_element, ct+"_items") logger.debug("Retrieving xdot data and forming pydot graph!") xdot = graph_from_dot_data(dot.create(self.program, "xdot")) parser = XDotParser() for node in xdot.get_node_list(): diagram_node = parser.parse_node(node) logger.debug( "Parsed node [%s] and received diagram node [%s]" % (node, diagram_node) ) if diagram_node is not None: for node_mapping in self.nodes: # FIXME: slow ct = node_mapping.containment_trait for element in getattr(new, ct): if str(id(element)) == diagram_node.dot_node.get_name(): logger.debug( "Referencing element [%s] from diagram node [%s]" % (element, diagram_node) ) diagram_node.element = element break # Tools if isinstance(diagram_node.element, node_mapping.element): for tool in node_mapping.tools: logger.debug( "Adding tool [%s] to diagram node [%s]" % (tool, diagram_node) ) diagram_node.tools.append(tool(diagram_node)) else: if diagram_node.element is None: logger.warning("Diagram node not referenced to element") self.diagram.diagram_canvas.add(diagram_node) del parser
[ "Maps", "a", "domain", "model", "to", "the", "diagram" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L219-L279
[ "def", "map_model", "(", "self", ",", "new", ")", ":", "logger", ".", "debug", "(", "\"Mapping the domain model!\"", ")", "dot", "=", "Dot", "(", ")", "self", ".", "diagram", ".", "clear_canvas", "(", ")", "for", "node_mapping", "in", "self", ".", "nodes", ":", "ct", "=", "node_mapping", ".", "containment_trait", "logger", ".", "debug", "(", "\"Mapping elements contained by the '%s' trait\"", "%", "ct", ")", "if", "hasattr", "(", "new", ",", "ct", ")", ":", "elements", "=", "getattr", "(", "new", ",", "ct", ")", "logger", ".", "debug", "(", "\"%d element(s) found\"", "%", "len", "(", "elements", ")", ")", "for", "element", "in", "elements", ":", "pydot_node", "=", "Node", "(", "str", "(", "id", "(", "element", ")", ")", ")", "dot_attrs", "=", "node_mapping", ".", "dot_node", "if", "dot_attrs", "is", "not", "None", ":", "self", ".", "_style_node", "(", "pydot_node", ",", "dot_attrs", ")", "dot", ".", "add_node", "(", "pydot_node", ")", "new", ".", "on_trait_change", "(", "self", ".", "map_element", ",", "ct", "+", "\"_items\"", ")", "logger", ".", "debug", "(", "\"Retrieving xdot data and forming pydot graph!\"", ")", "xdot", "=", "graph_from_dot_data", "(", "dot", ".", "create", "(", "self", ".", "program", ",", "\"xdot\"", ")", ")", "parser", "=", "XDotParser", "(", ")", "for", "node", "in", "xdot", ".", "get_node_list", "(", ")", ":", "diagram_node", "=", "parser", ".", "parse_node", "(", "node", ")", "logger", ".", "debug", "(", "\"Parsed node [%s] and received diagram node [%s]\"", "%", "(", "node", ",", "diagram_node", ")", ")", "if", "diagram_node", "is", "not", "None", ":", "for", "node_mapping", "in", "self", ".", "nodes", ":", "# FIXME: slow", "ct", "=", "node_mapping", ".", "containment_trait", "for", "element", "in", "getattr", "(", "new", ",", "ct", ")", ":", "if", "str", "(", "id", "(", "element", ")", ")", "==", "diagram_node", ".", "dot_node", ".", "get_name", "(", ")", ":", "logger", ".", "debug", "(", "\"Referencing element [%s] from diagram node [%s]\"", "%", "(", "element", ",", "diagram_node", ")", ")", "diagram_node", ".", "element", "=", "element", "break", "# Tools", "if", "isinstance", "(", "diagram_node", ".", "element", ",", "node_mapping", ".", "element", ")", ":", "for", "tool", "in", "node_mapping", ".", "tools", ":", "logger", ".", "debug", "(", "\"Adding tool [%s] to diagram node [%s]\"", "%", "(", "tool", ",", "diagram_node", ")", ")", "diagram_node", ".", "tools", ".", "append", "(", "tool", "(", "diagram_node", ")", ")", "else", ":", "if", "diagram_node", ".", "element", "is", "None", ":", "logger", ".", "warning", "(", "\"Diagram node not referenced to element\"", ")", "self", ".", "diagram", ".", "diagram_canvas", ".", "add", "(", "diagram_node", ")", "del", "parser" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Mapping.unmap_model
Removes listeners from a domain model
godot/mapping.py
def unmap_model(self, old): """ Removes listeners from a domain model """ for node_mapping in self.nodes: ct = node_mapping.containment_trait if hasattr(old, ct): old_elements = getattr(old, ct) for old_element in old_elements: old.on_trait_change( self.map_element, ct+"_items", remove=True )
def unmap_model(self, old): """ Removes listeners from a domain model """ for node_mapping in self.nodes: ct = node_mapping.containment_trait if hasattr(old, ct): old_elements = getattr(old, ct) for old_element in old_elements: old.on_trait_change( self.map_element, ct+"_items", remove=True )
[ "Removes", "listeners", "from", "a", "domain", "model" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L282-L292
[ "def", "unmap_model", "(", "self", ",", "old", ")", ":", "for", "node_mapping", "in", "self", ".", "nodes", ":", "ct", "=", "node_mapping", ".", "containment_trait", "if", "hasattr", "(", "old", ",", "ct", ")", ":", "old_elements", "=", "getattr", "(", "old", ",", "ct", ")", "for", "old_element", "in", "old_elements", ":", "old", ".", "on_trait_change", "(", "self", ".", "map_element", ",", "ct", "+", "\"_items\"", ",", "remove", "=", "True", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Mapping.map_element
Handles mapping elements to diagram components
godot/mapping.py
def map_element(self, obj, name, event): """ Handles mapping elements to diagram components """ canvas = self.diagram.diagram_canvas parser = XDotParser() for element in event.added: logger.debug("Mapping new element [%s] to diagram node" % element) for node_mapping in self.nodes: ct = name[:-6] #strip '_items' if node_mapping.containment_trait == ct: dot_attrs = node_mapping.dot_node dot = Dot() graph_node = Node(str(id(element))) self._style_node(graph_node, dot_attrs) dot.add_node(graph_node) xdot = graph_from_dot_data(dot.create(self.program,"xdot")) diagram_nodes = parser.parse_nodes(xdot)#.get_node_list()) for dn in diagram_nodes: if dn is not None: dn.element = element # Tools for tool in node_mapping.tools: dn.tools.append(tool(dn)) canvas.add(dn) canvas.request_redraw() for element in event.removed: logger.debug("Unmapping element [%s] from diagram" % element) for component in canvas.components: if element == component.element: canvas.remove(component) canvas.request_redraw() break
def map_element(self, obj, name, event): """ Handles mapping elements to diagram components """ canvas = self.diagram.diagram_canvas parser = XDotParser() for element in event.added: logger.debug("Mapping new element [%s] to diagram node" % element) for node_mapping in self.nodes: ct = name[:-6] #strip '_items' if node_mapping.containment_trait == ct: dot_attrs = node_mapping.dot_node dot = Dot() graph_node = Node(str(id(element))) self._style_node(graph_node, dot_attrs) dot.add_node(graph_node) xdot = graph_from_dot_data(dot.create(self.program,"xdot")) diagram_nodes = parser.parse_nodes(xdot)#.get_node_list()) for dn in diagram_nodes: if dn is not None: dn.element = element # Tools for tool in node_mapping.tools: dn.tools.append(tool(dn)) canvas.add(dn) canvas.request_redraw() for element in event.removed: logger.debug("Unmapping element [%s] from diagram" % element) for component in canvas.components: if element == component.element: canvas.remove(component) canvas.request_redraw() break
[ "Handles", "mapping", "elements", "to", "diagram", "components" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L295-L329
[ "def", "map_element", "(", "self", ",", "obj", ",", "name", ",", "event", ")", ":", "canvas", "=", "self", ".", "diagram", ".", "diagram_canvas", "parser", "=", "XDotParser", "(", ")", "for", "element", "in", "event", ".", "added", ":", "logger", ".", "debug", "(", "\"Mapping new element [%s] to diagram node\"", "%", "element", ")", "for", "node_mapping", "in", "self", ".", "nodes", ":", "ct", "=", "name", "[", ":", "-", "6", "]", "#strip '_items'", "if", "node_mapping", ".", "containment_trait", "==", "ct", ":", "dot_attrs", "=", "node_mapping", ".", "dot_node", "dot", "=", "Dot", "(", ")", "graph_node", "=", "Node", "(", "str", "(", "id", "(", "element", ")", ")", ")", "self", ".", "_style_node", "(", "graph_node", ",", "dot_attrs", ")", "dot", ".", "add_node", "(", "graph_node", ")", "xdot", "=", "graph_from_dot_data", "(", "dot", ".", "create", "(", "self", ".", "program", ",", "\"xdot\"", ")", ")", "diagram_nodes", "=", "parser", ".", "parse_nodes", "(", "xdot", ")", "#.get_node_list())", "for", "dn", "in", "diagram_nodes", ":", "if", "dn", "is", "not", "None", ":", "dn", ".", "element", "=", "element", "# Tools", "for", "tool", "in", "node_mapping", ".", "tools", ":", "dn", ".", "tools", ".", "append", "(", "tool", "(", "dn", ")", ")", "canvas", ".", "add", "(", "dn", ")", "canvas", ".", "request_redraw", "(", ")", "for", "element", "in", "event", ".", "removed", ":", "logger", ".", "debug", "(", "\"Unmapping element [%s] from diagram\"", "%", "element", ")", "for", "component", "in", "canvas", ".", "components", ":", "if", "element", "==", "component", ".", "element", ":", "canvas", ".", "remove", "(", "component", ")", "canvas", ".", "request_redraw", "(", ")", "break" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Mapping._style_node
Styles a node
godot/mapping.py
def _style_node(self, pydot_node, dot_attrs): """ Styles a node """ pydot_node.set_shape(dot_attrs.shape) pydot_node.set_fixedsize(str(dot_attrs.fixed_size)) pydot_node.set_width(str(dot_attrs.width)) pydot_node.set_height(str(dot_attrs.height)) pydot_node.set_color(rgba2hex(dot_attrs.color_)) pydot_node.set_fillcolor( rgba2hex(dot_attrs.fill_color_) ) for sty in dot_attrs.style: logger.debug("Setting node style: %s" % sty) pydot_node.set_style(sty) return pydot_node
def _style_node(self, pydot_node, dot_attrs): """ Styles a node """ pydot_node.set_shape(dot_attrs.shape) pydot_node.set_fixedsize(str(dot_attrs.fixed_size)) pydot_node.set_width(str(dot_attrs.width)) pydot_node.set_height(str(dot_attrs.height)) pydot_node.set_color(rgba2hex(dot_attrs.color_)) pydot_node.set_fillcolor( rgba2hex(dot_attrs.fill_color_) ) for sty in dot_attrs.style: logger.debug("Setting node style: %s" % sty) pydot_node.set_style(sty) return pydot_node
[ "Styles", "a", "node" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/mapping.py#L338-L353
[ "def", "_style_node", "(", "self", ",", "pydot_node", ",", "dot_attrs", ")", ":", "pydot_node", ".", "set_shape", "(", "dot_attrs", ".", "shape", ")", "pydot_node", ".", "set_fixedsize", "(", "str", "(", "dot_attrs", ".", "fixed_size", ")", ")", "pydot_node", ".", "set_width", "(", "str", "(", "dot_attrs", ".", "width", ")", ")", "pydot_node", ".", "set_height", "(", "str", "(", "dot_attrs", ".", "height", ")", ")", "pydot_node", ".", "set_color", "(", "rgba2hex", "(", "dot_attrs", ".", "color_", ")", ")", "pydot_node", ".", "set_fillcolor", "(", "rgba2hex", "(", "dot_attrs", ".", "fill_color_", ")", ")", "for", "sty", "in", "dot_attrs", ".", "style", ":", "logger", ".", "debug", "(", "\"Setting node style: %s\"", "%", "sty", ")", "pydot_node", ".", "set_style", "(", "sty", ")", "return", "pydot_node" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser.parse_xdot_data
Parses xdot data and returns the associated components.
godot/xdot_parser.py
def parse_xdot_data(self, data): """ Parses xdot data and returns the associated components. """ parser = self.parser # if pyparsing_version >= "1.2": # parser.parseWithTabs() if data: return parser.parseString(data) else: return []
def parse_xdot_data(self, data): """ Parses xdot data and returns the associated components. """ parser = self.parser # if pyparsing_version >= "1.2": # parser.parseWithTabs() if data: return parser.parseString(data) else: return []
[ "Parses", "xdot", "data", "and", "returns", "the", "associated", "components", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L77-L86
[ "def", "parse_xdot_data", "(", "self", ",", "data", ")", ":", "parser", "=", "self", ".", "parser", "# if pyparsing_version >= \"1.2\":", "# parser.parseWithTabs()", "if", "data", ":", "return", "parser", ".", "parseString", "(", "data", ")", "else", ":", "return", "[", "]" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser.define_parser
Defines xdot grammar. @see: http://graphviz.org/doc/info/output.html#d:xdot
godot/xdot_parser.py
def define_parser(self): """ Defines xdot grammar. @see: http://graphviz.org/doc/info/output.html#d:xdot """ # Common constructs. point = Group(integer.setResultsName("x") + integer.setResultsName("y")) n_points = (integer.setResultsName("n") + OneOrMore(point).setResultsName("points")) n_bytes = Suppress(integer) + Suppress(minus) + \ Word(printables).setResultsName("b") justify = ToInteger( Literal("-1") | Literal("0") | Literal("1") ).setResultsName("j") # Attributes ---------------------------------------------------------- # Set fill color. The color value consists of the n bytes following # the '-'. fill = (Literal("C").suppress() + Suppress(integer) + Suppress(minus) + colour.setResultsName("color")).setResultsName("fill") # Set pen color. The color value consists of the n bytes following '-'. stroke = (Literal("c").suppress() + Suppress(integer) + Suppress(minus) + colour.setResultsName("color") ).setResultsName("stroke") # Set font. The font size is s points. The font name consists of the # n bytes following '-'. font = (Literal("F").suppress() + real.setResultsName("s") + n_bytes).setResultsName("font") # Set style attribute. The style value consists of the n bytes # following '-'. The syntax of the value is the same as specified for # a styleItem in style. style = (Literal("S").suppress() + n_bytes).setResultsName("style") # Shapes -------------------------------------------------------------- # Filled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1 filled_ellipse = (Literal("E").suppress() + integer.setResultsName("x0") + integer.setResultsName("y0") + integer.setResultsName("w") + integer.setResultsName("h") ).setResultsName("filled_ellipse") # Unfilled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1 ellipse = (Literal("e").suppress() + integer.setResultsName("x0") + integer.setResultsName("y0") + integer.setResultsName("w") + integer.setResultsName("h") ).setResultsName("ellipse") # Filled polygon using the given n points. filled_polygon = (Literal("P").suppress() + n_points).setResultsName("filled_polygon") # Unfilled polygon using the given n points. polygon = (Literal("p").suppress() + n_points).setResultsName("polygon") # Polyline using the given n points. polyline = (Literal("L").suppress() + n_points).setResultsName("polyline") # B-spline using the given n control points. bspline = (Literal("B").suppress() + n_points).setResultsName("bspline") # Filled B-spline using the given n control points. filled_bspline = (Literal("b").suppress() + n_points).setResultsName("filled_bspline") # Text drawn using the baseline point (x,y). The text consists of the # n bytes following '-'. The text should be left-aligned (centered, # right-aligned) on the point if j is -1 (0, 1), respectively. The # value w gives the width of the text as computed by the library. text = (Literal("T").suppress() + integer.setResultsName("x") + integer.setResultsName("y") + justify + integer.setResultsName("w") + n_bytes).setResultsName("text") # Externally-specified image drawn in the box with lower left corner # (x,y) and upper right corner (x+w,y+h). The name of the image # consists of the n bytes following '-'. This is usually a bitmap # image. Note that the image size, even when converted from pixels to # points, might be different from the required size (w,h). It is # assumed the renderer will perform the necessary scaling. image = (Literal("I").suppress() + integer.setResultsName("x") + integer.setResultsName("y") + integer.setResultsName("w") + integer.setResultsName("h") + n_bytes).setResultsName("image") # The value of the drawing attributes consists of the concatenation of # some (multi-)set of the 13 rendering or attribute operations. value = (Optional(quote).suppress() + OneOrMore(filled_ellipse | ellipse | filled_polygon | polygon | polyline | bspline | filled_bspline | text | fill | stroke | font | style | image) + Optional(quote).suppress()).setResultsName("value") # Drawing operation. # draw_ = Literal("_draw_") + Suppress(equals) + value # # Label drawing. # ldraw_ = Literal("_ldraw_") + Suppress(equals) + value # # Edge head arrowhead drawing. # hdraw_ = Literal("_hdraw_") + Suppress(equals) + value # # Edge tail arrowhead drawing. # tdraw_ = Literal("_tdraw_") + Suppress(equals) + value # # Edge head label drawing. # hldraw_ = Literal("_hldraw_") + Suppress(equals) + value # # Edge tail label drawing. # tldraw_ = Literal("_tldraw_") + Suppress(equals) + value # Parse actions. # n_points.setParseAction(self.proc_points) # Attribute parse actions. fill.setParseAction(self.proc_fill_color) stroke.setParseAction(self.proc_stroke_color) font.setParseAction(self.proc_font) style.setParseAction(self.proc_style) # Shape parse actions. filled_ellipse.setParseAction(self.proc_filled_ellipse) ellipse.setParseAction(self.proc_unfilled_ellipse) filled_polygon.setParseAction(self.proc_filled_polygon) polygon.setParseAction(self.proc_unfilled_polygon) polyline.setParseAction(self.proc_polyline) bspline.setParseAction(self.proc_unfilled_bspline) filled_bspline.setParseAction(self.proc_filled_bspline) text.setParseAction(self.proc_text) image.setParseAction(self.proc_image) return value
def define_parser(self): """ Defines xdot grammar. @see: http://graphviz.org/doc/info/output.html#d:xdot """ # Common constructs. point = Group(integer.setResultsName("x") + integer.setResultsName("y")) n_points = (integer.setResultsName("n") + OneOrMore(point).setResultsName("points")) n_bytes = Suppress(integer) + Suppress(minus) + \ Word(printables).setResultsName("b") justify = ToInteger( Literal("-1") | Literal("0") | Literal("1") ).setResultsName("j") # Attributes ---------------------------------------------------------- # Set fill color. The color value consists of the n bytes following # the '-'. fill = (Literal("C").suppress() + Suppress(integer) + Suppress(minus) + colour.setResultsName("color")).setResultsName("fill") # Set pen color. The color value consists of the n bytes following '-'. stroke = (Literal("c").suppress() + Suppress(integer) + Suppress(minus) + colour.setResultsName("color") ).setResultsName("stroke") # Set font. The font size is s points. The font name consists of the # n bytes following '-'. font = (Literal("F").suppress() + real.setResultsName("s") + n_bytes).setResultsName("font") # Set style attribute. The style value consists of the n bytes # following '-'. The syntax of the value is the same as specified for # a styleItem in style. style = (Literal("S").suppress() + n_bytes).setResultsName("style") # Shapes -------------------------------------------------------------- # Filled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1 filled_ellipse = (Literal("E").suppress() + integer.setResultsName("x0") + integer.setResultsName("y0") + integer.setResultsName("w") + integer.setResultsName("h") ).setResultsName("filled_ellipse") # Unfilled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1 ellipse = (Literal("e").suppress() + integer.setResultsName("x0") + integer.setResultsName("y0") + integer.setResultsName("w") + integer.setResultsName("h") ).setResultsName("ellipse") # Filled polygon using the given n points. filled_polygon = (Literal("P").suppress() + n_points).setResultsName("filled_polygon") # Unfilled polygon using the given n points. polygon = (Literal("p").suppress() + n_points).setResultsName("polygon") # Polyline using the given n points. polyline = (Literal("L").suppress() + n_points).setResultsName("polyline") # B-spline using the given n control points. bspline = (Literal("B").suppress() + n_points).setResultsName("bspline") # Filled B-spline using the given n control points. filled_bspline = (Literal("b").suppress() + n_points).setResultsName("filled_bspline") # Text drawn using the baseline point (x,y). The text consists of the # n bytes following '-'. The text should be left-aligned (centered, # right-aligned) on the point if j is -1 (0, 1), respectively. The # value w gives the width of the text as computed by the library. text = (Literal("T").suppress() + integer.setResultsName("x") + integer.setResultsName("y") + justify + integer.setResultsName("w") + n_bytes).setResultsName("text") # Externally-specified image drawn in the box with lower left corner # (x,y) and upper right corner (x+w,y+h). The name of the image # consists of the n bytes following '-'. This is usually a bitmap # image. Note that the image size, even when converted from pixels to # points, might be different from the required size (w,h). It is # assumed the renderer will perform the necessary scaling. image = (Literal("I").suppress() + integer.setResultsName("x") + integer.setResultsName("y") + integer.setResultsName("w") + integer.setResultsName("h") + n_bytes).setResultsName("image") # The value of the drawing attributes consists of the concatenation of # some (multi-)set of the 13 rendering or attribute operations. value = (Optional(quote).suppress() + OneOrMore(filled_ellipse | ellipse | filled_polygon | polygon | polyline | bspline | filled_bspline | text | fill | stroke | font | style | image) + Optional(quote).suppress()).setResultsName("value") # Drawing operation. # draw_ = Literal("_draw_") + Suppress(equals) + value # # Label drawing. # ldraw_ = Literal("_ldraw_") + Suppress(equals) + value # # Edge head arrowhead drawing. # hdraw_ = Literal("_hdraw_") + Suppress(equals) + value # # Edge tail arrowhead drawing. # tdraw_ = Literal("_tdraw_") + Suppress(equals) + value # # Edge head label drawing. # hldraw_ = Literal("_hldraw_") + Suppress(equals) + value # # Edge tail label drawing. # tldraw_ = Literal("_tldraw_") + Suppress(equals) + value # Parse actions. # n_points.setParseAction(self.proc_points) # Attribute parse actions. fill.setParseAction(self.proc_fill_color) stroke.setParseAction(self.proc_stroke_color) font.setParseAction(self.proc_font) style.setParseAction(self.proc_style) # Shape parse actions. filled_ellipse.setParseAction(self.proc_filled_ellipse) ellipse.setParseAction(self.proc_unfilled_ellipse) filled_polygon.setParseAction(self.proc_filled_polygon) polygon.setParseAction(self.proc_unfilled_polygon) polyline.setParseAction(self.proc_polyline) bspline.setParseAction(self.proc_unfilled_bspline) filled_bspline.setParseAction(self.proc_filled_bspline) text.setParseAction(self.proc_text) image.setParseAction(self.proc_image) return value
[ "Defines", "xdot", "grammar", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L92-L223
[ "def", "define_parser", "(", "self", ")", ":", "# Common constructs.", "point", "=", "Group", "(", "integer", ".", "setResultsName", "(", "\"x\"", ")", "+", "integer", ".", "setResultsName", "(", "\"y\"", ")", ")", "n_points", "=", "(", "integer", ".", "setResultsName", "(", "\"n\"", ")", "+", "OneOrMore", "(", "point", ")", ".", "setResultsName", "(", "\"points\"", ")", ")", "n_bytes", "=", "Suppress", "(", "integer", ")", "+", "Suppress", "(", "minus", ")", "+", "Word", "(", "printables", ")", ".", "setResultsName", "(", "\"b\"", ")", "justify", "=", "ToInteger", "(", "Literal", "(", "\"-1\"", ")", "|", "Literal", "(", "\"0\"", ")", "|", "Literal", "(", "\"1\"", ")", ")", ".", "setResultsName", "(", "\"j\"", ")", "# Attributes ----------------------------------------------------------", "# Set fill color. The color value consists of the n bytes following", "# the '-'.", "fill", "=", "(", "Literal", "(", "\"C\"", ")", ".", "suppress", "(", ")", "+", "Suppress", "(", "integer", ")", "+", "Suppress", "(", "minus", ")", "+", "colour", ".", "setResultsName", "(", "\"color\"", ")", ")", ".", "setResultsName", "(", "\"fill\"", ")", "# Set pen color. The color value consists of the n bytes following '-'.", "stroke", "=", "(", "Literal", "(", "\"c\"", ")", ".", "suppress", "(", ")", "+", "Suppress", "(", "integer", ")", "+", "Suppress", "(", "minus", ")", "+", "colour", ".", "setResultsName", "(", "\"color\"", ")", ")", ".", "setResultsName", "(", "\"stroke\"", ")", "# Set font. The font size is s points. The font name consists of the", "# n bytes following '-'.", "font", "=", "(", "Literal", "(", "\"F\"", ")", ".", "suppress", "(", ")", "+", "real", ".", "setResultsName", "(", "\"s\"", ")", "+", "n_bytes", ")", ".", "setResultsName", "(", "\"font\"", ")", "# Set style attribute. The style value consists of the n bytes", "# following '-'. The syntax of the value is the same as specified for", "# a styleItem in style.", "style", "=", "(", "Literal", "(", "\"S\"", ")", ".", "suppress", "(", ")", "+", "n_bytes", ")", ".", "setResultsName", "(", "\"style\"", ")", "# Shapes --------------------------------------------------------------", "# Filled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1", "filled_ellipse", "=", "(", "Literal", "(", "\"E\"", ")", ".", "suppress", "(", ")", "+", "integer", ".", "setResultsName", "(", "\"x0\"", ")", "+", "integer", ".", "setResultsName", "(", "\"y0\"", ")", "+", "integer", ".", "setResultsName", "(", "\"w\"", ")", "+", "integer", ".", "setResultsName", "(", "\"h\"", ")", ")", ".", "setResultsName", "(", "\"filled_ellipse\"", ")", "# Unfilled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1", "ellipse", "=", "(", "Literal", "(", "\"e\"", ")", ".", "suppress", "(", ")", "+", "integer", ".", "setResultsName", "(", "\"x0\"", ")", "+", "integer", ".", "setResultsName", "(", "\"y0\"", ")", "+", "integer", ".", "setResultsName", "(", "\"w\"", ")", "+", "integer", ".", "setResultsName", "(", "\"h\"", ")", ")", ".", "setResultsName", "(", "\"ellipse\"", ")", "# Filled polygon using the given n points.", "filled_polygon", "=", "(", "Literal", "(", "\"P\"", ")", ".", "suppress", "(", ")", "+", "n_points", ")", ".", "setResultsName", "(", "\"filled_polygon\"", ")", "# Unfilled polygon using the given n points.", "polygon", "=", "(", "Literal", "(", "\"p\"", ")", ".", "suppress", "(", ")", "+", "n_points", ")", ".", "setResultsName", "(", "\"polygon\"", ")", "# Polyline using the given n points.", "polyline", "=", "(", "Literal", "(", "\"L\"", ")", ".", "suppress", "(", ")", "+", "n_points", ")", ".", "setResultsName", "(", "\"polyline\"", ")", "# B-spline using the given n control points.", "bspline", "=", "(", "Literal", "(", "\"B\"", ")", ".", "suppress", "(", ")", "+", "n_points", ")", ".", "setResultsName", "(", "\"bspline\"", ")", "# Filled B-spline using the given n control points.", "filled_bspline", "=", "(", "Literal", "(", "\"b\"", ")", ".", "suppress", "(", ")", "+", "n_points", ")", ".", "setResultsName", "(", "\"filled_bspline\"", ")", "# Text drawn using the baseline point (x,y). The text consists of the", "# n bytes following '-'. The text should be left-aligned (centered,", "# right-aligned) on the point if j is -1 (0, 1), respectively. The", "# value w gives the width of the text as computed by the library.", "text", "=", "(", "Literal", "(", "\"T\"", ")", ".", "suppress", "(", ")", "+", "integer", ".", "setResultsName", "(", "\"x\"", ")", "+", "integer", ".", "setResultsName", "(", "\"y\"", ")", "+", "justify", "+", "integer", ".", "setResultsName", "(", "\"w\"", ")", "+", "n_bytes", ")", ".", "setResultsName", "(", "\"text\"", ")", "# Externally-specified image drawn in the box with lower left corner", "# (x,y) and upper right corner (x+w,y+h). The name of the image", "# consists of the n bytes following '-'. This is usually a bitmap", "# image. Note that the image size, even when converted from pixels to", "# points, might be different from the required size (w,h). It is", "# assumed the renderer will perform the necessary scaling.", "image", "=", "(", "Literal", "(", "\"I\"", ")", ".", "suppress", "(", ")", "+", "integer", ".", "setResultsName", "(", "\"x\"", ")", "+", "integer", ".", "setResultsName", "(", "\"y\"", ")", "+", "integer", ".", "setResultsName", "(", "\"w\"", ")", "+", "integer", ".", "setResultsName", "(", "\"h\"", ")", "+", "n_bytes", ")", ".", "setResultsName", "(", "\"image\"", ")", "# The value of the drawing attributes consists of the concatenation of", "# some (multi-)set of the 13 rendering or attribute operations.", "value", "=", "(", "Optional", "(", "quote", ")", ".", "suppress", "(", ")", "+", "OneOrMore", "(", "filled_ellipse", "|", "ellipse", "|", "filled_polygon", "|", "polygon", "|", "polyline", "|", "bspline", "|", "filled_bspline", "|", "text", "|", "fill", "|", "stroke", "|", "font", "|", "style", "|", "image", ")", "+", "Optional", "(", "quote", ")", ".", "suppress", "(", ")", ")", ".", "setResultsName", "(", "\"value\"", ")", "# Drawing operation.", "# draw_ = Literal(\"_draw_\") + Suppress(equals) + value", "# # Label drawing.", "# ldraw_ = Literal(\"_ldraw_\") + Suppress(equals) + value", "# # Edge head arrowhead drawing.", "# hdraw_ = Literal(\"_hdraw_\") + Suppress(equals) + value", "# # Edge tail arrowhead drawing.", "# tdraw_ = Literal(\"_tdraw_\") + Suppress(equals) + value", "# # Edge head label drawing.", "# hldraw_ = Literal(\"_hldraw_\") + Suppress(equals) + value", "# # Edge tail label drawing.", "# tldraw_ = Literal(\"_tldraw_\") + Suppress(equals) + value", "# Parse actions.", "# n_points.setParseAction(self.proc_points)", "# Attribute parse actions.", "fill", ".", "setParseAction", "(", "self", ".", "proc_fill_color", ")", "stroke", ".", "setParseAction", "(", "self", ".", "proc_stroke_color", ")", "font", ".", "setParseAction", "(", "self", ".", "proc_font", ")", "style", ".", "setParseAction", "(", "self", ".", "proc_style", ")", "# Shape parse actions.", "filled_ellipse", ".", "setParseAction", "(", "self", ".", "proc_filled_ellipse", ")", "ellipse", ".", "setParseAction", "(", "self", ".", "proc_unfilled_ellipse", ")", "filled_polygon", ".", "setParseAction", "(", "self", ".", "proc_filled_polygon", ")", "polygon", ".", "setParseAction", "(", "self", ".", "proc_unfilled_polygon", ")", "polyline", ".", "setParseAction", "(", "self", ".", "proc_polyline", ")", "bspline", ".", "setParseAction", "(", "self", ".", "proc_unfilled_bspline", ")", "filled_bspline", ".", "setParseAction", "(", "self", ".", "proc_filled_bspline", ")", "text", ".", "setParseAction", "(", "self", ".", "proc_text", ")", "image", ".", "setParseAction", "(", "self", ".", "proc_image", ")", "return", "value" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser._proc_color
The color traits of a Pen instance must be a string of the form (r,g,b) or (r,g,b,a) where r, g, b, and a are integers from 0 to 255, a wx.Colour instance, an integer which in hex is of the form 0xRRGGBB, where RR is red, GG is green, and BB is blue or a valid color name.
godot/xdot_parser.py
def _proc_color(self, tokens): """ The color traits of a Pen instance must be a string of the form (r,g,b) or (r,g,b,a) where r, g, b, and a are integers from 0 to 255, a wx.Colour instance, an integer which in hex is of the form 0xRRGGBB, where RR is red, GG is green, and BB is blue or a valid color name. """ keys = tokens.keys() if "red" in keys: # RGB(A) rr, gg, bb = tokens["red"], tokens["green"], tokens["blue"] hex2int = lambda h: int(h, 16) if "alpha" in keys: a = tokens["alpha"] c = str((hex2int(rr), hex2int(gg), hex2int(bb), hex2int(a))) else: c = str((hex2int(rr), hex2int(gg), hex2int(bb))) elif "hue" in keys: # HSV r, g, b = hsv_to_rgb(tokens["hue"], tokens["saturation"], tokens["value"]) c = str((int(r*255), int(g*255), int(b*255))) else: c = tokens["color"] return c
def _proc_color(self, tokens): """ The color traits of a Pen instance must be a string of the form (r,g,b) or (r,g,b,a) where r, g, b, and a are integers from 0 to 255, a wx.Colour instance, an integer which in hex is of the form 0xRRGGBB, where RR is red, GG is green, and BB is blue or a valid color name. """ keys = tokens.keys() if "red" in keys: # RGB(A) rr, gg, bb = tokens["red"], tokens["green"], tokens["blue"] hex2int = lambda h: int(h, 16) if "alpha" in keys: a = tokens["alpha"] c = str((hex2int(rr), hex2int(gg), hex2int(bb), hex2int(a))) else: c = str((hex2int(rr), hex2int(gg), hex2int(bb))) elif "hue" in keys: # HSV r, g, b = hsv_to_rgb(tokens["hue"], tokens["saturation"], tokens["value"]) c = str((int(r*255), int(g*255), int(b*255))) else: c = tokens["color"] return c
[ "The", "color", "traits", "of", "a", "Pen", "instance", "must", "be", "a", "string", "of", "the", "form", "(", "r", "g", "b", ")", "or", "(", "r", "g", "b", "a", ")", "where", "r", "g", "b", "and", "a", "are", "integers", "from", "0", "to", "255", "a", "wx", ".", "Colour", "instance", "an", "integer", "which", "in", "hex", "is", "of", "the", "form", "0xRRGGBB", "where", "RR", "is", "red", "GG", "is", "green", "and", "BB", "is", "blue", "or", "a", "valid", "color", "name", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L254-L277
[ "def", "_proc_color", "(", "self", ",", "tokens", ")", ":", "keys", "=", "tokens", ".", "keys", "(", ")", "if", "\"red\"", "in", "keys", ":", "# RGB(A)", "rr", ",", "gg", ",", "bb", "=", "tokens", "[", "\"red\"", "]", ",", "tokens", "[", "\"green\"", "]", ",", "tokens", "[", "\"blue\"", "]", "hex2int", "=", "lambda", "h", ":", "int", "(", "h", ",", "16", ")", "if", "\"alpha\"", "in", "keys", ":", "a", "=", "tokens", "[", "\"alpha\"", "]", "c", "=", "str", "(", "(", "hex2int", "(", "rr", ")", ",", "hex2int", "(", "gg", ")", ",", "hex2int", "(", "bb", ")", ",", "hex2int", "(", "a", ")", ")", ")", "else", ":", "c", "=", "str", "(", "(", "hex2int", "(", "rr", ")", ",", "hex2int", "(", "gg", ")", ",", "hex2int", "(", "bb", ")", ")", ")", "elif", "\"hue\"", "in", "keys", ":", "# HSV", "r", ",", "g", ",", "b", "=", "hsv_to_rgb", "(", "tokens", "[", "\"hue\"", "]", ",", "tokens", "[", "\"saturation\"", "]", ",", "tokens", "[", "\"value\"", "]", ")", "c", "=", "str", "(", "(", "int", "(", "r", "*", "255", ")", ",", "int", "(", "g", "*", "255", ")", ",", "int", "(", "b", "*", "255", ")", ")", ")", "else", ":", "c", "=", "tokens", "[", "\"color\"", "]", "return", "c" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser.proc_font
Sets the font.
godot/xdot_parser.py
def proc_font(self, tokens): """ Sets the font. """ size = int(tokens["s"]) self.pen.font = "%s %d" % (tokens["b"], size) return []
def proc_font(self, tokens): """ Sets the font. """ size = int(tokens["s"]) self.pen.font = "%s %d" % (tokens["b"], size) return []
[ "Sets", "the", "font", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L280-L285
[ "def", "proc_font", "(", "self", ",", "tokens", ")", ":", "size", "=", "int", "(", "tokens", "[", "\"s\"", "]", ")", "self", ".", "pen", ".", "font", "=", "\"%s %d\"", "%", "(", "tokens", "[", "\"b\"", "]", ",", "size", ")", "return", "[", "]" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser._proc_ellipse
Returns the components of an ellipse.
godot/xdot_parser.py
def _proc_ellipse(self, tokens, filled): """ Returns the components of an ellipse. """ component = Ellipse(pen=self.pen, x_origin=tokens["x0"], y_origin=tokens["y0"], e_width=tokens["w"], e_height=tokens["h"], filled=filled) return component
def _proc_ellipse(self, tokens, filled): """ Returns the components of an ellipse. """ component = Ellipse(pen=self.pen, x_origin=tokens["x0"], y_origin=tokens["y0"], e_width=tokens["w"], e_height=tokens["h"], filled=filled) return component
[ "Returns", "the", "components", "of", "an", "ellipse", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L314-L324
[ "def", "_proc_ellipse", "(", "self", ",", "tokens", ",", "filled", ")", ":", "component", "=", "Ellipse", "(", "pen", "=", "self", ".", "pen", ",", "x_origin", "=", "tokens", "[", "\"x0\"", "]", ",", "y_origin", "=", "tokens", "[", "\"y0\"", "]", ",", "e_width", "=", "tokens", "[", "\"w\"", "]", ",", "e_height", "=", "tokens", "[", "\"h\"", "]", ",", "filled", "=", "filled", ")", "return", "component" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser._proc_polygon
Returns the components of a polygon.
godot/xdot_parser.py
def _proc_polygon(self, tokens, filled): """ Returns the components of a polygon. """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = Polygon(pen=self.pen, points=pts, filled=filled) return component
def _proc_polygon(self, tokens, filled): """ Returns the components of a polygon. """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = Polygon(pen=self.pen, points=pts, filled=filled) return component
[ "Returns", "the", "components", "of", "a", "polygon", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L342-L348
[ "def", "_proc_polygon", "(", "self", ",", "tokens", ",", "filled", ")", ":", "pts", "=", "[", "(", "p", "[", "\"x\"", "]", ",", "p", "[", "\"y\"", "]", ")", "for", "p", "in", "tokens", "[", "\"points\"", "]", "]", "component", "=", "Polygon", "(", "pen", "=", "self", ".", "pen", ",", "points", "=", "pts", ",", "filled", "=", "filled", ")", "return", "component" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser.proc_polyline
Returns the components of a polyline.
godot/xdot_parser.py
def proc_polyline(self, tokens): """ Returns the components of a polyline. """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = Polyline(pen=self.pen, points=pts) return component
def proc_polyline(self, tokens): """ Returns the components of a polyline. """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = Polyline(pen=self.pen, points=pts) return component
[ "Returns", "the", "components", "of", "a", "polyline", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L354-L360
[ "def", "proc_polyline", "(", "self", ",", "tokens", ")", ":", "pts", "=", "[", "(", "p", "[", "\"x\"", "]", ",", "p", "[", "\"y\"", "]", ")", "for", "p", "in", "tokens", "[", "\"points\"", "]", "]", "component", "=", "Polyline", "(", "pen", "=", "self", ".", "pen", ",", "points", "=", "pts", ")", "return", "component" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser._proc_bspline
Returns the components of a B-spline (Bezier curve).
godot/xdot_parser.py
def _proc_bspline(self, tokens, filled): """ Returns the components of a B-spline (Bezier curve). """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = BSpline(pen=self.pen, points=pts, filled=filled) return component
def _proc_bspline(self, tokens, filled): """ Returns the components of a B-spline (Bezier curve). """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = BSpline(pen=self.pen, points=pts, filled=filled) return component
[ "Returns", "the", "components", "of", "a", "B", "-", "spline", "(", "Bezier", "curve", ")", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L378-L384
[ "def", "_proc_bspline", "(", "self", ",", "tokens", ",", "filled", ")", ":", "pts", "=", "[", "(", "p", "[", "\"x\"", "]", ",", "p", "[", "\"y\"", "]", ")", "for", "p", "in", "tokens", "[", "\"points\"", "]", "]", "component", "=", "BSpline", "(", "pen", "=", "self", ".", "pen", ",", "points", "=", "pts", ",", "filled", "=", "filled", ")", "return", "component" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser.proc_text
Returns text components.
godot/xdot_parser.py
def proc_text(self, tokens): """ Returns text components. """ component = Text(pen=self.pen, text_x=tokens["x"], text_y=tokens["y"], justify=tokens["j"], text_w=tokens["w"], text=tokens["b"]) return component
def proc_text(self, tokens): """ Returns text components. """ component = Text(pen=self.pen, text_x=tokens["x"], text_y=tokens["y"], justify=tokens["j"], text_w=tokens["w"], text=tokens["b"]) return component
[ "Returns", "text", "components", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L390-L400
[ "def", "proc_text", "(", "self", ",", "tokens", ")", ":", "component", "=", "Text", "(", "pen", "=", "self", ".", "pen", ",", "text_x", "=", "tokens", "[", "\"x\"", "]", ",", "text_y", "=", "tokens", "[", "\"y\"", "]", ",", "justify", "=", "tokens", "[", "\"j\"", "]", ",", "text_w", "=", "tokens", "[", "\"w\"", "]", ",", "text", "=", "tokens", "[", "\"b\"", "]", ")", "return", "component" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
XdotAttrParser.proc_image
Returns the components of an image.
godot/xdot_parser.py
def proc_image(self, tokens): """ Returns the components of an image. """ print "IMAGE:", tokens, tokens.asList(), tokens.keys() raise NotImplementedError
def proc_image(self, tokens): """ Returns the components of an image. """ print "IMAGE:", tokens, tokens.asList(), tokens.keys() raise NotImplementedError
[ "Returns", "the", "components", "of", "an", "image", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L406-L411
[ "def", "proc_image", "(", "self", ",", "tokens", ")", ":", "print", "\"IMAGE:\"", ",", "tokens", ",", "tokens", ".", "asList", "(", ")", ",", "tokens", ".", "keys", "(", ")", "raise", "NotImplementedError" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
render_grid_file
Allow direct use of GridOut GridFS file wrappers as endpoint responses.
web/db/mongo/grid.py
def render_grid_file(context, f): """Allow direct use of GridOut GridFS file wrappers as endpoint responses.""" f.seek(0) # Ensure we are reading from the beginning. response = context.response # Frequently accessed, so made local. Useless optimization on Pypy. if __debug__: # We add some useful diagnostic information in development, omitting from production due to sec. response.headers['Grid-ID'] = str(f._id) # The GridFS file ID. log.debug("Serving GridFS file.", extra=dict( identifier = str(f._id), filename = f.filename, length = f.length, mimetype = f.content_type )) response.conditional_response = True response.accept_ranges = 'bytes' # We allow returns of partial content, if requested. response.content_type = f.content_type # Direct transfer of GridFS-stored MIME type. response.content_length = f.length # The length was pre-computed when the file was uploaded. response.content_md5 = response.etag = f.md5 # As was the MD5, used for simple integrity testing. response.last_modified = f.metadata.get('modified', None) # Optional additional metadata. response.content_disposition = 'attachment; filename=' + f.name # Preserve the filename through to the client. # Being asked for a range or not determines the streaming style used. if context.request.if_range.match_response(response): response.body_file = f # Support seek + limited read. else: response.app_iter = iter(f) # Assign the body as a streaming, chunked iterator. return True
def render_grid_file(context, f): """Allow direct use of GridOut GridFS file wrappers as endpoint responses.""" f.seek(0) # Ensure we are reading from the beginning. response = context.response # Frequently accessed, so made local. Useless optimization on Pypy. if __debug__: # We add some useful diagnostic information in development, omitting from production due to sec. response.headers['Grid-ID'] = str(f._id) # The GridFS file ID. log.debug("Serving GridFS file.", extra=dict( identifier = str(f._id), filename = f.filename, length = f.length, mimetype = f.content_type )) response.conditional_response = True response.accept_ranges = 'bytes' # We allow returns of partial content, if requested. response.content_type = f.content_type # Direct transfer of GridFS-stored MIME type. response.content_length = f.length # The length was pre-computed when the file was uploaded. response.content_md5 = response.etag = f.md5 # As was the MD5, used for simple integrity testing. response.last_modified = f.metadata.get('modified', None) # Optional additional metadata. response.content_disposition = 'attachment; filename=' + f.name # Preserve the filename through to the client. # Being asked for a range or not determines the streaming style used. if context.request.if_range.match_response(response): response.body_file = f # Support seek + limited read. else: response.app_iter = iter(f) # Assign the body as a streaming, chunked iterator. return True
[ "Allow", "direct", "use", "of", "GridOut", "GridFS", "file", "wrappers", "as", "endpoint", "responses", "." ]
marrow/web.db
python
https://github.com/marrow/web.db/blob/c755fbff7028a5edc223d6a631b8421858274fc4/web/db/mongo/grid.py#L9-L38
[ "def", "render_grid_file", "(", "context", ",", "f", ")", ":", "f", ".", "seek", "(", "0", ")", "# Ensure we are reading from the beginning.", "response", "=", "context", ".", "response", "# Frequently accessed, so made local. Useless optimization on Pypy.", "if", "__debug__", ":", "# We add some useful diagnostic information in development, omitting from production due to sec.", "response", ".", "headers", "[", "'Grid-ID'", "]", "=", "str", "(", "f", ".", "_id", ")", "# The GridFS file ID.", "log", ".", "debug", "(", "\"Serving GridFS file.\"", ",", "extra", "=", "dict", "(", "identifier", "=", "str", "(", "f", ".", "_id", ")", ",", "filename", "=", "f", ".", "filename", ",", "length", "=", "f", ".", "length", ",", "mimetype", "=", "f", ".", "content_type", ")", ")", "response", ".", "conditional_response", "=", "True", "response", ".", "accept_ranges", "=", "'bytes'", "# We allow returns of partial content, if requested.", "response", ".", "content_type", "=", "f", ".", "content_type", "# Direct transfer of GridFS-stored MIME type.", "response", ".", "content_length", "=", "f", ".", "length", "# The length was pre-computed when the file was uploaded.", "response", ".", "content_md5", "=", "response", ".", "etag", "=", "f", ".", "md5", "# As was the MD5, used for simple integrity testing.", "response", ".", "last_modified", "=", "f", ".", "metadata", ".", "get", "(", "'modified'", ",", "None", ")", "# Optional additional metadata.", "response", ".", "content_disposition", "=", "'attachment; filename='", "+", "f", ".", "name", "# Preserve the filename through to the client.", "# Being asked for a range or not determines the streaming style used.", "if", "context", ".", "request", ".", "if_range", ".", "match_response", "(", "response", ")", ":", "response", ".", "body_file", "=", "f", "# Support seek + limited read.", "else", ":", "response", ".", "app_iter", "=", "iter", "(", "f", ")", "# Assign the body as a streaming, chunked iterator.", "return", "True" ]
c755fbff7028a5edc223d6a631b8421858274fc4
test
DotFileIResourceAdapter.save
Save to file.
godot/plugin/dot_adapter.py
def save(self, obj): """ Save to file. """ fd = None try: fd = open(self.dot_file.absolute_path, "wb") obj.save_dot(fd) finally: if fd is not None: fd.close() # self.m_time = getmtime(self.adaptee.absolute_path) return
def save(self, obj): """ Save to file. """ fd = None try: fd = open(self.dot_file.absolute_path, "wb") obj.save_dot(fd) finally: if fd is not None: fd.close() # self.m_time = getmtime(self.adaptee.absolute_path) return
[ "Save", "to", "file", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/plugin/dot_adapter.py#L60-L71
[ "def", "save", "(", "self", ",", "obj", ")", ":", "fd", "=", "None", "try", ":", "fd", "=", "open", "(", "self", ".", "dot_file", ".", "absolute_path", ",", "\"wb\"", ")", "obj", ".", "save_dot", "(", "fd", ")", "finally", ":", "if", "fd", "is", "not", "None", ":", "fd", ".", "close", "(", ")", "# self.m_time = getmtime(self.adaptee.absolute_path)", "return" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
DotFileIResourceAdapter.load
Load the file.
godot/plugin/dot_adapter.py
def load(self): """ Load the file. """ fd = None try: obj = parse_dot_file( self.dot_file.absolute_path ) finally: if fd is not None: fd.close() return obj
def load(self): """ Load the file. """ fd = None try: obj = parse_dot_file( self.dot_file.absolute_path ) finally: if fd is not None: fd.close() return obj
[ "Load", "the", "file", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/plugin/dot_adapter.py#L74-L83
[ "def", "load", "(", "self", ")", ":", "fd", "=", "None", "try", ":", "obj", "=", "parse_dot_file", "(", "self", ".", "dot_file", ".", "absolute_path", ")", "finally", ":", "if", "fd", "is", "not", "None", ":", "fd", ".", "close", "(", ")", "return", "obj" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Ellipse._draw_mainlayer
Draws the component
godot/component/ellipse.py
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ x_origin = self.x_origin y_origin = self.y_origin gc.save_state() try: # self._draw_bounds(gc) gc.begin_path() gc.translate_ctm(x_origin, y_origin) gc.scale_ctm(self.e_width, self.e_height) gc.arc(0.0, 0.0, 1.0, 0, 2.0*pi) gc.close_path() # Draw stroke at same scale as graphics context # ctm = gc.get_ctm() # if hasattr(ctm, "__len__") and len(ctm) == 6: # scale = sqrt( (ctm[0]+ctm[1]) * (ctm[0]+ctm[1]) / 2.0 + \ # (ctm[2]+ctm[3]) * (ctm[2]+ctm[3]) / 2.0 ) # elif hasattr(gc, "get_ctm_scale"): # scale = gc.get_ctm_scale() # else: # raise RuntimeError("Unable to get scale from GC.") gc.set_line_width(self.pen.line_width) gc.set_stroke_color(self.pen.color_) if self.filled: gc.set_fill_color(self.pen.fill_color_) gc.draw_path(FILL_STROKE) else: gc.stroke_path() finally: gc.restore_state()
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ x_origin = self.x_origin y_origin = self.y_origin gc.save_state() try: # self._draw_bounds(gc) gc.begin_path() gc.translate_ctm(x_origin, y_origin) gc.scale_ctm(self.e_width, self.e_height) gc.arc(0.0, 0.0, 1.0, 0, 2.0*pi) gc.close_path() # Draw stroke at same scale as graphics context # ctm = gc.get_ctm() # if hasattr(ctm, "__len__") and len(ctm) == 6: # scale = sqrt( (ctm[0]+ctm[1]) * (ctm[0]+ctm[1]) / 2.0 + \ # (ctm[2]+ctm[3]) * (ctm[2]+ctm[3]) / 2.0 ) # elif hasattr(gc, "get_ctm_scale"): # scale = gc.get_ctm_scale() # else: # raise RuntimeError("Unable to get scale from GC.") gc.set_line_width(self.pen.line_width) gc.set_stroke_color(self.pen.color_) if self.filled: gc.set_fill_color(self.pen.fill_color_) gc.draw_path(FILL_STROKE) else: gc.stroke_path() finally: gc.restore_state()
[ "Draws", "the", "component" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/ellipse.py#L89-L123
[ "def", "_draw_mainlayer", "(", "self", ",", "gc", ",", "view_bounds", "=", "None", ",", "mode", "=", "\"default\"", ")", ":", "x_origin", "=", "self", ".", "x_origin", "y_origin", "=", "self", ".", "y_origin", "gc", ".", "save_state", "(", ")", "try", ":", "# self._draw_bounds(gc)", "gc", ".", "begin_path", "(", ")", "gc", ".", "translate_ctm", "(", "x_origin", ",", "y_origin", ")", "gc", ".", "scale_ctm", "(", "self", ".", "e_width", ",", "self", ".", "e_height", ")", "gc", ".", "arc", "(", "0.0", ",", "0.0", ",", "1.0", ",", "0", ",", "2.0", "*", "pi", ")", "gc", ".", "close_path", "(", ")", "# Draw stroke at same scale as graphics context", "# ctm = gc.get_ctm()", "# if hasattr(ctm, \"__len__\") and len(ctm) == 6:", "# scale = sqrt( (ctm[0]+ctm[1]) * (ctm[0]+ctm[1]) / 2.0 + \\", "# (ctm[2]+ctm[3]) * (ctm[2]+ctm[3]) / 2.0 )", "# elif hasattr(gc, \"get_ctm_scale\"):", "# scale = gc.get_ctm_scale()", "# else:", "# raise RuntimeError(\"Unable to get scale from GC.\")", "gc", ".", "set_line_width", "(", "self", ".", "pen", ".", "line_width", ")", "gc", ".", "set_stroke_color", "(", "self", ".", "pen", ".", "color_", ")", "if", "self", ".", "filled", ":", "gc", ".", "set_fill_color", "(", "self", ".", "pen", ".", "fill_color_", ")", "gc", ".", "draw_path", "(", "FILL_STROKE", ")", "else", ":", "gc", ".", "stroke_path", "(", ")", "finally", ":", "gc", ".", "restore_state", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Ellipse.is_in
Test if the point is within this ellipse
godot/component/ellipse.py
def is_in(self, point_x, point_y): """ Test if the point is within this ellipse """ x = self.x_origin y = self.y_origin a = self.e_width#/2 # FIXME: Why divide by two b = self.e_height#/2 return ((point_x-x)**2/(a**2)) + ((point_y-y)**2/(b**2)) < 1.0
def is_in(self, point_x, point_y): """ Test if the point is within this ellipse """ x = self.x_origin y = self.y_origin a = self.e_width#/2 # FIXME: Why divide by two b = self.e_height#/2 return ((point_x-x)**2/(a**2)) + ((point_y-y)**2/(b**2)) < 1.0
[ "Test", "if", "the", "point", "is", "within", "this", "ellipse" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/ellipse.py#L126-L134
[ "def", "is_in", "(", "self", ",", "point_x", ",", "point_y", ")", ":", "x", "=", "self", ".", "x_origin", "y", "=", "self", ".", "y_origin", "a", "=", "self", ".", "e_width", "#/2 # FIXME: Why divide by two", "b", "=", "self", ".", "e_height", "#/2", "return", "(", "(", "point_x", "-", "x", ")", "**", "2", "/", "(", "a", "**", "2", ")", ")", "+", "(", "(", "point_y", "-", "y", ")", "**", "2", "/", "(", "b", "**", "2", ")", ")", "<", "1.0" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Ellipse._draw_bounds
Draws the component bounds for testing purposes
godot/component/ellipse.py
def _draw_bounds(self, gc): """ Draws the component bounds for testing purposes """ dx, dy = self.bounds x, y = self.position gc.rect(x, y, dx, dy) gc.stroke_path()
def _draw_bounds(self, gc): """ Draws the component bounds for testing purposes """ dx, dy = self.bounds x, y = self.position gc.rect(x, y, dx, dy) gc.stroke_path()
[ "Draws", "the", "component", "bounds", "for", "testing", "purposes" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/ellipse.py#L137-L143
[ "def", "_draw_bounds", "(", "self", ",", "gc", ")", ":", "dx", ",", "dy", "=", "self", ".", "bounds", "x", ",", "y", "=", "self", ".", "position", "gc", ".", "rect", "(", "x", ",", "y", ",", "dx", ",", "dy", ")", "gc", ".", "stroke_path", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
NewDotGraphAction.perform
Perform the action.
godot/plugin/action.py
def perform(self, event): """ Perform the action. """ wizard = NewDotGraphWizard(parent=self.window.control, window=self.window, title="New Graph") # Open the wizard if wizard.open() == OK: wizard.finished = True
def perform(self, event): """ Perform the action. """ wizard = NewDotGraphWizard(parent=self.window.control, window=self.window, title="New Graph") # Open the wizard if wizard.open() == OK: wizard.finished = True
[ "Perform", "the", "action", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/plugin/action.py#L70-L78
[ "def", "perform", "(", "self", ",", "event", ")", ":", "wizard", "=", "NewDotGraphWizard", "(", "parent", "=", "self", ".", "window", ".", "control", ",", "window", "=", "self", ".", "window", ",", "title", "=", "\"New Graph\"", ")", "# Open the wizard", "if", "wizard", ".", "open", "(", ")", "==", "OK", ":", "wizard", ".", "finished", "=", "True" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
polar
Convert from rectangular (x,y) to polar (r,w) r = sqrt(x^2 + y^2) w = arctan(y/x) = [-\pi,\pi] = [-180,180]
godot/component/recipes.py
def polar(x, y, deg=0): # radian if deg=0; degree if deg=1 """ Convert from rectangular (x,y) to polar (r,w) r = sqrt(x^2 + y^2) w = arctan(y/x) = [-\pi,\pi] = [-180,180] """ if deg: return hypot(x, y), 180.0 * atan2(y, x) / pi else: return hypot(x, y), atan2(y, x)
def polar(x, y, deg=0): # radian if deg=0; degree if deg=1 """ Convert from rectangular (x,y) to polar (r,w) r = sqrt(x^2 + y^2) w = arctan(y/x) = [-\pi,\pi] = [-180,180] """ if deg: return hypot(x, y), 180.0 * atan2(y, x) / pi else: return hypot(x, y), atan2(y, x)
[ "Convert", "from", "rectangular", "(", "x", "y", ")", "to", "polar", "(", "r", "w", ")", "r", "=", "sqrt", "(", "x^2", "+", "y^2", ")", "w", "=", "arctan", "(", "y", "/", "x", ")", "=", "[", "-", "\\", "pi", "\\", "pi", "]", "=", "[", "-", "180", "180", "]" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/recipes.py#L18-L28
[ "def", "polar", "(", "x", ",", "y", ",", "deg", "=", "0", ")", ":", "# radian if deg=0; degree if deg=1", "if", "deg", ":", "return", "hypot", "(", "x", ",", "y", ")", ",", "180.0", "*", "atan2", "(", "y", ",", "x", ")", "/", "pi", "else", ":", "return", "hypot", "(", "x", ",", "y", ")", ",", "atan2", "(", "y", ",", "x", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
quadratic
x^2 + ax + b = 0 (or ax^2 + bx + c = 0) By substituting x = y-t and t = a/2, the equation reduces to y^2 + (b-t^2) = 0 which has easy solution y = +/- sqrt(t^2-b)
godot/component/recipes.py
def quadratic(a, b, c=None): """ x^2 + ax + b = 0 (or ax^2 + bx + c = 0) By substituting x = y-t and t = a/2, the equation reduces to y^2 + (b-t^2) = 0 which has easy solution y = +/- sqrt(t^2-b) """ if c: # (ax^2 + bx + c = 0) a, b = b / float(a), c / float(a) t = a / 2.0 r = t**2 - b if r >= 0: # real roots y1 = sqrt(r) else: # complex roots y1 = cmath.sqrt(r) y2 = -y1 return y1 - t, y2 - t
def quadratic(a, b, c=None): """ x^2 + ax + b = 0 (or ax^2 + bx + c = 0) By substituting x = y-t and t = a/2, the equation reduces to y^2 + (b-t^2) = 0 which has easy solution y = +/- sqrt(t^2-b) """ if c: # (ax^2 + bx + c = 0) a, b = b / float(a), c / float(a) t = a / 2.0 r = t**2 - b if r >= 0: # real roots y1 = sqrt(r) else: # complex roots y1 = cmath.sqrt(r) y2 = -y1 return y1 - t, y2 - t
[ "x^2", "+", "ax", "+", "b", "=", "0", "(", "or", "ax^2", "+", "bx", "+", "c", "=", "0", ")", "By", "substituting", "x", "=", "y", "-", "t", "and", "t", "=", "a", "/", "2", "the", "equation", "reduces", "to", "y^2", "+", "(", "b", "-", "t^2", ")", "=", "0", "which", "has", "easy", "solution", "y", "=", "+", "/", "-", "sqrt", "(", "t^2", "-", "b", ")" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/recipes.py#L31-L53
[ "def", "quadratic", "(", "a", ",", "b", ",", "c", "=", "None", ")", ":", "if", "c", ":", "# (ax^2 + bx + c = 0)", "a", ",", "b", "=", "b", "/", "float", "(", "a", ")", ",", "c", "/", "float", "(", "a", ")", "t", "=", "a", "/", "2.0", "r", "=", "t", "**", "2", "-", "b", "if", "r", ">=", "0", ":", "# real roots", "y1", "=", "sqrt", "(", "r", ")", "else", ":", "# complex roots", "y1", "=", "cmath", ".", "sqrt", "(", "r", ")", "y2", "=", "-", "y1", "return", "y1", "-", "t", ",", "y2", "-", "t" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
cubic
x^3 + ax^2 + bx + c = 0 (or ax^3 + bx^2 + cx + d = 0) With substitution x = y-t and t = a/3, the cubic equation reduces to y^3 + py + q = 0, where p = b-3t^2 and q = c-bt+2t^3. Then, one real root y1 = u+v can be determined by solving w^2 + qw - (p/3)^3 = 0 where w = u^3, v^3. From Vieta's theorem, y1 + y2 + y3 = 0 y1 y2 + y1 y3 + y2 y3 = p y1 y2 y3 = -q, the other two (real or complex) roots can be obtained by solving y^2 + (y1)y + (p+y1^2) = 0
godot/component/recipes.py
def cubic(a, b, c, d=None): """ x^3 + ax^2 + bx + c = 0 (or ax^3 + bx^2 + cx + d = 0) With substitution x = y-t and t = a/3, the cubic equation reduces to y^3 + py + q = 0, where p = b-3t^2 and q = c-bt+2t^3. Then, one real root y1 = u+v can be determined by solving w^2 + qw - (p/3)^3 = 0 where w = u^3, v^3. From Vieta's theorem, y1 + y2 + y3 = 0 y1 y2 + y1 y3 + y2 y3 = p y1 y2 y3 = -q, the other two (real or complex) roots can be obtained by solving y^2 + (y1)y + (p+y1^2) = 0 """ if d: # (ax^3 + bx^2 + cx + d = 0) a, b, c = b / float(a), c / float(a), d / float(a) t = a / 3.0 p, q = b - 3 * t**2, c - b * t + 2 * t**3 u, v = quadratic(q, -(p/3.0)**3) if type(u) == type(0j): # complex cubic root r, w = polar(u.real, u.imag) y1 = 2 * cbrt(r) * cos(w / 3.0) else: # real root y1 = cbrt(u) + cbrt(v) y2, y3 = quadratic(y1, p + y1**2) return y1 - t, y2 - t, y3 - t
def cubic(a, b, c, d=None): """ x^3 + ax^2 + bx + c = 0 (or ax^3 + bx^2 + cx + d = 0) With substitution x = y-t and t = a/3, the cubic equation reduces to y^3 + py + q = 0, where p = b-3t^2 and q = c-bt+2t^3. Then, one real root y1 = u+v can be determined by solving w^2 + qw - (p/3)^3 = 0 where w = u^3, v^3. From Vieta's theorem, y1 + y2 + y3 = 0 y1 y2 + y1 y3 + y2 y3 = p y1 y2 y3 = -q, the other two (real or complex) roots can be obtained by solving y^2 + (y1)y + (p+y1^2) = 0 """ if d: # (ax^3 + bx^2 + cx + d = 0) a, b, c = b / float(a), c / float(a), d / float(a) t = a / 3.0 p, q = b - 3 * t**2, c - b * t + 2 * t**3 u, v = quadratic(q, -(p/3.0)**3) if type(u) == type(0j): # complex cubic root r, w = polar(u.real, u.imag) y1 = 2 * cbrt(r) * cos(w / 3.0) else: # real root y1 = cbrt(u) + cbrt(v) y2, y3 = quadratic(y1, p + y1**2) return y1 - t, y2 - t, y3 - t
[ "x^3", "+", "ax^2", "+", "bx", "+", "c", "=", "0", "(", "or", "ax^3", "+", "bx^2", "+", "cx", "+", "d", "=", "0", ")", "With", "substitution", "x", "=", "y", "-", "t", "and", "t", "=", "a", "/", "3", "the", "cubic", "equation", "reduces", "to", "y^3", "+", "py", "+", "q", "=", "0", "where", "p", "=", "b", "-", "3t^2", "and", "q", "=", "c", "-", "bt", "+", "2t^3", ".", "Then", "one", "real", "root", "y1", "=", "u", "+", "v", "can", "be", "determined", "by", "solving", "w^2", "+", "qw", "-", "(", "p", "/", "3", ")", "^3", "=", "0", "where", "w", "=", "u^3", "v^3", ".", "From", "Vieta", "s", "theorem", "y1", "+", "y2", "+", "y3", "=", "0", "y1", "y2", "+", "y1", "y3", "+", "y2", "y3", "=", "p", "y1", "y2", "y3", "=", "-", "q", "the", "other", "two", "(", "real", "or", "complex", ")", "roots", "can", "be", "obtained", "by", "solving", "y^2", "+", "(", "y1", ")", "y", "+", "(", "p", "+", "y1^2", ")", "=", "0" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/recipes.py#L56-L86
[ "def", "cubic", "(", "a", ",", "b", ",", "c", ",", "d", "=", "None", ")", ":", "if", "d", ":", "# (ax^3 + bx^2 + cx + d = 0)", "a", ",", "b", ",", "c", "=", "b", "/", "float", "(", "a", ")", ",", "c", "/", "float", "(", "a", ")", ",", "d", "/", "float", "(", "a", ")", "t", "=", "a", "/", "3.0", "p", ",", "q", "=", "b", "-", "3", "*", "t", "**", "2", ",", "c", "-", "b", "*", "t", "+", "2", "*", "t", "**", "3", "u", ",", "v", "=", "quadratic", "(", "q", ",", "-", "(", "p", "/", "3.0", ")", "**", "3", ")", "if", "type", "(", "u", ")", "==", "type", "(", "0j", ")", ":", "# complex cubic root", "r", ",", "w", "=", "polar", "(", "u", ".", "real", ",", "u", ".", "imag", ")", "y1", "=", "2", "*", "cbrt", "(", "r", ")", "*", "cos", "(", "w", "/", "3.0", ")", "else", ":", "# real root", "y1", "=", "cbrt", "(", "u", ")", "+", "cbrt", "(", "v", ")", "y2", ",", "y3", "=", "quadratic", "(", "y1", ",", "p", "+", "y1", "**", "2", ")", "return", "y1", "-", "t", ",", "y2", "-", "t", ",", "y3", "-", "t" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
SQLAlchemyConnection.start
Construct the SQLAlchemy engine and session factory.
web/db/sa.py
def start(self, context): """Construct the SQLAlchemy engine and session factory.""" if __debug__: log.info("Connecting SQLAlchemy database layer.", extra=dict( uri = redact_uri(self.uri), config = self.config, alias = self.alias, )) # Construct the engine. engine = self.engine = create_engine(self.uri, **self.config) # Construct the session factory. self.Session = scoped_session(sessionmaker(bind=engine)) # Test the connection. engine.connect().close() # Assign the engine to our database alias. context.db[self.alias] = engine
def start(self, context): """Construct the SQLAlchemy engine and session factory.""" if __debug__: log.info("Connecting SQLAlchemy database layer.", extra=dict( uri = redact_uri(self.uri), config = self.config, alias = self.alias, )) # Construct the engine. engine = self.engine = create_engine(self.uri, **self.config) # Construct the session factory. self.Session = scoped_session(sessionmaker(bind=engine)) # Test the connection. engine.connect().close() # Assign the engine to our database alias. context.db[self.alias] = engine
[ "Construct", "the", "SQLAlchemy", "engine", "and", "session", "factory", "." ]
marrow/web.db
python
https://github.com/marrow/web.db/blob/c755fbff7028a5edc223d6a631b8421858274fc4/web/db/sa.py#L36-L56
[ "def", "start", "(", "self", ",", "context", ")", ":", "if", "__debug__", ":", "log", ".", "info", "(", "\"Connecting SQLAlchemy database layer.\"", ",", "extra", "=", "dict", "(", "uri", "=", "redact_uri", "(", "self", ".", "uri", ")", ",", "config", "=", "self", ".", "config", ",", "alias", "=", "self", ".", "alias", ",", ")", ")", "# Construct the engine.", "engine", "=", "self", ".", "engine", "=", "create_engine", "(", "self", ".", "uri", ",", "*", "*", "self", ".", "config", ")", "# Construct the session factory.", "self", ".", "Session", "=", "scoped_session", "(", "sessionmaker", "(", "bind", "=", "engine", ")", ")", "# Test the connection.", "engine", ".", "connect", "(", ")", ".", "close", "(", ")", "# Assign the engine to our database alias.", "context", ".", "db", "[", "self", ".", "alias", "]", "=", "engine" ]
c755fbff7028a5edc223d6a631b8421858274fc4
test
GraphViewModel._parse_dot_code_fired
Parses the dot_code string and replaces the existing model.
godot/ui/graph_view_model.py
def _parse_dot_code_fired(self): """ Parses the dot_code string and replaces the existing model. """ parser = GodotDataParser() graph = parser.parse_dot_data(self.dot_code) if graph is not None: self.model = graph
def _parse_dot_code_fired(self): """ Parses the dot_code string and replaces the existing model. """ parser = GodotDataParser() graph = parser.parse_dot_data(self.dot_code) if graph is not None: self.model = graph
[ "Parses", "the", "dot_code", "string", "and", "replaces", "the", "existing", "model", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L180-L186
[ "def", "_parse_dot_code_fired", "(", "self", ")", ":", "parser", "=", "GodotDataParser", "(", ")", "graph", "=", "parser", ".", "parse_dot_data", "(", "self", ".", "dot_code", ")", "if", "graph", "is", "not", "None", ":", "self", ".", "model", "=", "graph" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.new_model
Handles the new Graph action.
godot/ui/graph_view_model.py
def new_model(self, info): """ Handles the new Graph action. """ if info.initialized: retval = confirm(parent = info.ui.control, message = "Replace existing graph?", title = "New Graph", default = YES) if retval == YES: self.model = Graph()
def new_model(self, info): """ Handles the new Graph action. """ if info.initialized: retval = confirm(parent = info.ui.control, message = "Replace existing graph?", title = "New Graph", default = YES) if retval == YES: self.model = Graph()
[ "Handles", "the", "new", "Graph", "action", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L201-L210
[ "def", "new_model", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "retval", "=", "confirm", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "message", "=", "\"Replace existing graph?\"", ",", "title", "=", "\"New Graph\"", ",", "default", "=", "YES", ")", "if", "retval", "==", "YES", ":", "self", ".", "model", "=", "Graph", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.open_file
Handles the open action.
godot/ui/graph_view_model.py
def open_file(self, info): """ Handles the open action. """ if not info.initialized: return # Escape. # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "open", wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|" "All Files (*.*)|*.*|") if dlg.open() == OK: parser = GodotDataParser() model = parser.parse_dot_file(dlg.path) if model is not None: self.model = model else: print "error parsing: %s" % dlg.path self.save_file = dlg.path del dlg
def open_file(self, info): """ Handles the open action. """ if not info.initialized: return # Escape. # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "open", wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|" "All Files (*.*)|*.*|") if dlg.open() == OK: parser = GodotDataParser() model = parser.parse_dot_file(dlg.path) if model is not None: self.model = model else: print "error parsing: %s" % dlg.path self.save_file = dlg.path del dlg
[ "Handles", "the", "open", "action", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L213-L235
[ "def", "open_file", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "# Escape.", "# retval = self.edit_traits(parent=info.ui.control, view=\"file_view\")", "dlg", "=", "FileDialog", "(", "action", "=", "\"open\"", ",", "wildcard", "=", "\"Graphviz Files (*.dot, *.xdot, *.txt)|\"", "\"*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|\"", "\"All Files (*.*)|*.*|\"", ")", "if", "dlg", ".", "open", "(", ")", "==", "OK", ":", "parser", "=", "GodotDataParser", "(", ")", "model", "=", "parser", ".", "parse_dot_file", "(", "dlg", ".", "path", ")", "if", "model", "is", "not", "None", ":", "self", ".", "model", "=", "model", "else", ":", "print", "\"error parsing: %s\"", "%", "dlg", ".", "path", "self", ".", "save_file", "=", "dlg", ".", "path", "del", "dlg" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.save
Handles saving the current model to the last file.
godot/ui/graph_view_model.py
def save(self, info): """ Handles saving the current model to the last file. """ save_file = self.save_file if not isfile(save_file): self.save_as(info) else: fd = None try: fd = open(save_file, "wb") dot_code = str(self.model) fd.write(dot_code) finally: if fd is not None: fd.close()
def save(self, info): """ Handles saving the current model to the last file. """ save_file = self.save_file if not isfile(save_file): self.save_as(info) else: fd = None try: fd = open(save_file, "wb") dot_code = str(self.model) fd.write(dot_code) finally: if fd is not None: fd.close()
[ "Handles", "saving", "the", "current", "model", "to", "the", "last", "file", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L251-L266
[ "def", "save", "(", "self", ",", "info", ")", ":", "save_file", "=", "self", ".", "save_file", "if", "not", "isfile", "(", "save_file", ")", ":", "self", ".", "save_as", "(", "info", ")", "else", ":", "fd", "=", "None", "try", ":", "fd", "=", "open", "(", "save_file", ",", "\"wb\"", ")", "dot_code", "=", "str", "(", "self", ".", "model", ")", "fd", ".", "write", "(", "dot_code", ")", "finally", ":", "if", "fd", "is", "not", "None", ":", "fd", ".", "close", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.save_as
Handles saving the current model to file.
godot/ui/graph_view_model.py
def save_as(self, info): """ Handles saving the current model to file. """ if not info.initialized: return # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "save as", wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" \ "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|" \ "All Files (*.*)|*.*|") if dlg.open() == OK: fd = None try: fd = open(dlg.path, "wb") dot_code = str(self.model) fd.write(dot_code) self.save_file = dlg.path except: error(parent=info.ui.control, title="Save Error", message="An error was encountered when saving\nto %s" % self.file) finally: if fd is not None: fd.close() del dlg
def save_as(self, info): """ Handles saving the current model to file. """ if not info.initialized: return # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "save as", wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" \ "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|" \ "All Files (*.*)|*.*|") if dlg.open() == OK: fd = None try: fd = open(dlg.path, "wb") dot_code = str(self.model) fd.write(dot_code) self.save_file = dlg.path except: error(parent=info.ui.control, title="Save Error", message="An error was encountered when saving\nto %s" % self.file) finally: if fd is not None: fd.close() del dlg
[ "Handles", "saving", "the", "current", "model", "to", "file", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L269-L300
[ "def", "save_as", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "# retval = self.edit_traits(parent=info.ui.control, view=\"file_view\")", "dlg", "=", "FileDialog", "(", "action", "=", "\"save as\"", ",", "wildcard", "=", "\"Graphviz Files (*.dot, *.xdot, *.txt)|\"", "\"*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|\"", "\"All Files (*.*)|*.*|\"", ")", "if", "dlg", ".", "open", "(", ")", "==", "OK", ":", "fd", "=", "None", "try", ":", "fd", "=", "open", "(", "dlg", ".", "path", ",", "\"wb\"", ")", "dot_code", "=", "str", "(", "self", ".", "model", ")", "fd", ".", "write", "(", "dot_code", ")", "self", ".", "save_file", "=", "dlg", ".", "path", "except", ":", "error", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "title", "=", "\"Save Error\"", ",", "message", "=", "\"An error was encountered when saving\\nto %s\"", "%", "self", ".", "file", ")", "finally", ":", "if", "fd", "is", "not", "None", ":", "fd", ".", "close", "(", ")", "del", "dlg" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.configure_graph
Handles display of the graph dot traits.
godot/ui/graph_view_model.py
def configure_graph(self, info): """ Handles display of the graph dot traits. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=attr_view)
def configure_graph(self, info): """ Handles display of the graph dot traits. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=attr_view)
[ "Handles", "display", "of", "the", "graph", "dot", "traits", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L303-L308
[ "def", "configure_graph", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "self", ".", "model", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"live\"", ",", "view", "=", "attr_view", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.configure_nodes
Handles display of the nodes editor.
godot/ui/graph_view_model.py
def configure_nodes(self, info): """ Handles display of the nodes editor. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=nodes_view)
def configure_nodes(self, info): """ Handles display of the nodes editor. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=nodes_view)
[ "Handles", "display", "of", "the", "nodes", "editor", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L311-L316
[ "def", "configure_nodes", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "self", ".", "model", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"live\"", ",", "view", "=", "nodes_view", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.configure_edges
Handles display of the edges editor.
godot/ui/graph_view_model.py
def configure_edges(self, info): """ Handles display of the edges editor. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=edges_view)
def configure_edges(self, info): """ Handles display of the edges editor. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=edges_view)
[ "Handles", "display", "of", "the", "edges", "editor", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L319-L324
[ "def", "configure_edges", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "self", ".", "model", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"live\"", ",", "view", "=", "edges_view", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.about_godot
Handles displaying a view about Godot.
godot/ui/graph_view_model.py
def about_godot(self, info): """ Handles displaying a view about Godot. """ if info.initialized: self.edit_traits(parent=info.ui.control, kind="livemodal", view=about_view)
def about_godot(self, info): """ Handles displaying a view about Godot. """ if info.initialized: self.edit_traits(parent=info.ui.control, kind="livemodal", view=about_view)
[ "Handles", "displaying", "a", "view", "about", "Godot", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L327-L332
[ "def", "about_godot", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "self", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ",", "view", "=", "about_view", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.add_node
Handles adding a Node to the graph.
godot/ui/graph_view_model.py
def add_node(self, info): """ Handles adding a Node to the graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is None: return IDs = [v.ID for v in graph.nodes] node = Node(ID=make_unique_name("node", IDs)) graph.nodes.append(node) retval = node.edit_traits(parent=info.ui.control, kind="livemodal") if not retval.result: graph.nodes.remove(node)
def add_node(self, info): """ Handles adding a Node to the graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is None: return IDs = [v.ID for v in graph.nodes] node = Node(ID=make_unique_name("node", IDs)) graph.nodes.append(node) retval = node.edit_traits(parent=info.ui.control, kind="livemodal") if not retval.result: graph.nodes.remove(node)
[ "Handles", "adding", "a", "Node", "to", "the", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L335-L353
[ "def", "add_node", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "graph", "=", "self", ".", "_request_graph", "(", "info", ".", "ui", ".", "control", ")", "if", "graph", "is", "None", ":", "return", "IDs", "=", "[", "v", ".", "ID", "for", "v", "in", "graph", ".", "nodes", "]", "node", "=", "Node", "(", "ID", "=", "make_unique_name", "(", "\"node\"", ",", "IDs", ")", ")", "graph", ".", "nodes", ".", "append", "(", "node", ")", "retval", "=", "node", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ")", "if", "not", "retval", ".", "result", ":", "graph", ".", "nodes", ".", "remove", "(", "node", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.add_edge
Handles adding an Edge to the graph.
godot/ui/graph_view_model.py
def add_edge(self, info): """ Handles adding an Edge to the graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is None: return n_nodes = len(graph.nodes) IDs = [v.ID for v in graph.nodes] if n_nodes == 0: tail_node = Node(ID=make_unique_name("node", IDs)) head_name = make_unique_name("node", IDs + [tail_node.ID]) head_node = Node(ID=head_name) elif n_nodes == 1: tail_node = graph.nodes[0] head_node = Node(ID=make_unique_name("node", IDs)) else: tail_node = graph.nodes[0] head_node = graph.nodes[1] edge = Edge(tail_node, head_node, _nodes=graph.nodes) retval = edge.edit_traits(parent=info.ui.control, kind="livemodal") if retval.result: graph.edges.append(edge)
def add_edge(self, info): """ Handles adding an Edge to the graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is None: return n_nodes = len(graph.nodes) IDs = [v.ID for v in graph.nodes] if n_nodes == 0: tail_node = Node(ID=make_unique_name("node", IDs)) head_name = make_unique_name("node", IDs + [tail_node.ID]) head_node = Node(ID=head_name) elif n_nodes == 1: tail_node = graph.nodes[0] head_node = Node(ID=make_unique_name("node", IDs)) else: tail_node = graph.nodes[0] head_node = graph.nodes[1] edge = Edge(tail_node, head_node, _nodes=graph.nodes) retval = edge.edit_traits(parent=info.ui.control, kind="livemodal") if retval.result: graph.edges.append(edge)
[ "Handles", "adding", "an", "Edge", "to", "the", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L356-L386
[ "def", "add_edge", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "graph", "=", "self", ".", "_request_graph", "(", "info", ".", "ui", ".", "control", ")", "if", "graph", "is", "None", ":", "return", "n_nodes", "=", "len", "(", "graph", ".", "nodes", ")", "IDs", "=", "[", "v", ".", "ID", "for", "v", "in", "graph", ".", "nodes", "]", "if", "n_nodes", "==", "0", ":", "tail_node", "=", "Node", "(", "ID", "=", "make_unique_name", "(", "\"node\"", ",", "IDs", ")", ")", "head_name", "=", "make_unique_name", "(", "\"node\"", ",", "IDs", "+", "[", "tail_node", ".", "ID", "]", ")", "head_node", "=", "Node", "(", "ID", "=", "head_name", ")", "elif", "n_nodes", "==", "1", ":", "tail_node", "=", "graph", ".", "nodes", "[", "0", "]", "head_node", "=", "Node", "(", "ID", "=", "make_unique_name", "(", "\"node\"", ",", "IDs", ")", ")", "else", ":", "tail_node", "=", "graph", ".", "nodes", "[", "0", "]", "head_node", "=", "graph", ".", "nodes", "[", "1", "]", "edge", "=", "Edge", "(", "tail_node", ",", "head_node", ",", "_nodes", "=", "graph", ".", "nodes", ")", "retval", "=", "edge", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ")", "if", "retval", ".", "result", ":", "graph", ".", "edges", ".", "append", "(", "edge", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.add_subgraph
Handles adding a Subgraph to the main graph.
godot/ui/graph_view_model.py
def add_subgraph(self, info): """ Handles adding a Subgraph to the main graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is not None: subgraph = Subgraph()#root=graph, parent=graph) retval = subgraph.edit_traits(parent = info.ui.control, kind = "livemodal") if retval.result: graph.subgraphs.append(subgraph)
def add_subgraph(self, info): """ Handles adding a Subgraph to the main graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is not None: subgraph = Subgraph()#root=graph, parent=graph) retval = subgraph.edit_traits(parent = info.ui.control, kind = "livemodal") if retval.result: graph.subgraphs.append(subgraph)
[ "Handles", "adding", "a", "Subgraph", "to", "the", "main", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L389-L402
[ "def", "add_subgraph", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "graph", "=", "self", ".", "_request_graph", "(", "info", ".", "ui", ".", "control", ")", "if", "graph", "is", "not", "None", ":", "subgraph", "=", "Subgraph", "(", ")", "#root=graph, parent=graph)", "retval", "=", "subgraph", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ")", "if", "retval", ".", "result", ":", "graph", ".", "subgraphs", ".", "append", "(", "subgraph", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.add_cluster
Handles adding a Cluster to the main graph.
godot/ui/graph_view_model.py
def add_cluster(self, info): """ Handles adding a Cluster to the main graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is not None: cluster = Cluster()#root=graph, parent=graph) retval = cluster.edit_traits(parent = info.ui.control, kind = "livemodal") if retval.result: graph.clusters.append(cluster)
def add_cluster(self, info): """ Handles adding a Cluster to the main graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is not None: cluster = Cluster()#root=graph, parent=graph) retval = cluster.edit_traits(parent = info.ui.control, kind = "livemodal") if retval.result: graph.clusters.append(cluster)
[ "Handles", "adding", "a", "Cluster", "to", "the", "main", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L405-L418
[ "def", "add_cluster", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "graph", "=", "self", ".", "_request_graph", "(", "info", ".", "ui", ".", "control", ")", "if", "graph", "is", "not", "None", ":", "cluster", "=", "Cluster", "(", ")", "#root=graph, parent=graph)", "retval", "=", "cluster", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ")", "if", "retval", ".", "result", ":", "graph", ".", "clusters", ".", "append", "(", "cluster", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel._request_graph
Displays a dialog for graph selection if more than one exists. Returns None if the dialog is canceled.
godot/ui/graph_view_model.py
def _request_graph(self, parent=None): """ Displays a dialog for graph selection if more than one exists. Returns None if the dialog is canceled. """ if (len(self.all_graphs) > 1) and (self.select_graph): retval = self.edit_traits(parent = parent, view = "all_graphs_view") if not retval.result: return None if self.selected_graph is not None: return self.selected_graph else: return self.model
def _request_graph(self, parent=None): """ Displays a dialog for graph selection if more than one exists. Returns None if the dialog is canceled. """ if (len(self.all_graphs) > 1) and (self.select_graph): retval = self.edit_traits(parent = parent, view = "all_graphs_view") if not retval.result: return None if self.selected_graph is not None: return self.selected_graph else: return self.model
[ "Displays", "a", "dialog", "for", "graph", "selection", "if", "more", "than", "one", "exists", ".", "Returns", "None", "if", "the", "dialog", "is", "canceled", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L421-L435
[ "def", "_request_graph", "(", "self", ",", "parent", "=", "None", ")", ":", "if", "(", "len", "(", "self", ".", "all_graphs", ")", ">", "1", ")", "and", "(", "self", ".", "select_graph", ")", ":", "retval", "=", "self", ".", "edit_traits", "(", "parent", "=", "parent", ",", "view", "=", "\"all_graphs_view\"", ")", "if", "not", "retval", ".", "result", ":", "return", "None", "if", "self", ".", "selected_graph", "is", "not", "None", ":", "return", "self", ".", "selected_graph", "else", ":", "return", "self", ".", "model" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.godot_options
Handles display of the options menu.
godot/ui/graph_view_model.py
def godot_options(self, info): """ Handles display of the options menu. """ if info.initialized: self.edit_traits( parent = info.ui.control, kind = "livemodal", view = "options_view" )
def godot_options(self, info): """ Handles display of the options menu. """ if info.initialized: self.edit_traits( parent = info.ui.control, kind = "livemodal", view = "options_view" )
[ "Handles", "display", "of", "the", "options", "menu", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L445-L451
[ "def", "godot_options", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "self", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ",", "view", "=", "\"options_view\"", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.configure_dot_code
Handles display of the dot code in a text editor.
godot/ui/graph_view_model.py
def configure_dot_code(self, info): """ Handles display of the dot code in a text editor. """ if not info.initialized: return self.dot_code = str(self.model) retval = self.edit_traits( parent = info.ui.control, kind = "livemodal", view = "dot_code_view" )
def configure_dot_code(self, info): """ Handles display of the dot code in a text editor. """ if not info.initialized: return self.dot_code = str(self.model) retval = self.edit_traits( parent = info.ui.control, kind = "livemodal", view = "dot_code_view" )
[ "Handles", "display", "of", "the", "dot", "code", "in", "a", "text", "editor", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L454-L463
[ "def", "configure_dot_code", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "self", ".", "dot_code", "=", "str", "(", "self", ".", "model", ")", "retval", "=", "self", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ",", "view", "=", "\"dot_code_view\"", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GraphViewModel.on_exit
Handles the user attempting to exit Godot.
godot/ui/graph_view_model.py
def on_exit(self, info): """ Handles the user attempting to exit Godot. """ if self.prompt_on_exit:# and (not is_ok): retval = confirm(parent = info.ui.control, message = "Exit Godot?", title = "Confirm exit", default = YES) if retval == YES: self._on_close( info ) else: self._on_close( info )
def on_exit(self, info): """ Handles the user attempting to exit Godot. """ if self.prompt_on_exit:# and (not is_ok): retval = confirm(parent = info.ui.control, message = "Exit Godot?", title = "Confirm exit", default = YES) if retval == YES: self._on_close( info ) else: self._on_close( info )
[ "Handles", "the", "user", "attempting", "to", "exit", "Godot", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L474-L485
[ "def", "on_exit", "(", "self", ",", "info", ")", ":", "if", "self", ".", "prompt_on_exit", ":", "# and (not is_ok):", "retval", "=", "confirm", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "message", "=", "\"Exit Godot?\"", ",", "title", "=", "\"Confirm exit\"", ",", "default", "=", "YES", ")", "if", "retval", "==", "YES", ":", "self", ".", "_on_close", "(", "info", ")", "else", ":", "self", ".", "_on_close", "(", "info", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
move_to_origin
Components are positioned relative to their container. Use this method to position the bottom-left corner of the components at the origin.
godot/util.py
def move_to_origin(components): """ Components are positioned relative to their container. Use this method to position the bottom-left corner of the components at the origin. """ for component in components: if isinstance(component, Ellipse): component.x_origin = component.e_width component.y_origin = component.e_height elif isinstance(component, (Polygon, BSpline)): min_x = min( [t[0] for t in component.points] ) min_y = min( [t[1] for t in component.points] ) component.points = [ ( p[0]-min_x, p[1]-min_y ) for p in component.points ] elif isinstance(component, Text): font = str_to_font( str(component.pen.font) ) component.text_x = 0#-( component.text_w / 2 ) component.text_y = 0
def move_to_origin(components): """ Components are positioned relative to their container. Use this method to position the bottom-left corner of the components at the origin. """ for component in components: if isinstance(component, Ellipse): component.x_origin = component.e_width component.y_origin = component.e_height elif isinstance(component, (Polygon, BSpline)): min_x = min( [t[0] for t in component.points] ) min_y = min( [t[1] for t in component.points] ) component.points = [ ( p[0]-min_x, p[1]-min_y ) for p in component.points ] elif isinstance(component, Text): font = str_to_font( str(component.pen.font) ) component.text_x = 0#-( component.text_w / 2 ) component.text_y = 0
[ "Components", "are", "positioned", "relative", "to", "their", "container", ".", "Use", "this", "method", "to", "position", "the", "bottom", "-", "left", "corner", "of", "the", "components", "at", "the", "origin", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/util.py#L139-L160
[ "def", "move_to_origin", "(", "components", ")", ":", "for", "component", "in", "components", ":", "if", "isinstance", "(", "component", ",", "Ellipse", ")", ":", "component", ".", "x_origin", "=", "component", ".", "e_width", "component", ".", "y_origin", "=", "component", ".", "e_height", "elif", "isinstance", "(", "component", ",", "(", "Polygon", ",", "BSpline", ")", ")", ":", "min_x", "=", "min", "(", "[", "t", "[", "0", "]", "for", "t", "in", "component", ".", "points", "]", ")", "min_y", "=", "min", "(", "[", "t", "[", "1", "]", "for", "t", "in", "component", ".", "points", "]", ")", "component", ".", "points", "=", "[", "(", "p", "[", "0", "]", "-", "min_x", ",", "p", "[", "1", "]", "-", "min_y", ")", "for", "p", "in", "component", ".", "points", "]", "elif", "isinstance", "(", "component", ",", "Text", ")", ":", "font", "=", "str_to_font", "(", "str", "(", "component", ".", "pen", ".", "font", ")", ")", "component", ".", "text_x", "=", "0", "#-( component.text_w / 2 )", "component", ".", "text_y", "=", "0" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Serializable.save_to_file_like
Save the object to a given file like object in the given format.
godot/util.py
def save_to_file_like(self, flo, format=None, **kwargs): """ Save the object to a given file like object in the given format. """ format = self.format if format is None else format save = getattr(self, "save_%s" % format, None) if save is None: raise ValueError("Unknown format '%s'." % format) save(flo, **kwargs)
def save_to_file_like(self, flo, format=None, **kwargs): """ Save the object to a given file like object in the given format. """ format = self.format if format is None else format save = getattr(self, "save_%s" % format, None) if save is None: raise ValueError("Unknown format '%s'." % format) save(flo, **kwargs)
[ "Save", "the", "object", "to", "a", "given", "file", "like", "object", "in", "the", "given", "format", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/util.py#L65-L72
[ "def", "save_to_file_like", "(", "self", ",", "flo", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "format", "=", "self", ".", "format", "if", "format", "is", "None", "else", "format", "save", "=", "getattr", "(", "self", ",", "\"save_%s\"", "%", "format", ",", "None", ")", "if", "save", "is", "None", ":", "raise", "ValueError", "(", "\"Unknown format '%s'.\"", "%", "format", ")", "save", "(", "flo", ",", "*", "*", "kwargs", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Serializable.load_from_file_like
Load the object to a given file like object with the given protocol.
godot/util.py
def load_from_file_like(cls, flo, format=None): """ Load the object to a given file like object with the given protocol. """ format = self.format if format is None else format load = getattr(cls, "load_%s" % format, None) if load is None: raise ValueError("Unknown format '%s'." % format) return load(flo)
def load_from_file_like(cls, flo, format=None): """ Load the object to a given file like object with the given protocol. """ format = self.format if format is None else format load = getattr(cls, "load_%s" % format, None) if load is None: raise ValueError("Unknown format '%s'." % format) return load(flo)
[ "Load", "the", "object", "to", "a", "given", "file", "like", "object", "with", "the", "given", "protocol", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/util.py#L76-L84
[ "def", "load_from_file_like", "(", "cls", ",", "flo", ",", "format", "=", "None", ")", ":", "format", "=", "self", ".", "format", "if", "format", "is", "None", "else", "format", "load", "=", "getattr", "(", "cls", ",", "\"load_%s\"", "%", "format", ",", "None", ")", "if", "load", "is", "None", ":", "raise", "ValueError", "(", "\"Unknown format '%s'.\"", "%", "format", ")", "return", "load", "(", "flo", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Serializable.save_to_file
Save the object to file given by filename.
godot/util.py
def save_to_file(self, filename, format=None, **kwargs): """ Save the object to file given by filename. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) with file(filename, 'wb') as fp: self.save_to_file_like(fp, format, **kwargs)
def save_to_file(self, filename, format=None, **kwargs): """ Save the object to file given by filename. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) with file(filename, 'wb') as fp: self.save_to_file_like(fp, format, **kwargs)
[ "Save", "the", "object", "to", "file", "given", "by", "filename", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/util.py#L87-L94
[ "def", "save_to_file", "(", "self", ",", "filename", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "format", "is", "None", ":", "# try to derive protocol from file extension", "format", "=", "format_from_extension", "(", "filename", ")", "with", "file", "(", "filename", ",", "'wb'", ")", "as", "fp", ":", "self", ".", "save_to_file_like", "(", "fp", ",", "format", ",", "*", "*", "kwargs", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Serializable.load_from_file
Return an instance of the class that is saved in the file with the given filename in the specified format.
godot/util.py
def load_from_file(cls, filename, format=None): """ Return an instance of the class that is saved in the file with the given filename in the specified format. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) with file(filename,'rbU') as fp: obj = cls.load_from_file_like(fp, format) obj.filename = filename return obj
def load_from_file(cls, filename, format=None): """ Return an instance of the class that is saved in the file with the given filename in the specified format. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) with file(filename,'rbU') as fp: obj = cls.load_from_file_like(fp, format) obj.filename = filename return obj
[ "Return", "an", "instance", "of", "the", "class", "that", "is", "saved", "in", "the", "file", "with", "the", "given", "filename", "in", "the", "specified", "format", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/util.py#L98-L108
[ "def", "load_from_file", "(", "cls", ",", "filename", ",", "format", "=", "None", ")", ":", "if", "format", "is", "None", ":", "# try to derive protocol from file extension", "format", "=", "format_from_extension", "(", "filename", ")", "with", "file", "(", "filename", ",", "'rbU'", ")", "as", "fp", ":", "obj", "=", "cls", ".", "load_from_file_like", "(", "fp", ",", "format", ")", "obj", ".", "filename", "=", "filename", "return", "obj" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Text._draw_mainlayer
Draws the component
godot/component/text.py
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ gc.save_state() try: # Specify the font font = str_to_font(str(self.pen.font)) gc.set_font(font) gc.set_fill_color(self.pen.color_) x = self.text_x - ( self.text_w / 2 ) y = self.text_y - ( font.size / 2 ) # Show text at the same scale as the graphics context ctm = gc.get_ctm() if hasattr(ctm, "__len__") and len(ctm) == 6: scale = sqrt( (ctm[0] + ctm[1]) * (ctm[0] + ctm[1]) / 2.0 + \ (ctm[2] + ctm[3]) * (ctm[2] + ctm[3]) / 2.0 ) elif hasattr(gc, "get_ctm_scale"): scale = gc.get_ctm_scale() else: raise RuntimeError("Unable to get scale from GC.") x *= scale y *= scale gc.show_text_at_point(self.text, x, y) finally: gc.restore_state()
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ gc.save_state() try: # Specify the font font = str_to_font(str(self.pen.font)) gc.set_font(font) gc.set_fill_color(self.pen.color_) x = self.text_x - ( self.text_w / 2 ) y = self.text_y - ( font.size / 2 ) # Show text at the same scale as the graphics context ctm = gc.get_ctm() if hasattr(ctm, "__len__") and len(ctm) == 6: scale = sqrt( (ctm[0] + ctm[1]) * (ctm[0] + ctm[1]) / 2.0 + \ (ctm[2] + ctm[3]) * (ctm[2] + ctm[3]) / 2.0 ) elif hasattr(gc, "get_ctm_scale"): scale = gc.get_ctm_scale() else: raise RuntimeError("Unable to get scale from GC.") x *= scale y *= scale gc.show_text_at_point(self.text, x, y) finally: gc.restore_state()
[ "Draws", "the", "component" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/text.py#L93-L120
[ "def", "_draw_mainlayer", "(", "self", ",", "gc", ",", "view_bounds", "=", "None", ",", "mode", "=", "\"default\"", ")", ":", "gc", ".", "save_state", "(", ")", "try", ":", "# Specify the font", "font", "=", "str_to_font", "(", "str", "(", "self", ".", "pen", ".", "font", ")", ")", "gc", ".", "set_font", "(", "font", ")", "gc", ".", "set_fill_color", "(", "self", ".", "pen", ".", "color_", ")", "x", "=", "self", ".", "text_x", "-", "(", "self", ".", "text_w", "/", "2", ")", "y", "=", "self", ".", "text_y", "-", "(", "font", ".", "size", "/", "2", ")", "# Show text at the same scale as the graphics context", "ctm", "=", "gc", ".", "get_ctm", "(", ")", "if", "hasattr", "(", "ctm", ",", "\"__len__\"", ")", "and", "len", "(", "ctm", ")", "==", "6", ":", "scale", "=", "sqrt", "(", "(", "ctm", "[", "0", "]", "+", "ctm", "[", "1", "]", ")", "*", "(", "ctm", "[", "0", "]", "+", "ctm", "[", "1", "]", ")", "/", "2.0", "+", "(", "ctm", "[", "2", "]", "+", "ctm", "[", "3", "]", ")", "*", "(", "ctm", "[", "2", "]", "+", "ctm", "[", "3", "]", ")", "/", "2.0", ")", "elif", "hasattr", "(", "gc", ",", "\"get_ctm_scale\"", ")", ":", "scale", "=", "gc", ".", "get_ctm_scale", "(", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unable to get scale from GC.\"", ")", "x", "*=", "scale", "y", "*=", "scale", "gc", ".", "show_text_at_point", "(", "self", ".", "text", ",", "x", ",", "y", ")", "finally", ":", "gc", ".", "restore_state", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
Alias
Syntactically concise alias trait but creates a pair of lambda functions for every alias you declare. class MyClass(HasTraits): line_width = Float(3.0) thickness = Alias("line_width")
godot/common.py
def Alias(name, **metadata): """ Syntactically concise alias trait but creates a pair of lambda functions for every alias you declare. class MyClass(HasTraits): line_width = Float(3.0) thickness = Alias("line_width") """ return Property(lambda obj: getattr(obj, name), lambda obj, val: setattr(obj, name, val), **metadata)
def Alias(name, **metadata): """ Syntactically concise alias trait but creates a pair of lambda functions for every alias you declare. class MyClass(HasTraits): line_width = Float(3.0) thickness = Alias("line_width") """ return Property(lambda obj: getattr(obj, name), lambda obj, val: setattr(obj, name, val), **metadata)
[ "Syntactically", "concise", "alias", "trait", "but", "creates", "a", "pair", "of", "lambda", "functions", "for", "every", "alias", "you", "declare", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/common.py#L40-L52
[ "def", "Alias", "(", "name", ",", "*", "*", "metadata", ")", ":", "return", "Property", "(", "lambda", "obj", ":", "getattr", "(", "obj", ",", "name", ")", ",", "lambda", "obj", ",", "val", ":", "setattr", "(", "obj", ",", "name", ",", "val", ")", ",", "*", "*", "metadata", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
parse
!DEMO! Simple file parsing generator Args: filename: absolute or relative path to file on disk encoding: encoding string that is passed to open function
markov.py
def parse(filename, encoding=None): """ !DEMO! Simple file parsing generator Args: filename: absolute or relative path to file on disk encoding: encoding string that is passed to open function """ with open(filename, encoding=encoding) as source: for line in source: for word in line.split(): yield word
def parse(filename, encoding=None): """ !DEMO! Simple file parsing generator Args: filename: absolute or relative path to file on disk encoding: encoding string that is passed to open function """ with open(filename, encoding=encoding) as source: for line in source: for word in line.split(): yield word
[ "!DEMO!", "Simple", "file", "parsing", "generator" ]
fm4d/PyMarkovTextGenerator
python
https://github.com/fm4d/PyMarkovTextGenerator/blob/4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37/markov.py#L80-L93
[ "def", "parse", "(", "filename", ",", "encoding", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "encoding", "=", "encoding", ")", "as", "source", ":", "for", "line", "in", "source", ":", "for", "word", "in", "line", ".", "split", "(", ")", ":", "yield", "word" ]
4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37
test
MarkovChain.startwords
!DEMO! Cached list of keys that can be used to generate sentence.
markov.py
def startwords(self): """ !DEMO! Cached list of keys that can be used to generate sentence. """ if self._start_words is not None: return self._start_words else: self._start_words = list(filter( lambda x: str.isupper(x[0][0]) and x[0][-1] not in ['.', '?', '!'], self.content.keys() )) return self._start_words
def startwords(self): """ !DEMO! Cached list of keys that can be used to generate sentence. """ if self._start_words is not None: return self._start_words else: self._start_words = list(filter( lambda x: str.isupper(x[0][0]) and x[0][-1] not in ['.', '?', '!'], self.content.keys() )) return self._start_words
[ "!DEMO!", "Cached", "list", "of", "keys", "that", "can", "be", "used", "to", "generate", "sentence", "." ]
fm4d/PyMarkovTextGenerator
python
https://github.com/fm4d/PyMarkovTextGenerator/blob/4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37/markov.py#L107-L120
[ "def", "startwords", "(", "self", ")", ":", "if", "self", ".", "_start_words", "is", "not", "None", ":", "return", "self", ".", "_start_words", "else", ":", "self", ".", "_start_words", "=", "list", "(", "filter", "(", "lambda", "x", ":", "str", ".", "isupper", "(", "x", "[", "0", "]", "[", "0", "]", ")", "and", "x", "[", "0", "]", "[", "-", "1", "]", "not", "in", "[", "'.'", ",", "'?'", ",", "'!'", "]", ",", "self", ".", "content", ".", "keys", "(", ")", ")", ")", "return", "self", ".", "_start_words" ]
4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37
test
MarkovGenerator.add_chain
Add chain to current shelve file Args: name: chain name order: markov chain order
markov.py
def add_chain(self, name, order): """ Add chain to current shelve file Args: name: chain name order: markov chain order """ if name not in self.chains: setattr(self.chains, name, MarkovChain(order=order)) else: raise ValueError("Chain with this name already exists")
def add_chain(self, name, order): """ Add chain to current shelve file Args: name: chain name order: markov chain order """ if name not in self.chains: setattr(self.chains, name, MarkovChain(order=order)) else: raise ValueError("Chain with this name already exists")
[ "Add", "chain", "to", "current", "shelve", "file" ]
fm4d/PyMarkovTextGenerator
python
https://github.com/fm4d/PyMarkovTextGenerator/blob/4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37/markov.py#L143-L155
[ "def", "add_chain", "(", "self", ",", "name", ",", "order", ")", ":", "if", "name", "not", "in", "self", ".", "chains", ":", "setattr", "(", "self", ".", "chains", ",", "name", ",", "MarkovChain", "(", "order", "=", "order", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Chain with this name already exists\"", ")" ]
4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37
test
MarkovGenerator.remove_chain
Remove chain from current shelve file Args: name: chain name
markov.py
def remove_chain(self, name): """ Remove chain from current shelve file Args: name: chain name """ if name in self.chains: delattr(self.chains, name) else: raise ValueError("Chain with this name not found")
def remove_chain(self, name): """ Remove chain from current shelve file Args: name: chain name """ if name in self.chains: delattr(self.chains, name) else: raise ValueError("Chain with this name not found")
[ "Remove", "chain", "from", "current", "shelve", "file" ]
fm4d/PyMarkovTextGenerator
python
https://github.com/fm4d/PyMarkovTextGenerator/blob/4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37/markov.py#L157-L168
[ "def", "remove_chain", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "chains", ":", "delattr", "(", "self", ".", "chains", ",", "name", ")", "else", ":", "raise", "ValueError", "(", "\"Chain with this name not found\"", ")" ]
4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37
test
MarkovGenerator.build_chain
Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source
markov.py
def build_chain(self, source, chain): """ Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source """ for group in WalkByGroup(source, chain.order+1): pre = group[:-1] res = group[-1] if pre not in chain.content: chain.content[pre] = {res: 1} else: if res not in chain.content[pre]: chain.content[pre][res] = 1 else: chain.content[pre][res] += 1 chain.decache()
def build_chain(self, source, chain): """ Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source """ for group in WalkByGroup(source, chain.order+1): pre = group[:-1] res = group[-1] if pre not in chain.content: chain.content[pre] = {res: 1} else: if res not in chain.content[pre]: chain.content[pre][res] = 1 else: chain.content[pre][res] += 1 chain.decache()
[ "Build", "markov", "chain", "from", "source", "on", "top", "of", "existin", "chain" ]
fm4d/PyMarkovTextGenerator
python
https://github.com/fm4d/PyMarkovTextGenerator/blob/4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37/markov.py#L170-L192
[ "def", "build_chain", "(", "self", ",", "source", ",", "chain", ")", ":", "for", "group", "in", "WalkByGroup", "(", "source", ",", "chain", ".", "order", "+", "1", ")", ":", "pre", "=", "group", "[", ":", "-", "1", "]", "res", "=", "group", "[", "-", "1", "]", "if", "pre", "not", "in", "chain", ".", "content", ":", "chain", ".", "content", "[", "pre", "]", "=", "{", "res", ":", "1", "}", "else", ":", "if", "res", "not", "in", "chain", ".", "content", "[", "pre", "]", ":", "chain", ".", "content", "[", "pre", "]", "[", "res", "]", "=", "1", "else", ":", "chain", ".", "content", "[", "pre", "]", "[", "res", "]", "+=", "1", "chain", ".", "decache", "(", ")" ]
4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37
test
MarkovGenerator.generate_sentence
!DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit. Args: chain: MarkovChain that will be used to generate sentence
markov.py
def generate_sentence(self, chain): """ !DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit. Args: chain: MarkovChain that will be used to generate sentence """ def weighted_choice(choices): total_weight = sum(weight for val, weight in choices) rand = random.uniform(0, total_weight) upto = 0 for val, weight in choices: if upto + weight >= rand: return val upto += weight sentence = list(random.choice(chain.startwords)) while not sentence[-1][-1] in ['.', '?', '!']: sentence.append( weighted_choice( chain.content[tuple(sentence[-2:])].items() ) ) return ' '.join(sentence)
def generate_sentence(self, chain): """ !DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit. Args: chain: MarkovChain that will be used to generate sentence """ def weighted_choice(choices): total_weight = sum(weight for val, weight in choices) rand = random.uniform(0, total_weight) upto = 0 for val, weight in choices: if upto + weight >= rand: return val upto += weight sentence = list(random.choice(chain.startwords)) while not sentence[-1][-1] in ['.', '?', '!']: sentence.append( weighted_choice( chain.content[tuple(sentence[-2:])].items() ) ) return ' '.join(sentence)
[ "!DEMO!", "Demo", "function", "that", "shows", "how", "to", "generate", "a", "simple", "sentence", "starting", "with", "uppercase", "letter", "without", "lenght", "limit", "." ]
fm4d/PyMarkovTextGenerator
python
https://github.com/fm4d/PyMarkovTextGenerator/blob/4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37/markov.py#L194-L223
[ "def", "generate_sentence", "(", "self", ",", "chain", ")", ":", "def", "weighted_choice", "(", "choices", ")", ":", "total_weight", "=", "sum", "(", "weight", "for", "val", ",", "weight", "in", "choices", ")", "rand", "=", "random", ".", "uniform", "(", "0", ",", "total_weight", ")", "upto", "=", "0", "for", "val", ",", "weight", "in", "choices", ":", "if", "upto", "+", "weight", ">=", "rand", ":", "return", "val", "upto", "+=", "weight", "sentence", "=", "list", "(", "random", ".", "choice", "(", "chain", ".", "startwords", ")", ")", "while", "not", "sentence", "[", "-", "1", "]", "[", "-", "1", "]", "in", "[", "'.'", ",", "'?'", ",", "'!'", "]", ":", "sentence", ".", "append", "(", "weighted_choice", "(", "chain", ".", "content", "[", "tuple", "(", "sentence", "[", "-", "2", ":", "]", ")", "]", ".", "items", "(", ")", ")", ")", "return", "' '", ".", "join", "(", "sentence", ")" ]
4a7e8e2cfe14c9745aba6b9df7d7b402a9029a37
test
BaseGraph.create
Creates and returns a representation of the graph using the Graphviz layout program given by 'prog', according to the given format. Writes the graph to a temporary dot file and processes it with the program given by 'prog' (which defaults to 'dot'), reading the output and returning it as a string if the operation is successful. On failure None is returned.
godot/base_graph.py
def create(self, prog=None, format=None): """ Creates and returns a representation of the graph using the Graphviz layout program given by 'prog', according to the given format. Writes the graph to a temporary dot file and processes it with the program given by 'prog' (which defaults to 'dot'), reading the output and returning it as a string if the operation is successful. On failure None is returned. """ prog = self.program if prog is None else prog format = self.format if format is None else format # Make a temporary file ... tmp_fd, tmp_name = tempfile.mkstemp() os.close( tmp_fd ) # ... and save the graph to it. dot_fd = file( tmp_name, "w+b" ) self.save_dot( dot_fd ) dot_fd.close() # Get the temporary file directory name. tmp_dir = os.path.dirname( tmp_name ) # TODO: Shape image files (See PyDot). Important. # Process the file using the layout program, specifying the format. p = subprocess.Popen( ( self.programs[ prog ], '-T'+format, tmp_name ), cwd=tmp_dir, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stderr = p.stderr stdout = p.stdout # Make sense of the standard output form the process. stdout_output = list() while True: data = stdout.read() if not data: break stdout_output.append(data) stdout.close() if stdout_output: stdout_output = ''.join(stdout_output) # Similarly so for any standard error. if not stderr.closed: stderr_output = list() while True: data = stderr.read() if not data: break stderr_output.append(data) stderr.close() if stderr_output: stderr_output = ''.join(stderr_output) #pid, status = os.waitpid(p.pid, 0) status = p.wait() if status != 0 : logger.error("Program terminated with status: %d. stderr " \ "follows: %s" % ( status, stderr_output ) ) elif stderr_output: logger.error( "%s", stderr_output ) # TODO: Remove shape image files from the temporary directory. # Remove the temporary file. os.unlink(tmp_name) return stdout_output
def create(self, prog=None, format=None): """ Creates and returns a representation of the graph using the Graphviz layout program given by 'prog', according to the given format. Writes the graph to a temporary dot file and processes it with the program given by 'prog' (which defaults to 'dot'), reading the output and returning it as a string if the operation is successful. On failure None is returned. """ prog = self.program if prog is None else prog format = self.format if format is None else format # Make a temporary file ... tmp_fd, tmp_name = tempfile.mkstemp() os.close( tmp_fd ) # ... and save the graph to it. dot_fd = file( tmp_name, "w+b" ) self.save_dot( dot_fd ) dot_fd.close() # Get the temporary file directory name. tmp_dir = os.path.dirname( tmp_name ) # TODO: Shape image files (See PyDot). Important. # Process the file using the layout program, specifying the format. p = subprocess.Popen( ( self.programs[ prog ], '-T'+format, tmp_name ), cwd=tmp_dir, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stderr = p.stderr stdout = p.stdout # Make sense of the standard output form the process. stdout_output = list() while True: data = stdout.read() if not data: break stdout_output.append(data) stdout.close() if stdout_output: stdout_output = ''.join(stdout_output) # Similarly so for any standard error. if not stderr.closed: stderr_output = list() while True: data = stderr.read() if not data: break stderr_output.append(data) stderr.close() if stderr_output: stderr_output = ''.join(stderr_output) #pid, status = os.waitpid(p.pid, 0) status = p.wait() if status != 0 : logger.error("Program terminated with status: %d. stderr " \ "follows: %s" % ( status, stderr_output ) ) elif stderr_output: logger.error( "%s", stderr_output ) # TODO: Remove shape image files from the temporary directory. # Remove the temporary file. os.unlink(tmp_name) return stdout_output
[ "Creates", "and", "returns", "a", "representation", "of", "the", "graph", "using", "the", "Graphviz", "layout", "program", "given", "by", "prog", "according", "to", "the", "given", "format", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L340-L414
[ "def", "create", "(", "self", ",", "prog", "=", "None", ",", "format", "=", "None", ")", ":", "prog", "=", "self", ".", "program", "if", "prog", "is", "None", "else", "prog", "format", "=", "self", ".", "format", "if", "format", "is", "None", "else", "format", "# Make a temporary file ...", "tmp_fd", ",", "tmp_name", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "close", "(", "tmp_fd", ")", "# ... and save the graph to it.", "dot_fd", "=", "file", "(", "tmp_name", ",", "\"w+b\"", ")", "self", ".", "save_dot", "(", "dot_fd", ")", "dot_fd", ".", "close", "(", ")", "# Get the temporary file directory name.", "tmp_dir", "=", "os", ".", "path", ".", "dirname", "(", "tmp_name", ")", "# TODO: Shape image files (See PyDot). Important.", "# Process the file using the layout program, specifying the format.", "p", "=", "subprocess", ".", "Popen", "(", "(", "self", ".", "programs", "[", "prog", "]", ",", "'-T'", "+", "format", ",", "tmp_name", ")", ",", "cwd", "=", "tmp_dir", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "stderr", "=", "p", ".", "stderr", "stdout", "=", "p", ".", "stdout", "# Make sense of the standard output form the process.", "stdout_output", "=", "list", "(", ")", "while", "True", ":", "data", "=", "stdout", ".", "read", "(", ")", "if", "not", "data", ":", "break", "stdout_output", ".", "append", "(", "data", ")", "stdout", ".", "close", "(", ")", "if", "stdout_output", ":", "stdout_output", "=", "''", ".", "join", "(", "stdout_output", ")", "# Similarly so for any standard error.", "if", "not", "stderr", ".", "closed", ":", "stderr_output", "=", "list", "(", ")", "while", "True", ":", "data", "=", "stderr", ".", "read", "(", ")", "if", "not", "data", ":", "break", "stderr_output", ".", "append", "(", "data", ")", "stderr", ".", "close", "(", ")", "if", "stderr_output", ":", "stderr_output", "=", "''", ".", "join", "(", "stderr_output", ")", "#pid, status = os.waitpid(p.pid, 0)", "status", "=", "p", ".", "wait", "(", ")", "if", "status", "!=", "0", ":", "logger", ".", "error", "(", "\"Program terminated with status: %d. stderr \"", "\"follows: %s\"", "%", "(", "status", ",", "stderr_output", ")", ")", "elif", "stderr_output", ":", "logger", ".", "error", "(", "\"%s\"", ",", "stderr_output", ")", "# TODO: Remove shape image files from the temporary directory.", "# Remove the temporary file.", "os", ".", "unlink", "(", "tmp_name", ")", "return", "stdout_output" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph.add_node
Adds a node to the graph.
godot/base_graph.py
def add_node(self, node_or_ID, **kwds): """ Adds a node to the graph. """ if not isinstance(node_or_ID, Node): nodeID = str( node_or_ID ) if nodeID in self.nodes: node = self.nodes[ self.nodes.index(nodeID) ] else: if self.default_node is not None: node = self.default_node.clone_traits(copy="deep") node.ID = nodeID else: node = Node(nodeID) self.nodes.append( node ) else: node = node_or_ID if node in self.nodes: node = self.nodes[ self.nodes.index(node_or_ID) ] else: self.nodes.append( node ) node.set( **kwds ) return node
def add_node(self, node_or_ID, **kwds): """ Adds a node to the graph. """ if not isinstance(node_or_ID, Node): nodeID = str( node_or_ID ) if nodeID in self.nodes: node = self.nodes[ self.nodes.index(nodeID) ] else: if self.default_node is not None: node = self.default_node.clone_traits(copy="deep") node.ID = nodeID else: node = Node(nodeID) self.nodes.append( node ) else: node = node_or_ID if node in self.nodes: node = self.nodes[ self.nodes.index(node_or_ID) ] else: self.nodes.append( node ) node.set( **kwds ) return node
[ "Adds", "a", "node", "to", "the", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L436-L459
[ "def", "add_node", "(", "self", ",", "node_or_ID", ",", "*", "*", "kwds", ")", ":", "if", "not", "isinstance", "(", "node_or_ID", ",", "Node", ")", ":", "nodeID", "=", "str", "(", "node_or_ID", ")", "if", "nodeID", "in", "self", ".", "nodes", ":", "node", "=", "self", ".", "nodes", "[", "self", ".", "nodes", ".", "index", "(", "nodeID", ")", "]", "else", ":", "if", "self", ".", "default_node", "is", "not", "None", ":", "node", "=", "self", ".", "default_node", ".", "clone_traits", "(", "copy", "=", "\"deep\"", ")", "node", ".", "ID", "=", "nodeID", "else", ":", "node", "=", "Node", "(", "nodeID", ")", "self", ".", "nodes", ".", "append", "(", "node", ")", "else", ":", "node", "=", "node_or_ID", "if", "node", "in", "self", ".", "nodes", ":", "node", "=", "self", ".", "nodes", "[", "self", ".", "nodes", ".", "index", "(", "node_or_ID", ")", "]", "else", ":", "self", ".", "nodes", ".", "append", "(", "node", ")", "node", ".", "set", "(", "*", "*", "kwds", ")", "return", "node" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph.delete_node
Removes a node from the graph.
godot/base_graph.py
def delete_node(self, node_or_ID): """ Removes a node from the graph. """ if isinstance(node_or_ID, Node): # name = node_or_ID.ID node = node_or_ID else: # name = node_or_ID node = self.get_node(node_or_ID) if node is None: raise ValueError("Node %s does not exists" % node_or_ID) # try: # del self.nodes[name] # except: # raise ValueError("Node %s does not exists" % name) # self.nodes = [n for n in self.nodes if n.ID != name] # idx = self.nodes.index(name) # return self.nodes.pop(idx) self.nodes.remove(node)
def delete_node(self, node_or_ID): """ Removes a node from the graph. """ if isinstance(node_or_ID, Node): # name = node_or_ID.ID node = node_or_ID else: # name = node_or_ID node = self.get_node(node_or_ID) if node is None: raise ValueError("Node %s does not exists" % node_or_ID) # try: # del self.nodes[name] # except: # raise ValueError("Node %s does not exists" % name) # self.nodes = [n for n in self.nodes if n.ID != name] # idx = self.nodes.index(name) # return self.nodes.pop(idx) self.nodes.remove(node)
[ "Removes", "a", "node", "from", "the", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L462-L483
[ "def", "delete_node", "(", "self", ",", "node_or_ID", ")", ":", "if", "isinstance", "(", "node_or_ID", ",", "Node", ")", ":", "# name = node_or_ID.ID", "node", "=", "node_or_ID", "else", ":", "# name = node_or_ID", "node", "=", "self", ".", "get_node", "(", "node_or_ID", ")", "if", "node", "is", "None", ":", "raise", "ValueError", "(", "\"Node %s does not exists\"", "%", "node_or_ID", ")", "# try:", "# del self.nodes[name]", "# except:", "# raise ValueError(\"Node %s does not exists\" % name)", "# self.nodes = [n for n in self.nodes if n.ID != name]", "# idx = self.nodes.index(name)", "# return self.nodes.pop(idx)", "self", ".", "nodes", ".", "remove", "(", "node", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph.get_node
Returns the node with the given ID or None.
godot/base_graph.py
def get_node(self, ID): """ Returns the node with the given ID or None. """ for node in self.nodes: if node.ID == str(ID): return node return None
def get_node(self, ID): """ Returns the node with the given ID or None. """ for node in self.nodes: if node.ID == str(ID): return node return None
[ "Returns", "the", "node", "with", "the", "given", "ID", "or", "None", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L486-L492
[ "def", "get_node", "(", "self", ",", "ID", ")", ":", "for", "node", "in", "self", ".", "nodes", ":", "if", "node", ".", "ID", "==", "str", "(", "ID", ")", ":", "return", "node", "return", "None" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph.delete_edge
Removes an edge from the graph. Returns the deleted edge or None.
godot/base_graph.py
def delete_edge(self, tail_node_or_ID, head_node_or_ID): """ Removes an edge from the graph. Returns the deleted edge or None. """ if isinstance(tail_node_or_ID, Node): tail_node = tail_node_or_ID else: tail_node = self.get_node(tail_node_or_ID) if isinstance(head_node_or_ID, Node): head_node = head_node_or_ID else: head_node = self.get_node(head_node_or_ID) if (tail_node is None) or (head_node is None): return None for i, edge in enumerate(self.edges): if (edge.tail_node == tail_node) and (edge.head_node == head_node): edge = self.edges.pop(i) return edge return None
def delete_edge(self, tail_node_or_ID, head_node_or_ID): """ Removes an edge from the graph. Returns the deleted edge or None. """ if isinstance(tail_node_or_ID, Node): tail_node = tail_node_or_ID else: tail_node = self.get_node(tail_node_or_ID) if isinstance(head_node_or_ID, Node): head_node = head_node_or_ID else: head_node = self.get_node(head_node_or_ID) if (tail_node is None) or (head_node is None): return None for i, edge in enumerate(self.edges): if (edge.tail_node == tail_node) and (edge.head_node == head_node): edge = self.edges.pop(i) return edge return None
[ "Removes", "an", "edge", "from", "the", "graph", ".", "Returns", "the", "deleted", "edge", "or", "None", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L495-L516
[ "def", "delete_edge", "(", "self", ",", "tail_node_or_ID", ",", "head_node_or_ID", ")", ":", "if", "isinstance", "(", "tail_node_or_ID", ",", "Node", ")", ":", "tail_node", "=", "tail_node_or_ID", "else", ":", "tail_node", "=", "self", ".", "get_node", "(", "tail_node_or_ID", ")", "if", "isinstance", "(", "head_node_or_ID", ",", "Node", ")", ":", "head_node", "=", "head_node_or_ID", "else", ":", "head_node", "=", "self", ".", "get_node", "(", "head_node_or_ID", ")", "if", "(", "tail_node", "is", "None", ")", "or", "(", "head_node", "is", "None", ")", ":", "return", "None", "for", "i", ",", "edge", "in", "enumerate", "(", "self", ".", "edges", ")", ":", "if", "(", "edge", ".", "tail_node", "==", "tail_node", ")", "and", "(", "edge", ".", "head_node", "==", "head_node", ")", ":", "edge", "=", "self", ".", "edges", ".", "pop", "(", "i", ")", "return", "edge", "return", "None" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph.add_edge
Adds an edge to the graph.
godot/base_graph.py
def add_edge(self, tail_node_or_ID, head_node_or_ID, **kwds): """ Adds an edge to the graph. """ tail_node = self.add_node(tail_node_or_ID) head_node = self.add_node(head_node_or_ID) # Only top level graphs are directed and/or strict. if "directed" in self.trait_names(): directed = self.directed else: directed = False if self.default_edge is not None: edge = self.default_edge.clone_traits(copy="deep") edge.tail_node = tail_node edge.head_node = head_node edge.conn = "->" if directed else "--" edge.set( **kwds ) else: edge = Edge(tail_node, head_node, directed, **kwds) if "strict" in self.trait_names(): if not self.strict: self.edges.append(edge) else: self.edges.append(edge) # FIXME: Implement strict graphs. # raise NotImplementedError else: self.edges.append(edge)
def add_edge(self, tail_node_or_ID, head_node_or_ID, **kwds): """ Adds an edge to the graph. """ tail_node = self.add_node(tail_node_or_ID) head_node = self.add_node(head_node_or_ID) # Only top level graphs are directed and/or strict. if "directed" in self.trait_names(): directed = self.directed else: directed = False if self.default_edge is not None: edge = self.default_edge.clone_traits(copy="deep") edge.tail_node = tail_node edge.head_node = head_node edge.conn = "->" if directed else "--" edge.set( **kwds ) else: edge = Edge(tail_node, head_node, directed, **kwds) if "strict" in self.trait_names(): if not self.strict: self.edges.append(edge) else: self.edges.append(edge) # FIXME: Implement strict graphs. # raise NotImplementedError else: self.edges.append(edge)
[ "Adds", "an", "edge", "to", "the", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L519-L548
[ "def", "add_edge", "(", "self", ",", "tail_node_or_ID", ",", "head_node_or_ID", ",", "*", "*", "kwds", ")", ":", "tail_node", "=", "self", ".", "add_node", "(", "tail_node_or_ID", ")", "head_node", "=", "self", ".", "add_node", "(", "head_node_or_ID", ")", "# Only top level graphs are directed and/or strict.", "if", "\"directed\"", "in", "self", ".", "trait_names", "(", ")", ":", "directed", "=", "self", ".", "directed", "else", ":", "directed", "=", "False", "if", "self", ".", "default_edge", "is", "not", "None", ":", "edge", "=", "self", ".", "default_edge", ".", "clone_traits", "(", "copy", "=", "\"deep\"", ")", "edge", ".", "tail_node", "=", "tail_node", "edge", ".", "head_node", "=", "head_node", "edge", ".", "conn", "=", "\"->\"", "if", "directed", "else", "\"--\"", "edge", ".", "set", "(", "*", "*", "kwds", ")", "else", ":", "edge", "=", "Edge", "(", "tail_node", ",", "head_node", ",", "directed", ",", "*", "*", "kwds", ")", "if", "\"strict\"", "in", "self", ".", "trait_names", "(", ")", ":", "if", "not", "self", ".", "strict", ":", "self", ".", "edges", ".", "append", "(", "edge", ")", "else", ":", "self", ".", "edges", ".", "append", "(", "edge", ")", "# FIXME: Implement strict graphs.", "# raise NotImplementedError", "else", ":", "self", ".", "edges", ".", "append", "(", "edge", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph.add_subgraph
Adds a subgraph to the graph.
godot/base_graph.py
def add_subgraph(self, subgraph_or_ID): """ Adds a subgraph to the graph. """ if not isinstance(subgraph_or_ID, (godot.subgraph.Subgraph, godot.cluster.Cluster)): subgraphID = str( subgraph_or_ID ) if subgraph_or_ID.startswith("cluster"): subgraph = godot.cluster.Cluster(ID=subgraphID) else: subgraph = godot.subgraph.Subgraph(ID=subgraphID) else: subgraph = subgraph_or_ID subgraph.default_node = self.default_node subgraph.default_edge = self.default_edge # subgraph.level = self.level + 1 # subgraph.padding += self.padding if isinstance(subgraph, godot.subgraph.Subgraph): self.subgraphs.append(subgraph) elif isinstance(subgraph, godot.cluster.Cluster): self.clusters.append(subgraph) else: raise return subgraph
def add_subgraph(self, subgraph_or_ID): """ Adds a subgraph to the graph. """ if not isinstance(subgraph_or_ID, (godot.subgraph.Subgraph, godot.cluster.Cluster)): subgraphID = str( subgraph_or_ID ) if subgraph_or_ID.startswith("cluster"): subgraph = godot.cluster.Cluster(ID=subgraphID) else: subgraph = godot.subgraph.Subgraph(ID=subgraphID) else: subgraph = subgraph_or_ID subgraph.default_node = self.default_node subgraph.default_edge = self.default_edge # subgraph.level = self.level + 1 # subgraph.padding += self.padding if isinstance(subgraph, godot.subgraph.Subgraph): self.subgraphs.append(subgraph) elif isinstance(subgraph, godot.cluster.Cluster): self.clusters.append(subgraph) else: raise return subgraph
[ "Adds", "a", "subgraph", "to", "the", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L551-L576
[ "def", "add_subgraph", "(", "self", ",", "subgraph_or_ID", ")", ":", "if", "not", "isinstance", "(", "subgraph_or_ID", ",", "(", "godot", ".", "subgraph", ".", "Subgraph", ",", "godot", ".", "cluster", ".", "Cluster", ")", ")", ":", "subgraphID", "=", "str", "(", "subgraph_or_ID", ")", "if", "subgraph_or_ID", ".", "startswith", "(", "\"cluster\"", ")", ":", "subgraph", "=", "godot", ".", "cluster", ".", "Cluster", "(", "ID", "=", "subgraphID", ")", "else", ":", "subgraph", "=", "godot", ".", "subgraph", ".", "Subgraph", "(", "ID", "=", "subgraphID", ")", "else", ":", "subgraph", "=", "subgraph_or_ID", "subgraph", ".", "default_node", "=", "self", ".", "default_node", "subgraph", ".", "default_edge", "=", "self", ".", "default_edge", "# subgraph.level = self.level + 1", "# subgraph.padding += self.padding", "if", "isinstance", "(", "subgraph", ",", "godot", ".", "subgraph", ".", "Subgraph", ")", ":", "self", ".", "subgraphs", ".", "append", "(", "subgraph", ")", "elif", "isinstance", "(", "subgraph", ",", "godot", ".", "cluster", ".", "Cluster", ")", ":", "self", ".", "clusters", ".", "append", "(", "subgraph", ")", "else", ":", "raise", "return", "subgraph" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph._program_changed
Handles the Graphviz layout program selection changing.
godot/base_graph.py
def _program_changed(self, new): """ Handles the Graphviz layout program selection changing. """ progs = self.progs if not progs.has_key(prog): logger.warning( 'GraphViz\'s executable "%s" not found' % prog ) if not os.path.exists( progs[prog] ) or not \ os.path.isfile( progs[prog] ): logger.warning( "GraphViz's executable '%s' is not a " "file or doesn't exist" % progs[prog] )
def _program_changed(self, new): """ Handles the Graphviz layout program selection changing. """ progs = self.progs if not progs.has_key(prog): logger.warning( 'GraphViz\'s executable "%s" not found' % prog ) if not os.path.exists( progs[prog] ) or not \ os.path.isfile( progs[prog] ): logger.warning( "GraphViz's executable '%s' is not a " "file or doesn't exist" % progs[prog] )
[ "Handles", "the", "Graphviz", "layout", "program", "selection", "changing", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L589-L600
[ "def", "_program_changed", "(", "self", ",", "new", ")", ":", "progs", "=", "self", ".", "progs", "if", "not", "progs", ".", "has_key", "(", "prog", ")", ":", "logger", ".", "warning", "(", "'GraphViz\\'s executable \"%s\" not found'", "%", "prog", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "progs", "[", "prog", "]", ")", "or", "not", "os", ".", "path", ".", "isfile", "(", "progs", "[", "prog", "]", ")", ":", "logger", ".", "warning", "(", "\"GraphViz's executable '%s' is not a \"", "\"file or doesn't exist\"", "%", "progs", "[", "prog", "]", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
BaseGraph._set_node_lists
Maintains each edge's list of available nodes.
godot/base_graph.py
def _set_node_lists(self, new): """ Maintains each edge's list of available nodes. """ for edge in self.edges: edge._nodes = self.nodes
def _set_node_lists(self, new): """ Maintains each edge's list of available nodes. """ for edge in self.edges: edge._nodes = self.nodes
[ "Maintains", "each", "edge", "s", "list", "of", "available", "nodes", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/base_graph.py#L623-L627
[ "def", "_set_node_lists", "(", "self", ",", "new", ")", ":", "for", "edge", "in", "self", ".", "edges", ":", "edge", ".", "_nodes", "=", "self", ".", "nodes" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
parse_dot_file
Parses a DOT file and returns a Godot graph.
godot/dot_data_parser.py
def parse_dot_file(filename): """ Parses a DOT file and returns a Godot graph. """ parser = GodotDataParser() graph = parser.parse_dot_file(filename) del parser return graph
def parse_dot_file(filename): """ Parses a DOT file and returns a Godot graph. """ parser = GodotDataParser() graph = parser.parse_dot_file(filename) del parser return graph
[ "Parses", "a", "DOT", "file", "and", "returns", "a", "Godot", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/dot_data_parser.py#L223-L230
[ "def", "parse_dot_file", "(", "filename", ")", ":", "parser", "=", "GodotDataParser", "(", ")", "graph", "=", "parser", ".", "parse_dot_file", "(", "filename", ")", "del", "parser", "return", "graph" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GodotDataParser._proc_node_stmt
Return (ADD_NODE, node_name, options)
godot/dot_data_parser.py
def _proc_node_stmt(self, toks): """ Return (ADD_NODE, node_name, options) """ opts = toks[1] dummy_node = Node("dummy") # Coerce attribute types. for key, value in opts.iteritems(): trait = dummy_node.trait(key) if trait is not None: if trait.is_trait_type( Float ): opts[key] = float( value ) elif trait.is_trait_type( Tuple ): opts[key] = tuple( [float(c) for c in value.split(",")] ) return super(GodotDataParser, self)._proc_node_stmt(toks)
def _proc_node_stmt(self, toks): """ Return (ADD_NODE, node_name, options) """ opts = toks[1] dummy_node = Node("dummy") # Coerce attribute types. for key, value in opts.iteritems(): trait = dummy_node.trait(key) if trait is not None: if trait.is_trait_type( Float ): opts[key] = float( value ) elif trait.is_trait_type( Tuple ): opts[key] = tuple( [float(c) for c in value.split(",")] ) return super(GodotDataParser, self)._proc_node_stmt(toks)
[ "Return", "(", "ADD_NODE", "node_name", "options", ")" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/dot_data_parser.py#L51-L66
[ "def", "_proc_node_stmt", "(", "self", ",", "toks", ")", ":", "opts", "=", "toks", "[", "1", "]", "dummy_node", "=", "Node", "(", "\"dummy\"", ")", "# Coerce attribute types.", "for", "key", ",", "value", "in", "opts", ".", "iteritems", "(", ")", ":", "trait", "=", "dummy_node", ".", "trait", "(", "key", ")", "if", "trait", "is", "not", "None", ":", "if", "trait", ".", "is_trait_type", "(", "Float", ")", ":", "opts", "[", "key", "]", "=", "float", "(", "value", ")", "elif", "trait", ".", "is_trait_type", "(", "Tuple", ")", ":", "opts", "[", "key", "]", "=", "tuple", "(", "[", "float", "(", "c", ")", "for", "c", "in", "value", ".", "split", "(", "\",\"", ")", "]", ")", "return", "super", "(", "GodotDataParser", ",", "self", ")", ".", "_proc_node_stmt", "(", "toks", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GodotDataParser._proc_edge_stmt
Returns a tuple of the form (ADD_EDGE, src, dest, options).
godot/dot_data_parser.py
def _proc_edge_stmt(self, toks): """ Returns a tuple of the form (ADD_EDGE, src, dest, options). """ opts = toks[3] dummy_edge = Edge("dummy1", "dummy2") # Coerce attribute types. for key, value in opts.iteritems(): trait = dummy_edge.trait(key) if trait is not None: # FIXME: Implement Graphviz spline types. if trait.is_trait_type( List ): p = [] # List of float doublets. for t in value.split( " " ): l = t.split( "," ) if len(l) == 3: # pos="e,39,61 39,97 39,89 39,80 39,71" l.pop(0) f = [ float(a) for a in l ] p.append( tuple(f) ) opts[key] = p elif trait.is_trait_type( Float ): opts[key] = float( value ) elif trait.is_trait_type( Tuple ): opts[key] = tuple( [float(c) for c in value.split(",")] ) return super(GodotDataParser, self)._proc_edge_stmt(toks)
def _proc_edge_stmt(self, toks): """ Returns a tuple of the form (ADD_EDGE, src, dest, options). """ opts = toks[3] dummy_edge = Edge("dummy1", "dummy2") # Coerce attribute types. for key, value in opts.iteritems(): trait = dummy_edge.trait(key) if trait is not None: # FIXME: Implement Graphviz spline types. if trait.is_trait_type( List ): p = [] # List of float doublets. for t in value.split( " " ): l = t.split( "," ) if len(l) == 3: # pos="e,39,61 39,97 39,89 39,80 39,71" l.pop(0) f = [ float(a) for a in l ] p.append( tuple(f) ) opts[key] = p elif trait.is_trait_type( Float ): opts[key] = float( value ) elif trait.is_trait_type( Tuple ): opts[key] = tuple( [float(c) for c in value.split(",")] ) return super(GodotDataParser, self)._proc_edge_stmt(toks)
[ "Returns", "a", "tuple", "of", "the", "form", "(", "ADD_EDGE", "src", "dest", "options", ")", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/dot_data_parser.py#L69-L95
[ "def", "_proc_edge_stmt", "(", "self", ",", "toks", ")", ":", "opts", "=", "toks", "[", "3", "]", "dummy_edge", "=", "Edge", "(", "\"dummy1\"", ",", "\"dummy2\"", ")", "# Coerce attribute types.", "for", "key", ",", "value", "in", "opts", ".", "iteritems", "(", ")", ":", "trait", "=", "dummy_edge", ".", "trait", "(", "key", ")", "if", "trait", "is", "not", "None", ":", "# FIXME: Implement Graphviz spline types.", "if", "trait", ".", "is_trait_type", "(", "List", ")", ":", "p", "=", "[", "]", "# List of float doublets.", "for", "t", "in", "value", ".", "split", "(", "\" \"", ")", ":", "l", "=", "t", ".", "split", "(", "\",\"", ")", "if", "len", "(", "l", ")", "==", "3", ":", "# pos=\"e,39,61 39,97 39,89 39,80 39,71\"", "l", ".", "pop", "(", "0", ")", "f", "=", "[", "float", "(", "a", ")", "for", "a", "in", "l", "]", "p", ".", "append", "(", "tuple", "(", "f", ")", ")", "opts", "[", "key", "]", "=", "p", "elif", "trait", ".", "is_trait_type", "(", "Float", ")", ":", "opts", "[", "key", "]", "=", "float", "(", "value", ")", "elif", "trait", ".", "is_trait_type", "(", "Tuple", ")", ":", "opts", "[", "key", "]", "=", "tuple", "(", "[", "float", "(", "c", ")", "for", "c", "in", "value", ".", "split", "(", "\",\"", ")", "]", ")", "return", "super", "(", "GodotDataParser", ",", "self", ")", ".", "_proc_edge_stmt", "(", "toks", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GodotDataParser.parse_dot_file
Returns a graph given a file or a filename.
godot/dot_data_parser.py
def parse_dot_file(self, file_or_filename): """ Returns a graph given a file or a filename. """ if isinstance(file_or_filename, basestring): file = None try: file = open(file_or_filename, "rb") data = file.read() except: print "Could not open %s." % file_or_filename return None finally: if file is not None: file.close() else: file = file_or_filename data = file.read() return self.parse_dot_data(data)
def parse_dot_file(self, file_or_filename): """ Returns a graph given a file or a filename. """ if isinstance(file_or_filename, basestring): file = None try: file = open(file_or_filename, "rb") data = file.read() except: print "Could not open %s." % file_or_filename return None finally: if file is not None: file.close() else: file = file_or_filename data = file.read() return self.parse_dot_data(data)
[ "Returns", "a", "graph", "given", "a", "file", "or", "a", "filename", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/dot_data_parser.py#L98-L116
[ "def", "parse_dot_file", "(", "self", ",", "file_or_filename", ")", ":", "if", "isinstance", "(", "file_or_filename", ",", "basestring", ")", ":", "file", "=", "None", "try", ":", "file", "=", "open", "(", "file_or_filename", ",", "\"rb\"", ")", "data", "=", "file", ".", "read", "(", ")", "except", ":", "print", "\"Could not open %s.\"", "%", "file_or_filename", "return", "None", "finally", ":", "if", "file", "is", "not", "None", ":", "file", ".", "close", "(", ")", "else", ":", "file", "=", "file_or_filename", "data", "=", "file", ".", "read", "(", ")", "return", "self", ".", "parse_dot_data", "(", "data", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GodotDataParser.build_top_graph
Build a Godot graph instance from parsed data.
godot/dot_data_parser.py
def build_top_graph(self,tokens): """ Build a Godot graph instance from parsed data. """ # Get basic graph information. strict = tokens[0] == 'strict' graphtype = tokens[1] directed = graphtype == 'digraph' graphname = tokens[2] # Build the graph graph = Graph(ID=graphname, strict=strict, directed=directed) self.graph = self.build_graph(graph, tokens[3])
def build_top_graph(self,tokens): """ Build a Godot graph instance from parsed data. """ # Get basic graph information. strict = tokens[0] == 'strict' graphtype = tokens[1] directed = graphtype == 'digraph' graphname = tokens[2] # Build the graph graph = Graph(ID=graphname, strict=strict, directed=directed) self.graph = self.build_graph(graph, tokens[3])
[ "Build", "a", "Godot", "graph", "instance", "from", "parsed", "data", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/dot_data_parser.py#L119-L129
[ "def", "build_top_graph", "(", "self", ",", "tokens", ")", ":", "# Get basic graph information.", "strict", "=", "tokens", "[", "0", "]", "==", "'strict'", "graphtype", "=", "tokens", "[", "1", "]", "directed", "=", "graphtype", "==", "'digraph'", "graphname", "=", "tokens", "[", "2", "]", "# Build the graph", "graph", "=", "Graph", "(", "ID", "=", "graphname", ",", "strict", "=", "strict", ",", "directed", "=", "directed", ")", "self", ".", "graph", "=", "self", ".", "build_graph", "(", "graph", ",", "tokens", "[", "3", "]", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
GodotDataParser.build_graph
Builds a Godot graph.
godot/dot_data_parser.py
def build_graph(self, graph, tokens): """ Builds a Godot graph. """ subgraph = None for element in tokens: cmd = element[0] if cmd == ADD_NODE: cmd, nodename, opts = element graph.add_node(nodename, **opts) elif cmd == ADD_EDGE: cmd, src, dest, opts = element srcport = destport = "" if isinstance(src,tuple): srcport = src[1] src = src[0] if isinstance(dest,tuple): destport = dest[1] dest = dest[0] graph.add_edge(src, dest, tailport=srcport, headport=destport, **opts) elif cmd in [ADD_GRAPH_TO_NODE_EDGE, ADD_GRAPH_TO_GRAPH_EDGE, ADD_NODE_TO_GRAPH_EDGE]: cmd, src, dest, opts = element srcport = destport = "" if isinstance(src,tuple): srcport = src[1] if isinstance(dest,tuple): destport = dest[1] if not (cmd == ADD_NODE_TO_GRAPH_EDGE): if cmd == ADD_GRAPH_TO_NODE_EDGE: src = subgraph else: src = prev_subgraph dest = subgraph else: dest = subgraph src_is_graph = isinstance(src, (Subgraph, Cluster)) dst_is_graph = isinstance(dst, (Subgraph, Cluster)) if src_is_graph: src_nodes = src.nodes else: src_nodes = [src] if dst_is_graph: dst_nodes = dst.nodes else: dst_nodes = [dst] for src_node in src_nodes: for dst_node in dst_nodes: graph.add_edge(from_node=src_node, to_node=dst_node, tailport=srcport, headport=destport, **kwds) elif cmd == SET_GRAPH_ATTR: graph.set( **element[1] ) elif cmd == SET_DEF_NODE_ATTR: graph.default_node.set( **element[1] ) elif cmd == SET_DEF_EDGE_ATTR: graph.default_edge.set( **element[1] ) elif cmd == SET_DEF_GRAPH_ATTR: graph.default_graph.set( **element[1] ) elif cmd == ADD_SUBGRAPH: cmd, name, elements = element if subgraph: prev_subgraph = subgraph if name.startswith("cluster"): cluster = Cluster(ID=name) cluster = self.build_graph(cluster, elements) graph.add_cluster(cluster) else: subgraph = Subgraph(ID=name) subgraph = self.build_graph(subgraph, elements) graph.add_subgraph(subgraph) return graph
def build_graph(self, graph, tokens): """ Builds a Godot graph. """ subgraph = None for element in tokens: cmd = element[0] if cmd == ADD_NODE: cmd, nodename, opts = element graph.add_node(nodename, **opts) elif cmd == ADD_EDGE: cmd, src, dest, opts = element srcport = destport = "" if isinstance(src,tuple): srcport = src[1] src = src[0] if isinstance(dest,tuple): destport = dest[1] dest = dest[0] graph.add_edge(src, dest, tailport=srcport, headport=destport, **opts) elif cmd in [ADD_GRAPH_TO_NODE_EDGE, ADD_GRAPH_TO_GRAPH_EDGE, ADD_NODE_TO_GRAPH_EDGE]: cmd, src, dest, opts = element srcport = destport = "" if isinstance(src,tuple): srcport = src[1] if isinstance(dest,tuple): destport = dest[1] if not (cmd == ADD_NODE_TO_GRAPH_EDGE): if cmd == ADD_GRAPH_TO_NODE_EDGE: src = subgraph else: src = prev_subgraph dest = subgraph else: dest = subgraph src_is_graph = isinstance(src, (Subgraph, Cluster)) dst_is_graph = isinstance(dst, (Subgraph, Cluster)) if src_is_graph: src_nodes = src.nodes else: src_nodes = [src] if dst_is_graph: dst_nodes = dst.nodes else: dst_nodes = [dst] for src_node in src_nodes: for dst_node in dst_nodes: graph.add_edge(from_node=src_node, to_node=dst_node, tailport=srcport, headport=destport, **kwds) elif cmd == SET_GRAPH_ATTR: graph.set( **element[1] ) elif cmd == SET_DEF_NODE_ATTR: graph.default_node.set( **element[1] ) elif cmd == SET_DEF_EDGE_ATTR: graph.default_edge.set( **element[1] ) elif cmd == SET_DEF_GRAPH_ATTR: graph.default_graph.set( **element[1] ) elif cmd == ADD_SUBGRAPH: cmd, name, elements = element if subgraph: prev_subgraph = subgraph if name.startswith("cluster"): cluster = Cluster(ID=name) cluster = self.build_graph(cluster, elements) graph.add_cluster(cluster) else: subgraph = Subgraph(ID=name) subgraph = self.build_graph(subgraph, elements) graph.add_subgraph(subgraph) return graph
[ "Builds", "a", "Godot", "graph", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/dot_data_parser.py#L132-L220
[ "def", "build_graph", "(", "self", ",", "graph", ",", "tokens", ")", ":", "subgraph", "=", "None", "for", "element", "in", "tokens", ":", "cmd", "=", "element", "[", "0", "]", "if", "cmd", "==", "ADD_NODE", ":", "cmd", ",", "nodename", ",", "opts", "=", "element", "graph", ".", "add_node", "(", "nodename", ",", "*", "*", "opts", ")", "elif", "cmd", "==", "ADD_EDGE", ":", "cmd", ",", "src", ",", "dest", ",", "opts", "=", "element", "srcport", "=", "destport", "=", "\"\"", "if", "isinstance", "(", "src", ",", "tuple", ")", ":", "srcport", "=", "src", "[", "1", "]", "src", "=", "src", "[", "0", "]", "if", "isinstance", "(", "dest", ",", "tuple", ")", ":", "destport", "=", "dest", "[", "1", "]", "dest", "=", "dest", "[", "0", "]", "graph", ".", "add_edge", "(", "src", ",", "dest", ",", "tailport", "=", "srcport", ",", "headport", "=", "destport", ",", "*", "*", "opts", ")", "elif", "cmd", "in", "[", "ADD_GRAPH_TO_NODE_EDGE", ",", "ADD_GRAPH_TO_GRAPH_EDGE", ",", "ADD_NODE_TO_GRAPH_EDGE", "]", ":", "cmd", ",", "src", ",", "dest", ",", "opts", "=", "element", "srcport", "=", "destport", "=", "\"\"", "if", "isinstance", "(", "src", ",", "tuple", ")", ":", "srcport", "=", "src", "[", "1", "]", "if", "isinstance", "(", "dest", ",", "tuple", ")", ":", "destport", "=", "dest", "[", "1", "]", "if", "not", "(", "cmd", "==", "ADD_NODE_TO_GRAPH_EDGE", ")", ":", "if", "cmd", "==", "ADD_GRAPH_TO_NODE_EDGE", ":", "src", "=", "subgraph", "else", ":", "src", "=", "prev_subgraph", "dest", "=", "subgraph", "else", ":", "dest", "=", "subgraph", "src_is_graph", "=", "isinstance", "(", "src", ",", "(", "Subgraph", ",", "Cluster", ")", ")", "dst_is_graph", "=", "isinstance", "(", "dst", ",", "(", "Subgraph", ",", "Cluster", ")", ")", "if", "src_is_graph", ":", "src_nodes", "=", "src", ".", "nodes", "else", ":", "src_nodes", "=", "[", "src", "]", "if", "dst_is_graph", ":", "dst_nodes", "=", "dst", ".", "nodes", "else", ":", "dst_nodes", "=", "[", "dst", "]", "for", "src_node", "in", "src_nodes", ":", "for", "dst_node", "in", "dst_nodes", ":", "graph", ".", "add_edge", "(", "from_node", "=", "src_node", ",", "to_node", "=", "dst_node", ",", "tailport", "=", "srcport", ",", "headport", "=", "destport", ",", "*", "*", "kwds", ")", "elif", "cmd", "==", "SET_GRAPH_ATTR", ":", "graph", ".", "set", "(", "*", "*", "element", "[", "1", "]", ")", "elif", "cmd", "==", "SET_DEF_NODE_ATTR", ":", "graph", ".", "default_node", ".", "set", "(", "*", "*", "element", "[", "1", "]", ")", "elif", "cmd", "==", "SET_DEF_EDGE_ATTR", ":", "graph", ".", "default_edge", ".", "set", "(", "*", "*", "element", "[", "1", "]", ")", "elif", "cmd", "==", "SET_DEF_GRAPH_ATTR", ":", "graph", ".", "default_graph", ".", "set", "(", "*", "*", "element", "[", "1", "]", ")", "elif", "cmd", "==", "ADD_SUBGRAPH", ":", "cmd", ",", "name", ",", "elements", "=", "element", "if", "subgraph", ":", "prev_subgraph", "=", "subgraph", "if", "name", ".", "startswith", "(", "\"cluster\"", ")", ":", "cluster", "=", "Cluster", "(", "ID", "=", "name", ")", "cluster", "=", "self", ".", "build_graph", "(", "cluster", ",", "elements", ")", "graph", ".", "add_cluster", "(", "cluster", ")", "else", ":", "subgraph", "=", "Subgraph", "(", "ID", "=", "name", ")", "subgraph", "=", "self", ".", "build_graph", "(", "subgraph", ",", "elements", ")", "graph", ".", "add_subgraph", "(", "subgraph", ")", "return", "graph" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
get_time_units_and_multiplier
Given a duration in seconds, determines the best units and multiplier to use to display the time. Return value is a 2-tuple of units and multiplier.
elapsedtimer.py
def get_time_units_and_multiplier(seconds): """ Given a duration in seconds, determines the best units and multiplier to use to display the time. Return value is a 2-tuple of units and multiplier. """ for cutoff, units, multiplier in units_table: if seconds < cutoff: break return units, multiplier
def get_time_units_and_multiplier(seconds): """ Given a duration in seconds, determines the best units and multiplier to use to display the time. Return value is a 2-tuple of units and multiplier. """ for cutoff, units, multiplier in units_table: if seconds < cutoff: break return units, multiplier
[ "Given", "a", "duration", "in", "seconds", "determines", "the", "best", "units", "and", "multiplier", "to", "use", "to", "display", "the", "time", ".", "Return", "value", "is", "a", "2", "-", "tuple", "of", "units", "and", "multiplier", "." ]
flit/elapsedtimer
python
https://github.com/flit/elapsedtimer/blob/30cd61bb4e3f4dff4e13c7a3e49c410795224a4b/elapsedtimer.py#L68-L76
[ "def", "get_time_units_and_multiplier", "(", "seconds", ")", ":", "for", "cutoff", ",", "units", ",", "multiplier", "in", "units_table", ":", "if", "seconds", "<", "cutoff", ":", "break", "return", "units", ",", "multiplier" ]
30cd61bb4e3f4dff4e13c7a3e49c410795224a4b
test
format_duration
Formats a number of seconds using the best units.
elapsedtimer.py
def format_duration(seconds): """Formats a number of seconds using the best units.""" units, divider = get_time_units_and_multiplier(seconds) seconds *= divider return "%.3f %s" % (seconds, units)
def format_duration(seconds): """Formats a number of seconds using the best units.""" units, divider = get_time_units_and_multiplier(seconds) seconds *= divider return "%.3f %s" % (seconds, units)
[ "Formats", "a", "number", "of", "seconds", "using", "the", "best", "units", "." ]
flit/elapsedtimer
python
https://github.com/flit/elapsedtimer/blob/30cd61bb4e3f4dff4e13c7a3e49c410795224a4b/elapsedtimer.py#L78-L82
[ "def", "format_duration", "(", "seconds", ")", ":", "units", ",", "divider", "=", "get_time_units_and_multiplier", "(", "seconds", ")", "seconds", "*=", "divider", "return", "\"%.3f %s\"", "%", "(", "seconds", ",", "units", ")" ]
30cd61bb4e3f4dff4e13c7a3e49c410795224a4b
test
TreeEditor._name_default
Trait initialiser.
godot/plugin/tree_editor.py
def _name_default(self): """ Trait initialiser. """ # 'obj' is a io.File self.obj.on_trait_change(self.on_path, "path") return basename(self.obj.path)
def _name_default(self): """ Trait initialiser. """ # 'obj' is a io.File self.obj.on_trait_change(self.on_path, "path") return basename(self.obj.path)
[ "Trait", "initialiser", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/plugin/tree_editor.py#L71-L77
[ "def", "_name_default", "(", "self", ")", ":", "# 'obj' is a io.File", "self", ".", "obj", ".", "on_trait_change", "(", "self", ".", "on_path", ",", "\"path\"", ")", "return", "basename", "(", "self", ".", "obj", ".", "path", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
TreeEditor.on_path
Handle the file path changing.
godot/plugin/tree_editor.py
def on_path(self, new): """ Handle the file path changing. """ self.name = basename(new) self.graph = self.editor_input.load()
def on_path(self, new): """ Handle the file path changing. """ self.name = basename(new) self.graph = self.editor_input.load()
[ "Handle", "the", "file", "path", "changing", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/plugin/tree_editor.py#L80-L84
[ "def", "on_path", "(", "self", ",", "new", ")", ":", "self", ".", "name", "=", "basename", "(", "new", ")", "self", ".", "graph", "=", "self", ".", "editor_input", ".", "load", "(", ")" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
TreeEditor.create_ui
Creates the toolkit-specific control that represents the editor. 'parent' is the toolkit-specific control that is the editor's parent.
godot/plugin/tree_editor.py
def create_ui(self, parent): """ Creates the toolkit-specific control that represents the editor. 'parent' is the toolkit-specific control that is the editor's parent. """ self.graph = self.editor_input.load() view = View(Item(name="graph", editor=graph_tree_editor, show_label=False), id="godot.graph_editor", kind="live", resizable=True) ui = self.edit_traits(view=view, parent=parent, kind="subpanel") return ui
def create_ui(self, parent): """ Creates the toolkit-specific control that represents the editor. 'parent' is the toolkit-specific control that is the editor's parent. """ self.graph = self.editor_input.load() view = View(Item(name="graph", editor=graph_tree_editor, show_label=False), id="godot.graph_editor", kind="live", resizable=True) ui = self.edit_traits(view=view, parent=parent, kind="subpanel") return ui
[ "Creates", "the", "toolkit", "-", "specific", "control", "that", "represents", "the", "editor", ".", "parent", "is", "the", "toolkit", "-", "specific", "control", "that", "is", "the", "editor", "s", "parent", "." ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/plugin/tree_editor.py#L96-L109
[ "def", "create_ui", "(", "self", ",", "parent", ")", ":", "self", ".", "graph", "=", "self", ".", "editor_input", ".", "load", "(", ")", "view", "=", "View", "(", "Item", "(", "name", "=", "\"graph\"", ",", "editor", "=", "graph_tree_editor", ",", "show_label", "=", "False", ")", ",", "id", "=", "\"godot.graph_editor\"", ",", "kind", "=", "\"live\"", ",", "resizable", "=", "True", ")", "ui", "=", "self", ".", "edit_traits", "(", "view", "=", "view", ",", "parent", "=", "parent", ",", "kind", "=", "\"subpanel\"", ")", "return", "ui" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
nsplit
Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will split strings into individual characters. Examples: >>> nsplit("aabbcc") [("a", "a"), ("b", "b"), ("c", "c")] >>> nsplit("aabbcc",n=3) [("a", "a", "b"), ("b", "c", "c")] # Note that cc is discarded >>> nsplit("aabbcc",n=4) [("a", "a", "b", "b")]
godot/parsing_util.py
def nsplit(seq, n=2): """ Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will split strings into individual characters. Examples: >>> nsplit("aabbcc") [("a", "a"), ("b", "b"), ("c", "c")] >>> nsplit("aabbcc",n=3) [("a", "a", "b"), ("b", "c", "c")] # Note that cc is discarded >>> nsplit("aabbcc",n=4) [("a", "a", "b", "b")] """ return [xy for xy in itertools.izip(*[iter(seq)]*n)]
def nsplit(seq, n=2): """ Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will split strings into individual characters. Examples: >>> nsplit("aabbcc") [("a", "a"), ("b", "b"), ("c", "c")] >>> nsplit("aabbcc",n=3) [("a", "a", "b"), ("b", "c", "c")] # Note that cc is discarded >>> nsplit("aabbcc",n=4) [("a", "a", "b", "b")] """ return [xy for xy in itertools.izip(*[iter(seq)]*n)]
[ "Split", "a", "sequence", "into", "pieces", "of", "length", "n" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/parsing_util.py#L255-L273
[ "def", "nsplit", "(", "seq", ",", "n", "=", "2", ")", ":", "return", "[", "xy", "for", "xy", "in", "itertools", ".", "izip", "(", "*", "[", "iter", "(", "seq", ")", "]", "*", "n", ")", "]" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
test
windows
Code snippet from Python Cookbook, 2nd Edition by David Ascher, Alex Martelli and Anna Ravenscroft; O'Reilly 2005 Problem: You have an iterable s and need to make another iterable whose items are sublists (i.e., sliding windows), each of the same given length, over s' items, with successive windows overlapping by a specified amount.
godot/parsing_util.py
def windows(iterable, length=2, overlap=0, padding=True): """ Code snippet from Python Cookbook, 2nd Edition by David Ascher, Alex Martelli and Anna Ravenscroft; O'Reilly 2005 Problem: You have an iterable s and need to make another iterable whose items are sublists (i.e., sliding windows), each of the same given length, over s' items, with successive windows overlapping by a specified amount. """ it = iter(iterable) results = list(itertools.islice(it, length)) while len(results) == length: yield results results = results[length-overlap:] results.extend(itertools.islice(it, length-overlap)) if padding and results: results.extend(itertools.repeat(None, length-len(results))) yield results
def windows(iterable, length=2, overlap=0, padding=True): """ Code snippet from Python Cookbook, 2nd Edition by David Ascher, Alex Martelli and Anna Ravenscroft; O'Reilly 2005 Problem: You have an iterable s and need to make another iterable whose items are sublists (i.e., sliding windows), each of the same given length, over s' items, with successive windows overlapping by a specified amount. """ it = iter(iterable) results = list(itertools.islice(it, length)) while len(results) == length: yield results results = results[length-overlap:] results.extend(itertools.islice(it, length-overlap)) if padding and results: results.extend(itertools.repeat(None, length-len(results))) yield results
[ "Code", "snippet", "from", "Python", "Cookbook", "2nd", "Edition", "by", "David", "Ascher", "Alex", "Martelli", "and", "Anna", "Ravenscroft", ";", "O", "Reilly", "2005" ]
rwl/godot
python
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/parsing_util.py#L279-L297
[ "def", "windows", "(", "iterable", ",", "length", "=", "2", ",", "overlap", "=", "0", ",", "padding", "=", "True", ")", ":", "it", "=", "iter", "(", "iterable", ")", "results", "=", "list", "(", "itertools", ".", "islice", "(", "it", ",", "length", ")", ")", "while", "len", "(", "results", ")", "==", "length", ":", "yield", "results", "results", "=", "results", "[", "length", "-", "overlap", ":", "]", "results", ".", "extend", "(", "itertools", ".", "islice", "(", "it", ",", "length", "-", "overlap", ")", ")", "if", "padding", "and", "results", ":", "results", ".", "extend", "(", "itertools", ".", "repeat", "(", "None", ",", "length", "-", "len", "(", "results", ")", ")", ")", "yield", "results" ]
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f