code large_stringlengths 52 373k | docstring large_stringlengths 3 47.2k | language large_stringclasses 6
values |
|---|---|---|
def _nth(arr, n):
"""
Return the nth value of array
If it is missing return NaN
"""
try:
return arr.iloc[n]
except (KeyError, IndexError):
return np.nan | Return the nth value of array
If it is missing return NaN | python |
def make_time(h=0, m=0, s=0, ms=0, frames=None, fps=None):
"""
Convert time to milliseconds.
See :func:`pysubs2.time.times_to_ms()`. When both frames and fps are specified,
:func:`pysubs2.time.frames_to_ms()` is called instead.
Raises:
ValueError: Invalid fps, or one of frames/fps is missi... | Convert time to milliseconds.
See :func:`pysubs2.time.times_to_ms()`. When both frames and fps are specified,
:func:`pysubs2.time.frames_to_ms()` is called instead.
Raises:
ValueError: Invalid fps, or one of frames/fps is missing.
Example:
>>> make_time(s=1.5)
1500
>>>... | python |
def shift(self, h=0, m=0, s=0, ms=0, frames=None, fps=None):
"""
Shift start and end times.
See :meth:`SSAFile.shift()` for full description.
"""
delta = make_time(h=h, m=m, s=s, ms=ms, frames=frames, fps=fps)
self.start += delta
self.end += delta | Shift start and end times.
See :meth:`SSAFile.shift()` for full description. | python |
def equals(self, other):
"""Field-based equality for SSAEvents."""
if isinstance(other, SSAEvent):
return self.as_dict() == other.as_dict()
else:
raise TypeError("Cannot compare to non-SSAEvent object") | Field-based equality for SSAEvents. | python |
def load(cls, path, encoding="utf-8", format_=None, fps=None, **kwargs):
"""
Load subtitle file from given path.
Arguments:
path (str): Path to subtitle file.
encoding (str): Character encoding of input file.
Defaults to UTF-8, you may need to change this... | Load subtitle file from given path.
Arguments:
path (str): Path to subtitle file.
encoding (str): Character encoding of input file.
Defaults to UTF-8, you may need to change this.
format_ (str): Optional, forces use of specific parser
(eg. `"s... | python |
def from_string(cls, string, format_=None, fps=None, **kwargs):
"""
Load subtitle file from string.
See :meth:`SSAFile.load()` for full description.
Arguments:
string (str): Subtitle file in a string. Note that the string
must be Unicode (in Python 2).
... | Load subtitle file from string.
See :meth:`SSAFile.load()` for full description.
Arguments:
string (str): Subtitle file in a string. Note that the string
must be Unicode (in Python 2).
Returns:
SSAFile
Example:
>>> text = '''
... | python |
def from_file(cls, fp, format_=None, fps=None, **kwargs):
"""
Read subtitle file from file object.
See :meth:`SSAFile.load()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.load()`
or :meth:`SSAFile.from_string()` is prefe... | Read subtitle file from file object.
See :meth:`SSAFile.load()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.load()`
or :meth:`SSAFile.from_string()` is preferable.
Arguments:
fp (file object): A file object, ie. :c... | python |
def save(self, path, encoding="utf-8", format_=None, fps=None, **kwargs):
"""
Save subtitle file to given path.
Arguments:
path (str): Path to subtitle file.
encoding (str): Character encoding of output file.
Defaults to UTF-8, which should be fine for mo... | Save subtitle file to given path.
Arguments:
path (str): Path to subtitle file.
encoding (str): Character encoding of output file.
Defaults to UTF-8, which should be fine for most purposes.
format_ (str): Optional, specifies desired subtitle format
... | python |
def to_string(self, format_, fps=None, **kwargs):
"""
Get subtitle file as a string.
See :meth:`SSAFile.save()` for full description.
Returns:
str
"""
fp = io.StringIO()
self.to_file(fp, format_, fps=fps, **kwargs)
return fp.getvalue() | Get subtitle file as a string.
See :meth:`SSAFile.save()` for full description.
Returns:
str | python |
def to_file(self, fp, format_, fps=None, **kwargs):
"""
Write subtitle file to file object.
See :meth:`SSAFile.save()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.save()`
or :meth:`SSAFile.to_string()` is preferable.
... | Write subtitle file to file object.
See :meth:`SSAFile.save()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.save()`
or :meth:`SSAFile.to_string()` is preferable.
Arguments:
fp (file object): A file object, ie. :clas... | python |
def rename_style(self, old_name, new_name):
"""
Rename a style, including references to it.
Arguments:
old_name (str): Style to be renamed.
new_name (str): New name for the style (must be unused).
Raises:
KeyError: No style named old_name.
... | Rename a style, including references to it.
Arguments:
old_name (str): Style to be renamed.
new_name (str): New name for the style (must be unused).
Raises:
KeyError: No style named old_name.
ValueError: new_name is not a legal name (cannot use commas)
... | python |
def import_styles(self, subs, overwrite=True):
"""
Merge in styles from other SSAFile.
Arguments:
subs (SSAFile): Subtitle file imported from.
overwrite (bool): On name conflict, use style from the other file
(default: True).
"""
if not i... | Merge in styles from other SSAFile.
Arguments:
subs (SSAFile): Subtitle file imported from.
overwrite (bool): On name conflict, use style from the other file
(default: True). | python |
def equals(self, other):
"""
Equality of two SSAFiles.
Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`.
Order of entries in OrderedDicts does not matter. "ScriptType" key in info is
considered an implementation detail and thus ignored.
U... | Equality of two SSAFiles.
Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`.
Order of entries in OrderedDicts does not matter. "ScriptType" key in info is
considered an implementation detail and thus ignored.
Useful mostly in unit tests. Differences are l... | python |
def get_file_extension(format_):
"""Format identifier -> file extension"""
if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS:
raise UnknownFormatIdentifierError(format_)
for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items():
if f == format_:
return ext
raise RuntimeEr... | Format identifier -> file extension | python |
def autodetect_format(content):
"""Return format identifier for given fragment or raise FormatAutodetectionError."""
formats = set()
for impl in FORMAT_IDENTIFIER_TO_FORMAT_CLASS.values():
guess = impl.guess_format(content)
if guess is not None:
formats.add(guess)
if len(for... | Return format identifier for given fragment or raise FormatAutodetectionError. | python |
async def src_reload(app, path: str = None):
"""
prompt each connected browser to reload by sending websocket message.
:param path: if supplied this must be a path relative to app['static_path'],
eg. reload of a single file is only supported for static resources.
:return: number of sources relo... | prompt each connected browser to reload by sending websocket message.
:param path: if supplied this must be a path relative to app['static_path'],
eg. reload of a single file is only supported for static resources.
:return: number of sources reloaded | python |
def substitute_environ(self):
"""
Substitute environment variables into settings.
"""
for attr_name in dir(self):
if attr_name.startswith('_') or attr_name.upper() != attr_name:
continue
orig_value = getattr(self, attr_name)
is_require... | Substitute environment variables into settings. | python |
def serve(path, livereload, port, verbose):
"""
Serve static files from a directory.
"""
setup_logging(verbose)
run_app(*serve_static(static_path=path, livereload=livereload, port=port)) | Serve static files from a directory. | python |
def runserver(**config):
"""
Run a development server for an aiohttp apps.
Takes one argument "app-path" which should be a path to either a directory containing a recognized default file
("app.py" or "main.py") or to a specific file. Defaults to the environment variable "AIO_APP_PATH" or ".".
The ... | Run a development server for an aiohttp apps.
Takes one argument "app-path" which should be a path to either a directory containing a recognized default file
("app.py" or "main.py") or to a specific file. Defaults to the environment variable "AIO_APP_PATH" or ".".
The app path is run directly, see the "--... | python |
def scenario(weight=1, delay=0.0, name=None):
"""Decorator to register a function as a Molotov test.
Options:
- **weight** used by Molotov when the scenarii are randomly picked.
The functions with the highest values are more likely to be picked.
Integer, defaults to 1. This value is ignored wh... | Decorator to register a function as a Molotov test.
Options:
- **weight** used by Molotov when the scenarii are randomly picked.
The functions with the highest values are more likely to be picked.
Integer, defaults to 1. This value is ignored when the
*scenario_picker* decorator is used.
... | python |
def request(endpoint, verb='GET', session_options=None, **options):
"""Performs a synchronous request.
Uses a dedicated event loop and aiohttp.ClientSession object.
Options:
- endpoint: the endpoint to call
- verb: the HTTP verb to use (defaults: GET)
- session_options: a dict containing opti... | Performs a synchronous request.
Uses a dedicated event loop and aiohttp.ClientSession object.
Options:
- endpoint: the endpoint to call
- verb: the HTTP verb to use (defaults: GET)
- session_options: a dict containing options to initialize the session
(defaults: None)
- options: extra o... | python |
def get_var(name, factory=None):
"""Gets a global variable given its name.
If factory is not None and the variable is not set, factory
is a callable that will set the variable.
If not set, returns None.
"""
if name not in _VARS and factory is not None:
_VARS[name] = factory()
retur... | Gets a global variable given its name.
If factory is not None and the variable is not set, factory
is a callable that will set the variable.
If not set, returns None. | python |
async def step(self, step_id, session, scenario=None):
""" single scenario call.
When it returns 1, it works. -1 the script failed,
0 the test is stopping or needs to stop.
"""
if scenario is None:
scenario = pick_scenario(self.wid, step_id)
try:
... | single scenario call.
When it returns 1, it works. -1 the script failed,
0 the test is stopping or needs to stop. | python |
def main():
"""Moloslave clones a git repo and runs a molotov test
"""
parser = argparse.ArgumentParser(description='Github-based load test')
parser.add_argument('--version', action='store_true', default=False,
help='Displays version and exits.')
parser.add_argument('--virt... | Moloslave clones a git repo and runs a molotov test | python |
def copy_files(source_files, target_directory, source_directory=None):
"""Copies a list of files to the specified directory.
If source_directory is provided, it will be prepended to each source file."""
try:
os.makedirs(target_directory)
except: # TODO: specific exception?
pass
f... | Copies a list of files to the specified directory.
If source_directory is provided, it will be prepended to each source file. | python |
def yes_or_no(message):
"""Gets user input and returns True for yes and False for no."""
while True:
print message, '(yes/no)',
line = raw_input()
if line is None:
return None
line = line.lower()
if line == 'y' or line == 'ye' or line == 'yes':
ret... | Gets user input and returns True for yes and False for no. | python |
def add_plugin(plugin, directory=None):
"""Adds the specified plugin. This returns False if it was already added."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins', expect_type=dict)
if plugin in plugins:
return False
plugins[plugin] = {}
set_value(repo, 'plugins', p... | Adds the specified plugin. This returns False if it was already added. | python |
def get_plugin_settings(plugin, directory=None):
"""Gets the settings for the specified plugin."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins')
return plugins.get(plugin) if isinstance(plugins, dict) else None | Gets the settings for the specified plugin. | python |
def preview(directory=None, host=None, port=None, watch=True):
"""Runs a local server to preview the working directory of a repository."""
directory = directory or '.'
host = host or '127.0.0.1'
port = port or 5000
# TODO: admin interface
# TODO: use cache_only to keep from modifying output di... | Runs a local server to preview the working directory of a repository. | python |
def require_repo(directory=None):
"""Checks for a presentation repository and raises an exception if not found."""
if directory and not os.path.isdir(directory):
raise ValueError('Directory not found: ' + repr(directory))
repo = repo_path(directory)
if not os.path.isdir(repo):
raise Repo... | Checks for a presentation repository and raises an exception if not found. | python |
def init(directory=None):
"""Initializes a Gitpress presentation repository at the specified directory."""
repo = repo_path(directory)
if os.path.isdir(repo):
raise RepositoryAlreadyExistsError(directory, repo)
# Initialize repository with default template
shutil.copytree(default_template_p... | Initializes a Gitpress presentation repository at the specified directory. | python |
def iterate_presentation_files(path=None, excludes=None, includes=None):
"""Iterates the repository presentation files relative to 'path',
not including themes. Note that 'includes' take priority."""
# Defaults
if includes is None:
includes = []
if excludes is None:
excludes = []
... | Iterates the repository presentation files relative to 'path',
not including themes. Note that 'includes' take priority. | python |
def read_config_file(path):
"""Returns the configuration from the specified file."""
try:
with open(path, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict)
except IOError as ex:
if ex != errno.ENOENT:
raise
return {} | Returns the configuration from the specified file. | python |
def write_config(repo_directory, config):
"""Writes the specified configuration to the presentation repository."""
return write_config_file(os.path.join(repo_directory, config_file), config) | Writes the specified configuration to the presentation repository. | python |
def write_config_file(path, config):
"""Writes the specified configuration to the specified file."""
contents = json.dumps(config, indent=4, separators=(',', ': ')) + '\n'
try:
with open(path, 'w') as f:
f.write(contents)
return True
except IOError as ex:
if ex != err... | Writes the specified configuration to the specified file. | python |
def get_value(repo_directory, key, expect_type=None):
"""Gets the value of the specified key in the config file."""
config = read_config(repo_directory)
value = config.get(key)
if expect_type and value is not None and not isinstance(value, expect_type):
raise ConfigSchemaError('Expected config v... | Gets the value of the specified key in the config file. | python |
def set_value(repo_directory, key, value, strict=True):
"""Sets the value of a particular key in the config file. This has no effect when setting to the same value."""
if value is None:
raise ValueError('Argument "value" must not be None.')
# Read values and do nothing if not making any changes
... | Sets the value of a particular key in the config file. This has no effect when setting to the same value. | python |
def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mista... | Builds the site from its content and presentation repository. | python |
def gpp(argv=None):
"""Shortcut function for running the previewing command."""
if argv is None:
argv = sys.argv[1:]
argv.insert(0, 'preview')
return main(argv) | Shortcut function for running the previewing command. | python |
def use_theme(theme, directory=None):
"""Switches to the specified theme. This returns False if switching to the already active theme."""
repo = require_repo(directory)
if theme not in list_themes(directory):
raise ThemeNotFoundError(theme)
old_theme = set_value(repo, 'theme', theme)
return... | Switches to the specified theme. This returns False if switching to the already active theme. | python |
def data_type(data, grouped=False, columns=None, key_on='idx', iter_idx=None):
'''Data type check for automatic import'''
if iter_idx:
return Data.from_mult_iters(idx=iter_idx, **data)
if pd:
if isinstance(data, (pd.Series, pd.DataFrame)):
return Data.from_pandas(data, grouped=gr... | Data type check for automatic import | python |
def rebind(self, column=None, brew='GnBu'):
"""Bind a new column to the data map
Parameters
----------
column: str, default None
Pandas DataFrame column name
brew: str, default None
Color brewer abbreviation. See colors.py
"""
self.data['... | Bind a new column to the data map
Parameters
----------
column: str, default None
Pandas DataFrame column name
brew: str, default None
Color brewer abbreviation. See colors.py | python |
def axis_titles(self, x=None, y=None):
"""Apply axis titles to the figure.
This is a convenience method for manually modifying the "Axes" mark.
Parameters
----------
x: string, default 'null'
X-axis title
y: string, default 'null'
Y-axis title
... | Apply axis titles to the figure.
This is a convenience method for manually modifying the "Axes" mark.
Parameters
----------
x: string, default 'null'
X-axis title
y: string, default 'null'
Y-axis title
Example
-------
>>>vis.axis... | python |
def _set_axis_properties(self, axis):
"""Set AxisProperties and PropertySets"""
if not getattr(axis, 'properties'):
axis.properties = AxisProperties()
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks',
'title', 'labels']:
setattr(... | Set AxisProperties and PropertySets | python |
def _set_all_axis_color(self, axis, color):
"""Set axis ticks, title, labels to given color"""
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title',
'labels']:
prop_set = getattr(axis.properties, prop)
if color and prop in ['title', 'labels']:
... | Set axis ticks, title, labels to given color | python |
def _axis_properties(self, axis, title_size, title_offset, label_angle,
label_align, color):
"""Assign axis properties"""
if self.axes:
axis = [a for a in self.axes if a.scale == axis][0]
self._set_axis_properties(axis)
self._set_all_axis_colo... | Assign axis properties | python |
def common_axis_properties(self, color=None, title_size=None):
"""Set common axis properties such as color
Parameters
----------
color: str, default None
Hex color str, etc
"""
if self.axes:
for axis in self.axes:
self._set_axis_pr... | Set common axis properties such as color
Parameters
----------
color: str, default None
Hex color str, etc | python |
def x_axis_properties(self, title_size=None, title_offset=None,
label_angle=None, label_align=None, color=None):
"""Change x-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_off... | Change x-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
labe... | python |
def y_axis_properties(self, title_size=None, title_offset=None,
label_angle=None, label_align=None, color=None):
"""Change y-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_off... | Change y-axis title font size and label angle
Parameters
----------
title_size: int, default None
Title size, in px
title_offset: int, default None
Pixel offset from given axis
label_angle: int, default None
label angle in degrees
labe... | python |
def legend(self, title=None, scale='color', text_color=None):
"""Convience method for adding a legend to the figure.
Important: This defaults to the color scale that is generated with
Line, Area, Stacked Line, etc charts. For bar charts, the scale ref is
usually 'y'.
Parameters... | Convience method for adding a legend to the figure.
Important: This defaults to the color scale that is generated with
Line, Area, Stacked Line, etc charts. For bar charts, the scale ref is
usually 'y'.
Parameters
----------
title: string, default None
Legen... | python |
def colors(self, brew=None, range_=None):
"""Convenience method for adding color brewer scales to charts with a
color scale, such as stacked or grouped bars.
See the colors here: http://colorbrewer2.org/
Or here: http://bl.ocks.org/mbostock/5577023
This assumes that a 'color' ... | Convenience method for adding color brewer scales to charts with a
color scale, such as stacked or grouped bars.
See the colors here: http://colorbrewer2.org/
Or here: http://bl.ocks.org/mbostock/5577023
This assumes that a 'color' scale exists on your chart.
Parameters
... | python |
def validate(self, require_all=True, scale='colors'):
"""Validate the visualization contents.
Parameters
----------
require_all : boolean, default True
If True (default), then all fields ``data``, ``scales``,
``axes``, and ``marks`` must be defined. The user is a... | Validate the visualization contents.
Parameters
----------
require_all : boolean, default True
If True (default), then all fields ``data``, ``scales``,
``axes``, and ``marks`` must be defined. The user is allowed to
disable this if the intent is to define the... | python |
def display(self):
"""Display the visualization inline in the IPython notebook.
This is deprecated, use the following instead::
from IPython.display import display
display(viz)
"""
from IPython.core.display import display, HTML
display(HTML(self._repr_ht... | Display the visualization inline in the IPython notebook.
This is deprecated, use the following instead::
from IPython.display import display
display(viz) | python |
def validate(self, *args):
"""Validate contents of class
"""
super(self.__class__, self).validate(*args)
if not self.name:
raise ValidationError('name is required for Data') | Validate contents of class | python |
def serialize(obj):
"""Convert an object into a JSON-serializable value
This is used by the ``from_pandas`` and ``from_numpy`` functions to
convert data to JSON-serializable types when loading.
"""
if isinstance(obj, str_types):
return obj
elif hasattr(obj, '... | Convert an object into a JSON-serializable value
This is used by the ``from_pandas`` and ``from_numpy`` functions to
convert data to JSON-serializable types when loading. | python |
def from_pandas(cls, data, columns=None, key_on='idx', name=None,
series_key='data', grouped=False, records=False, **kwargs):
"""Load values from a pandas ``Series`` or ``DataFrame`` object
Parameters
----------
data : pandas ``Series`` or ``DataFrame``
P... | Load values from a pandas ``Series`` or ``DataFrame`` object
Parameters
----------
data : pandas ``Series`` or ``DataFrame``
Pandas object to import data from.
columns: list, default None
DataFrame columns to convert to Data. Keys default to col names.
... | python |
def from_numpy(cls, np_obj, name, columns, index=None, index_key=None,
**kwargs):
"""Load values from a numpy array
Parameters
----------
np_obj : numpy.ndarray
numpy array to load data from
name : string
``name`` field for the data
... | Load values from a numpy array
Parameters
----------
np_obj : numpy.ndarray
numpy array to load data from
name : string
``name`` field for the data
columns : iterable
Sequence of column names, from left to right. Must have same
len... | python |
def from_mult_iters(cls, name=None, idx=None, **kwargs):
"""Load values from multiple iters
Parameters
----------
name : string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
idx: string, default None
... | Load values from multiple iters
Parameters
----------
name : string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
idx: string, default None
Iterable to use for the data index
**kwargs : dict of ite... | python |
def from_iter(cls, data, name=None):
"""Convenience method for loading data from an iterable.
Defaults to numerical indexing for x-axis.
Parameters
----------
data: iterable
An iterable of data (list, tuple, dict of key/val pairs)
name: string, default None
... | Convenience method for loading data from an iterable.
Defaults to numerical indexing for x-axis.
Parameters
----------
data: iterable
An iterable of data (list, tuple, dict of key/val pairs)
name: string, default None
Name of the data set. If None (defau... | python |
def _numpy_to_values(data):
'''Convert a NumPy array to values attribute'''
def to_list_no_index(xvals, yvals):
return [{"x": x, "y": np.asscalar(y)}
for x, y in zip(xvals, yvals)]
if len(data.shape) == 1 or data.shape[1] == 1:
xvals = range(data.shap... | Convert a NumPy array to values attribute | python |
def to_json(self, validate=False, pretty_print=True, data_path=None):
"""Convert data to JSON
Parameters
----------
data_path : string
If not None, then data is written to a separate file at the
specified path. Note that the ``url`` attribute if the data must
... | Convert data to JSON
Parameters
----------
data_path : string
If not None, then data is written to a separate file at the
specified path. Note that the ``url`` attribute if the data must
be set independently for the data to load correctly.
Returns
... | python |
def _assert_is_type(name, value, value_type):
"""Assert that a value must be a given type."""
if not isinstance(value, value_type):
if type(value_type) is tuple:
types = ', '.join(t.__name__ for t in value_type)
raise ValueError('{0} must be one of ({1})'.format(name, types))
... | Assert that a value must be a given type. | python |
def grammar(grammar_type=None, grammar_name=None):
"""Decorator to define properties that map to the ``grammar``
dict. This dict is the canonical representation of the Vega grammar
within Vincent.
This decorator is intended for classes that map to some pre-defined JSON
structure, such as axes, data... | Decorator to define properties that map to the ``grammar``
dict. This dict is the canonical representation of the Vega grammar
within Vincent.
This decorator is intended for classes that map to some pre-defined JSON
structure, such as axes, data, marks, scales, etc. It is assumed that this
decorate... | python |
def validate(self):
"""Validate the contents of the object.
This calls ``setattr`` for each of the class's grammar properties. It
will catch ``ValueError``s raised by the grammar property's setters
and re-raise them as :class:`ValidationError`.
"""
for key, val in self.g... | Validate the contents of the object.
This calls ``setattr`` for each of the class's grammar properties. It
will catch ``ValueError``s raised by the grammar property's setters
and re-raise them as :class:`ValidationError`. | python |
def to_json(self, path=None, html_out=False,
html_path='vega_template.html', validate=False,
pretty_print=True):
"""Convert object to JSON
Parameters
----------
path: string, default None
Path to write JSON out. If there is no path provided, J... | Convert object to JSON
Parameters
----------
path: string, default None
Path to write JSON out. If there is no path provided, JSON
will be returned as a string to the console.
html_out: boolean, default False
If True, vincent will output an simple HTM... | python |
def useful_mimetype(text):
"""Check to see if the given mime type is a MIME type
which is useful in terms of how to treat this file.
"""
if text is None:
return False
mimetype = normalize_mimetype(text)
return mimetype not in [DEFAULT, PLAIN, None] | Check to see if the given mime type is a MIME type
which is useful in terms of how to treat this file. | python |
def normalize_extension(extension):
"""Normalise a file name extension."""
extension = decode_path(extension)
if extension is None:
return
if extension.startswith('.'):
extension = extension[1:]
if '.' in extension:
_, extension = os.path.splitext(extension)
extension = s... | Normalise a file name extension. | python |
def fetch(url: str, **kwargs) -> Selector:
"""
Send HTTP request and parse it as a DOM tree.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
tr... | Send HTTP request and parse it as a DOM tree.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions. | python |
async def async_fetch(url: str, **kwargs) -> Selector:
"""
Do the fetch in an async style.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', DEFAULT_HEADERS)
asyn... | Do the fetch in an async style.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions. | python |
def links(res: requests.models.Response,
search: str = None,
pattern: str = None) -> list:
"""Get the links of the page.
Args:
res (requests.models.Response): The response of the page.
search (str, optional): Defaults to None. Search the links you want.
pattern (str,... | Get the links of the page.
Args:
res (requests.models.Response): The response of the page.
search (str, optional): Defaults to None. Search the links you want.
pattern (str, optional): Defaults to None. Search the links use a regex pattern.
Returns:
list: All the links of the p... | python |
def save_as_json(total: list,
name='data.json',
sort_by: str = None,
no_duplicate=False,
order='asc'):
"""Save what you crawled as a json file.
Args:
total (list): Total of data you crawled.
name (str, optional): Defaults to 'd... | Save what you crawled as a json file.
Args:
total (list): Total of data you crawled.
name (str, optional): Defaults to 'data.json'. The name of the file.
sort_by (str, optional): Defaults to None. Sort items by a specific key.
no_duplicate (bool, optional): Defaults to False. If Tru... | python |
def set_observer(self, observer):
"""
Validates and sets the color's observer angle.
.. note:: This only changes the observer angle value. It does no conversion
of the color's coordinates.
:param str observer: One of '2' or '10'.
"""
observer = str(observer)... | Validates and sets the color's observer angle.
.. note:: This only changes the observer angle value. It does no conversion
of the color's coordinates.
:param str observer: One of '2' or '10'. | python |
def set_illuminant(self, illuminant):
"""
Validates and sets the color's illuminant.
.. note:: This only changes the illuminant. It does no conversion
of the color's coordinates. For this, you'll want to refer to
:py:meth:`XYZColor.apply_adaptation <colormath.color_objec... | Validates and sets the color's illuminant.
.. note:: This only changes the illuminant. It does no conversion
of the color's coordinates. For this, you'll want to refer to
:py:meth:`XYZColor.apply_adaptation <colormath.color_objects.XYZColor.apply_adaptation>`.
.. tip:: Call thi... | python |
def get_numpy_array(self):
"""
Dump this color into NumPy array.
"""
# This holds the obect's spectral data, and will be passed to
# numpy.array() to create a numpy array (matrix) for the matrix math
# that will be done during the conversion to XYZ.
values = []
... | Dump this color into NumPy array. | python |
def apply_adaptation(self, target_illuminant, adaptation='bradford'):
"""
This applies an adaptation matrix to change the XYZ color's illuminant.
You'll most likely only need this during RGB conversions.
"""
logger.debug(" \- Original illuminant: %s", self.illuminant)
lo... | This applies an adaptation matrix to change the XYZ color's illuminant.
You'll most likely only need this during RGB conversions. | python |
def _clamp_rgb_coordinate(self, coord):
"""
Clamps an RGB coordinate, taking into account whether or not the
color is upscaled or not.
:param float coord: The coordinate value.
:rtype: float
:returns: The clamped value.
"""
if not self.is_upscaled:
... | Clamps an RGB coordinate, taking into account whether or not the
color is upscaled or not.
:param float coord: The coordinate value.
:rtype: float
:returns: The clamped value. | python |
def get_upscaled_value_tuple(self):
"""
Scales an RGB color object from decimal 0.0-1.0 to int 0-255.
"""
# Scale up to 0-255 values.
rgb_r = int(math.floor(0.5 + self.rgb_r * 255))
rgb_g = int(math.floor(0.5 + self.rgb_g * 255))
rgb_b = int(math.floor(0.5 + self.... | Scales an RGB color object from decimal 0.0-1.0 to int 0-255. | python |
def auto_density(color):
"""
Given a SpectralColor, automatically choose the correct ANSI T filter.
Returns a tuple with a string representation of the filter the
calculated density.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:rtype: float
:return... | Given a SpectralColor, automatically choose the correct ANSI T filter.
Returns a tuple with a string representation of the filter the
calculated density.
:param SpectralColor color: The SpectralColor object to calculate
density for.
:rtype: float
:returns: The density value, with the filter... | python |
def _get_lab_color1_vector(color):
"""
Converts an LabColor into a NumPy vector.
:param LabColor color:
:rtype: numpy.ndarray
"""
if not color.__class__.__name__ == 'LabColor':
raise ValueError(
"Delta E functions can only be used with two LabColor objects.")
return nump... | Converts an LabColor into a NumPy vector.
:param LabColor color:
:rtype: numpy.ndarray | python |
def _get_adaptation_matrix(wp_src, wp_dst, observer, adaptation):
"""
Calculate the correct transformation matrix based on origin and target
illuminants. The observer angle must be the same between illuminants.
See colormath.color_constants.ADAPTATION_MATRICES for a list of possible
adaptations.
... | Calculate the correct transformation matrix based on origin and target
illuminants. The observer angle must be the same between illuminants.
See colormath.color_constants.ADAPTATION_MATRICES for a list of possible
adaptations.
Detailed conversion documentation is available at:
http://brucelindbloo... | python |
def apply_chromatic_adaptation(val_x, val_y, val_z, orig_illum, targ_illum,
observer='2', adaptation='bradford'):
"""
Applies a chromatic adaptation matrix to convert XYZ values between
illuminants. It is important to recognize that color transformation results
in color er... | Applies a chromatic adaptation matrix to convert XYZ values between
illuminants. It is important to recognize that color transformation results
in color errors, determined by how far the original illuminant is from the
target illuminant. For example, D65 to A could result in very high maximum
deviance.
... | python |
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation='bradford'):
"""
Convenience function to apply an adaptation directly to a Color object.
"""
xyz_x = color.xyz_x
xyz_y = color.xyz_y
xyz_z = color.xyz_z
orig_illum = color.illuminant
targ_illum = targ_illum.lower()
... | Convenience function to apply an adaptation directly to a Color object. | python |
def example_lab_to_xyz():
"""
This function shows a simple conversion of an Lab color to an XYZ color.
"""
print("=== Simple Example: Lab->XYZ ===")
# Instantiate an Lab color object with the given values.
lab = LabColor(0.903, 16.296, -2.22)
# Show a string representation.
print(lab)
... | This function shows a simple conversion of an Lab color to an XYZ color. | python |
def example_lchab_to_lchuv():
"""
This function shows very complex chain of conversions in action.
LCHab to LCHuv involves four different calculations, making this the
conversion requiring the most steps.
"""
print("=== Complex Example: LCHab->LCHuv ===")
# Instantiate an LCHab color objec... | This function shows very complex chain of conversions in action.
LCHab to LCHuv involves four different calculations, making this the
conversion requiring the most steps. | python |
def example_lab_to_rgb():
"""
Conversions to RGB are a little more complex mathematically. There are also
several kinds of RGB color spaces. When converting from a device-independent
color space to RGB, sRGB is assumed unless otherwise specified with the
target_rgb keyword arg.
"""
print("=... | Conversions to RGB are a little more complex mathematically. There are also
several kinds of RGB color spaces. When converting from a device-independent
color space to RGB, sRGB is assumed unless otherwise specified with the
target_rgb keyword arg. | python |
def example_rgb_to_xyz():
"""
The reverse is similar.
"""
print("=== RGB Example: RGB->XYZ ===")
# Instantiate an Lab color object with the given values.
rgb = sRGBColor(120, 130, 140)
# Show a string representation.
print(rgb)
# Convert RGB to XYZ using a D50 illuminant.
xyz = ... | The reverse is similar. | python |
def example_spectral_to_xyz():
"""
Instantiate an Lab color object with the given values. Note that the
spectral range can run from 340nm to 830nm. Any omitted values assume a
value of 0.0, which is more or less ignored. For the distribution below,
we are providing an example reading from an X-Rite ... | Instantiate an Lab color object with the given values. Note that the
spectral range can run from 340nm to 830nm. Any omitted values assume a
value of 0.0, which is more or less ignored. For the distribution below,
we are providing an example reading from an X-Rite i1 Pro, which only
measures between 380... | python |
def example_lab_to_ipt():
"""
This function shows a simple conversion of an XYZ color to an IPT color.
"""
print("=== Simple Example: XYZ->IPT ===")
# Instantiate an XYZ color object with the given values.
xyz = XYZColor(0.5, 0.5, 0.5, illuminant='d65')
# Show a string representation.
p... | This function shows a simple conversion of an XYZ color to an IPT color. | python |
def apply_RGB_matrix(var1, var2, var3, rgb_type, convtype="xyz_to_rgb"):
"""
Applies an RGB working matrix to convert from XYZ to RGB.
The arguments are tersely named var1, var2, and var3 to allow for the
passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and
var3 follow suite.
... | Applies an RGB working matrix to convert from XYZ to RGB.
The arguments are tersely named var1, var2, and var3 to allow for the
passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and
var3 follow suite. | python |
def color_conversion_function(start_type, target_type):
"""
Decorator to indicate a function that performs a conversion from one color
space to another.
This decorator will return the original function unmodified, however it will
be registered in the _conversion_manager so it can be used to perform... | Decorator to indicate a function that performs a conversion from one color
space to another.
This decorator will return the original function unmodified, however it will
be registered in the _conversion_manager so it can be used to perform color
space transformations between color spaces that do not ha... | python |
def Spectral_to_XYZ(cobj, illuminant_override=None, *args, **kwargs):
"""
Converts spectral readings to XYZ.
"""
# If the user provides an illuminant_override numpy array, use it.
if illuminant_override:
reference_illum = illuminant_override
else:
# Otherwise, look up the illumin... | Converts spectral readings to XYZ. | python |
def Lab_to_XYZ(cobj, *args, **kwargs):
"""
Convert from Lab to XYZ
"""
illum = cobj.get_illuminant_xyz()
xyz_y = (cobj.lab_l + 16.0) / 116.0
xyz_x = cobj.lab_a / 500.0 + xyz_y
xyz_z = xyz_y - cobj.lab_b / 200.0
if math.pow(xyz_y, 3) > color_constants.CIE_E:
xyz_y = math.pow(xyz_... | Convert from Lab to XYZ | python |
def Luv_to_XYZ(cobj, *args, **kwargs):
"""
Convert from Luv to XYZ.
"""
illum = cobj.get_illuminant_xyz()
# Without Light, there is no color. Short-circuit this and avoid some
# zero division errors in the var_a_frac calculation.
if cobj.luv_l <= 0.0:
xyz_x = 0.0
xyz_y = 0.0
... | Convert from Luv to XYZ. | python |
def xyY_to_XYZ(cobj, *args, **kwargs):
"""
Convert from xyY to XYZ.
"""
# avoid division by zero
if cobj.xyy_y == 0.0:
xyz_x = 0.0
xyz_y = 0.0
xyz_z = 0.0
else:
xyz_x = (cobj.xyy_x * cobj.xyy_Y) / cobj.xyy_y
xyz_y = cobj.xyy_Y
xyz_z = ((1.0 - cobj.... | Convert from xyY to XYZ. | python |
def XYZ_to_xyY(cobj, *args, **kwargs):
"""
Convert from XYZ to xyY.
"""
xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z
# avoid division by zero
if xyz_sum == 0.0:
xyy_x = 0.0
xyy_y = 0.0
else:
xyy_x = cobj.xyz_x / xyz_sum
xyy_y = cobj.xyz_y / xyz_sum
xyy_Y... | Convert from XYZ to xyY. | python |
def XYZ_to_Luv(cobj, *args, **kwargs):
"""
Convert from XYZ to Luv
"""
temp_x = cobj.xyz_x
temp_y = cobj.xyz_y
temp_z = cobj.xyz_z
denom = temp_x + (15.0 * temp_y) + (3.0 * temp_z)
# avoid division by zero
if denom == 0.0:
luv_u = 0.0
luv_v = 0.0
else:
luv... | Convert from XYZ to Luv | python |
def XYZ_to_Lab(cobj, *args, **kwargs):
"""
Converts XYZ to Lab.
"""
illum = cobj.get_illuminant_xyz()
temp_x = cobj.xyz_x / illum["X"]
temp_y = cobj.xyz_y / illum["Y"]
temp_z = cobj.xyz_z / illum["Z"]
if temp_x > color_constants.CIE_E:
temp_x = math.pow(temp_x, (1.0 / 3.0))
... | Converts XYZ to Lab. | python |
def XYZ_to_RGB(cobj, target_rgb, *args, **kwargs):
"""
XYZ to RGB conversion.
"""
temp_X = cobj.xyz_x
temp_Y = cobj.xyz_y
temp_Z = cobj.xyz_z
logger.debug(" \- Target RGB space: %s", target_rgb)
target_illum = target_rgb.native_illuminant
logger.debug(" \- Target native illuminant... | XYZ to RGB conversion. | python |
def RGB_to_XYZ(cobj, target_illuminant=None, *args, **kwargs):
"""
RGB to XYZ conversion. Expects 0-255 RGB values.
Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html
"""
# Will contain linearized RGB channels (removed the gamma func).
linear_channels = {}
if isinst... | RGB to XYZ conversion. Expects 0-255 RGB values.
Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html | python |
def RGB_to_HSV(cobj, *args, **kwargs):
"""
Converts from RGB to HSV.
H values are in degrees and are 0 to 360.
S values are a percentage, 0.0 to 1.0.
V values are a percentage, 0.0 to 1.0.
"""
var_R = cobj.rgb_r
var_G = cobj.rgb_g
var_B = cobj.rgb_b
var_max = max(var_R, var_G, ... | Converts from RGB to HSV.
H values are in degrees and are 0 to 360.
S values are a percentage, 0.0 to 1.0.
V values are a percentage, 0.0 to 1.0. | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.