repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
hobson/pug-ann | pug/ann/example.py | oneday_weather_forecast | python | def oneday_weather_forecast(
location='Portland, OR',
inputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity', 'Mean Humidity', 'Min Humidity', 'Max Sea Level Pressure', 'Mean Sea Level Pressure', 'Min Sea Level Pressure', 'Wind Direction'),
outputs=('Min Temperature', '... | Provide a weather forecast for tomorrow based on historical weather at that location | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/example.py#L82-L122 | [
"def train_weather_predictor(\n location='Portland, OR',\n years=range(2013, 2016,),\n delays=(1, 2, 3),\n inputs=('Min Temperature', 'Max Temperature', 'Min Sea Level Pressure', u'Max Sea Level Pressure', 'WindDirDegrees',),\n outputs=(u'Max TemperatureF',),\n N_hidden=6,\... | """Example pybrain network training to predict the weather
Installation:
pip install pug-ann
Examples:
In the future DataSets should have an attribute `columns` or `df` to facilitate converting back to dataframes
>>> trainer, df = train_weather_predictor('San Francisco, CA', epochs=2, inputs=['Max Tempe... |
hobson/pug-ann | pug/ann/example.py | run_competition | python | def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0):
results = []
builders = list(builders) + [buildNetwork, util.build_ann]
for r in range(rounds):
heat = []
# FIXME: shuffle the order of the builders to keep things f... | pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them!
Arguments:
task (Task): task to compete at
Optimizer (class): pybrain.Optimizer class to instantiate for each competitor
rounds (int): number of times to run the competition
max_eval (int)... | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/example.py#L286-L347 | null | """Example pybrain network training to predict the weather
Installation:
pip install pug-ann
Examples:
In the future DataSets should have an attribute `columns` or `df` to facilitate converting back to dataframes
>>> trainer, df = train_weather_predictor('San Francisco, CA', epochs=2, inputs=['Max Tempe... |
cemsbr/yala | yala/config.py | Config._set_linters | python | def _set_linters(self):
if 'linters' in self._config:
self.user_linters = list(self._parse_cfg_linters())
self.linters = {linter: self._all_linters[linter]
for linter in self.user_linters}
else:
self.linters = self._all_linters | Use user linters or all available when not specified. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L37-L44 | [
"def _parse_cfg_linters(self):\n \"\"\"Return valid linter names found in config files.\"\"\"\n user_value = self._config.get('linters', '')\n # For each line of \"linters\" value, use comma as separator\n for line in user_value.splitlines():\n yield from self._parse_linters_line(line)\n"
] | class Config:
"""Deal with default and user configuration.
Internal use only. If you are implementing your own linter, use
``self._config``.
"""
_config = None
_CFG_FILE = 'setup.cfg'
#: str: Section of the config file.
_CFG_SECTION = 'yala'
def __init__(self, all_linters):
... |
cemsbr/yala | yala/config.py | Config.print_config | python | def print_config(self):
linters = self.user_linters or list(self.linters)
print('linters:', ', '.join(linters))
for key, value in self._config.items():
if key != 'linters':
print('{}: {}'.format(key, value)) | Print all yala configurations, including default and user's. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L46-L52 | null | class Config:
"""Deal with default and user configuration.
Internal use only. If you are implementing your own linter, use
``self._config``.
"""
_config = None
_CFG_FILE = 'setup.cfg'
#: str: Section of the config file.
_CFG_SECTION = 'yala'
def __init__(self, all_linters):
... |
cemsbr/yala | yala/config.py | Config._parse_cfg_linters | python | def _parse_cfg_linters(self):
user_value = self._config.get('linters', '')
# For each line of "linters" value, use comma as separator
for line in user_value.splitlines():
yield from self._parse_linters_line(line) | Return valid linter names found in config files. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L58-L63 | [
"def _parse_linters_line(self, line):\n linters = (linter for linter in re.split(r'\\s*,\\s*', line))\n for linter in linters:\n if linter in self._all_linters:\n yield linter\n elif linter:\n LOG.warning('%s is not a valid linter', linter)\n"
] | class Config:
"""Deal with default and user configuration.
Internal use only. If you are implementing your own linter, use
``self._config``.
"""
_config = None
_CFG_FILE = 'setup.cfg'
#: str: Section of the config file.
_CFG_SECTION = 'yala'
def __init__(self, all_linters):
... |
cemsbr/yala | yala/config.py | Config.get_linter_config | python | def get_linter_config(self, name):
prefix = name + ' '
return {k[len(prefix):]: v
for k, v in self._config.items()
if k.startswith(prefix)} | Return linter options without linter name prefix. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L73-L78 | null | class Config:
"""Deal with default and user configuration.
Internal use only. If you are implementing your own linter, use
``self._config``.
"""
_config = None
_CFG_FILE = 'setup.cfg'
#: str: Section of the config file.
_CFG_SECTION = 'yala'
def __init__(self, all_linters):
... |
cemsbr/yala | yala/config.py | Config._merge | python | def _merge(cls, default, user):
section = cls._CFG_SECTION
merged = default[section]
if section not in user:
return merged
user = user[section]
for key, value in user.items():
if key in merged:
merged[key] += ' ' + value
else:... | Append user options to default options. Return yala section. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/config.py#L103-L117 | null | class Config:
"""Deal with default and user configuration.
Internal use only. If you are implementing your own linter, use
``self._config``.
"""
_config = None
_CFG_FILE = 'setup.cfg'
#: str: Section of the config file.
_CFG_SECTION = 'yala'
def __init__(self, all_linters):
... |
cemsbr/yala | yala/main.py | LinterRunner.get_results | python | def get_results(self):
try:
stdout, stderr = self._lint()
# Can't return a generator from a subprocess
return list(stdout), stderr or []
except FileNotFoundError as exception:
# Error if the linter was not found but was chosen by the user
if se... | Run the linter, parse, and return result list.
If a linter specified by the user is not found, return an error message
as result. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/main.py#L48-L65 | [
"def _lint(self):\n \"\"\"Run linter in a subprocess.\"\"\"\n command = self._get_command()\n process = subprocess.run(command, stdout=subprocess.PIPE, # nosec\n stderr=subprocess.PIPE)\n LOG.info('Finished %s', ' '.join(command))\n stdout, stderr = self._get_output_lines... | class LinterRunner:
"""Run linter and process results."""
config = None
targets = []
def __init__(self, linter_class):
"""Set linter class and its configuration."""
linter_class.config = self.config.get_linter_config(linter_class.name)
self._linter = linter_class()
@classm... |
cemsbr/yala | yala/main.py | LinterRunner._get_command | python | def _get_command(self):
targets = ' '.join(self.targets)
cmd_str = self._linter.command_with_options + ' ' + targets
cmd_shlex = shlex.split(cmd_str)
return list(cmd_shlex) | Return command with options and targets, ready for execution. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/main.py#L67-L72 | null | class LinterRunner:
"""Run linter and process results."""
config = None
targets = []
def __init__(self, linter_class):
"""Set linter class and its configuration."""
linter_class.config = self.config.get_linter_config(linter_class.name)
self._linter = linter_class()
@classm... |
cemsbr/yala | yala/main.py | LinterRunner._lint | python | def _lint(self):
command = self._get_command()
process = subprocess.run(command, stdout=subprocess.PIPE, # nosec
stderr=subprocess.PIPE)
LOG.info('Finished %s', ' '.join(command))
stdout, stderr = self._get_output_lines(process)
return self._lint... | Run linter in a subprocess. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/main.py#L74-L81 | [
"def _get_command(self):\n \"\"\"Return command with options and targets, ready for execution.\"\"\"\n targets = ' '.join(self.targets)\n cmd_str = self._linter.command_with_options + ' ' + targets\n cmd_shlex = shlex.split(cmd_str)\n return list(cmd_shlex)\n",
"def _get_output_lines(process):\n ... | class LinterRunner:
"""Run linter and process results."""
config = None
targets = []
def __init__(self, linter_class):
"""Set linter class and its configuration."""
linter_class.config = self.config.get_linter_config(linter_class.name)
self._linter = linter_class()
@classm... |
cemsbr/yala | yala/main.py | Main.lint | python | def lint(self, targets):
LinterRunner.targets = targets
linters = self._config.get_linter_classes()
with Pool() as pool:
out_err_none = pool.map(LinterRunner.run, linters)
out_err = [item for item in out_err_none if item is not None]
stdout, stderr = zip(*out_err)
... | Run linters in parallel and sort all results.
Args:
targets (list): List of files and folders to lint. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/main.py#L109-L121 | null | class Main:
"""Parse all linters and aggregate results."""
# We only need the ``run`` method.
# pylint: disable=too-few-public-methods
def __init__(self, config=None, all_linters=None):
"""Initialize the only Config object and assign it to other classes.
Args:
config (Conf... |
cemsbr/yala | yala/main.py | Main.run_from_cli | python | def run_from_cli(self, args):
if args['--dump-config']:
self._config.print_config()
else:
stdout, stderr = self.lint(args['<path>'])
self.print_results(stdout, stderr) | Read arguments, run and print results.
Args:
args (dict): Arguments parsed by docopt. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/main.py#L123-L133 | [
"def lint(self, targets):\n \"\"\"Run linters in parallel and sort all results.\n\n Args:\n targets (list): List of files and folders to lint.\n \"\"\"\n LinterRunner.targets = targets\n linters = self._config.get_linter_classes()\n with Pool() as pool:\n out_err_none = pool.map(Lint... | class Main:
"""Parse all linters and aggregate results."""
# We only need the ``run`` method.
# pylint: disable=too-few-public-methods
def __init__(self, config=None, all_linters=None):
"""Initialize the only Config object and assign it to other classes.
Args:
config (Conf... |
cemsbr/yala | yala/main.py | Main.print_results | python | def print_results(cls, stdout, stderr):
for line in stderr:
print(line, file=sys.stderr)
if stdout:
if stderr: # blank line to separate stdout from stderr
print(file=sys.stderr)
cls._print_stdout(stdout)
else:
print(':) No issues f... | Print linter results and exits with an error if there's any. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/main.py#L136-L145 | [
"def _print_stdout(stdout):\n for line in stdout:\n print(line)\n issue = 'issues' if len(stdout) > 1 else 'issue'\n sys.exit('\\n:( {} {} found.'.format(len(stdout), issue))\n"
] | class Main:
"""Parse all linters and aggregate results."""
# We only need the ``run`` method.
# pylint: disable=too-few-public-methods
def __init__(self, config=None, all_linters=None):
"""Initialize the only Config object and assign it to other classes.
Args:
config (Conf... |
cemsbr/yala | yala/base.py | LinterOutput._cmp_key | python | def _cmp_key(self, obj=None):
if not obj:
obj = self
line_nr = int(obj.line_nr) if obj.line_nr else 0
col = int(obj.col) if obj.col else 0
return (obj.path, line_nr, col, obj.msg) | Comparison key for sorting results from all linters.
The sort should group files and lines from different linters to make it
easier for refactoring. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L41-L51 | null | class LinterOutput:
"""A one-line linter result. It can be sorted and printed as string."""
# We only override magic methods.
# pylint: disable=too-few-public-methods
def __init__(self, linter_name, path, msg, line_nr=None, col=None):
"""Optionally set all attributes.
Args:
... |
cemsbr/yala | yala/base.py | Linter.command_with_options | python | def command_with_options(self):
if 'args' in self.config:
return ' '.join((self.command, self.config['args']))
return self.command | Add arguments from config to :attr:`command`. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L85-L89 | null | class Linter(metaclass=ABCMeta):
"""Linter implementations should inherit from this class."""
# Most methods are for child class only, not public.
#: dict: Configuration for a specific linter
config = None
@property
@classmethod
@abstractmethod
def name(cls):
"""Name of this l... |
cemsbr/yala | yala/base.py | Linter._get_relative_path | python | def _get_relative_path(self, full_path):
try:
rel_path = Path(full_path).relative_to(Path().absolute())
except ValueError:
LOG.error("%s: Couldn't find relative path of '%s' from '%s'.",
self.name, full_path, Path().absolute())
return full_path
... | Return the relative path from current path. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L104-L112 | null | class Linter(metaclass=ABCMeta):
"""Linter implementations should inherit from this class."""
# Most methods are for child class only, not public.
#: dict: Configuration for a specific linter
config = None
@property
@classmethod
@abstractmethod
def name(cls):
"""Name of this l... |
cemsbr/yala | yala/base.py | Linter._parse_by_pattern | python | def _parse_by_pattern(self, lines, pattern):
for line in lines:
match = pattern.match(line)
if match:
params = match.groupdict()
if not params:
params = match.groups()
yield self._create_output_from_match(params) | Match pattern line by line and return Results.
Use ``_create_output_from_match`` to convert pattern match groups to
Result instances.
Args:
lines (iterable): Output lines to be parsed.
pattern: Compiled pattern to match against lines.
result_fn (function): R... | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L114-L135 | [
"def _create_output_from_match(self, match_result):\n \"\"\"Create Result instance from pattern match results.\n\n Args:\n match: Pattern match.\n \"\"\"\n if isinstance(match_result, dict):\n return LinterOutput(self.name, **match_result)\n return LinterOutput(self.name, *match_result)... | class Linter(metaclass=ABCMeta):
"""Linter implementations should inherit from this class."""
# Most methods are for child class only, not public.
#: dict: Configuration for a specific linter
config = None
@property
@classmethod
@abstractmethod
def name(cls):
"""Name of this l... |
cemsbr/yala | yala/base.py | Linter._create_output_from_match | python | def _create_output_from_match(self, match_result):
if isinstance(match_result, dict):
return LinterOutput(self.name, **match_result)
return LinterOutput(self.name, *match_result) | Create Result instance from pattern match results.
Args:
match: Pattern match. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/base.py#L137-L145 | null | class Linter(metaclass=ABCMeta):
"""Linter implementations should inherit from this class."""
# Most methods are for child class only, not public.
#: dict: Configuration for a specific linter
config = None
@property
@classmethod
@abstractmethod
def name(cls):
"""Name of this l... |
cemsbr/yala | yala/linters.py | Isort._create_output_from_match | python | def _create_output_from_match(self, match_result):
full_path = match_result['full_path']
path = self._get_relative_path(full_path)
return LinterOutput(self.name, path, match_result['msg']) | As isort outputs full path, we change it to relative path. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/linters.py#L23-L27 | null | class Isort(Linter):
"""Isort parser."""
name = 'isort'
def parse(self, lines):
"""Get full path and message from each output line."""
# E.g. "ERROR: /my/path/main.py Imports are incorrectly sorted."
pattern = re.compile(r'''
^.+?
... |
cemsbr/yala | yala/linters.py | Pydocstyle.parse | python | def parse(self, lines):
patterns = [re.compile(r'^(.+?):(\d+)'),
re.compile(r'^\s+(.+)$')]
for i, line in enumerate(lines):
if i % 2 == 0:
path, line_nr = patterns[0].match(line).groups()
else:
msg = patterns[1].match(line).grou... | Get :class:`base.Result` parameters using regex.
There are 2 lines for each pydocstyle result:
1. Filename and line number;
2. Message for the problem found. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/linters.py#L64-L78 | null | class Pydocstyle(Linter):
"""Pydocstyle parser."""
name = 'pydocstyle'
|
cemsbr/yala | yala/linters.py | Pylint.parse | python | def parse(self, lines):
pattern = re.compile(r"""^(?P<path>.+?)
:(?P<msg>.+)
:(?P<line_nr>\d+?)
:(?P<col>\d+?)$""", re.VERBOSE)
return self._parse_by_pattern(lines, pattern) | Get :class:`base.Result` parameters using regex. | train | https://github.com/cemsbr/yala/blob/efceb044cb3de8d1c12140087ae9d5f8269bfbf9/yala/linters.py#L86-L92 | [
"def _parse_by_pattern(self, lines, pattern):\n \"\"\"Match pattern line by line and return Results.\n\n Use ``_create_output_from_match`` to convert pattern match groups to\n Result instances.\n\n Args:\n lines (iterable): Output lines to be parsed.\n pattern: Compiled pattern to match ag... | class Pylint(Linter):
"""Pylint parser."""
name = 'pylint'
|
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/calage_bdf_cn.py | calcul_ratios_calage | python | def calcul_ratios_calage(year_data, year_calage, data_bdf, data_cn):
'''
Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf.
'''
masses = data_cn.merge(
data_bdf,... | Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn.py#L91-L110 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/calage_bdf_cn.py | get_bdf_data_frames | python | def get_bdf_data_frames(depenses, year_data = None):
assert year_data is not None
'''
Récupère les dépenses de budget des familles et les agrège par poste
(en tenant compte des poids respectifs des ménages)
'''
depenses_by_grosposte = pandas.DataFrame()
for grosposte in range(1, 13):
... | Récupère les dépenses de budget des familles et les agrège par poste
(en tenant compte des poids respectifs des ménages) | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn.py#L113-L141 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_1_2_imputations_loyers_proprietaires.py | build_imputation_loyers_proprietaires | python | def build_imputation_loyers_proprietaires(temporary_store = None, year = None):
assert temporary_store is not None
assert year is not None
# Load data
bdf_survey_collection = SurveyCollection.load(collection = 'budget_des_familles',
config_files_directory = config_files_directory)
survey =... | Build menage consumption by categorie fiscale dataframe | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_1_2_imputations_loyers_proprietaires.py#L50-L178 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_4_homogeneisation_revenus_menages.py | build_homogeneisation_revenus_menages | python | def build_homogeneisation_revenus_menages(temporary_store = None, year = None):
assert temporary_store is not None
assert year is not None
# Load data
bdf_survey_collection = SurveyCollection.load(
collection = 'budget_des_familles', config_files_directory = config_files_directory)
survey =... | Build menage consumption by categorie fiscale dataframe | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_4_homogeneisation_revenus_menages.py#L46-L387 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_2_homogeneisation_vehicules.py | build_homogeneisation_vehicules | python | def build_homogeneisation_vehicules(temporary_store = None, year = None):
assert temporary_store is not None
assert year is not None
# Load data
bdf_survey_collection = SurveyCollection.load(
collection = 'budget_des_familles', config_files_directory = config_files_directory)
survey = bdf_s... | Compute vehicule numbers by type | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_2_homogeneisation_vehicules.py#L55-L109 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/model/base.py | droit_d_accise | python | def droit_d_accise(depense, droit_cn, consommation_cn, taux_plein_tva):
return depense * ((1 + taux_plein_tva) * droit_cn) / (consommation_cn - (1 + taux_plein_tva) * droit_cn) | Calcule le montant de droit d'accise sur un volume de dépense payé pour le poste adéquat. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/model/base.py#L54-L58 | null | # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_3_homogeneisation_caracteristiques_menages.py | build_homogeneisation_caracteristiques_sociales | python | def build_homogeneisation_caracteristiques_sociales(temporary_store = None, year = None):
u"""Homogénéisation des caractéristiques sociales des ménages """
assert temporary_store is not None
assert year is not None
# Load data
bdf_survey_collection = SurveyCollection.load(
collection = 'bud... | u"""Homogénéisation des caractéristiques sociales des ménages | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_3_homogeneisation_caracteristiques_menages.py#L44-L666 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/utils.py | collapsesum | python | def collapsesum(data_frame, by = None, var = None):
'''
Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe.
'''
assert by is not None
assert var is not None
grouped = data_frame.groupby([by])
return grouped.apply(lambda x: weighted_sum(groupe = x, var =var)) | Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/utils.py#L30-L37 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/utils.py | weighted_sum | python | def weighted_sum(groupe, var):
'''
Fonction qui calcule la moyenne pondérée par groupe d'une variable
'''
data = groupe[var]
weights = groupe['pondmen']
return (data * weights).sum() | Fonction qui calcule la moyenne pondérée par groupe d'une variable | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/utils.py#L52-L58 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py | build_depenses_homogenisees | python | def build_depenses_homogenisees(temporary_store = None, year = None):
assert temporary_store is not None
assert year is not None
bdf_survey_collection = SurveyCollection.load(
collection = 'budget_des_familles', config_files_directory = config_files_directory
)
survey = bdf_survey_colle... | Build menage consumption by categorie fiscale dataframe | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py#L47-L217 | [
"def get_transfert_data_frames(year = None):\n assert year is not None\n matrice_passage_csv_file_path = os.path.join(\n assets_directory,\n 'legislation',\n 'Matrice passage {}-COICOP.csv'.format(year),\n )\n if os.path.exists(matrice_passage_csv_file_path):\n matrice_pa... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py | normalize_code_coicop | python | def normalize_code_coicop(code):
'''Normalize_coicop est function d'harmonisation de la colonne d'entiers posteCOICOP de la table
matrice_passage_data_frame en la transformant en une chaine de 5 caractères afin de pouvoir par la suite agréger les postes
COICOP selon les 12 postes agrégés de la nomenclature de la co... | Normalize_coicop est function d'harmonisation de la colonne d'entiers posteCOICOP de la table
matrice_passage_data_frame en la transformant en une chaine de 5 caractères afin de pouvoir par la suite agréger les postes
COICOP selon les 12 postes agrégés de la nomenclature de la comptabilité nationale. Chaque poste conti... | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_1_1_homogeneisation_donnees_depenses.py#L220-L258 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redist... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/utils_example.py | simulate | python | def simulate(simulated_variables, year):
'''
Construction de la DataFrame à partir de laquelle sera faite l'analyse des données
'''
input_data_frame = get_input_data_frame(year)
TaxBenefitSystem = openfisca_france_indirect_taxation.init_country()
tax_benefit_system = TaxBenefitSystem()
surv... | Construction de la DataFrame à partir de laquelle sera faite l'analyse des données | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/utils_example.py#L39-L58 | [
"def init_country():\n class TaxBenefitSystem(XmlBasedTaxBenefitSystem):\n entity_class_by_key_plural = {\n entity_class.key_plural: entity_class\n for entity_class in entity_class_by_symbol.itervalues()\n }\n legislation_xml_file_path = os.path.join(\n o... | # -*- coding: utf-8 -*-
from __future__ import division
from pandas import DataFrame
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import openfisca_france_indirect_taxation
from openfisca_france_indirect_taxation.surveys import get_input_data_frame
from openfisca_survey_manager.survey_collecti... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/utils_example.py | wavg | python | def wavg(groupe, var):
'''
Fonction qui calcule la moyenne pondérée par groupe d'une variable
'''
d = groupe[var]
w = groupe['pondmen']
return (d * w).sum() / w.sum() | Fonction qui calcule la moyenne pondérée par groupe d'une variable | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/utils_example.py#L107-L113 | null | # -*- coding: utf-8 -*-
from __future__ import division
from pandas import DataFrame
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import openfisca_france_indirect_taxation
from openfisca_france_indirect_taxation.surveys import get_input_data_frame
from openfisca_survey_manager.survey_collecti... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/utils_example.py | collapse | python | def collapse(dataframe, groupe, var):
'''
Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe.
'''
grouped = dataframe.groupby([groupe])
var_weighted_grouped = grouped.apply(lambda x: wavg(groupe = x, var = var))
return var_weighted_grouped | Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/utils_example.py#L116-L122 | null | # -*- coding: utf-8 -*-
from __future__ import division
from pandas import DataFrame
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import openfisca_france_indirect_taxation
from openfisca_france_indirect_taxation.surveys import get_input_data_frame
from openfisca_survey_manager.survey_collecti... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/utils_example.py | df_weighted_average_grouped | python | def df_weighted_average_grouped(dataframe, groupe, varlist):
'''
Agrège les résultats de weighted_average_grouped() en une unique dataframe pour la liste de variable 'varlist'.
'''
return DataFrame(
dict([
(var, collapse(dataframe, groupe, var)) for var in varlist
])
... | Agrège les résultats de weighted_average_grouped() en une unique dataframe pour la liste de variable 'varlist'. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/utils_example.py#L125-L133 | null | # -*- coding: utf-8 -*-
from __future__ import division
from pandas import DataFrame
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import openfisca_france_indirect_taxation
from openfisca_france_indirect_taxation.surveys import get_input_data_frame
from openfisca_survey_manager.survey_collecti... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/param/preprocessing.py | preprocess_legislation | python | def preprocess_legislation(legislation_json):
'''
Preprocess the legislation parameters to add prices and amounts from national accounts
'''
import os
import pkg_resources
import pandas as pd
# Add fuel prices to the tree
default_config_files_directory = os.path.join(
pkg_resou... | Preprocess the legislation parameters to add prices and amounts from national accounts | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/param/preprocessing.py#L29-L475 | null | # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014, 2015 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py | get_inflators_bdf_to_cn | python | def get_inflators_bdf_to_cn(data_year):
'''
Calcule les ratios de calage (bdf sur cn pour année de données)
à partir des masses de comptabilité nationale et des masses de consommation de bdf.
'''
data_cn = get_cn_aggregates(data_year)
data_bdf = get_bdf_aggregates(data_year)
masses = data_cn... | Calcule les ratios de calage (bdf sur cn pour année de données)
à partir des masses de comptabilité nationale et des masses de consommation de bdf. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py#L82-L95 | [
"def get_bdf_aggregates(data_year = None):\n assert data_year is not None\n\n depenses = get_input_data_frame(data_year)\n depenses_by_grosposte = pandas.DataFrame()\n for grosposte in range(1, 13):\n if depenses_by_grosposte is None:\n depenses_by_grosposte = depenses['coicop12_{}'.fo... | # -*- coding: utf-8 -*-
from __future__ import division
import logging
import os
import pkg_resources
import pandas
from pandas import concat
from openfisca_france_indirect_taxation.examples.utils_example import get_input_data_frame
from openfisca_france_indirect_taxation.build_survey_data.utils import find_neares... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py | get_inflators_cn_to_cn | python | def get_inflators_cn_to_cn(target_year):
'''
Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale.
'''
data_year = find_nearest_inferior(data_years, target_year)
data_year_cn_aggregates = get_cn_aggregates(data_year)['consoCN_COICOP_{}'.format(data_year)].to_dict()... | Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py#L98-L109 | [
"def find_nearest_inferior(years, year):\n # years = year_data_list\n anterior_years = [\n available_year for available_year in years if available_year <= year\n ]\n return max(anterior_years)\n",
"def get_cn_aggregates(target_year = None):\n assert target_year is not None\n default_c... | # -*- coding: utf-8 -*-
from __future__ import division
import logging
import os
import pkg_resources
import pandas
from pandas import concat
from openfisca_france_indirect_taxation.examples.utils_example import get_input_data_frame
from openfisca_france_indirect_taxation.build_survey_data.utils import find_neares... |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py | get_inflators | python | def get_inflators(target_year):
'''
Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf.
'''
data_year = find_nearest_inferior(data_years, target_year)
inflators_bdf_t... | Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf. | train | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/examples/calage_bdf_cn_bis.py#L112-L125 | [
"def find_nearest_inferior(years, year):\n # years = year_data_list\n anterior_years = [\n available_year for available_year in years if available_year <= year\n ]\n return max(anterior_years)\n",
"def get_inflators_bdf_to_cn(data_year):\n '''\n Calcule les ratios de calage (bdf sur c... | # -*- coding: utf-8 -*-
from __future__ import division
import logging
import os
import pkg_resources
import pandas
from pandas import concat
from openfisca_france_indirect_taxation.examples.utils_example import get_input_data_frame
from openfisca_france_indirect_taxation.build_survey_data.utils import find_neares... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound._retrieve_cached_zone_variable | python | def _retrieve_cached_zone_variable(self, zone_id, name):
try:
s = self._zone_state[zone_id][name.lower()]
logger.debug("Zone Cache retrieve %s.%s = %s",
zone_id.device_str(), name, s)
return s
except KeyError:
raise UncachedVariabl... | Retrieves the cache state of the named variable for a particular
zone. If the variable has not been cached then the UncachedVariable
exception is raised. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L78-L90 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound._store_cached_zone_variable | python | def _store_cached_zone_variable(self, zone_id, name, value):
zone_state = self._zone_state.setdefault(zone_id, {})
name = name.lower()
zone_state[name] = value
logger.debug("Zone Cache store %s.%s = %s",
zone_id.device_str(), name, value)
for callback in self... | Stores the current known value of a zone variable into the cache.
Calls any zone callbacks. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L92-L103 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound._retrieve_cached_source_variable | python | def _retrieve_cached_source_variable(self, source_id, name):
try:
s = self._source_state[source_id][name.lower()]
logger.debug("Source Cache retrieve S[%d].%s = %s",
source_id, name, s)
return s
except KeyError:
raise UncachedVaria... | Retrieves the cache state of the named variable for a particular
source. If the variable has not been cached then the UncachedVariable
exception is raised. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L105-L117 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound._store_cached_source_variable | python | def _store_cached_source_variable(self, source_id, name, value):
source_state = self._source_state.setdefault(source_id, {})
name = name.lower()
source_state[name] = value
logger.debug("Source Cache store S[%d].%s = %s",
source_id, name, value)
for callback i... | Stores the current known value of a source variable into the cache.
Calls any source callbacks. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L119-L130 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.connect | python | def connect(self):
logger.info("Connecting to %s:%s", self._host, self._port)
reader, writer = yield from asyncio.open_connection(
self._host, self._port, loop=self._loop)
self._ioloop_future = ensure_future(
self._ioloop(reader, writer), loop=self._loop)
... | Connect to the controller and start processing responses. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L247-L256 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.close | python | def close(self):
logger.info("Closing connection to %s:%s", self._host, self._port)
self._ioloop_future.cancel()
try:
yield from self._ioloop_future
except asyncio.CancelledError:
pass | Disconnect from the controller. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L259-L268 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.set_zone_variable | python | def set_zone_variable(self, zone_id, variable, value):
return self._send_cmd("SET %s.%s=\"%s\"" % (
zone_id.device_str(), variable, value)) | Set a zone variable to a new value. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L271-L276 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.get_zone_variable | python | def get_zone_variable(self, zone_id, variable):
try:
return self._retrieve_cached_zone_variable(zone_id, variable)
except UncachedVariable:
return (yield from self._send_cmd("GET %s.%s" % (
zone_id.device_str(), variable))) | Retrieve the current value of a zone variable. If the variable is
not found in the local cache then the value is requested from the
controller. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L279-L288 | [
"def _retrieve_cached_zone_variable(self, zone_id, name):\n \"\"\"\n Retrieves the cache state of the named variable for a particular\n zone. If the variable has not been cached then the UncachedVariable\n exception is raised.\n \"\"\"\n try:\n s = self._zone_state[zone_id][name.lower()]\n ... | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.get_cached_zone_variable | python | def get_cached_zone_variable(self, zone_id, variable, default=None):
try:
return self._retrieve_cached_zone_variable(zone_id, variable)
except UncachedVariable:
return default | Retrieve the current value of a zone variable from the cache or
return the default value if the variable is not present. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L290-L297 | [
"def _retrieve_cached_zone_variable(self, zone_id, name):\n \"\"\"\n Retrieves the cache state of the named variable for a particular\n zone. If the variable has not been cached then the UncachedVariable\n exception is raised.\n \"\"\"\n try:\n s = self._zone_state[zone_id][name.lower()]\n ... | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.watch_zone | python | def watch_zone(self, zone_id):
r = yield from self._send_cmd(
"WATCH %s ON" % (zone_id.device_str(), ))
self._watched_zones.add(zone_id)
return r | Add a zone to the watchlist.
Zones on the watchlist will push all
state changes (and those of the source they are currently connected to)
back to the client | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L300-L308 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.unwatch_zone | python | def unwatch_zone(self, zone_id):
self._watched_zones.remove(zone_id)
return (yield from
self._send_cmd("WATCH %s OFF" % (zone_id.device_str(), ))) | Remove a zone from the watchlist. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L311-L315 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.send_zone_event | python | def send_zone_event(self, zone_id, event_name, *args):
cmd = "EVENT %s!%s %s" % (
zone_id.device_str(), event_name,
" ".join(str(x) for x in args))
return (yield from self._send_cmd(cmd)) | Send an event to a zone. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L318-L323 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.enumerate_zones | python | def enumerate_zones(self):
zones = []
for controller in range(1, 8):
for zone in range(1, 17):
zone_id = ZoneID(zone, controller)
try:
name = yield from self.get_zone_variable(zone_id, 'name')
if name:
... | Return a list of (zone_id, zone_name) tuples | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L326-L338 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.set_source_variable | python | def set_source_variable(self, source_id, variable, value):
source_id = int(source_id)
return self._send_cmd("SET S[%d].%s=\"%s\"" % (
source_id, variable, value)) | Change the value of a source variable. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L341-L345 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.get_source_variable | python | def get_source_variable(self, source_id, variable):
source_id = int(source_id)
try:
return self._retrieve_cached_source_variable(
source_id, variable)
except UncachedVariable:
return (yield from self._send_cmd("GET S[%d].%s" % (
source... | Get the current value of a source variable. If the variable is not
in the cache it will be retrieved from the controller. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L348-L358 | [
"def _retrieve_cached_source_variable(self, source_id, name):\n \"\"\"\n Retrieves the cache state of the named variable for a particular\n source. If the variable has not been cached then the UncachedVariable\n exception is raised.\n \"\"\"\n try:\n s = self._source_state[source_id][name.l... | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.get_cached_source_variable | python | def get_cached_source_variable(self, source_id, variable, default=None):
source_id = int(source_id)
try:
return self._retrieve_cached_source_variable(
source_id, variable)
except UncachedVariable:
return default | Get the cached value of a source variable. If the variable is not
cached return the default value. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L360-L369 | [
"def _retrieve_cached_source_variable(self, source_id, name):\n \"\"\"\n Retrieves the cache state of the named variable for a particular\n source. If the variable has not been cached then the UncachedVariable\n exception is raised.\n \"\"\"\n try:\n s = self._source_state[source_id][name.l... | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.watch_source | python | def watch_source(self, source_id):
source_id = int(source_id)
r = yield from self._send_cmd(
"WATCH S[%d] ON" % (source_id, ))
self._watched_source.add(source_id)
return r | Add a souce to the watchlist. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L372-L378 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.unwatch_source | python | def unwatch_source(self, source_id):
source_id = int(source_id)
self._watched_sources.remove(source_id)
return (yield from
self._send_cmd("WATCH S[%d] OFF" % (
source_id, ))) | Remove a souce from the watchlist. | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L381-L387 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
wickerwaka/russound_rio | russound_rio/rio.py | Russound.enumerate_sources | python | def enumerate_sources(self):
sources = []
for source_id in range(1, 17):
try:
name = yield from self.get_source_variable(source_id, 'name')
if name:
sources.append((source_id, name))
except CommandException:
brea... | Return a list of (source_id, source_name) tuples | train | https://github.com/wickerwaka/russound_rio/blob/e331985fd1544abec6a1da3637090550d6f93f76/russound_rio/rio.py#L390-L400 | null | class Russound:
"""Manages the RIO connection to a Russound device."""
def __init__(self, loop, host, port=9621):
"""
Initialize the Russound object using the event loop, host and port
provided.
"""
self._loop = loop
self._host = host
self._port = port
... |
cimatosa/progression | progression/decorators.py | ProgressBar._get_callargs | python | def _get_callargs(self, *args, **kwargs):
callargs = getcallargs(self.func, *args, **kwargs)
return callargs | Retrieve all arguments that `self.func` needs and
return a dictionary with call arguments. | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/decorators.py#L130-L136 | null | class ProgressBar(object):
""" A wrapper/decorator with a text-based progress bar.
Methods:
- __init__
- __call__
The idea is to add a status bar for a regular
function just by wrapping the function via
python's decorator syntax.
In order to do so, the function needs to provide some
... |
cimatosa/progression | progression/terminal.py | get_terminal_size | python | def get_terminal_size(defaultw=80):
if hasattr(shutil_get_terminal_size, "__call__"):
return shutil_get_terminal_size()
else:
try:
import fcntl, termios, struct
fd = 0
hw = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
... | Checks various methods to determine the terminal size
Methods:
- shutil.get_terminal_size (only Python3)
- fcntl.ioctl
- subprocess.check_output
- os.environ
Parameters
----------
defaultw : int
Default width of terminal.
Returns
-------
width, height : int
... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/terminal.py#L40-L82 | null | # -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import sys
import subprocess as sp
import logging
import platform
if platform.system() == 'Windows':
width_correction = -1
else:
width_correction = 0
try:
from shutil import get_terminal_size as shutil_get_terminal_size
exc... |
cimatosa/progression | progression/terminal.py | terminal_reserve | python | def terminal_reserve(progress_obj, terminal_obj=None, identifier=None):
if terminal_obj is None:
terminal_obj = sys.stdout
if identifier is None:
identifier = ''
if terminal_obj in TERMINAL_RESERVATION: # terminal was already registered
log.debug("this terminal %s has already been... | Registers the terminal (stdout) for printing.
Useful to prevent multiple processes from writing progress bars
to stdout.
One process (server) prints to stdout and a couple of subprocesses
do not print to the same stdout, because the server has reserved it.
Of course, the clients have to be nice an... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/terminal.py#L95-L131 | null | # -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import sys
import subprocess as sp
import logging
import platform
if platform.system() == 'Windows':
width_correction = -1
else:
width_correction = 0
try:
from shutil import get_terminal_size as shutil_get_terminal_size
exc... |
cimatosa/progression | progression/terminal.py | terminal_unreserve | python | def terminal_unreserve(progress_obj, terminal_obj=None, verbose=0, identifier=None):
if terminal_obj is None:
terminal_obj = sys.stdout
if identifier is None:
identifier = ''
else:
identifier = identifier + ': '
po = TERMINAL_RESERVATION.get(terminal_obj)
if po is None:
... | Unregisters the terminal (stdout) for printing.
an instance (progress_obj) can only unreserve the tty (terminal_obj) when it also reserved it
see terminal_reserved for more information
Returns
-------
None | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/terminal.py#L134-L163 | null | # -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import sys
import subprocess as sp
import logging
import platform
if platform.system() == 'Windows':
width_correction = -1
else:
width_correction = 0
try:
from shutil import get_terminal_size as shutil_get_terminal_size
exc... |
cimatosa/progression | progression/progress.py | _loop_wrapper_func | python | def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name,
logging_level, conn_send, func_running, log_queue):
prefix = get_identifier(name) + ' '
global log
log = logging.getLogger(__name__+".log_{}".format(get_identifier(name, bold=False))... | to be executed as a separate process (that's why this functions is declared static) | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L263-L323 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Progression module
------------------
This module provides the (so far) four variants to display progress information:
* :py:class:`.ProgressBar`
This class monitors one or multiple processes showing the total elapsed time (TET), the current speed
... |
cimatosa/progression | progression/progress.py | show_stat_base | python | def show_stat_base(count_value, max_count_value, prepend, speed, tet, ttg, width, **kwargs):
raise NotImplementedError | A function that formats the progress information
This function will be called periodically for each progress that is monitored.
Overwrite this function in a subclass to implement a specific formating of the progress information
:param count_value: a number holding the current state
:param max_cou... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L574-L590 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Progression module
------------------
This module provides the (so far) four variants to display progress information:
* :py:class:`.ProgressBar`
This class monitors one or multiple processes showing the total elapsed time (TET), the current speed
... |
cimatosa/progression | progression/progress.py | _show_stat_wrapper_Progress | python | def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, add_args,
i, lock):
count_value, max_count_value, speed, tet, ttg, = Progress._calc(count,
... | calculate | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L592-L606 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Progression module
------------------
This module provides the (so far) four variants to display progress information:
* :py:class:`.ProgressBar`
This class monitors one or multiple processes showing the total elapsed time (TET), the current speed
... |
cimatosa/progression | progression/progress.py | _show_stat_wrapper_multi_Progress | python | def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, len_,
add_args, lock, info_line, no_move_up=False):
# print(ESC_BOLD, end='')
# ... | call the static method show_stat_wrapper for each process | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L608-L638 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Progression module
------------------
This module provides the (so far) four variants to display progress information:
* :py:class:`.ProgressBar`
This class monitors one or multiple processes showing the total elapsed time (TET), the current speed
... |
cimatosa/progression | progression/progress.py | getCountKwargs | python | def getCountKwargs(func):
# Get all arguments of the function
if hasattr(func, "__code__"):
func_args = func.__code__.co_varnames[:func.__code__.co_argcount]
for pair in validCountKwargs:
if ( pair[0] in func_args and pair[1] in func_args ):
return pair
# else
... | Returns a list ["count kwarg", "count_max kwarg"] for a
given function. Valid combinations are defined in
`progress.validCountKwargs`.
Returns None if no keyword arguments are found. | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L1378-L1392 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Progression module
------------------
This module provides the (so far) four variants to display progress information:
* :py:class:`.ProgressBar`
This class monitors one or multiple processes showing the total elapsed time (TET), the current speed
... |
cimatosa/progression | progression/progress.py | humanize_speed | python | def humanize_speed(c_per_sec):
scales = [60, 60, 24]
units = ['c/s', 'c/min', 'c/h', 'c/d']
speed = c_per_sec
i = 0
if speed > 0:
while (speed < 1) and (i < len(scales)):
speed *= scales[i]
i += 1
return "{:.1f}{}".format(speed, units[i]) | convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero. | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L1394-L1406 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Progression module
------------------
This module provides the (so far) four variants to display progress information:
* :py:class:`.ProgressBar`
This class monitors one or multiple processes showing the total elapsed time (TET), the current speed
... |
cimatosa/progression | progression/progress.py | humanize_time | python | def humanize_time(secs):
if secs is None:
return '--'
if secs < 1:
return "{:.2f}ms".format(secs*1000)
elif secs < 10:
return "{:.2f}s".format(secs)
else:
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return '{:02d}:{:02d}:{:02d}'.format(in... | convert second in to hh:mm:ss format | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L1409-L1422 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Progression module
------------------
This module provides the (so far) four variants to display progress information:
* :py:class:`.ProgressBar`
This class monitors one or multiple processes showing the total elapsed time (TET), the current speed
... |
cimatosa/progression | progression/progress.py | Loop.__cleanup | python | def __cleanup(self):
# set run to False and wait some time -> see what happens
self._run.value = False
if check_process_termination(proc = self._proc,
timeout = 2*self.interval,
... | Wait at most twice as long as the given repetition interval
for the _wrapper_function to terminate.
If after that time the _wrapper_function has not terminated,
send SIGTERM to and the process.
Wait at most five times as long as the given repetition interval
for... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L422-L454 | [
"def check_process_termination(proc, prefix, timeout, auto_kill_on_last_resort = False):\n proc.join(timeout)\n if not proc.is_alive():\n log.debug(\"termination of process (pid %s) within timeout of %s SUCCEEDED!\", proc.pid, humanize_time(timeout))\n return True\n\n # process still runs -> ... | class Loop(object):
"""
class to run a function periodically an seperate process.
In case the called function returns True, the loop will stop.
Otherwise a time interval given by interval will be slept before
another execution is triggered.
The shared memory variable _run (accessible via the c... |
cimatosa/progression | progression/progress.py | Loop.start | python | def start(self, timeout=None):
if self.is_alive():
log.warning("a process with pid %s is already running", self._proc.pid)
return
self._run.value = True
self._func_running.value = False
name = self.__class__.__name__
self.conn_recv, ... | uses multiprocess Process to call _wrapper_func in subprocess | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L465-L516 | [
"def is_alive(self):\n if self._proc is None:\n return False\n else:\n return self._proc.is_alive()\n"
] | class Loop(object):
"""
class to run a function periodically an seperate process.
In case the called function returns True, the loop will stop.
Otherwise a time interval given by interval will be slept before
another execution is triggered.
The shared memory variable _run (accessible via the c... |
cimatosa/progression | progression/progress.py | Loop.stop | python | def stop(self):
"""
stops the process triggered by start
Setting the shared memory boolean run to false, which should prevent
the loop from repeating. Call __cleanup to make sure the process
stopped. After that we could trigger start() again.
"""
... | stops the process triggered by start
Setting the shared memory boolean run to false, which should prevent
the loop from repeating. Call __cleanup to make sure the process
stopped. After that we could trigger start() again. | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L518-L537 | [
"def __cleanup(self):\n \"\"\"\n Wait at most twice as long as the given repetition interval\n for the _wrapper_function to terminate.\n\n If after that time the _wrapper_function has not terminated,\n send SIGTERM to and the process.\n\n Wait at most five times as long as the given repetition int... | class Loop(object):
"""
class to run a function periodically an seperate process.
In case the called function returns True, the loop will stop.
Otherwise a time interval given by interval will be slept before
another execution is triggered.
The shared memory variable _run (accessible via the c... |
cimatosa/progression | progression/progress.py | Progress._calc | python | def _calc(count,
last_count,
start_time,
max_count,
speed_calc_cycles,
q,
last_speed,
lock):
count_value = count.value
start_time_value = start_time.value
current_time = time.time()
... | do the pre calculations in order to get TET, speed, TTG
:param count: count
:param last_count: count at the last call, allows to treat the case of no progress
between sequential calls
:param start_time: the time when start was triggered
... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L806-L874 | null | class Progress(Loop):
"""
Abstract Progress Class
The :py:class:`Progress` Class uses :py:class:`Loop` to provide a repeating
function which calculates progress information from a changing counter value.
The formatting of these information is done by overwriting the static member
:py:func:`Prog... |
cimatosa/progression | progression/progress.py | Progress._reset_i | python | def _reset_i(self, i):
self.count[i].value=0
log.debug("reset counter %s", i)
self.lock[i].acquire()
for x in range(self.q[i].qsize()):
self.q[i].get()
self.lock[i].release()
self.start_time[i].value = time.time() | reset i-th progress information | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L883-L894 | null | class Progress(Loop):
"""
Abstract Progress Class
The :py:class:`Progress` Class uses :py:class:`Loop` to provide a repeating
function which calculates progress information from a changing counter value.
The formatting of these information is done by overwriting the static member
:py:func:`Prog... |
cimatosa/progression | progression/progress.py | Progress._show_stat | python | def _show_stat(self):
_show_stat_wrapper_multi_Progress(self.count,
self.last_count,
self.start_time,
self.max_count,
self.speed_calc_cycles,... | convenient functions to call the static show_stat_wrapper_multi with
the given class members | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L896-L915 | [
"def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles, \n width, q, last_speed, prepend, show_stat_function, len_, \n add_args, lock, info_line, no_move_up=False):\n \"\"\"\n call the sta... | class Progress(Loop):
"""
Abstract Progress Class
The :py:class:`Progress` Class uses :py:class:`Loop` to provide a repeating
function which calculates progress information from a changing counter value.
The formatting of these information is done by overwriting the static member
:py:func:`Prog... |
cimatosa/progression | progression/progress.py | Progress.start | python | def start(self):
# before printing any output to stout, we can now check this
# variable to see if any other ProgressBar has reserved that
# terminal.
if (self.__class__.__name__ in terminal.TERMINAL_PRINT_LOOP_CLASSES):
if not terminal.terminal_reserve(progress_obj=... | start | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L931-L945 | [
"def start(self, timeout=None):\n \"\"\"\n uses multiprocess Process to call _wrapper_func in subprocess \n \"\"\"\n\n if self.is_alive():\n log.warning(\"a process with pid %s is already running\", self._proc.pid)\n return\n\n self._run.value = True\n self._func_running.value = Fals... | class Progress(Loop):
"""
Abstract Progress Class
The :py:class:`Progress` Class uses :py:class:`Loop` to provide a repeating
function which calculates progress information from a changing counter value.
The formatting of these information is done by overwriting the static member
:py:func:`Prog... |
cimatosa/progression | progression/progress.py | Progress.stop | python | def stop(self):
super(Progress, self).stop()
terminal.terminal_unreserve(progress_obj=self, verbose=self.verbose)
if self.show_on_exit:
if not isinstance(self.pipe_handler, PipeToPrint):
myout = inMemoryBuffer()
stdout = sys.stdout
sys... | trigger clean up by hand, needs to be done when not using
context management via 'with' statement
- will terminate loop process
- show a last progress -> see the full 100% on exit
- releases terminal reservation | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L947-L970 | [
"def stop(self):\n \"\"\"\n stops the process triggered by start\n\n Setting the shared memory boolean run to false, which should prevent\n the loop from repeating. Call __cleanup to make sure the process\n stopped. After that we could trigger start() again.\n \"\"\" \n if self.is_alive(... | class Progress(Loop):
"""
Abstract Progress Class
The :py:class:`Progress` Class uses :py:class:`Loop` to provide a repeating
function which calculates progress information from a changing counter value.
The formatting of these information is done by overwriting the static member
:py:func:`Prog... |
rcarmo/pngcanvas | pngcanvas.py | blend | python | def blend(c1, c2):
return [c1[i] * (0xFF - c2[3]) + c2[i] * c2[3] >> 8 for i in range(3)] | Alpha blends two colors, using the alpha given by c2 | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L36-L38 | null | """Simple PNG Canvas for Python - updated for bytearray()"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
__version__ = "1.0.3"
__license__ = "MIT"
import struct
import sys
import zlib
# Py2 - Py3 compatibility
if sys.version < '3':
range = xrange # NOQA
# Colo... |
rcarmo/pngcanvas | pngcanvas.py | gradient_list | python | def gradient_list(start, end, steps):
delta = [end[i] - start[i] for i in range(4)]
return [bytearray(start[j] + (delta[j] * i) // steps for j in range(4))
for i in range(steps + 1)] | Compute gradient colors | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L51-L55 | null | """Simple PNG Canvas for Python - updated for bytearray()"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
__version__ = "1.0.3"
__license__ = "MIT"
import struct
import sys
import zlib
# Py2 - Py3 compatibility
if sys.version < '3':
range = xrange # NOQA
# Colo... |
rcarmo/pngcanvas | pngcanvas.py | rgb2rgba | python | def rgb2rgba(rgb):
rgba = []
for i in range(0, len(rgb), 3):
rgba += rgb[i:i+3]
rgba.append(255)
return rgba | Take a row of RGB bytes, and convert to a row of RGBA bytes. | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L58-L65 | null | """Simple PNG Canvas for Python - updated for bytearray()"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
__version__ = "1.0.3"
__license__ = "MIT"
import struct
import sys
import zlib
# Py2 - Py3 compatibility
if sys.version < '3':
range = xrange # NOQA
# Colo... |
rcarmo/pngcanvas | pngcanvas.py | ByteReader.read | python | def read(self, num_bytes):
while len(self.decoded) < num_bytes:
try:
tag, data = next(self.chunks)
except StopIteration:
raise EOFError()
if tag != b'IDAT':
continue
self.decoded += self.decompressor.decompress(data)... | Read `num_bytes` from the compressed data chunks.
Data is returned as `bytes` of length `num_bytes`
Will raise an EOFError if data is unavailable.
Note: Will always return `num_bytes` of data (unlike the file read method). | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L74-L95 | null | class ByteReader(object):
def __init__(self, chunks):
self.chunks = chunks
self.decoded = b''
self.decompressor = zlib.decompressobj()
|
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas._offset | python | def _offset(self, x, y):
x, y = force_int(x, y)
return y * self.width * 4 + x * 4 | Helper for internal data | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L108-L111 | [
"def force_int(*args):\n return tuple(int(x) for x in args)\n"
] | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.point | python | def point(self, x, y, color=None):
if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1:
return
if color is None:
color = self.color
o = self._offset(x, y)
self.canvas[o:o + 3] = blend(self.canvas[o:o + 3], bytearray(color)) | Set a pixel | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L113-L121 | [
"def blend(c1, c2):\n \"\"\"Alpha blends two colors, using the alpha given by c2\"\"\"\n return [c1[i] * (0xFF - c2[3]) + c2[i] * c2[3] >> 8 for i in range(3)]\n",
"def _offset(self, x, y):\n \"\"\"Helper for internal data\"\"\"\n x, y = force_int(x, y)\n return y * self.width * 4 + x * 4\n"
] | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.rect_helper | python | def rect_helper(x0, y0, x1, y1):
x0, y0, x1, y1 = force_int(x0, y0, x1, y1)
if x0 > x1:
x0, x1 = x1, x0
if y0 > y1:
y0, y1 = y1, y0
return x0, y0, x1, y1 | Rectangle helper | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L124-L131 | [
"def force_int(*args):\n return tuple(int(x) for x in args)\n"
] | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.vertical_gradient | python | def vertical_gradient(self, x0, y0, x1, y1, start, end):
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
grad = gradient_list(start, end, y1 - y0)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
self.point(x, y, grad[y - y0]) | Draw a vertical gradient | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L133-L139 | [
"def gradient_list(start, end, steps):\n \"\"\"Compute gradient colors\"\"\"\n delta = [end[i] - start[i] for i in range(4)]\n return [bytearray(start[j] + (delta[j] * i) // steps for j in range(4))\n for i in range(steps + 1)]\n",
"def point(self, x, y, color=None):\n \"\"\"Set a pixel\"\"... | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.rectangle | python | def rectangle(self, x0, y0, x1, y1):
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
self.polyline([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]]) | Draw a rectangle | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L141-L144 | [
"def rect_helper(x0, y0, x1, y1):\n \"\"\"Rectangle helper\"\"\"\n x0, y0, x1, y1 = force_int(x0, y0, x1, y1)\n if x0 > x1:\n x0, x1 = x1, x0\n if y0 > y1:\n y0, y1 = y1, y0\n return x0, y0, x1, y1\n",
"def polyline(self, arr):\n \"\"\"Draw a set of lines\"\"\"\n for i in range(... | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.filled_rectangle | python | def filled_rectangle(self, x0, y0, x1, y1):
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
self.point(x, y, self.color) | Draw a filled rectangle | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L146-L151 | [
"def point(self, x, y, color=None):\n \"\"\"Set a pixel\"\"\"\n if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1:\n return\n if color is None:\n color = self.color\n o = self._offset(x, y)\n\n self.canvas[o:o + 3] = blend(self.canvas[o:o + 3], bytearray(color))\n",
"def ... | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.copy_rect | python | def copy_rect(self, x0, y0, x1, y1, dx, dy, destination):
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
dx, dy = force_int(dx, dy)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
d = destination._offset(dx + x - x0, dy + y - y0)
o = self._... | Copy (blit) a rectangle onto another part of the image | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L153-L162 | [
"def force_int(*args):\n return tuple(int(x) for x in args)\n",
"def _offset(self, x, y):\n \"\"\"Helper for internal data\"\"\"\n x, y = force_int(x, y)\n return y * self.width * 4 + x * 4\n",
"def rect_helper(x0, y0, x1, y1):\n \"\"\"Rectangle helper\"\"\"\n x0, y0, x1, y1 = force_int(x0, y0... | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.blend_rect | python | def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff):
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
o = self._offset(x, y)
rgba = self.canvas[o:o + 4]
rgba[3] = alpha
... | Blend a rectangle onto the image | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L164-L172 | [
"def _offset(self, x, y):\n \"\"\"Helper for internal data\"\"\"\n x, y = force_int(x, y)\n return y * self.width * 4 + x * 4\n",
"def point(self, x, y, color=None):\n \"\"\"Set a pixel\"\"\"\n if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1:\n return\n if color is None:\n ... | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.line | python | def line(self, x0, y0, x1, y1):
# clean params
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
if y0 > y1:
y0, y1, x0, x1 = y1, y0, x1, x0
dx = x1 - x0
if dx < 0:
sx = -1
else:
sx = 1
dx *= sx
dy = y1 - y0
#... | Draw a line using Xiaolin Wu's antialiasing technique | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L174-L230 | null | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.polyline | python | def polyline(self, arr):
for i in range(0, len(arr) - 1):
self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]) | Draw a set of lines | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L232-L235 | [
"def line(self, x0, y0, x1, y1):\n \"\"\"Draw a line using Xiaolin Wu's antialiasing technique\"\"\"\n # clean params\n x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)\n if y0 > y1:\n y0, y1, x0, x1 = y1, y0, x1, x0\n dx = x1 - x0\n if dx < 0:\n sx = -1\n else:\n sx = 1... | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.dump | python | def dump(self):
scan_lines = bytearray()
for y in range(self.height):
scan_lines.append(0) # filter type 0 (None)
scan_lines.extend(
self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
)
# image represented as RGBA tuples, no interlac... | Dump the image data | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L237-L251 | [
"def pack_chunk(tag, data):\n \"\"\"Pack a PNG chunk for serializing to disk\"\"\"\n to_check = tag + data\n return (struct.pack(b\"!I\", len(data)) + to_check +\n struct.pack(b\"!I\", zlib.crc32(to_check) & 0xFFFFFFFF))\n"
] | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.pack_chunk | python | def pack_chunk(tag, data):
to_check = tag + data
return (struct.pack(b"!I", len(data)) + to_check +
struct.pack(b"!I", zlib.crc32(to_check) & 0xFFFFFFFF)) | Pack a PNG chunk for serializing to disk | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L254-L258 | null | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.load | python | def load(self, f):
SUPPORTED_COLOR_TYPES = (COLOR_TYPE_TRUECOLOR, COLOR_TYPE_TRUECOLOR_WITH_ALPHA)
SAMPLES_PER_PIXEL = { COLOR_TYPE_TRUECOLOR: 3,
COLOR_TYPE_TRUECOLOR_WITH_ALPHA: 4 }
assert f.read(8) == SIGNATURE
chunks = iter(self.chunks(f))
heade... | Load a PNG image | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L260-L307 | [
"def rgb2rgba(rgb):\n \"\"\"Take a row of RGB bytes, and convert to a row of RGBA bytes.\"\"\"\n rgba = []\n for i in range(0, len(rgb), 3):\n rgba += rgb[i:i+3]\n rgba.append(255)\n\n return rgba\n",
"def read(self, num_bytes):\n \"\"\"Read `num_bytes` from the compressed data chunks... | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.defilter | python | def defilter(cur, prev, filter_type, bpp=4):
if filter_type == 0: # No filter
return cur
elif filter_type == 1: # Sub
xp = 0
for xc in range(bpp, len(cur)):
cur[xc] = (cur[xc] + cur[xp]) % 256
xp += 1
elif filter_type == 2: #... | Decode a chunk | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L310-L351 | null | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
rcarmo/pngcanvas | pngcanvas.py | PNGCanvas.chunks | python | def chunks(f):
while 1:
try:
length = struct.unpack(b"!I", f.read(4))[0]
tag = f.read(4)
data = f.read(length)
crc = struct.unpack(b"!I", f.read(4))[0]
except struct.error:
return
if zlib.crc32(ta... | Split read PNG image data into chunks | train | https://github.com/rcarmo/pngcanvas/blob/e2eaa0d5ba353005b3b658f6ee453c1956340670/pngcanvas.py#L354-L366 | null | class PNGCanvas(object):
def __init__(self, width, height,
bgcolor=(0xff, 0xff, 0xff, 0xff),
color=(0, 0, 0, 0xff)):
self.width = width
self.height = height
self.color = bytearray(color) # rgba
self.bgcolor = bytearray(bgcolor)
self.canvas =... |
cnelson/python-fleet | fleet/v1/objects/unit.py | Unit._set_options_from_file | python | def _set_options_from_file(self, file_handle):
# TODO: Find a library to handle this unit file parsing
# Can't use configparser, it doesn't handle multiple entries for the same key in the same section
# This is terribly naive
# build our output here
options = []
# keep... | Parses a unit file and updates self._data['options']
Args:
file_handle (file): a file-like object (supporting read()) containing a unit
Returns:
True: The file was successfuly parsed and options were updated
Raises:
IOError: from_file was specified and it d... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/objects/unit.py#L134-L224 | null | class Unit(FleetObject):
"""This object represents a Unit in Fleet
Create and modify Unit entities to communicate to fleet the desired state of the cluster.
This simply declares what should be happening; the backend system still has to react to the changes in
this desired state. The actual state of the... |
cnelson/python-fleet | fleet/v1/objects/unit.py | Unit.add_option | python | def add_option(self, section, name, value):
# Don't allow updating units we loaded from fleet, it's not supported
if self._is_live():
raise RuntimeError('Submitted units cannot update their options')
option = {
'section': section,
'name': name,
'... | Add an option to a section of the unit file
Args:
section (str): The name of the section, If it doesn't exist it will be created
name (str): The name of the option to add
value (str): The value of the option
Returns:
True: The item was added | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/objects/unit.py#L241-L266 | [
"def _is_live(self):\n \"\"\"Checks to see if this unit came from fleet, or was created locally\n\n Only units with a .name property (set by the server), and _client property are considered 'live'\n\n Returns:\n True: The object is live\n False: The object is not\n\n \"\"\"\n if 'name' ... | class Unit(FleetObject):
"""This object represents a Unit in Fleet
Create and modify Unit entities to communicate to fleet the desired state of the cluster.
This simply declares what should be happening; the backend system still has to react to the changes in
this desired state. The actual state of the... |
cnelson/python-fleet | fleet/v1/objects/unit.py | Unit.remove_option | python | def remove_option(self, section, name, value=None):
# Don't allow updating units we loaded from fleet, it's not supported
if self._is_live():
raise RuntimeError('Submitted units cannot update their options')
removed = 0
# iterate through a copy of the options
for opt... | Remove an option from a unit
Args:
section (str): The section to remove from.
name (str): The item to remove.
value (str, optional): If specified, only the option matching this value will be removed
If not specified, all options with ``name... | train | https://github.com/cnelson/python-fleet/blob/a11dcd8bb3986d1d8f0af90d2da7399c9cc54b4d/fleet/v1/objects/unit.py#L268-L302 | [
"def _is_live(self):\n \"\"\"Checks to see if this unit came from fleet, or was created locally\n\n Only units with a .name property (set by the server), and _client property are considered 'live'\n\n Returns:\n True: The object is live\n False: The object is not\n\n \"\"\"\n if 'name' ... | class Unit(FleetObject):
"""This object represents a Unit in Fleet
Create and modify Unit entities to communicate to fleet the desired state of the cluster.
This simply declares what should be happening; the backend system still has to react to the changes in
this desired state. The actual state of the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.