text stringlengths 81 112k |
|---|
Query an object.
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if exactly one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool
def xor(cls, obj, **kwargs):
"""Query an object.
:param... |
Follow a kwargsql expression starting from a given object
and return the deduced object.
:param obj: the object to start from
:param list path: list of operations to perform. It does not contain
the optional operation of a traditional kwargsql
... |
Apply a kwargsql expression to every item of a sequence,
and returns it.
:param seq: the list to transform
:param path: kwargsql expression to apply to every elements of
the given sequence.
def _sequence_map(cls, seq, path):
"""Apply a kwargsql expression to every ... |
not operation
def _not(cls, operation):
"""not operation"""
def _wrap(*args, **kwargs):
return not operation(*args, **kwargs)
return _wrap |
Populate the list of projects that belong to this experiment.
Args:
projects_to_filter (list(Project)):
List of projects we want to assign to this experiment.
We intersect the list of projects with the list of supported
projects to get the list of projects that belong to... |
Return a clang that hides CFLAGS and LDFLAGS.
This will generate a wrapper script in the current directory
and return a complete plumbum command to it.
Args:
cflags: The CFLAGS we want to hide.
ldflags: The LDFLAGS we want to hide.
func (optional): A function that will be pickled a... |
Return a clang++ that hides CFLAGS and LDFLAGS.
This will generate a wrapper script in the current directory
and return a complete plumbum command to it.
Args:
cflags: The CFLAGS we want to hide.
ldflags: The LDFLAGS we want to hide.
func (optional): A function that will be pickled... |
Get a usable clang++ plumbum command.
This searches for a usable clang++ in the llvm binary path
Returns:
plumbum Command that executes clang++
def compiler(name):
"""
Get a usable clang++ plumbum command.
This searches for a usable clang++ in the llvm binary path
Returns:
p... |
Strip prefix from path.
Args:
ipath: input path
prefix: the prefix to remove, if it is found in :ipath:
Examples:
>>> strip_path_prefix("/foo/bar", "/bar")
'/foo/bar'
>>> strip_path_prefix("/foo/bar", "/")
'foo/bar'
>>> strip_path_prefix("/foo/bar", "/fo... |
Unpickle a python object from the given path.
def unpickle(pickle_file):
"""Unpickle a python object from the given path."""
pickle = None
with open(pickle_file, "rb") as pickle_f:
pickle = dill.load(pickle_f)
if not pickle:
LOG.error("Could not load python object from file")
return... |
Wrap the binary :name: with the runtime extension of the project.
This module generates a python tool that replaces :name:
The function in runner only accepts the replaced binaries
name as argument. We use the cloudpickle package to
perform the serialization, make sure :runner: can be serialized
wi... |
Substitute a compiler with a script that hides CFLAGS & LDFLAGS.
This will generate a wrapper script in the current directory
and return a complete plumbum command to it.
Args:
filepath (str): Path to the wrapper script.
compiler (benchbuild.utils.cmd):
Real compiler command we... |
Persist an object in the filesystem.
This will generate a pickled version of the given obj in the filename path.
Objects shall provide an id() method to be able to use this persistence API.
If not, we will use the id() builtin of python to generate an identifier
for you.
The file will be created, ... |
Load a pickled obj from the filesystem.
You better know what you expect from the given pickle, because we don't check it.
Args:
filename (str): The filename we load the object from.
Returns:
The object we were able to unpickle, else None.
def load(filename):
"""Load a pickled obj fro... |
Extend shape/polygon outline away from polygon center point by absolute
distance.
def extend_shapes(df_shapes, axis, distance):
'''
Extend shape/polygon outline away from polygon center point by absolute
distance.
'''
df_shapes_i = df_shapes.copy()
offsets = df_shapes_i[axis + '_center_offs... |
Generate list of connections between "adjacent" polygon shapes based on
geometrical "closeness".
Parameters
----------
df_shapes : pandas.DataFrame
Table of polygon shape vertices (one row per vertex).
Table rows with the same value in the :data:`shape_i_column` column
are grou... |
Return matrix where $a_{i,j} = 1$ indicates polygon $i$ is connected to
polygon $j$.
Also, return mapping (and reverse mapping) from original keys in
`df_connected` to zero-based integer index used for matrix rows and
columns.
def get_adjacency_matrix(df_connected):
'''
Return matrix where $a_... |
Load all ``<svg:line>`` elements and ``<svg:path>`` elements from a layer
of an SVG source. For each element, if endpoints overlap distinct shapes
in :data:`shapes_canvas`, add connection between overlapped shapes.
.. versionchanged:: 0.6.post1
Allow both ``<svg:line>`` *and* ``<svg:path>`` instan... |
Import all experiments listed in *_PLUGINS_REPORTS.
Tests:
>>> from benchbuild.settings import CFG
>>> from benchbuild.reports import discover
>>> import logging as lg
>>> import sys
>>> l = lg.getLogger('benchbuild')
>>> l.setLevel(lg.DEBUG)
>>> l.handlers =... |
Get Elasticsearch client
def es_client(self):
"""Get Elasticsearch client
"""
es_conf = self.campaign.export.elasticsearch
return Elasticsearch(self.hosts, **es_conf.connection_params) |
Get Elasticsearch index name associated to the campaign
def index_name(self):
"""Get Elasticsearch index name associated to the campaign
"""
fmt = self.campaign.export.elasticsearch.index_name
fields = dict(date=self.report['date'])
return fmt.format(**fields).lower() |
Remove Elasticsearch index associated to the campaign
def remove_index(self):
"""Remove Elasticsearch index associated to the campaign"""
self.index_client.close(self.index_name)
self.index_client.delete(self.index_name) |
Parses arguments, returns (options, args).
def parse_args(args=None):
"""Parses arguments, returns (options, args)."""
from argparse import ArgumentParser
if args is None:
args = sys.argv
parser = ArgumentParser(description='Rename template project with'
'hyphen-se... |
Extracts the build information from a given executable.
The build information is expected to be in json format, which is parsed
and returned as a dictionary.
If no build information is found an empty dictionary is returned.
This assumes binutils 2.25 to work.
Args:
exe_path (str): The ful... |
im: 图片字节
im_type: 题目类型
def rk_create(self, im, im_type, timeout=60):
"""
im: 图片字节
im_type: 题目类型
"""
params = {
'typeid': im_type,
'timeout': timeout,
}
params.update(self.base_params)
files = {'image': ('check_code.png', im... |
im_id:报错题目的ID
def rk_report_error(self, im_id):
"""
im_id:报错题目的ID
"""
params = {
'id': im_id,
}
params.update(self.base_params)
r = requests.post('http://api.ruokuai.com/reporterror.json', data=params, headers=self.headers)
return r.json() |
Evaluates the accuracy of a predictive measure (e.g. r-squared)
:param value: float, between 0.0 and 1.0.
:return:
def lc_score(value):
"""
Evaluates the accuracy of a predictive measure (e.g. r-squared)
:param value: float, between 0.0 and 1.0.
:return:
"""
rebased = 2 * (value - 0.5... |
Return a customizable uchroot command.
Args:
args: List of additional arguments for uchroot (typical: mounts)
Return:
chroot_cmd
def uchroot(*args, **kwargs):
"""
Return a customizable uchroot command.
Args:
args: List of additional arguments for uchroot (typical: mounts)
... |
Return a customizable uchroot command.
The command will be executed inside a uchroot environment.
Args:
args: List of additional arguments for uchroot (typical: mounts)
Return:
chroot_cmd
def no_llvm(*args, uid=0, gid=0, **kwargs):
"""
Return a customizable uchroot command.
T... |
Return the uchroot command without any customizations.
def no_args(**kwargs):
"""Return the uchroot command without any customizations."""
from benchbuild.utils.cmd import uchroot as uchrt
prefixes = CFG["container"]["prefixes"].value
p_paths, p_libs = env(prefixes)
uchrt = run.with_env_recursive(... |
Return a uchroot command with all mounts enabled.
def with_mounts(*args, uchroot_cmd_fn=no_args, **kwargs):
"""Return a uchroot command with all mounts enabled."""
mounts = CFG["container"]["mounts"].value
prefixes = CFG["container"]["prefixes"].value
uchroot_opts, mounts = __mounts__("mnt", mounts)
... |
Returns a uchroot cmd that runs inside a filtered environment.
def clean_env(uchroot_cmd, varnames):
"""Returns a uchroot cmd that runs inside a filtered environment."""
env = uchroot_cmd["/usr/bin/env"]
__clean_env = env["-u", ",".join(varnames)]
return __clean_env |
Compute the mountpoints of the current user.
Args:
prefix: Define where the job was running if it ran on a cluster.
mounts: All mounts the user currently uses in his file system.
Return:
mntpoints
def mounts(prefix, __mounts):
"""
Compute the mountpoints of the current user.
... |
Compute the environment of the change root for the user.
Args:
mounts: The mountpoints of the current user.
Return:
paths
ld_libs
def env(mounts):
"""
Compute the environment of the change root for the user.
Args:
mounts: The mountpoints of the current user.
Re... |
For the sake of profiling.
def get_abbreviations(kb):
"""
For the sake of profiling.
"""
return {"%s$$n%i" % (author.get_urn(), i): abbrev
for author in kb.get_authors()
for i, abbrev in enumerate(author.get_abbreviations())
if author.get_urn() is not Non... |
Returns a dictionary like this:
{
"urn:cts:greekLit:tlg0012$$n1" : "Homer"
, "urn:cts:greekLit:tlg0012$$n2" : "Omero"
, ...
}
def author_names(self):
"""
Returns a dictionary like this:
{
"urn:cts:greekLit:tlg0012$$n1" : "Homer"
... |
Fetch the resource corresponding to the input CTS URN.
Currently supports
only HucitAuthor and HucitWork.
:param urn: the CTS URN of the resource to fetch
:return: either an instance of `HucitAuthor` or of `HucitWork`
def get_resource_by_urn(self, urn):
"""Fetch the resource c... |
Searches for a given string through the resources' labels.
:param search_string:
:return: an instance of `HucitAuthor` or `HucitWork`.
def search(self, search_string):
"""
Searches for a given string through the resources' labels.
:param search_string:
:return: an inst... |
Returns the authors in the Knowledge Base.
:return: a list of `HucitAuthor` instances.
def get_authors(self):
"""
Returns the authors in the Knowledge Base.
:return: a list of `HucitAuthor` instances.
"""
Person = self._session.get_class(surf.ns.EFRBROO['F10_Person'])... |
Return the author's works.
:return: a list of `HucitWork` instances.
def get_works(self):
"""Return the author's works.
:return: a list of `HucitWork` instances.
"""
Work = self._session.get_class(surf.ns.EFRBROO['F1_Work'])
return list(Work.all()) |
Get the label corresponding to the author identified by the CTS URN.
try to get an lang=en label (if multiple labels in this lang pick the shortest)
try to get a lang=la label (if multiple labels in this lang exist pick the shortest)
try to get a lang=None label (if multiple labels in this lang... |
Gather basic stats about the Knowledge Base and its contents.
:return: a dictionary
def get_statistics(self):
"""
Gather basic stats about the Knowledge Base and its contents.
:return: a dictionary
"""
statistics = {
"number_authors": 0,
"numbe... |
Return the author's opux maximum (None otherwise).
Given the CTS URN of an author, this method returns its opus maximum.
If not available returns None.
:param author_cts_urn: the author's CTS URN.
:return: an instance of `surfext.HucitWork` or None
def get_opus_maximum_of(self, author... |
Serialises the content of the KnowledgeBase as JSON.
:return: TODO
def to_json(self):
"""
Serialises the content of the KnowledgeBase as JSON.
:return: TODO
"""
return json.dumps({
"statistics": self.get_statistics()
, "authors": [json.loads(aut... |
Decorator used in campaign node post-processing
def write_yaml_report(func):
"""Decorator used in campaign node post-processing
"""
@wraps(func)
def _wrapper(*args, **kwargs):
now = datetime.datetime.now()
with Timer() as timer:
data = func(*args, **kwargs)
if i... |
class function that MUST be specified as decorator
to the `__call__` method overriden by sub-classes.
def call_decorator(cls, func):
"""class function that MUST be specified as decorator
to the `__call__` method overriden by sub-classes.
"""
@wraps(func)
def _wrap(self,... |
Enumerate children and build associated objects
def traverse(self):
"""Enumerate children and build associated objects
"""
builder = self.child_builder
for child in self._children:
with pushd(str(child)):
yield child, builder(child) |
Second moment of inertia around the width axis.
:return:
def i_ww(self):
"""
Second moment of inertia around the width axis.
:return:
"""
d_values = []
for i in range(self.n_pads_l):
d_values.append(self.pad_position_l(i))
d_values = np.array(... |
Second moment of inertia around the length axis.
:return:
def i_ll(self):
"""
Second moment of inertia around the length axis.
:return:
"""
d_values = []
for i in range(self.n_pads_w):
d_values.append(self.pad_position_w(i))
d_values = np.arra... |
Determines the position of the ith pad in the length direction.
Assumes equally spaced pads.
:param i: ith number of pad in length direction (0-indexed)
:return:
def pad_position_l(self, i):
"""
Determines the position of the ith pad in the length direction.
Assumes equ... |
Determines the position of the ith pad in the width direction.
Assumes equally spaced pads.
:param i: ith number of pad in width direction (0-indexed)
:return:
def pad_position_w(self, i):
"""
Determines the position of the ith pad in the width direction.
Assumes equall... |
Adds paths to the given batch object. They are all added as
GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL
primitive.
def add_to_batch(self, batch):
'''
Adds paths to the given batch object. They are all added as
GL_TRIANGLES, so the batch will aggregate... |
Parse all <path> elements from xml_root.
Optional on_error arg specifies a callback function to be run when
an error occurs during parsing.
The specified on_error function must accept 3 arguments:
<svg filename>, <path_tag>, <error message>
An example on_error handler is pro... |
Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
def alphanum_key(s):
"""Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [int(c) if c.isdigit() else c for c in _RE_INT.split(s)] |
Import all experiments listed in PLUGINS_EXPERIMENTS.
Tests:
>>> from benchbuild.settings import CFG
>>> from benchbuild.experiments import discover
>>> import logging as lg
>>> import sys
>>> l = lg.getLogger('benchbuild')
>>> lg.getLogger('benchbuild').setLevel(lg.... |
Print a list of projects registered for that experiment.
Args:
exp: The experiment to print all projects for.
def print_projects(projects=None):
"""
Print a list of projects registered for that experiment.
Args:
exp: The experiment to print all projects for.
"""
grouped_by = ... |
Run a CTS API from command line.
.. warning:: This function should not be used in the production context
:param repositories:
:param port:
:param ip:
:param debug:
:param cache:
:param cache_path:
:return:
def _commandline(repositories,
port=8000, host="127.0.0.1", de... |
Escape string for LaTeX usage
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
def tex_escape(text):
"""Escape string for LaTeX usage
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
"""
conv = {
'... |
Generate report from a campaign
:param template: Jinja template to use, ``DEFAULT_TEMPLATE`` is used
if not specified
:param ostr: output file or filename. Default is standard output
def render(template=None, ostr=None, **kwargs):
"""Generate report from a campaign
:param template: Jinja template... |
Return two-ple containing:
- A `pymunk.Space` instance.
- A `pandas.Series` mapping each `pymunk.Body` object in the `Space` to a
shape index.
The `Body` to shape index mapping makes it possible to, for example, look
up the index of the convex shape associated with a `Body` returned by a
... |
Given a json file it creates a dictionary of sfsi objects
:param ffp: str, Full file path to json file
:param custom: dict, used to load custom objects, {model type: custom object}
:param verbose: int, console output
:return: dict
def load_json(ffp, custom=None, verbose=0):
"""
Given a json fi... |
Given a json string it creates a dictionary of sfsi objects
:param ffp: str, Full file path to json file
:param custom: dict, used to load custom objects, {model type: custom object}
:param meta: bool, if true then also return all ecp meta data in separate dict
:param verbose: int, console output
:... |
Given an ecp dictionary, build a dictionary of sfsi objects
:param ecp_dict: dict, engineering consistency project dictionary
:param custom: dict, used to load custom objects, {model type: custom object}
:param verbose: int, console output
:return: dict
def ecp_dict_to_objects(ecp_dict, custom_map=Non... |
Migrates and ECP file to the current version of sfsimodels
def migrate_ecp(in_ffp, out_ffp):
"""Migrates and ECP file to the current version of sfsimodels"""
objs, meta_data = load_json_and_meta(in_ffp)
ecp_output = Output()
for m_type in objs:
for instance in objs[m_type]:
ecp_outp... |
Convert models to json serialisable output
:param an_object: An instance of a model object
:param extras: A dictionary of extra variables that should be
:return:
def add_to_dict(self, an_object, extras=None):
"""
Convert models to json serialisable output
:param an_obj... |
Can add additional objects or dictionaries to output file that don't conform to standard objects.
:param mtype:
:param m_id:
:param serialisable_dict:
:return:
def add_to_output(self, mtype, m_id, serialisable_dict):
"""
Can add additional objects or dictionaries to out... |
Unhashed
def models(self):
"""Unhashed"""
models_dict = OrderedDict()
collected = []
for item in standard_types:
if item in self.unordered_models:
new_dict, replacement_dict = unhash_dict(self.unordered_models[item])
models_dict[item] = new_di... |
Get the number of available CPUs.
Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program.
Returns:
Number of avaialable CPUs.
def available_cpu_count() -> int:
"""
Get the number of ... |
Shell-Escape a yaml input string.
Args:
raw_str: The unescaped string.
def escape_yaml(raw_str: str) -> str:
"""
Shell-Escape a yaml input string.
Args:
raw_str: The unescaped string.
"""
escape_list = [char for char in raw_str if char in ['!', '{', '[']]
if len(escape_lis... |
Convert a given value to a YAML string.
def to_yaml(value) -> str:
"""Convert a given value to a YAML string."""
stream = yaml.io.StringIO()
dumper = ConfigDumper(stream, default_flow_style=True, width=sys.maxsize)
val = None
try:
dumper.open()
dumper.represent(value)
val = ... |
Create an environment variable from a name and a value.
This generates a shell-compatible representation of an
environment variable that is assigned a YAML representation of
a value.
Args:
env_var (str): Name of the environment variable.
value (Any): A value we convert from.
def to_en... |
Find the path to the default config file.
We look at :root: for the :default: config file. If we can't find it
there we start looking at the parent directory recursively until we
find a file named :default: and return the absolute path to it.
If we can't find anything, we return None.
Args:
... |
This will initialize the given configuration object.
The following resources are available in the same order:
1) Default settings.
2) Config file.
3) Environment variables.
WARNING: Environment variables do _not_ take precedence over the config
file right now. (init_from_e... |
Provide forward migration for configuration files.
def upgrade(cfg):
"""Provide forward migration for configuration files."""
db_node = cfg["db"]
old_db_elems = ["host", "name", "port", "pass", "user", "dialect"]
has_old_db_elems = [x in db_node for x in old_db_elems]
if any(has_old_db_elems):
... |
Construct a uuid.UUID object form a scalar YAML node.
Tests:
>>> yaml.add_constructor("!uuid", uuid_constructor, Loader=yaml.SafeLoader)
>>> yaml.safe_load("{'test': !uuid 'cc3702ca-699a-4aa6-8226-4c938f294d9b'}")
{'test': UUID('cc3702ca-699a-4aa6-8226-4c938f294d9b')}
def uuid_constructor(... |
Attach an implicit pattern resolver for UUID objects.
Tests:
>>> class TestDumper(yaml.SafeDumper): pass
>>> class TestLoader(yaml.SafeLoader): pass
>>> TUUID = 'cc3702ca-699a-4aa6-8226-4c938f294d9b'
>>> IN = {'test': uuid.UUID(TUUID)}
>>> OUT = '{test: cc3702ca-699a-4aa6-82... |
Store the configuration dictionary to a file.
def store(self, config_file):
""" Store the configuration dictionary to a file."""
selfcopy = copy.deepcopy(self)
selfcopy.filter_exports()
with open(config_file, 'w') as outf:
yaml.dump(
selfcopy.node,
... |
Load the configuration dictionary from file.
def load(self, _from):
"""Load the configuration dictionary from file."""
def load_rec(inode, config):
"""Recursive part of loading."""
for k in config:
if isinstance(config[k], dict) and \
k not in... |
Initialize this node from environment.
If we're a leaf node, i.e., a node containing a dictionary that
consist of a 'default' key, compute our env variable and initialize
our value from the environment.
Otherwise, init our children.
def init_from_env(self):
"""
Initiali... |
Return the node value, if we're a leaf node.
Examples:
>>> c = Configuration("test")
>>> c['x'] = { "y" : { "value" : None }, "z" : { "value" : 2 }}
>>> c['x']['y'].value == None
True
>>> c['x']['z'].value
2
>>> c['x'].value
... |
Convert configuration object to a flat dictionary.
def to_env_dict(self):
"""Convert configuration object to a flat dictionary."""
entries = {}
if self.has_value():
return {self.__to_env_var__(): self.node['value']}
if self.has_default():
return {self.__to_env_va... |
New record with same keys or renamed keys if key found in key_map.
def rename_keys(record: Mapping, key_map: Mapping) -> dict:
"""New record with same keys or renamed keys if key found in key_map."""
new_record = dict()
for k, v in record.items():
key = key_map[k] if k in key_map else k
n... |
New record with renamed keys including keys only found in key_map.
def replace_keys(record: Mapping, key_map: Mapping) -> dict:
"""New record with renamed keys including keys only found in key_map."""
return {key_map[k]: v for k, v in record.items() if k in key_map} |
Insert None as value for missing fields.
def inject_nulls(data: Mapping, field_names) -> dict:
"""Insert None as value for missing fields."""
record = dict()
for field in field_names:
record[field] = data.get(field, None)
return record |
Read a likwid struct from the text stream.
Args:
fstream: Likwid's filestream.
Returns (dict(str: str)):
A dict containing all likwid's struct info as key/value pairs.
def read_struct(fstream):
"""
Read a likwid struct from the text stream.
Args:
fstream: Likwid's filestr... |
Read a likwid table info from the text stream.
Args:
fstream: Likwid's filestream.
Returns (dict(str: str)):
A dict containing likwid's table info as key/value pairs.
def read_table(fstream):
"""
Read a likwid table info from the text stream.
Args:
fstream: Likwid's files... |
Read all structs from likwid's file stream.
Args:
fstream: Likwid's output file stream.
Returns:
A generator that can be used to iterate over all structs in the
fstream.
def read_structs(fstream):
"""
Read all structs from likwid's file stream.
Args:
fstream: Likw... |
Read all tables from likwid's file stream.
Args:
fstream: Likwid's output file stream.
Returns:
A generator that can be used to iterate over all tables in the fstream.
def read_tables(fstream):
"""
Read all tables from likwid's file stream.
Args:
fstream: Likwid's output ... |
Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (int): default = 0
Returns (list((region, metric, core, value))):
A list of measurement tupl... |
Get a complete list of all measurements.
Args:
infile: The filestream containing all likwid output.
Returns:
A list of all measurements extracted from likwid's file stream.
def perfcounters(infile):
"""
Get a complete list of all measurements.
Args:
infile: The filestream... |
Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
def setup_logger(verbose, logfile):
"""Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level
"""
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif... |
Program initialization for all provided executables
def cli_common(doc, **kwargs):
"""Program initialization for all provided executables
"""
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'], arguments['--log'])
load_components()
try:
imp... |
Parameters
----------
svg_path_d : str
``"d"`` attribute of SVG ``path`` element.
Returns
-------
list
List of coordinates of points found in SVG path.
Each point is represented by a dictionary with keys ``x`` and ``y``.
def shape_path_points(svg_path_d):
'''
Param... |
Construct a data frame with one row per vertex for all shapes in
:data:`svg_source``.
Arguments
---------
svg_source : str or file-like
A file path, URI, or file-like object.
xpath : str, optional
XPath path expression to select shape nodes.
By default, all ``svg:path`` and... |
Construct a data frame with one row per vertex for all shapes (e.g.,
``svg:path``, ``svg:polygon``) in :data:`svg_source``.
Arguments
---------
svg_source : str or file-like
A file path, URI, or file-like object.
xpath : str, optional
XPath path expression to select shape nodes.
... |
Compute the center point of each polygon shape, and the offset of each
vertex to the corresponding polygon center point.
Parameters
----------
df_shapes : pandas.DataFrame
Table of polygon shape vertices (one row per vertex).
Must have at least the following columns:
- ``verte... |
Translate points such that bounding box is anchored at (0, 0) and scale
``x`` and ``y`` columns of input frame by specified :data:`scale`.
Parameters
----------
df_points : pandas.DataFrame
Table of ``x``/``y`` point positions.
Must have at least the following columns:
- ``x``... |
Return scale factor (scalar float) to fit `a_shape` into `b_shape` while
maintaining aspect ratio.
Arguments
---------
a_shape, b_shape : pandas.Series
Input shapes containing numeric `width` and `height` values.
Returns
-------
float
Scale factor to fit :data:`a_shape` int... |
Return data frame with ``x``, ``y`` columns scaled to fit points from
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A frame with at least the columns ``x`` and ``y``, containing one row
per point.
... |
Return offset and scale factor to scale ``x``, ``y`` columns of
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A frame with at least the columns ``x`` and ``y``, containing one row
per point.
boundi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.