repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
klen/pylama | pylama/libs/inirama.py | InterpolationSection.iteritems | def iteritems(self, raw=False):
""" Iterate self items. """
for key in self:
yield key, self.__getitem__(key, raw=raw) | python | def iteritems(self, raw=False):
""" Iterate self items. """
for key in self:
yield key, self.__getitem__(key, raw=raw) | [
"def",
"iteritems",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"for",
"key",
"in",
"self",
":",
"yield",
"key",
",",
"self",
".",
"__getitem__",
"(",
"key",
",",
"raw",
"=",
"raw",
")"
] | Iterate self items. | [
"Iterate",
"self",
"items",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L242-L246 | train | 206,200 |
klen/pylama | pylama/libs/inirama.py | Namespace.read | def read(self, *files, **params):
""" Read and parse INI files.
:param *files: Files for reading
:param **params: Params for parsing
Set `update=False` for prevent values redefinition.
"""
for f in files:
try:
with io.open(f, encoding='utf-8') as ff:
NS_LOGGER.info('Read from `{0}`'.format(ff.name))
self.parse(ff.read(), **params)
except (IOError, TypeError, SyntaxError, io.UnsupportedOperation):
if not self.silent_read:
NS_LOGGER.error('Reading error `{0}`'.format(ff.name))
raise | python | def read(self, *files, **params):
""" Read and parse INI files.
:param *files: Files for reading
:param **params: Params for parsing
Set `update=False` for prevent values redefinition.
"""
for f in files:
try:
with io.open(f, encoding='utf-8') as ff:
NS_LOGGER.info('Read from `{0}`'.format(ff.name))
self.parse(ff.read(), **params)
except (IOError, TypeError, SyntaxError, io.UnsupportedOperation):
if not self.silent_read:
NS_LOGGER.error('Reading error `{0}`'.format(ff.name))
raise | [
"def",
"read",
"(",
"self",
",",
"*",
"files",
",",
"*",
"*",
"params",
")",
":",
"for",
"f",
"in",
"files",
":",
"try",
":",
"with",
"io",
".",
"open",
"(",
"f",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"ff",
":",
"NS_LOGGER",
".",
"info",
... | Read and parse INI files.
:param *files: Files for reading
:param **params: Params for parsing
Set `update=False` for prevent values redefinition. | [
"Read",
"and",
"parse",
"INI",
"files",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L297-L314 | train | 206,201 |
klen/pylama | pylama/libs/inirama.py | Namespace.write | def write(self, f):
""" Write namespace as INI file.
:param f: File object or path to file.
"""
if isinstance(f, str):
f = io.open(f, 'w', encoding='utf-8')
if not hasattr(f, 'read'):
raise AttributeError("Wrong type of file: {0}".format(type(f)))
NS_LOGGER.info('Write to `{0}`'.format(f.name))
for section in self.sections.keys():
f.write('[{0}]\n'.format(section))
for k, v in self[section].items():
f.write('{0:15}= {1}\n'.format(k, v))
f.write('\n')
f.close() | python | def write(self, f):
""" Write namespace as INI file.
:param f: File object or path to file.
"""
if isinstance(f, str):
f = io.open(f, 'w', encoding='utf-8')
if not hasattr(f, 'read'):
raise AttributeError("Wrong type of file: {0}".format(type(f)))
NS_LOGGER.info('Write to `{0}`'.format(f.name))
for section in self.sections.keys():
f.write('[{0}]\n'.format(section))
for k, v in self[section].items():
f.write('{0:15}= {1}\n'.format(k, v))
f.write('\n')
f.close() | [
"def",
"write",
"(",
"self",
",",
"f",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"str",
")",
":",
"f",
"=",
"io",
".",
"open",
"(",
"f",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"not",
"hasattr",
"(",
"f",
",",
"'read'",
")"... | Write namespace as INI file.
:param f: File object or path to file. | [
"Write",
"namespace",
"as",
"INI",
"file",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L316-L334 | train | 206,202 |
klen/pylama | pylama/libs/inirama.py | Namespace.parse | def parse(self, source, update=True, **params):
""" Parse INI source as string.
:param source: Source of INI
:param update: Replace already defined items
"""
scanner = INIScanner(source)
scanner.scan()
section = self.default_section
name = None
for token in scanner.tokens:
if token[0] == 'KEY_VALUE':
name, value = re.split('[=:]', token[1], 1)
name, value = name.strip(), value.strip()
if not update and name in self[section]:
continue
self[section][name] = value
elif token[0] == 'SECTION':
section = token[1].strip('[]')
elif token[0] == 'CONTINUATION':
if not name:
raise SyntaxError(
"SyntaxError[@char {0}: {1}]".format(
token[2], "Bad continuation."))
self[section][name] += '\n' + token[1].strip() | python | def parse(self, source, update=True, **params):
""" Parse INI source as string.
:param source: Source of INI
:param update: Replace already defined items
"""
scanner = INIScanner(source)
scanner.scan()
section = self.default_section
name = None
for token in scanner.tokens:
if token[0] == 'KEY_VALUE':
name, value = re.split('[=:]', token[1], 1)
name, value = name.strip(), value.strip()
if not update and name in self[section]:
continue
self[section][name] = value
elif token[0] == 'SECTION':
section = token[1].strip('[]')
elif token[0] == 'CONTINUATION':
if not name:
raise SyntaxError(
"SyntaxError[@char {0}: {1}]".format(
token[2], "Bad continuation."))
self[section][name] += '\n' + token[1].strip() | [
"def",
"parse",
"(",
"self",
",",
"source",
",",
"update",
"=",
"True",
",",
"*",
"*",
"params",
")",
":",
"scanner",
"=",
"INIScanner",
"(",
"source",
")",
"scanner",
".",
"scan",
"(",
")",
"section",
"=",
"self",
".",
"default_section",
"name",
"="... | Parse INI source as string.
:param source: Source of INI
:param update: Replace already defined items | [
"Parse",
"INI",
"source",
"as",
"string",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/libs/inirama.py#L336-L365 | train | 206,203 |
klen/pylama | pylama/core.py | parse_modeline | def parse_modeline(code):
"""Parse params from file's modeline.
:return dict: Linter params.
"""
seek = MODELINE_RE.search(code)
if seek:
return dict(v.split('=') for v in seek.group(1).split(':'))
return dict() | python | def parse_modeline(code):
"""Parse params from file's modeline.
:return dict: Linter params.
"""
seek = MODELINE_RE.search(code)
if seek:
return dict(v.split('=') for v in seek.group(1).split(':'))
return dict() | [
"def",
"parse_modeline",
"(",
"code",
")",
":",
"seek",
"=",
"MODELINE_RE",
".",
"search",
"(",
"code",
")",
"if",
"seek",
":",
"return",
"dict",
"(",
"v",
".",
"split",
"(",
"'='",
")",
"for",
"v",
"in",
"seek",
".",
"group",
"(",
"1",
")",
".",... | Parse params from file's modeline.
:return dict: Linter params. | [
"Parse",
"params",
"from",
"file",
"s",
"modeline",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/core.py#L106-L116 | train | 206,204 |
klen/pylama | pylama/core.py | prepare_params | def prepare_params(modeline, fileconfig, options):
"""Prepare and merge a params from modelines and configs.
:return dict:
"""
params = dict(skip=False, ignore=[], select=[], linters=[])
if options:
params['ignore'] = list(options.ignore)
params['select'] = list(options.select)
for config in filter(None, [modeline, fileconfig]):
for key in ('ignore', 'select', 'linters'):
params[key] += process_value(key, config.get(key, []))
params['skip'] = bool(int(config.get('skip', False)))
# TODO: skip what? This is causing erratic behavior for linters.
params['skip'] = False
params['ignore'] = set(params['ignore'])
params['select'] = set(params['select'])
return params | python | def prepare_params(modeline, fileconfig, options):
"""Prepare and merge a params from modelines and configs.
:return dict:
"""
params = dict(skip=False, ignore=[], select=[], linters=[])
if options:
params['ignore'] = list(options.ignore)
params['select'] = list(options.select)
for config in filter(None, [modeline, fileconfig]):
for key in ('ignore', 'select', 'linters'):
params[key] += process_value(key, config.get(key, []))
params['skip'] = bool(int(config.get('skip', False)))
# TODO: skip what? This is causing erratic behavior for linters.
params['skip'] = False
params['ignore'] = set(params['ignore'])
params['select'] = set(params['select'])
return params | [
"def",
"prepare_params",
"(",
"modeline",
",",
"fileconfig",
",",
"options",
")",
":",
"params",
"=",
"dict",
"(",
"skip",
"=",
"False",
",",
"ignore",
"=",
"[",
"]",
",",
"select",
"=",
"[",
"]",
",",
"linters",
"=",
"[",
"]",
")",
"if",
"options"... | Prepare and merge a params from modelines and configs.
:return dict: | [
"Prepare",
"and",
"merge",
"a",
"params",
"from",
"modelines",
"and",
"configs",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/core.py#L119-L140 | train | 206,205 |
klen/pylama | pylama/core.py | filter_errors | def filter_errors(errors, select=None, ignore=None, **params):
"""Filter errors by select and ignore options.
:return bool:
"""
select = select or []
ignore = ignore or []
for e in errors:
for s in select:
if e.number.startswith(s):
yield e
break
else:
for s in ignore:
if e.number.startswith(s):
break
else:
yield e | python | def filter_errors(errors, select=None, ignore=None, **params):
"""Filter errors by select and ignore options.
:return bool:
"""
select = select or []
ignore = ignore or []
for e in errors:
for s in select:
if e.number.startswith(s):
yield e
break
else:
for s in ignore:
if e.number.startswith(s):
break
else:
yield e | [
"def",
"filter_errors",
"(",
"errors",
",",
"select",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"select",
"=",
"select",
"or",
"[",
"]",
"ignore",
"=",
"ignore",
"or",
"[",
"]",
"for",
"e",
"in",
"errors",
":",
"... | Filter errors by select and ignore options.
:return bool: | [
"Filter",
"errors",
"by",
"select",
"and",
"ignore",
"options",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/core.py#L143-L162 | train | 206,206 |
klen/pylama | pylama/core.py | filter_skiplines | def filter_skiplines(code, errors):
"""Filter lines by `noqa`.
:return list: A filtered errors
"""
if not errors:
return errors
enums = set(er.lnum for er in errors)
removed = set([
num for num, l in enumerate(code.split('\n'), 1)
if num in enums and SKIP_PATTERN(l)
])
if removed:
errors = [er for er in errors if er.lnum not in removed]
return errors | python | def filter_skiplines(code, errors):
"""Filter lines by `noqa`.
:return list: A filtered errors
"""
if not errors:
return errors
enums = set(er.lnum for er in errors)
removed = set([
num for num, l in enumerate(code.split('\n'), 1)
if num in enums and SKIP_PATTERN(l)
])
if removed:
errors = [er for er in errors if er.lnum not in removed]
return errors | [
"def",
"filter_skiplines",
"(",
"code",
",",
"errors",
")",
":",
"if",
"not",
"errors",
":",
"return",
"errors",
"enums",
"=",
"set",
"(",
"er",
".",
"lnum",
"for",
"er",
"in",
"errors",
")",
"removed",
"=",
"set",
"(",
"[",
"num",
"for",
"num",
",... | Filter lines by `noqa`.
:return list: A filtered errors | [
"Filter",
"lines",
"by",
"noqa",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/core.py#L165-L183 | train | 206,207 |
klen/pylama | pylama/check_async.py | check_async | def check_async(paths, options, rootdir=None):
"""Check given paths asynchronously.
:return list: list of errors
"""
LOGGER.info('Async code checking is enabled.')
path_queue = Queue.Queue()
result_queue = Queue.Queue()
for num in range(CPU_COUNT):
worker = Worker(path_queue, result_queue)
worker.setDaemon(True)
LOGGER.info('Start worker #%s', (num + 1))
worker.start()
for path in paths:
path_queue.put((path, dict(options=options, rootdir=rootdir)))
path_queue.join()
errors = []
while True:
try:
errors += result_queue.get(False)
except Queue.Empty:
break
return errors | python | def check_async(paths, options, rootdir=None):
"""Check given paths asynchronously.
:return list: list of errors
"""
LOGGER.info('Async code checking is enabled.')
path_queue = Queue.Queue()
result_queue = Queue.Queue()
for num in range(CPU_COUNT):
worker = Worker(path_queue, result_queue)
worker.setDaemon(True)
LOGGER.info('Start worker #%s', (num + 1))
worker.start()
for path in paths:
path_queue.put((path, dict(options=options, rootdir=rootdir)))
path_queue.join()
errors = []
while True:
try:
errors += result_queue.get(False)
except Queue.Empty:
break
return errors | [
"def",
"check_async",
"(",
"paths",
",",
"options",
",",
"rootdir",
"=",
"None",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Async code checking is enabled.'",
")",
"path_queue",
"=",
"Queue",
".",
"Queue",
"(",
")",
"result_queue",
"=",
"Queue",
".",
"Queue",
... | Check given paths asynchronously.
:return list: list of errors | [
"Check",
"given",
"paths",
"asynchronously",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/check_async.py#L44-L72 | train | 206,208 |
klen/pylama | pylama/check_async.py | Worker.run | def run(self):
""" Run tasks from queue. """
while True:
path, params = self.path_queue.get()
errors = run(path, **params)
self.result_queue.put(errors)
self.path_queue.task_done() | python | def run(self):
""" Run tasks from queue. """
while True:
path, params = self.path_queue.get()
errors = run(path, **params)
self.result_queue.put(errors)
self.path_queue.task_done() | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"path",
",",
"params",
"=",
"self",
".",
"path_queue",
".",
"get",
"(",
")",
"errors",
"=",
"run",
"(",
"path",
",",
"*",
"*",
"params",
")",
"self",
".",
"result_queue",
".",
"put",
"(",... | Run tasks from queue. | [
"Run",
"tasks",
"from",
"queue",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/check_async.py#L35-L41 | train | 206,209 |
klen/pylama | pylama/lint/pylama_mypy.py | _MyPyMessage._parse | def _parse(self, line):
"""Parse the output line"""
try:
result = line.split(':', maxsplit=4)
filename, line_num_txt, column_txt, message_type, text = result
except ValueError:
return
try:
self.line_num = int(line_num_txt.strip())
self.column = int(column_txt.strip())
except ValueError:
return
self.filename = filename
self.message_type = message_type.strip()
self.text = text.strip()
self.valid = True | python | def _parse(self, line):
"""Parse the output line"""
try:
result = line.split(':', maxsplit=4)
filename, line_num_txt, column_txt, message_type, text = result
except ValueError:
return
try:
self.line_num = int(line_num_txt.strip())
self.column = int(column_txt.strip())
except ValueError:
return
self.filename = filename
self.message_type = message_type.strip()
self.text = text.strip()
self.valid = True | [
"def",
"_parse",
"(",
"self",
",",
"line",
")",
":",
"try",
":",
"result",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"maxsplit",
"=",
"4",
")",
"filename",
",",
"line_num_txt",
",",
"column_txt",
",",
"message_type",
",",
"text",
"=",
"result",
"ex... | Parse the output line | [
"Parse",
"the",
"output",
"line"
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_mypy.py#L27-L44 | train | 206,210 |
klen/pylama | pylama/lint/pylama_mypy.py | _MyPyMessage.to_result | def to_result(self):
"""Convert to the Linter.run return value"""
text = [self.text]
if self.note:
text.append(self.note)
return {
'lnum': self.line_num,
'col': self.column,
'text': ' - '.join(text),
'type': self.types.get(self.message_type, '')
} | python | def to_result(self):
"""Convert to the Linter.run return value"""
text = [self.text]
if self.note:
text.append(self.note)
return {
'lnum': self.line_num,
'col': self.column,
'text': ' - '.join(text),
'type': self.types.get(self.message_type, '')
} | [
"def",
"to_result",
"(",
"self",
")",
":",
"text",
"=",
"[",
"self",
".",
"text",
"]",
"if",
"self",
".",
"note",
":",
"text",
".",
"append",
"(",
"self",
".",
"note",
")",
"return",
"{",
"'lnum'",
":",
"self",
".",
"line_num",
",",
"'col'",
":",... | Convert to the Linter.run return value | [
"Convert",
"to",
"the",
"Linter",
".",
"run",
"return",
"value"
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_mypy.py#L50-L61 | train | 206,211 |
klen/pylama | pylama/lint/pylama_mypy.py | Linter.run | def run(path, code=None, params=None, **meta):
"""Check code with mypy.
:return list: List of errors.
"""
args = [path, '--follow-imports=skip', '--show-column-numbers']
stdout, stderr, status = api.run(args)
messages = []
for line in stdout.split('\n'):
line.strip()
if not line:
continue
message = _MyPyMessage(line)
if message.valid:
if message.message_type == 'note':
if messages[-1].line_num == message.line_num:
messages[-1].add_note(message.text)
else:
messages.append(message)
return [m.to_result() for m in messages] | python | def run(path, code=None, params=None, **meta):
"""Check code with mypy.
:return list: List of errors.
"""
args = [path, '--follow-imports=skip', '--show-column-numbers']
stdout, stderr, status = api.run(args)
messages = []
for line in stdout.split('\n'):
line.strip()
if not line:
continue
message = _MyPyMessage(line)
if message.valid:
if message.message_type == 'note':
if messages[-1].line_num == message.line_num:
messages[-1].add_note(message.text)
else:
messages.append(message)
return [m.to_result() for m in messages] | [
"def",
"run",
"(",
"path",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"args",
"=",
"[",
"path",
",",
"'--follow-imports=skip'",
",",
"'--show-column-numbers'",
"]",
"stdout",
",",
"stderr",
",",
"status",
"="... | Check code with mypy.
:return list: List of errors. | [
"Check",
"code",
"with",
"mypy",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_mypy.py#L68-L88 | train | 206,212 |
klen/pylama | pylama/lint/pylama_pylint.py | _Params.prepare_value | def prepare_value(value):
"""Prepare value to pylint."""
if isinstance(value, (list, tuple, set)):
return ",".join(value)
if isinstance(value, bool):
return "y" if value else "n"
return str(value) | python | def prepare_value(value):
"""Prepare value to pylint."""
if isinstance(value, (list, tuple, set)):
return ",".join(value)
if isinstance(value, bool):
return "y" if value else "n"
return str(value) | [
"def",
"prepare_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"\",\"",
".",
"join",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",... | Prepare value to pylint. | [
"Prepare",
"value",
"to",
"pylint",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_pylint.py#L89-L97 | train | 206,213 |
klen/pylama | pylama/lint/pylama_pycodestyle.py | Linter.run | def run(path, code=None, params=None, **meta):
"""Check code with pycodestyle.
:return list: List of errors.
"""
parser = get_parser()
for option in parser.option_list:
if option.dest and option.dest in params:
value = params[option.dest]
if isinstance(value, str):
params[option.dest] = option.convert_value(option, value)
for key in ["filename", "exclude", "select", "ignore"]:
if key in params and isinstance(params[key], str):
params[key] = _parse_multi_options(params[key])
P8Style = StyleGuide(reporter=_PycodestyleReport, **params)
buf = StringIO(code)
return P8Style.input_file(path, lines=buf.readlines()) | python | def run(path, code=None, params=None, **meta):
"""Check code with pycodestyle.
:return list: List of errors.
"""
parser = get_parser()
for option in parser.option_list:
if option.dest and option.dest in params:
value = params[option.dest]
if isinstance(value, str):
params[option.dest] = option.convert_value(option, value)
for key in ["filename", "exclude", "select", "ignore"]:
if key in params and isinstance(params[key], str):
params[key] = _parse_multi_options(params[key])
P8Style = StyleGuide(reporter=_PycodestyleReport, **params)
buf = StringIO(code)
return P8Style.input_file(path, lines=buf.readlines()) | [
"def",
"run",
"(",
"path",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"for",
"option",
"in",
"parser",
".",
"option_list",
":",
"if",
"option",
".",
"dest",
"and",
... | Check code with pycodestyle.
:return list: List of errors. | [
"Check",
"code",
"with",
"pycodestyle",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_pycodestyle.py#L18-L36 | train | 206,214 |
klen/pylama | pylama/lint/pylama_pycodestyle.py | _PycodestyleReport.init_file | def init_file(self, filename, lines, expected, line_offset):
"""Prepare storage for errors."""
super(_PycodestyleReport, self).init_file(
filename, lines, expected, line_offset)
self.errors = [] | python | def init_file(self, filename, lines, expected, line_offset):
"""Prepare storage for errors."""
super(_PycodestyleReport, self).init_file(
filename, lines, expected, line_offset)
self.errors = [] | [
"def",
"init_file",
"(",
"self",
",",
"filename",
",",
"lines",
",",
"expected",
",",
"line_offset",
")",
":",
"super",
"(",
"_PycodestyleReport",
",",
"self",
")",
".",
"init_file",
"(",
"filename",
",",
"lines",
",",
"expected",
",",
"line_offset",
")",
... | Prepare storage for errors. | [
"Prepare",
"storage",
"for",
"errors",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_pycodestyle.py#L45-L49 | train | 206,215 |
klen/pylama | pylama/lint/pylama_pycodestyle.py | _PycodestyleReport.error | def error(self, line_number, offset, text, check):
"""Save errors."""
code = super(_PycodestyleReport, self).error(
line_number, offset, text, check)
if code:
self.errors.append(dict(
text=text,
type=code.replace('E', 'C'),
col=offset + 1,
lnum=line_number,
)) | python | def error(self, line_number, offset, text, check):
"""Save errors."""
code = super(_PycodestyleReport, self).error(
line_number, offset, text, check)
if code:
self.errors.append(dict(
text=text,
type=code.replace('E', 'C'),
col=offset + 1,
lnum=line_number,
)) | [
"def",
"error",
"(",
"self",
",",
"line_number",
",",
"offset",
",",
"text",
",",
"check",
")",
":",
"code",
"=",
"super",
"(",
"_PycodestyleReport",
",",
"self",
")",
".",
"error",
"(",
"line_number",
",",
"offset",
",",
"text",
",",
"check",
")",
"... | Save errors. | [
"Save",
"errors",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_pycodestyle.py#L51-L62 | train | 206,216 |
klen/pylama | pylama/lint/pylama_pydocstyle.py | Linter.run | def run(path, code=None, params=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
if 'ignore_decorators' in params:
ignore_decorators = params['ignore_decorators']
else:
ignore_decorators = None
check_source_args = (code, path, ignore_decorators) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)] | python | def run(path, code=None, params=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
if 'ignore_decorators' in params:
ignore_decorators = params['ignore_decorators']
else:
ignore_decorators = None
check_source_args = (code, path, ignore_decorators) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)] | [
"def",
"run",
"(",
"path",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"if",
"'ignore_decorators'",
"in",
"params",
":",
"ignore_decorators",
"=",
"params",
"[",
"'ignore_decorators'",
"]",
"else",
":",
"ignore_... | pydocstyle code checking.
:return list: List of errors. | [
"pydocstyle",
"code",
"checking",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_pydocstyle.py#L20-L37 | train | 206,217 |
klen/pylama | pylama/lint/pylama_radon.py | Linter.run | def run(path, code=None, params=None, ignore=None, select=None, **meta):
"""Check code with Radon.
:return list: List of errors.
"""
complexity = params.get('complexity', 10)
no_assert = params.get('no_assert', False)
show_closures = params.get('show_closures', False)
visitor = ComplexityVisitor.from_code(code, no_assert=no_assert)
blocks = visitor.blocks
if show_closures:
blocks = add_inner_blocks(blocks)
return [
{'lnum': block.lineno, 'col': block.col_offset, 'type': 'R', 'number': 'R709',
'text': 'R701: %s is too complex %d' % (block.name, block.complexity)}
for block in visitor.blocks if block.complexity > complexity
] | python | def run(path, code=None, params=None, ignore=None, select=None, **meta):
"""Check code with Radon.
:return list: List of errors.
"""
complexity = params.get('complexity', 10)
no_assert = params.get('no_assert', False)
show_closures = params.get('show_closures', False)
visitor = ComplexityVisitor.from_code(code, no_assert=no_assert)
blocks = visitor.blocks
if show_closures:
blocks = add_inner_blocks(blocks)
return [
{'lnum': block.lineno, 'col': block.col_offset, 'type': 'R', 'number': 'R709',
'text': 'R701: %s is too complex %d' % (block.name, block.complexity)}
for block in visitor.blocks if block.complexity > complexity
] | [
"def",
"run",
"(",
"path",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"select",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"complexity",
"=",
"params",
".",
"get",
"(",
"'complexity'",
",",
"10",
")"... | Check code with Radon.
:return list: List of errors. | [
"Check",
"code",
"with",
"Radon",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_radon.py#L12-L30 | train | 206,218 |
klen/pylama | pylama/hook.py | git_hook | def git_hook(error=True):
"""Run pylama after git commit."""
_, files_modified, _ = run("git diff-index --cached --name-only HEAD")
options = parse_options()
setup_logger(options)
if sys.version_info >= (3,):
candidates = [f.decode('utf-8') for f in files_modified]
else:
candidates = [str(f) for f in files_modified]
if candidates:
process_paths(options, candidates=candidates, error=error) | python | def git_hook(error=True):
"""Run pylama after git commit."""
_, files_modified, _ = run("git diff-index --cached --name-only HEAD")
options = parse_options()
setup_logger(options)
if sys.version_info >= (3,):
candidates = [f.decode('utf-8') for f in files_modified]
else:
candidates = [str(f) for f in files_modified]
if candidates:
process_paths(options, candidates=candidates, error=error) | [
"def",
"git_hook",
"(",
"error",
"=",
"True",
")",
":",
"_",
",",
"files_modified",
",",
"_",
"=",
"run",
"(",
"\"git diff-index --cached --name-only HEAD\"",
")",
"options",
"=",
"parse_options",
"(",
")",
"setup_logger",
"(",
"options",
")",
"if",
"sys",
"... | Run pylama after git commit. | [
"Run",
"pylama",
"after",
"git",
"commit",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/hook.py#L30-L42 | train | 206,219 |
klen/pylama | pylama/hook.py | hg_hook | def hg_hook(ui, repo, node=None, **kwargs):
"""Run pylama after mercurial commit."""
seen = set()
paths = []
if len(repo):
for rev in range(repo[node], len(repo)):
for file_ in repo[rev].files():
file_ = op.join(repo.root, file_)
if file_ in seen or not op.exists(file_):
continue
seen.add(file_)
paths.append(file_)
options = parse_options()
setup_logger(options)
if paths:
process_paths(options, candidates=paths) | python | def hg_hook(ui, repo, node=None, **kwargs):
"""Run pylama after mercurial commit."""
seen = set()
paths = []
if len(repo):
for rev in range(repo[node], len(repo)):
for file_ in repo[rev].files():
file_ = op.join(repo.root, file_)
if file_ in seen or not op.exists(file_):
continue
seen.add(file_)
paths.append(file_)
options = parse_options()
setup_logger(options)
if paths:
process_paths(options, candidates=paths) | [
"def",
"hg_hook",
"(",
"ui",
",",
"repo",
",",
"node",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"seen",
"=",
"set",
"(",
")",
"paths",
"=",
"[",
"]",
"if",
"len",
"(",
"repo",
")",
":",
"for",
"rev",
"in",
"range",
"(",
"repo",
"[",
... | Run pylama after mercurial commit. | [
"Run",
"pylama",
"after",
"mercurial",
"commit",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/hook.py#L45-L61 | train | 206,220 |
klen/pylama | pylama/hook.py | install_git | def install_git(path):
"""Install hook in Git repository."""
hook = op.join(path, 'pre-commit')
with open(hook, 'w') as fd:
fd.write("""#!/usr/bin/env python
import sys
from pylama.hook import git_hook
if __name__ == '__main__':
sys.exit(git_hook())
""")
chmod(hook, 484) | python | def install_git(path):
"""Install hook in Git repository."""
hook = op.join(path, 'pre-commit')
with open(hook, 'w') as fd:
fd.write("""#!/usr/bin/env python
import sys
from pylama.hook import git_hook
if __name__ == '__main__':
sys.exit(git_hook())
""")
chmod(hook, 484) | [
"def",
"install_git",
"(",
"path",
")",
":",
"hook",
"=",
"op",
".",
"join",
"(",
"path",
",",
"'pre-commit'",
")",
"with",
"open",
"(",
"hook",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"\"\"\"#!/usr/bin/env python\nimport sys\nfrom pylam... | Install hook in Git repository. | [
"Install",
"hook",
"in",
"Git",
"repository",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/hook.py#L64-L75 | train | 206,221 |
klen/pylama | pylama/hook.py | install_hg | def install_hg(path):
""" Install hook in Mercurial repository. """
hook = op.join(path, 'hgrc')
if not op.isfile(hook):
open(hook, 'w+').close()
c = ConfigParser()
c.readfp(open(hook, 'r'))
if not c.has_section('hooks'):
c.add_section('hooks')
if not c.has_option('hooks', 'commit'):
c.set('hooks', 'commit', 'python:pylama.hooks.hg_hook')
if not c.has_option('hooks', 'qrefresh'):
c.set('hooks', 'qrefresh', 'python:pylama.hooks.hg_hook')
c.write(open(hook, 'w+')) | python | def install_hg(path):
""" Install hook in Mercurial repository. """
hook = op.join(path, 'hgrc')
if not op.isfile(hook):
open(hook, 'w+').close()
c = ConfigParser()
c.readfp(open(hook, 'r'))
if not c.has_section('hooks'):
c.add_section('hooks')
if not c.has_option('hooks', 'commit'):
c.set('hooks', 'commit', 'python:pylama.hooks.hg_hook')
if not c.has_option('hooks', 'qrefresh'):
c.set('hooks', 'qrefresh', 'python:pylama.hooks.hg_hook')
c.write(open(hook, 'w+')) | [
"def",
"install_hg",
"(",
"path",
")",
":",
"hook",
"=",
"op",
".",
"join",
"(",
"path",
",",
"'hgrc'",
")",
"if",
"not",
"op",
".",
"isfile",
"(",
"hook",
")",
":",
"open",
"(",
"hook",
",",
"'w+'",
")",
".",
"close",
"(",
")",
"c",
"=",
"Co... | Install hook in Mercurial repository. | [
"Install",
"hook",
"in",
"Mercurial",
"repository",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/hook.py#L78-L95 | train | 206,222 |
klen/pylama | pylama/hook.py | install_hook | def install_hook(path):
""" Auto definition of SCM and hook installation. """
git = op.join(path, '.git', 'hooks')
hg = op.join(path, '.hg')
if op.exists(git):
install_git(git)
LOGGER.warn('Git hook has been installed.')
elif op.exists(hg):
install_hg(hg)
LOGGER.warn('Mercurial hook has been installed.')
else:
LOGGER.error('VCS has not found. Check your path.')
sys.exit(1) | python | def install_hook(path):
""" Auto definition of SCM and hook installation. """
git = op.join(path, '.git', 'hooks')
hg = op.join(path, '.hg')
if op.exists(git):
install_git(git)
LOGGER.warn('Git hook has been installed.')
elif op.exists(hg):
install_hg(hg)
LOGGER.warn('Mercurial hook has been installed.')
else:
LOGGER.error('VCS has not found. Check your path.')
sys.exit(1) | [
"def",
"install_hook",
"(",
"path",
")",
":",
"git",
"=",
"op",
".",
"join",
"(",
"path",
",",
"'.git'",
",",
"'hooks'",
")",
"hg",
"=",
"op",
".",
"join",
"(",
"path",
",",
"'.hg'",
")",
"if",
"op",
".",
"exists",
"(",
"git",
")",
":",
"instal... | Auto definition of SCM and hook installation. | [
"Auto",
"definition",
"of",
"SCM",
"and",
"hook",
"installation",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/hook.py#L98-L112 | train | 206,223 |
klen/pylama | pylama/lint/pylama_eradicate.py | Linter.run | def run(path, code=None, params=None, **meta):
"""Eradicate code checking.
:return list: List of errors.
"""
code = converter(code)
line_numbers = commented_out_code_line_numbers(code)
lines = code.split('\n')
result = []
for line_number in line_numbers:
line = lines[line_number - 1]
result.append(dict(
lnum=line_number,
offset=len(line) - len(line.rstrip()),
# https://github.com/sobolevn/flake8-eradicate#output-example
text=converter('E800 Found commented out code: ') + line,
# https://github.com/sobolevn/flake8-eradicate#error-codes
type='E800',
))
return result | python | def run(path, code=None, params=None, **meta):
"""Eradicate code checking.
:return list: List of errors.
"""
code = converter(code)
line_numbers = commented_out_code_line_numbers(code)
lines = code.split('\n')
result = []
for line_number in line_numbers:
line = lines[line_number - 1]
result.append(dict(
lnum=line_number,
offset=len(line) - len(line.rstrip()),
# https://github.com/sobolevn/flake8-eradicate#output-example
text=converter('E800 Found commented out code: ') + line,
# https://github.com/sobolevn/flake8-eradicate#error-codes
type='E800',
))
return result | [
"def",
"run",
"(",
"path",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"code",
"=",
"converter",
"(",
"code",
")",
"line_numbers",
"=",
"commented_out_code_line_numbers",
"(",
"code",
")",
"lines",
"=",
"code"... | Eradicate code checking.
:return list: List of errors. | [
"Eradicate",
"code",
"checking",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_eradicate.py#L16-L36 | train | 206,224 |
klen/pylama | pylama/errors.py | remove_duplicates | def remove_duplicates(errors):
""" Filter duplicates from given error's list. """
passed = defaultdict(list)
for error in errors:
key = error.linter, error.number
if key in DUPLICATES:
if key in passed[error.lnum]:
continue
passed[error.lnum] = DUPLICATES[key]
yield error | python | def remove_duplicates(errors):
""" Filter duplicates from given error's list. """
passed = defaultdict(list)
for error in errors:
key = error.linter, error.number
if key in DUPLICATES:
if key in passed[error.lnum]:
continue
passed[error.lnum] = DUPLICATES[key]
yield error | [
"def",
"remove_duplicates",
"(",
"errors",
")",
":",
"passed",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"error",
"in",
"errors",
":",
"key",
"=",
"error",
".",
"linter",
",",
"error",
".",
"number",
"if",
"key",
"in",
"DUPLICATES",
":",
"if",
"key"... | Filter duplicates from given error's list. | [
"Filter",
"duplicates",
"from",
"given",
"error",
"s",
"list",
"."
] | f436ccc6b55b33381a295ded753e467953cf4379 | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/errors.py#L71-L80 | train | 206,225 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk.fork | def fork(self, strictindex, new_value):
"""
Return a chunk referring to the same location in a duplicated document.
Used when modifying a YAML chunk so that the modification can be validated
before changing it.
"""
forked_chunk = YAMLChunk(
deepcopy(self._ruamelparsed),
pointer=self.pointer,
label=self.label,
key_association=copy(self._key_association),
)
forked_chunk.contents[self.ruamelindex(strictindex)] = new_value.as_marked_up()
forked_chunk.strictparsed()[strictindex] = deepcopy(new_value.as_marked_up())
return forked_chunk | python | def fork(self, strictindex, new_value):
"""
Return a chunk referring to the same location in a duplicated document.
Used when modifying a YAML chunk so that the modification can be validated
before changing it.
"""
forked_chunk = YAMLChunk(
deepcopy(self._ruamelparsed),
pointer=self.pointer,
label=self.label,
key_association=copy(self._key_association),
)
forked_chunk.contents[self.ruamelindex(strictindex)] = new_value.as_marked_up()
forked_chunk.strictparsed()[strictindex] = deepcopy(new_value.as_marked_up())
return forked_chunk | [
"def",
"fork",
"(",
"self",
",",
"strictindex",
",",
"new_value",
")",
":",
"forked_chunk",
"=",
"YAMLChunk",
"(",
"deepcopy",
"(",
"self",
".",
"_ruamelparsed",
")",
",",
"pointer",
"=",
"self",
".",
"pointer",
",",
"label",
"=",
"self",
".",
"label",
... | Return a chunk referring to the same location in a duplicated document.
Used when modifying a YAML chunk so that the modification can be validated
before changing it. | [
"Return",
"a",
"chunk",
"referring",
"to",
"the",
"same",
"location",
"in",
"a",
"duplicated",
"document",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L130-L145 | train | 206,226 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk.make_child_of | def make_child_of(self, chunk):
"""
Link one YAML chunk to another.
Used when inserting a chunk of YAML into another chunk.
"""
if self.is_mapping():
for key, value in self.contents.items():
self.key(key, key).pointer.make_child_of(chunk.pointer)
self.val(key).make_child_of(chunk)
elif self.is_sequence():
for index, item in enumerate(self.contents):
self.index(index).make_child_of(chunk)
else:
self.pointer.make_child_of(chunk.pointer) | python | def make_child_of(self, chunk):
"""
Link one YAML chunk to another.
Used when inserting a chunk of YAML into another chunk.
"""
if self.is_mapping():
for key, value in self.contents.items():
self.key(key, key).pointer.make_child_of(chunk.pointer)
self.val(key).make_child_of(chunk)
elif self.is_sequence():
for index, item in enumerate(self.contents):
self.index(index).make_child_of(chunk)
else:
self.pointer.make_child_of(chunk.pointer) | [
"def",
"make_child_of",
"(",
"self",
",",
"chunk",
")",
":",
"if",
"self",
".",
"is_mapping",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"contents",
".",
"items",
"(",
")",
":",
"self",
".",
"key",
"(",
"key",
",",
"key",
")",
... | Link one YAML chunk to another.
Used when inserting a chunk of YAML into another chunk. | [
"Link",
"one",
"YAML",
"chunk",
"to",
"another",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L154-L168 | train | 206,227 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk._select | def _select(self, pointer):
"""
Get a YAMLChunk referenced by a pointer.
"""
return YAMLChunk(
self._ruamelparsed,
pointer=pointer,
label=self._label,
strictparsed=self._strictparsed,
key_association=copy(self._key_association),
) | python | def _select(self, pointer):
"""
Get a YAMLChunk referenced by a pointer.
"""
return YAMLChunk(
self._ruamelparsed,
pointer=pointer,
label=self._label,
strictparsed=self._strictparsed,
key_association=copy(self._key_association),
) | [
"def",
"_select",
"(",
"self",
",",
"pointer",
")",
":",
"return",
"YAMLChunk",
"(",
"self",
".",
"_ruamelparsed",
",",
"pointer",
"=",
"pointer",
",",
"label",
"=",
"self",
".",
"_label",
",",
"strictparsed",
"=",
"self",
".",
"_strictparsed",
",",
"key... | Get a YAMLChunk referenced by a pointer. | [
"Get",
"a",
"YAMLChunk",
"referenced",
"by",
"a",
"pointer",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L170-L180 | train | 206,228 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk.index | def index(self, strictindex):
"""
Return a chunk in a sequence referenced by index.
"""
return self._select(self._pointer.index(self.ruamelindex(strictindex))) | python | def index(self, strictindex):
"""
Return a chunk in a sequence referenced by index.
"""
return self._select(self._pointer.index(self.ruamelindex(strictindex))) | [
"def",
"index",
"(",
"self",
",",
"strictindex",
")",
":",
"return",
"self",
".",
"_select",
"(",
"self",
".",
"_pointer",
".",
"index",
"(",
"self",
".",
"ruamelindex",
"(",
"strictindex",
")",
")",
")"
] | Return a chunk in a sequence referenced by index. | [
"Return",
"a",
"chunk",
"in",
"a",
"sequence",
"referenced",
"by",
"index",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L182-L186 | train | 206,229 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk.ruamelindex | def ruamelindex(self, strictindex):
"""
Get the ruamel equivalent of a strict parsed index.
E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify
"""
return (
self.key_association.get(strictindex, strictindex)
if self.is_mapping()
else strictindex
) | python | def ruamelindex(self, strictindex):
"""
Get the ruamel equivalent of a strict parsed index.
E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify
"""
return (
self.key_association.get(strictindex, strictindex)
if self.is_mapping()
else strictindex
) | [
"def",
"ruamelindex",
"(",
"self",
",",
"strictindex",
")",
":",
"return",
"(",
"self",
".",
"key_association",
".",
"get",
"(",
"strictindex",
",",
"strictindex",
")",
"if",
"self",
".",
"is_mapping",
"(",
")",
"else",
"strictindex",
")"
] | Get the ruamel equivalent of a strict parsed index.
E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify | [
"Get",
"the",
"ruamel",
"equivalent",
"of",
"a",
"strict",
"parsed",
"index",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L188-L198 | train | 206,230 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk.val | def val(self, strictkey):
"""
Return a chunk referencing a value in a mapping with the key 'key'.
"""
ruamelkey = self.ruamelindex(strictkey)
return self._select(self._pointer.val(ruamelkey, strictkey)) | python | def val(self, strictkey):
"""
Return a chunk referencing a value in a mapping with the key 'key'.
"""
ruamelkey = self.ruamelindex(strictkey)
return self._select(self._pointer.val(ruamelkey, strictkey)) | [
"def",
"val",
"(",
"self",
",",
"strictkey",
")",
":",
"ruamelkey",
"=",
"self",
".",
"ruamelindex",
"(",
"strictkey",
")",
"return",
"self",
".",
"_select",
"(",
"self",
".",
"_pointer",
".",
"val",
"(",
"ruamelkey",
",",
"strictkey",
")",
")"
] | Return a chunk referencing a value in a mapping with the key 'key'. | [
"Return",
"a",
"chunk",
"referencing",
"a",
"value",
"in",
"a",
"mapping",
"with",
"the",
"key",
"key",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L200-L205 | train | 206,231 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk.key | def key(self, key, strictkey=None):
"""
Return a chunk referencing a key in a mapping with the name 'key'.
"""
return self._select(self._pointer.key(key, strictkey)) | python | def key(self, key, strictkey=None):
"""
Return a chunk referencing a key in a mapping with the name 'key'.
"""
return self._select(self._pointer.key(key, strictkey)) | [
"def",
"key",
"(",
"self",
",",
"key",
",",
"strictkey",
"=",
"None",
")",
":",
"return",
"self",
".",
"_select",
"(",
"self",
".",
"_pointer",
".",
"key",
"(",
"key",
",",
"strictkey",
")",
")"
] | Return a chunk referencing a key in a mapping with the name 'key'. | [
"Return",
"a",
"chunk",
"referencing",
"a",
"key",
"in",
"a",
"mapping",
"with",
"the",
"name",
"key",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L207-L211 | train | 206,232 |
crdoconnor/strictyaml | strictyaml/yamllocation.py | YAMLChunk.textslice | def textslice(self, start, end):
"""
Return a chunk referencing a slice of a scalar text value.
"""
return self._select(self._pointer.textslice(start, end)) | python | def textslice(self, start, end):
"""
Return a chunk referencing a slice of a scalar text value.
"""
return self._select(self._pointer.textslice(start, end)) | [
"def",
"textslice",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"return",
"self",
".",
"_select",
"(",
"self",
".",
"_pointer",
".",
"textslice",
"(",
"start",
",",
"end",
")",
")"
] | Return a chunk referencing a slice of a scalar text value. | [
"Return",
"a",
"chunk",
"referencing",
"a",
"slice",
"of",
"a",
"scalar",
"text",
"value",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/yamllocation.py#L213-L217 | train | 206,233 |
crdoconnor/strictyaml | strictyaml/utils.py | flatten | def flatten(items):
"""
Yield items from any nested iterable.
>>> list(flatten([[1, 2, 3], [[4, 5], 6, 7]]))
[1, 2, 3, 4, 5, 6, 7]
"""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
for sub_x in flatten(x):
yield sub_x
else:
yield x | python | def flatten(items):
"""
Yield items from any nested iterable.
>>> list(flatten([[1, 2, 3], [[4, 5], 6, 7]]))
[1, 2, 3, 4, 5, 6, 7]
"""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
for sub_x in flatten(x):
yield sub_x
else:
yield x | [
"def",
"flatten",
"(",
"items",
")",
":",
"for",
"x",
"in",
"items",
":",
"if",
"isinstance",
"(",
"x",
",",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"x",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"for",
"sub_x",
"in",
"flatten",
"("... | Yield items from any nested iterable.
>>> list(flatten([[1, 2, 3], [[4, 5], 6, 7]]))
[1, 2, 3, 4, 5, 6, 7] | [
"Yield",
"items",
"from",
"any",
"nested",
"iterable",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/utils.py#L13-L25 | train | 206,234 |
crdoconnor/strictyaml | strictyaml/utils.py | comma_separated_positions | def comma_separated_positions(text):
"""
Start and end positions of comma separated text items.
Commas and trailing spaces should not be included.
>>> comma_separated_positions("ABC, 2,3")
[(0, 3), (5, 6), (7, 8)]
"""
chunks = []
start = 0
end = 0
for item in text.split(","):
space_increment = 1 if item[0] == " " else 0
start += space_increment # Is there a space after the comma to ignore? ", "
end += len(item.lstrip()) + space_increment
chunks.append((start, end))
start += len(item.lstrip()) + 1 # Plus comma
end = start
return chunks | python | def comma_separated_positions(text):
"""
Start and end positions of comma separated text items.
Commas and trailing spaces should not be included.
>>> comma_separated_positions("ABC, 2,3")
[(0, 3), (5, 6), (7, 8)]
"""
chunks = []
start = 0
end = 0
for item in text.split(","):
space_increment = 1 if item[0] == " " else 0
start += space_increment # Is there a space after the comma to ignore? ", "
end += len(item.lstrip()) + space_increment
chunks.append((start, end))
start += len(item.lstrip()) + 1 # Plus comma
end = start
return chunks | [
"def",
"comma_separated_positions",
"(",
"text",
")",
":",
"chunks",
"=",
"[",
"]",
"start",
"=",
"0",
"end",
"=",
"0",
"for",
"item",
"in",
"text",
".",
"split",
"(",
"\",\"",
")",
":",
"space_increment",
"=",
"1",
"if",
"item",
"[",
"0",
"]",
"==... | Start and end positions of comma separated text items.
Commas and trailing spaces should not be included.
>>> comma_separated_positions("ABC, 2,3")
[(0, 3), (5, 6), (7, 8)] | [
"Start",
"and",
"end",
"positions",
"of",
"comma",
"separated",
"text",
"items",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/utils.py#L83-L102 | train | 206,235 |
crdoconnor/strictyaml | strictyaml/utils.py | ruamel_structure | def ruamel_structure(data, validator=None):
"""
Take dicts and lists and return a ruamel.yaml style
structure of CommentedMaps, CommentedSeqs and
data.
If a validator is presented and the type is unknown,
it is checked against the validator to see if it will
turn it back in to YAML.
"""
if isinstance(data, dict):
if len(data) == 0:
raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(
"Document must be built with non-empty dicts and lists"
)
return CommentedMap(
[
(ruamel_structure(key), ruamel_structure(value))
for key, value in data.items()
]
)
elif isinstance(data, list):
if len(data) == 0:
raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(
"Document must be built with non-empty dicts and lists"
)
return CommentedSeq([ruamel_structure(item) for item in data])
elif isinstance(data, bool):
return u"yes" if data else u"no"
elif isinstance(data, (int, float)):
return str(data)
else:
if not is_string(data):
raise exceptions.CannotBuildDocumentFromInvalidData(
(
"Document must be built from a combination of:\n"
"string, int, float, bool or nonempty list/dict\n\n"
"Instead, found variable with type '{}': '{}'"
).format(type(data).__name__, data)
)
return data | python | def ruamel_structure(data, validator=None):
"""
Take dicts and lists and return a ruamel.yaml style
structure of CommentedMaps, CommentedSeqs and
data.
If a validator is presented and the type is unknown,
it is checked against the validator to see if it will
turn it back in to YAML.
"""
if isinstance(data, dict):
if len(data) == 0:
raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(
"Document must be built with non-empty dicts and lists"
)
return CommentedMap(
[
(ruamel_structure(key), ruamel_structure(value))
for key, value in data.items()
]
)
elif isinstance(data, list):
if len(data) == 0:
raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(
"Document must be built with non-empty dicts and lists"
)
return CommentedSeq([ruamel_structure(item) for item in data])
elif isinstance(data, bool):
return u"yes" if data else u"no"
elif isinstance(data, (int, float)):
return str(data)
else:
if not is_string(data):
raise exceptions.CannotBuildDocumentFromInvalidData(
(
"Document must be built from a combination of:\n"
"string, int, float, bool or nonempty list/dict\n\n"
"Instead, found variable with type '{}': '{}'"
).format(type(data).__name__, data)
)
return data | [
"def",
"ruamel_structure",
"(",
"data",
",",
"validator",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"raise",
"exceptions",
".",
"CannotBuildDocumentsFromEmptyDictOrList",
"... | Take dicts and lists and return a ruamel.yaml style
structure of CommentedMaps, CommentedSeqs and
data.
If a validator is presented and the type is unknown,
it is checked against the validator to see if it will
turn it back in to YAML. | [
"Take",
"dicts",
"and",
"lists",
"and",
"return",
"a",
"ruamel",
".",
"yaml",
"style",
"structure",
"of",
"CommentedMaps",
"CommentedSeqs",
"and",
"data",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/utils.py#L105-L145 | train | 206,236 |
crdoconnor/strictyaml | hitch/key.py | rbdd | def rbdd(*keywords):
"""
Run story matching keywords and rewrite story if code changed.
"""
settings = _personal_settings().data
settings["engine"]["rewrite"] = True
_storybook(settings["engine"]).with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play() | python | def rbdd(*keywords):
"""
Run story matching keywords and rewrite story if code changed.
"""
settings = _personal_settings().data
settings["engine"]["rewrite"] = True
_storybook(settings["engine"]).with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play() | [
"def",
"rbdd",
"(",
"*",
"keywords",
")",
":",
"settings",
"=",
"_personal_settings",
"(",
")",
".",
"data",
"settings",
"[",
"\"engine\"",
"]",
"[",
"\"rewrite\"",
"]",
"=",
"True",
"_storybook",
"(",
"settings",
"[",
"\"engine\"",
"]",
")",
".",
"with_... | Run story matching keywords and rewrite story if code changed. | [
"Run",
"story",
"matching",
"keywords",
"and",
"rewrite",
"story",
"if",
"code",
"changed",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/hitch/key.py#L73-L81 | train | 206,237 |
crdoconnor/strictyaml | hitch/key.py | rerun | def rerun(version="3.7.0"):
"""
Rerun last example code block with specified version of python.
"""
from commandlib import Command
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state")).run() | python | def rerun(version="3.7.0"):
"""
Rerun last example code block with specified version of python.
"""
from commandlib import Command
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state")).run() | [
"def",
"rerun",
"(",
"version",
"=",
"\"3.7.0\"",
")",
":",
"from",
"commandlib",
"import",
"Command",
"Command",
"(",
"DIR",
".",
"gen",
".",
"joinpath",
"(",
"\"py{0}\"",
".",
"format",
"(",
"version",
")",
",",
"\"bin\"",
",",
"\"python\"",
")",
")",
... | Rerun last example code block with specified version of python. | [
"Rerun",
"last",
"example",
"code",
"block",
"with",
"specified",
"version",
"of",
"python",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/hitch/key.py#L170-L178 | train | 206,238 |
crdoconnor/strictyaml | strictyaml/representation.py | YAML.data | def data(self):
"""
Returns raw data representation of the document or document segment.
Mappings are rendered as ordered dicts, sequences as lists and scalar values
as whatever the validator returns (int, string, etc.).
If no validators are used, scalar values are always returned as strings.
"""
if isinstance(self._value, CommentedMap):
mapping = OrderedDict()
for key, value in self._value.items():
mapping[key.data] = value.data
return mapping
elif isinstance(self._value, CommentedSeq):
return [item.data for item in self._value]
else:
return self._value | python | def data(self):
"""
Returns raw data representation of the document or document segment.
Mappings are rendered as ordered dicts, sequences as lists and scalar values
as whatever the validator returns (int, string, etc.).
If no validators are used, scalar values are always returned as strings.
"""
if isinstance(self._value, CommentedMap):
mapping = OrderedDict()
for key, value in self._value.items():
mapping[key.data] = value.data
return mapping
elif isinstance(self._value, CommentedSeq):
return [item.data for item in self._value]
else:
return self._value | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_value",
",",
"CommentedMap",
")",
":",
"mapping",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_value",
".",
"items",
"(",
")",
":",
"map... | Returns raw data representation of the document or document segment.
Mappings are rendered as ordered dicts, sequences as lists and scalar values
as whatever the validator returns (int, string, etc.).
If no validators are used, scalar values are always returned as strings. | [
"Returns",
"raw",
"data",
"representation",
"of",
"the",
"document",
"or",
"document",
"segment",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/representation.py#L102-L119 | train | 206,239 |
crdoconnor/strictyaml | strictyaml/representation.py | YAML.as_yaml | def as_yaml(self):
"""
Render the YAML node and subnodes as string.
"""
dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True)
return dumped if sys.version_info[0] == 3 else dumped.decode("utf8") | python | def as_yaml(self):
"""
Render the YAML node and subnodes as string.
"""
dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True)
return dumped if sys.version_info[0] == 3 else dumped.decode("utf8") | [
"def",
"as_yaml",
"(",
"self",
")",
":",
"dumped",
"=",
"dump",
"(",
"self",
".",
"as_marked_up",
"(",
")",
",",
"Dumper",
"=",
"StrictYAMLDumper",
",",
"allow_unicode",
"=",
"True",
")",
"return",
"dumped",
"if",
"sys",
".",
"version_info",
"[",
"0",
... | Render the YAML node and subnodes as string. | [
"Render",
"the",
"YAML",
"node",
"and",
"subnodes",
"as",
"string",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/representation.py#L240-L245 | train | 206,240 |
crdoconnor/strictyaml | strictyaml/representation.py | YAML.text | def text(self):
"""
Return string value of scalar, whatever value it was parsed as.
"""
if isinstance(self._value, CommentedMap):
raise TypeError("{0} is a mapping, has no text value.".format(repr(self)))
if isinstance(self._value, CommentedSeq):
raise TypeError("{0} is a sequence, has no text value.".format(repr(self)))
return self._text | python | def text(self):
"""
Return string value of scalar, whatever value it was parsed as.
"""
if isinstance(self._value, CommentedMap):
raise TypeError("{0} is a mapping, has no text value.".format(repr(self)))
if isinstance(self._value, CommentedSeq):
raise TypeError("{0} is a sequence, has no text value.".format(repr(self)))
return self._text | [
"def",
"text",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_value",
",",
"CommentedMap",
")",
":",
"raise",
"TypeError",
"(",
"\"{0} is a mapping, has no text value.\"",
".",
"format",
"(",
"repr",
"(",
"self",
")",
")",
")",
"if",
"isins... | Return string value of scalar, whatever value it was parsed as. | [
"Return",
"string",
"value",
"of",
"scalar",
"whatever",
"value",
"it",
"was",
"parsed",
"as",
"."
] | efdac7f89e81679fc95686288cd32b9563fde609 | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/representation.py#L290-L298 | train | 206,241 |
asottile/reorder_python_imports | reorder_python_imports.py | partition_source | def partition_source(src):
"""Partitions source into a list of `CodePartition`s for import
refactoring.
"""
# In python2, ast.parse(text_string_with_encoding_pragma) raises
# SyntaxError: encoding declaration in Unicode string
ast_obj = ast.parse(src.encode('UTF-8'))
visitor = TopLevelImportVisitor()
visitor.visit(ast_obj)
line_offsets = get_line_offsets_by_line_no(src)
chunks = []
startpos = 0
pending_chunk_type = None
possible_ending_tokens = None
seen_import = False
for (
token_type, token_text, (srow, scol), (erow, ecol), _,
) in tokenize.generate_tokens(io.StringIO(src).readline):
# Searching for a start of a chunk
if pending_chunk_type is None:
if not seen_import and token_type == tokenize.COMMENT:
if 'noreorder' in token_text:
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
else:
pending_chunk_type = CodeType.PRE_IMPORT_CODE
possible_ending_tokens = TERMINATES_COMMENT
elif not seen_import and token_type == tokenize.STRING:
pending_chunk_type = CodeType.PRE_IMPORT_CODE
possible_ending_tokens = TERMINATES_DOCSTRING
elif scol == 0 and srow in visitor.top_level_import_line_numbers:
seen_import = True
pending_chunk_type = CodeType.IMPORT
possible_ending_tokens = TERMINATES_IMPORT
elif token_type == tokenize.NL:
# A NL token is a non-important newline, we'll immediately
# append a NON_CODE partition
endpos = line_offsets[erow] + ecol
srctext = src[startpos:endpos]
startpos = endpos
chunks.append(CodePartition(CodeType.NON_CODE, srctext))
elif token_type == tokenize.COMMENT:
if 'noreorder' in token_text:
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
else:
pending_chunk_type = CodeType.CODE
possible_ending_tokens = TERMINATES_COMMENT
elif token_type == tokenize.ENDMARKER:
# Token ended right before end of file or file was empty
pass
else:
# We've reached a `CODE` block, which spans the rest of the
# file (intentionally timid). Let's append that block and be
# done
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
# Attempt to find ending of token
elif token_type in possible_ending_tokens:
endpos = line_offsets[erow] + ecol
srctext = src[startpos:endpos]
startpos = endpos
chunks.append(CodePartition(pending_chunk_type, srctext))
pending_chunk_type = None
possible_ending_tokens = None
elif token_type == tokenize.COMMENT and 'noreorder' in token_text:
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
chunks = [chunk for chunk in chunks if chunk.src]
# Make sure we're not removing any code
assert _partitions_to_src(chunks) == src
return chunks | python | def partition_source(src):
"""Partitions source into a list of `CodePartition`s for import
refactoring.
"""
# In python2, ast.parse(text_string_with_encoding_pragma) raises
# SyntaxError: encoding declaration in Unicode string
ast_obj = ast.parse(src.encode('UTF-8'))
visitor = TopLevelImportVisitor()
visitor.visit(ast_obj)
line_offsets = get_line_offsets_by_line_no(src)
chunks = []
startpos = 0
pending_chunk_type = None
possible_ending_tokens = None
seen_import = False
for (
token_type, token_text, (srow, scol), (erow, ecol), _,
) in tokenize.generate_tokens(io.StringIO(src).readline):
# Searching for a start of a chunk
if pending_chunk_type is None:
if not seen_import and token_type == tokenize.COMMENT:
if 'noreorder' in token_text:
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
else:
pending_chunk_type = CodeType.PRE_IMPORT_CODE
possible_ending_tokens = TERMINATES_COMMENT
elif not seen_import and token_type == tokenize.STRING:
pending_chunk_type = CodeType.PRE_IMPORT_CODE
possible_ending_tokens = TERMINATES_DOCSTRING
elif scol == 0 and srow in visitor.top_level_import_line_numbers:
seen_import = True
pending_chunk_type = CodeType.IMPORT
possible_ending_tokens = TERMINATES_IMPORT
elif token_type == tokenize.NL:
# A NL token is a non-important newline, we'll immediately
# append a NON_CODE partition
endpos = line_offsets[erow] + ecol
srctext = src[startpos:endpos]
startpos = endpos
chunks.append(CodePartition(CodeType.NON_CODE, srctext))
elif token_type == tokenize.COMMENT:
if 'noreorder' in token_text:
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
else:
pending_chunk_type = CodeType.CODE
possible_ending_tokens = TERMINATES_COMMENT
elif token_type == tokenize.ENDMARKER:
# Token ended right before end of file or file was empty
pass
else:
# We've reached a `CODE` block, which spans the rest of the
# file (intentionally timid). Let's append that block and be
# done
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
# Attempt to find ending of token
elif token_type in possible_ending_tokens:
endpos = line_offsets[erow] + ecol
srctext = src[startpos:endpos]
startpos = endpos
chunks.append(CodePartition(pending_chunk_type, srctext))
pending_chunk_type = None
possible_ending_tokens = None
elif token_type == tokenize.COMMENT and 'noreorder' in token_text:
chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
break
chunks = [chunk for chunk in chunks if chunk.src]
# Make sure we're not removing any code
assert _partitions_to_src(chunks) == src
return chunks | [
"def",
"partition_source",
"(",
"src",
")",
":",
"# In python2, ast.parse(text_string_with_encoding_pragma) raises",
"# SyntaxError: encoding declaration in Unicode string",
"ast_obj",
"=",
"ast",
".",
"parse",
"(",
"src",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
"visitor",... | Partitions source into a list of `CodePartition`s for import
refactoring. | [
"Partitions",
"source",
"into",
"a",
"list",
"of",
"CodePartition",
"s",
"for",
"import",
"refactoring",
"."
] | bc7b5b2f0fde191c9d0121588ef9bbb79f8e5e21 | https://github.com/asottile/reorder_python_imports/blob/bc7b5b2f0fde191c9d0121588ef9bbb79f8e5e21/reorder_python_imports.py#L57-L132 | train | 206,242 |
asottile/reorder_python_imports | reorder_python_imports.py | separate_comma_imports | def separate_comma_imports(partitions):
"""Turns `import a, b` into `import a` and `import b`"""
def _inner():
for partition in partitions:
if partition.code_type is CodeType.IMPORT:
import_obj = import_obj_from_str(partition.src)
if import_obj.has_multiple_imports:
for new_import_obj in import_obj.split_imports():
yield CodePartition(
CodeType.IMPORT, new_import_obj.to_text(),
)
else:
yield partition
else:
yield partition
return list(_inner()) | python | def separate_comma_imports(partitions):
"""Turns `import a, b` into `import a` and `import b`"""
def _inner():
for partition in partitions:
if partition.code_type is CodeType.IMPORT:
import_obj = import_obj_from_str(partition.src)
if import_obj.has_multiple_imports:
for new_import_obj in import_obj.split_imports():
yield CodePartition(
CodeType.IMPORT, new_import_obj.to_text(),
)
else:
yield partition
else:
yield partition
return list(_inner()) | [
"def",
"separate_comma_imports",
"(",
"partitions",
")",
":",
"def",
"_inner",
"(",
")",
":",
"for",
"partition",
"in",
"partitions",
":",
"if",
"partition",
".",
"code_type",
"is",
"CodeType",
".",
"IMPORT",
":",
"import_obj",
"=",
"import_obj_from_str",
"(",... | Turns `import a, b` into `import a` and `import b` | [
"Turns",
"import",
"a",
"b",
"into",
"import",
"a",
"and",
"import",
"b"
] | bc7b5b2f0fde191c9d0121588ef9bbb79f8e5e21 | https://github.com/asottile/reorder_python_imports/blob/bc7b5b2f0fde191c9d0121588ef9bbb79f8e5e21/reorder_python_imports.py#L148-L164 | train | 206,243 |
asottile/reorder_python_imports | reorder_python_imports.py | _module_to_base_modules | def _module_to_base_modules(s):
"""return all module names that would be imported due to this
import-import
"""
parts = s.split('.')
for i in range(1, len(parts)):
yield '.'.join(parts[:i]) | python | def _module_to_base_modules(s):
"""return all module names that would be imported due to this
import-import
"""
parts = s.split('.')
for i in range(1, len(parts)):
yield '.'.join(parts[:i]) | [
"def",
"_module_to_base_modules",
"(",
"s",
")",
":",
"parts",
"=",
"s",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"parts",
")",
")",
":",
"yield",
"'.'",
".",
"join",
"(",
"parts",
"[",
":",
"i",
"]",... | return all module names that would be imported due to this
import-import | [
"return",
"all",
"module",
"names",
"that",
"would",
"be",
"imported",
"due",
"to",
"this",
"import",
"-",
"import"
] | bc7b5b2f0fde191c9d0121588ef9bbb79f8e5e21 | https://github.com/asottile/reorder_python_imports/blob/bc7b5b2f0fde191c9d0121588ef9bbb79f8e5e21/reorder_python_imports.py#L245-L251 | train | 206,244 |
openfisca/openfisca-core | openfisca_core/formula_helpers.py | apply_thresholds | def apply_thresholds(input, thresholds, choices):
"""
Return one of the choices depending on the input position compared to thresholds, for each input.
>>> apply_thresholds(np.array([4]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([5]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([6]), [5, 7], [10, 15, 20])
array([15])
>>> apply_thresholds(np.array([8]), [5, 7], [10, 15, 20])
array([20])
>>> apply_thresholds(np.array([10]), [5, 7, 9], [10, 15, 20])
array([0])
"""
condlist = [input <= threshold for threshold in thresholds]
if len(condlist) == len(choices) - 1:
# If a choice is provided for input > highest threshold, last condition must be true to return it.
condlist += [True]
assert len(condlist) == len(choices), \
"apply_thresholds must be called with the same number of thresholds than choices, or one more choice"
return np.select(condlist, choices) | python | def apply_thresholds(input, thresholds, choices):
"""
Return one of the choices depending on the input position compared to thresholds, for each input.
>>> apply_thresholds(np.array([4]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([5]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([6]), [5, 7], [10, 15, 20])
array([15])
>>> apply_thresholds(np.array([8]), [5, 7], [10, 15, 20])
array([20])
>>> apply_thresholds(np.array([10]), [5, 7, 9], [10, 15, 20])
array([0])
"""
condlist = [input <= threshold for threshold in thresholds]
if len(condlist) == len(choices) - 1:
# If a choice is provided for input > highest threshold, last condition must be true to return it.
condlist += [True]
assert len(condlist) == len(choices), \
"apply_thresholds must be called with the same number of thresholds than choices, or one more choice"
return np.select(condlist, choices) | [
"def",
"apply_thresholds",
"(",
"input",
",",
"thresholds",
",",
"choices",
")",
":",
"condlist",
"=",
"[",
"input",
"<=",
"threshold",
"for",
"threshold",
"in",
"thresholds",
"]",
"if",
"len",
"(",
"condlist",
")",
"==",
"len",
"(",
"choices",
")",
"-",... | Return one of the choices depending on the input position compared to thresholds, for each input.
>>> apply_thresholds(np.array([4]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([5]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([6]), [5, 7], [10, 15, 20])
array([15])
>>> apply_thresholds(np.array([8]), [5, 7], [10, 15, 20])
array([20])
>>> apply_thresholds(np.array([10]), [5, 7, 9], [10, 15, 20])
array([0]) | [
"Return",
"one",
"of",
"the",
"choices",
"depending",
"on",
"the",
"input",
"position",
"compared",
"to",
"thresholds",
"for",
"each",
"input",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/formula_helpers.py#L10-L31 | train | 206,245 |
openfisca/openfisca-core | openfisca_core/parameters.py | Parameter.update | def update(self, period = None, start = None, stop = None, value = None):
"""Change the value for a given period.
:param period: Period where the value is modified. If set, `start` and `stop` should be `None`.
:param start: Start of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`.
:param stop: Stop of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`.
:param value: New value. If `None`, the parameter is removed from the legislation parameters for the given period.
"""
if period is not None:
if start is not None or stop is not None:
raise TypeError("Wrong input for 'update' method: use either 'update(period, value = value)' or 'update(start = start, stop = stop, value = value)'. You cannot both use 'period' and 'start' or 'stop'.")
if isinstance(period, str):
period = periods.period(period)
start = period.start
stop = period.stop
if start is None:
raise ValueError("You must provide either a start or a period")
start_str = str(start)
stop_str = str(stop.offset(1, 'day')) if stop else None
old_values = self.values_list
new_values = []
n = len(old_values)
i = 0
# Future intervals : not affected
if stop_str:
while (i < n) and (old_values[i].instant_str >= stop_str):
new_values.append(old_values[i])
i += 1
# Right-overlapped interval
if stop_str:
if new_values and (stop_str == new_values[-1].instant_str):
pass # such interval is empty
else:
if i < n:
overlapped_value = old_values[i].value
value_name = _compose_name(self.name, item_name = stop_str)
new_interval = ParameterAtInstant(value_name, stop_str, data = {'value': overlapped_value})
new_values.append(new_interval)
else:
value_name = _compose_name(self.name, item_name = stop_str)
new_interval = ParameterAtInstant(value_name, stop_str, data = {'value': None})
new_values.append(new_interval)
# Insert new interval
value_name = _compose_name(self.name, item_name = start_str)
new_interval = ParameterAtInstant(value_name, start_str, data = {'value': value})
new_values.append(new_interval)
# Remove covered intervals
while (i < n) and (old_values[i].instant_str >= start_str):
i += 1
# Past intervals : not affected
while i < n:
new_values.append(old_values[i])
i += 1
self.values_list = new_values | python | def update(self, period = None, start = None, stop = None, value = None):
"""Change the value for a given period.
:param period: Period where the value is modified. If set, `start` and `stop` should be `None`.
:param start: Start of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`.
:param stop: Stop of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`.
:param value: New value. If `None`, the parameter is removed from the legislation parameters for the given period.
"""
if period is not None:
if start is not None or stop is not None:
raise TypeError("Wrong input for 'update' method: use either 'update(period, value = value)' or 'update(start = start, stop = stop, value = value)'. You cannot both use 'period' and 'start' or 'stop'.")
if isinstance(period, str):
period = periods.period(period)
start = period.start
stop = period.stop
if start is None:
raise ValueError("You must provide either a start or a period")
start_str = str(start)
stop_str = str(stop.offset(1, 'day')) if stop else None
old_values = self.values_list
new_values = []
n = len(old_values)
i = 0
# Future intervals : not affected
if stop_str:
while (i < n) and (old_values[i].instant_str >= stop_str):
new_values.append(old_values[i])
i += 1
# Right-overlapped interval
if stop_str:
if new_values and (stop_str == new_values[-1].instant_str):
pass # such interval is empty
else:
if i < n:
overlapped_value = old_values[i].value
value_name = _compose_name(self.name, item_name = stop_str)
new_interval = ParameterAtInstant(value_name, stop_str, data = {'value': overlapped_value})
new_values.append(new_interval)
else:
value_name = _compose_name(self.name, item_name = stop_str)
new_interval = ParameterAtInstant(value_name, stop_str, data = {'value': None})
new_values.append(new_interval)
# Insert new interval
value_name = _compose_name(self.name, item_name = start_str)
new_interval = ParameterAtInstant(value_name, start_str, data = {'value': value})
new_values.append(new_interval)
# Remove covered intervals
while (i < n) and (old_values[i].instant_str >= start_str):
i += 1
# Past intervals : not affected
while i < n:
new_values.append(old_values[i])
i += 1
self.values_list = new_values | [
"def",
"update",
"(",
"self",
",",
"period",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"if",
"period",
"is",
"not",
"None",
":",
"if",
"start",
"is",
"not",
"None",
"or",
"stop",
"is",
... | Change the value for a given period.
:param period: Period where the value is modified. If set, `start` and `stop` should be `None`.
:param start: Start of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`.
:param stop: Stop of the period. Instance of `openfisca_core.periods.Instant`. If set, `period` should be `None`.
:param value: New value. If `None`, the parameter is removed from the legislation parameters for the given period. | [
"Change",
"the",
"value",
"for",
"a",
"given",
"period",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/parameters.py#L203-L263 | train | 206,246 |
openfisca/openfisca-core | openfisca_core/parameters.py | ParameterNode.merge | def merge(self, other):
"""
Merges another ParameterNode into the current node.
In case of child name conflict, the other node child will replace the current node child.
"""
for child_name, child in other.children.items():
self.add_child(child_name, child) | python | def merge(self, other):
"""
Merges another ParameterNode into the current node.
In case of child name conflict, the other node child will replace the current node child.
"""
for child_name, child in other.children.items():
self.add_child(child_name, child) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"for",
"child_name",
",",
"child",
"in",
"other",
".",
"children",
".",
"items",
"(",
")",
":",
"self",
".",
"add_child",
"(",
"child_name",
",",
"child",
")"
] | Merges another ParameterNode into the current node.
In case of child name conflict, the other node child will replace the current node child. | [
"Merges",
"another",
"ParameterNode",
"into",
"the",
"current",
"node",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/parameters.py#L423-L430 | train | 206,247 |
openfisca/openfisca-core | openfisca_core/parameters.py | ParameterNode.add_child | def add_child(self, name, child):
"""
Add a new child to the node.
:param name: Name of the child that must be used to access that child. Should not contain anything that could interfere with the operator `.` (dot).
:param child: The new child, an instance of :any:`Scale` or :any:`Parameter` or :any:`ParameterNode`.
"""
if name in self.children:
raise ValueError("{} has already a child named {}".format(self.name, name))
if not (isinstance(child, ParameterNode) or isinstance(child, Parameter) or isinstance(child, Scale)):
raise TypeError("child must be of type ParameterNode, Parameter, or Scale. Instead got {}".format(type(child)))
self.children[name] = child
setattr(self, name, child) | python | def add_child(self, name, child):
"""
Add a new child to the node.
:param name: Name of the child that must be used to access that child. Should not contain anything that could interfere with the operator `.` (dot).
:param child: The new child, an instance of :any:`Scale` or :any:`Parameter` or :any:`ParameterNode`.
"""
if name in self.children:
raise ValueError("{} has already a child named {}".format(self.name, name))
if not (isinstance(child, ParameterNode) or isinstance(child, Parameter) or isinstance(child, Scale)):
raise TypeError("child must be of type ParameterNode, Parameter, or Scale. Instead got {}".format(type(child)))
self.children[name] = child
setattr(self, name, child) | [
"def",
"add_child",
"(",
"self",
",",
"name",
",",
"child",
")",
":",
"if",
"name",
"in",
"self",
".",
"children",
":",
"raise",
"ValueError",
"(",
"\"{} has already a child named {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"name",
")",
")",
"if... | Add a new child to the node.
:param name: Name of the child that must be used to access that child. Should not contain anything that could interfere with the operator `.` (dot).
:param child: The new child, an instance of :any:`Scale` or :any:`Parameter` or :any:`ParameterNode`. | [
"Add",
"a",
"new",
"child",
"to",
"the",
"node",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/parameters.py#L432-L444 | train | 206,248 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.replace_variable | def replace_variable(self, variable):
"""
Replaces an existing OpenFisca variable in the tax and benefit system by a new one.
The new variable must have the same name than the replaced one.
If no variable with the given name exists in the tax and benefit system, no error will be raised and the new variable will be simply added.
:param Variable variable: New variable to add. Must be a subclass of Variable.
"""
name = variable.__name__
if self.variables.get(name) is not None:
del self.variables[name]
self.load_variable(variable, update = False) | python | def replace_variable(self, variable):
"""
Replaces an existing OpenFisca variable in the tax and benefit system by a new one.
The new variable must have the same name than the replaced one.
If no variable with the given name exists in the tax and benefit system, no error will be raised and the new variable will be simply added.
:param Variable variable: New variable to add. Must be a subclass of Variable.
"""
name = variable.__name__
if self.variables.get(name) is not None:
del self.variables[name]
self.load_variable(variable, update = False) | [
"def",
"replace_variable",
"(",
"self",
",",
"variable",
")",
":",
"name",
"=",
"variable",
".",
"__name__",
"if",
"self",
".",
"variables",
".",
"get",
"(",
"name",
")",
"is",
"not",
"None",
":",
"del",
"self",
".",
"variables",
"[",
"name",
"]",
"s... | Replaces an existing OpenFisca variable in the tax and benefit system by a new one.
The new variable must have the same name than the replaced one.
If no variable with the given name exists in the tax and benefit system, no error will be raised and the new variable will be simply added.
:param Variable variable: New variable to add. Must be a subclass of Variable. | [
"Replaces",
"an",
"existing",
"OpenFisca",
"variable",
"in",
"the",
"tax",
"and",
"benefit",
"system",
"by",
"a",
"new",
"one",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L167-L180 | train | 206,249 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.add_variables_from_file | def add_variables_from_file(self, file_path):
"""
Adds all OpenFisca variables contained in a given file to the tax and benefit system.
"""
try:
file_name = path.splitext(path.basename(file_path))[0]
# As Python remembers loaded modules by name, in order to prevent collisions, we need to make sure that:
# - Files with the same name, but located in different directories, have a different module names. Hence the file path hash in the module name.
# - The same file, loaded by different tax and benefit systems, has distinct module names. Hence the `id(self)` in the module name.
module_name = '{}_{}_{}'.format(id(self), hash(path.abspath(file_path)), file_name)
module_directory = path.dirname(file_path)
try:
module = load_module(module_name, *find_module(file_name, [module_directory]))
except NameError as e:
logging.error(str(e) + ": if this code used to work, this error might be due to a major change in OpenFisca-Core. Checkout the changelog to learn more: <https://github.com/openfisca/openfisca-core/blob/master/CHANGELOG.md>")
raise
potential_variables = [getattr(module, item) for item in dir(module) if not item.startswith('__')]
for pot_variable in potential_variables:
# We only want to get the module classes defined in this module (not imported)
if isclass(pot_variable) and issubclass(pot_variable, Variable) and pot_variable.__module__ == module_name:
self.add_variable(pot_variable)
except Exception:
log.error('Unable to load OpenFisca variables from file "{}"'.format(file_path))
raise | python | def add_variables_from_file(self, file_path):
"""
Adds all OpenFisca variables contained in a given file to the tax and benefit system.
"""
try:
file_name = path.splitext(path.basename(file_path))[0]
# As Python remembers loaded modules by name, in order to prevent collisions, we need to make sure that:
# - Files with the same name, but located in different directories, have a different module names. Hence the file path hash in the module name.
# - The same file, loaded by different tax and benefit systems, has distinct module names. Hence the `id(self)` in the module name.
module_name = '{}_{}_{}'.format(id(self), hash(path.abspath(file_path)), file_name)
module_directory = path.dirname(file_path)
try:
module = load_module(module_name, *find_module(file_name, [module_directory]))
except NameError as e:
logging.error(str(e) + ": if this code used to work, this error might be due to a major change in OpenFisca-Core. Checkout the changelog to learn more: <https://github.com/openfisca/openfisca-core/blob/master/CHANGELOG.md>")
raise
potential_variables = [getattr(module, item) for item in dir(module) if not item.startswith('__')]
for pot_variable in potential_variables:
# We only want to get the module classes defined in this module (not imported)
if isclass(pot_variable) and issubclass(pot_variable, Variable) and pot_variable.__module__ == module_name:
self.add_variable(pot_variable)
except Exception:
log.error('Unable to load OpenFisca variables from file "{}"'.format(file_path))
raise | [
"def",
"add_variables_from_file",
"(",
"self",
",",
"file_path",
")",
":",
"try",
":",
"file_name",
"=",
"path",
".",
"splitext",
"(",
"path",
".",
"basename",
"(",
"file_path",
")",
")",
"[",
"0",
"]",
"# As Python remembers loaded modules by name, in order to p... | Adds all OpenFisca variables contained in a given file to the tax and benefit system. | [
"Adds",
"all",
"OpenFisca",
"variables",
"contained",
"in",
"a",
"given",
"file",
"to",
"the",
"tax",
"and",
"benefit",
"system",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L196-L221 | train | 206,250 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.add_variables_from_directory | def add_variables_from_directory(self, directory):
"""
Recursively explores a directory, and adds all OpenFisca variables found there to the tax and benefit system.
"""
py_files = glob.glob(path.join(directory, "*.py"))
for py_file in py_files:
self.add_variables_from_file(py_file)
subdirectories = glob.glob(path.join(directory, "*/"))
for subdirectory in subdirectories:
self.add_variables_from_directory(subdirectory) | python | def add_variables_from_directory(self, directory):
"""
Recursively explores a directory, and adds all OpenFisca variables found there to the tax and benefit system.
"""
py_files = glob.glob(path.join(directory, "*.py"))
for py_file in py_files:
self.add_variables_from_file(py_file)
subdirectories = glob.glob(path.join(directory, "*/"))
for subdirectory in subdirectories:
self.add_variables_from_directory(subdirectory) | [
"def",
"add_variables_from_directory",
"(",
"self",
",",
"directory",
")",
":",
"py_files",
"=",
"glob",
".",
"glob",
"(",
"path",
".",
"join",
"(",
"directory",
",",
"\"*.py\"",
")",
")",
"for",
"py_file",
"in",
"py_files",
":",
"self",
".",
"add_variable... | Recursively explores a directory, and adds all OpenFisca variables found there to the tax and benefit system. | [
"Recursively",
"explores",
"a",
"directory",
"and",
"adds",
"all",
"OpenFisca",
"variables",
"found",
"there",
"to",
"the",
"tax",
"and",
"benefit",
"system",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L223-L232 | train | 206,251 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.load_extension | def load_extension(self, extension):
"""
Loads an extension to the tax and benefit system.
:param string extension: The extension to load. Can be an absolute path pointing to an extension directory, or the name of an OpenFisca extension installed as a pip package.
"""
# Load extension from installed pip package
try:
package = importlib.import_module(extension)
extension_directory = package.__path__[0]
except ImportError:
message = linesep.join([traceback.format_exc(),
'Error loading extension: `{}` is neither a directory, nor a package.'.format(extension),
'Are you sure it is installed in your environment? If so, look at the stack trace above to determine the origin of this error.',
'See more at <https://github.com/openfisca/openfisca-extension-template#installing>.'])
raise ValueError(message)
self.add_variables_from_directory(extension_directory)
param_dir = path.join(extension_directory, 'parameters')
if path.isdir(param_dir):
extension_parameters = ParameterNode(directory_path = param_dir)
self.parameters.merge(extension_parameters) | python | def load_extension(self, extension):
"""
Loads an extension to the tax and benefit system.
:param string extension: The extension to load. Can be an absolute path pointing to an extension directory, or the name of an OpenFisca extension installed as a pip package.
"""
# Load extension from installed pip package
try:
package = importlib.import_module(extension)
extension_directory = package.__path__[0]
except ImportError:
message = linesep.join([traceback.format_exc(),
'Error loading extension: `{}` is neither a directory, nor a package.'.format(extension),
'Are you sure it is installed in your environment? If so, look at the stack trace above to determine the origin of this error.',
'See more at <https://github.com/openfisca/openfisca-extension-template#installing>.'])
raise ValueError(message)
self.add_variables_from_directory(extension_directory)
param_dir = path.join(extension_directory, 'parameters')
if path.isdir(param_dir):
extension_parameters = ParameterNode(directory_path = param_dir)
self.parameters.merge(extension_parameters) | [
"def",
"load_extension",
"(",
"self",
",",
"extension",
")",
":",
"# Load extension from installed pip package",
"try",
":",
"package",
"=",
"importlib",
".",
"import_module",
"(",
"extension",
")",
"extension_directory",
"=",
"package",
".",
"__path__",
"[",
"0",
... | Loads an extension to the tax and benefit system.
:param string extension: The extension to load. Can be an absolute path pointing to an extension directory, or the name of an OpenFisca extension installed as a pip package. | [
"Loads",
"an",
"extension",
"to",
"the",
"tax",
"and",
"benefit",
"system",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L243-L265 | train | 206,252 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.apply_reform | def apply_reform(self, reform_path):
"""
Generates a new tax and benefit system applying a reform to the tax and benefit system.
The current tax and benefit system is **not** mutated.
:param string reform_path: The reform to apply. Must respect the format *installed_package.sub_module.reform*
:returns: A reformed tax and benefit system.
Example:
>>> self.apply_reform('openfisca_france.reforms.inversion_revenus')
"""
from openfisca_core.reforms import Reform
try:
reform_package, reform_name = reform_path.rsplit('.', 1)
except ValueError:
raise ValueError('`{}` does not seem to be a path pointing to a reform. A path looks like `some_country_package.reforms.some_reform.`'.format(reform_path))
try:
reform_module = importlib.import_module(reform_package)
except ImportError:
message = linesep.join([traceback.format_exc(),
'Could not import `{}`.'.format(reform_package),
'Are you sure of this reform module name? If so, look at the stack trace above to determine the origin of this error.'])
raise ValueError(message)
reform = getattr(reform_module, reform_name, None)
if reform is None:
raise ValueError('{} has no attribute {}'.format(reform_package, reform_name))
if not issubclass(reform, Reform):
raise ValueError('`{}` does not seem to be a valid Openfisca reform.'.format(reform_path))
return reform(self) | python | def apply_reform(self, reform_path):
"""
Generates a new tax and benefit system applying a reform to the tax and benefit system.
The current tax and benefit system is **not** mutated.
:param string reform_path: The reform to apply. Must respect the format *installed_package.sub_module.reform*
:returns: A reformed tax and benefit system.
Example:
>>> self.apply_reform('openfisca_france.reforms.inversion_revenus')
"""
from openfisca_core.reforms import Reform
try:
reform_package, reform_name = reform_path.rsplit('.', 1)
except ValueError:
raise ValueError('`{}` does not seem to be a path pointing to a reform. A path looks like `some_country_package.reforms.some_reform.`'.format(reform_path))
try:
reform_module = importlib.import_module(reform_package)
except ImportError:
message = linesep.join([traceback.format_exc(),
'Could not import `{}`.'.format(reform_package),
'Are you sure of this reform module name? If so, look at the stack trace above to determine the origin of this error.'])
raise ValueError(message)
reform = getattr(reform_module, reform_name, None)
if reform is None:
raise ValueError('{} has no attribute {}'.format(reform_package, reform_name))
if not issubclass(reform, Reform):
raise ValueError('`{}` does not seem to be a valid Openfisca reform.'.format(reform_path))
return reform(self) | [
"def",
"apply_reform",
"(",
"self",
",",
"reform_path",
")",
":",
"from",
"openfisca_core",
".",
"reforms",
"import",
"Reform",
"try",
":",
"reform_package",
",",
"reform_name",
"=",
"reform_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueEr... | Generates a new tax and benefit system applying a reform to the tax and benefit system.
The current tax and benefit system is **not** mutated.
:param string reform_path: The reform to apply. Must respect the format *installed_package.sub_module.reform*
:returns: A reformed tax and benefit system.
Example:
>>> self.apply_reform('openfisca_france.reforms.inversion_revenus') | [
"Generates",
"a",
"new",
"tax",
"and",
"benefit",
"system",
"applying",
"a",
"reform",
"to",
"the",
"tax",
"and",
"benefit",
"system",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L267-L300 | train | 206,253 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.get_variable | def get_variable(self, variable_name, check_existence = False):
"""
Get a variable from the tax and benefit system.
:param variable_name: Name of the requested variable.
:param check_existence: If True, raise an error if the requested variable does not exist.
"""
variables = self.variables
found = variables.get(variable_name)
if not found and check_existence:
raise VariableNotFound(variable_name, self)
return found | python | def get_variable(self, variable_name, check_existence = False):
"""
Get a variable from the tax and benefit system.
:param variable_name: Name of the requested variable.
:param check_existence: If True, raise an error if the requested variable does not exist.
"""
variables = self.variables
found = variables.get(variable_name)
if not found and check_existence:
raise VariableNotFound(variable_name, self)
return found | [
"def",
"get_variable",
"(",
"self",
",",
"variable_name",
",",
"check_existence",
"=",
"False",
")",
":",
"variables",
"=",
"self",
".",
"variables",
"found",
"=",
"variables",
".",
"get",
"(",
"variable_name",
")",
"if",
"not",
"found",
"and",
"check_existe... | Get a variable from the tax and benefit system.
:param variable_name: Name of the requested variable.
:param check_existence: If True, raise an error if the requested variable does not exist. | [
"Get",
"a",
"variable",
"from",
"the",
"tax",
"and",
"benefit",
"system",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L302-L313 | train | 206,254 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.neutralize_variable | def neutralize_variable(self, variable_name):
"""
Neutralizes an OpenFisca variable existing in the tax and benefit system.
A neutralized variable always returns its default value when computed.
Trying to set inputs for a neutralized variable has no effect except raising a warning.
"""
self.variables[variable_name] = get_neutralized_variable(self.get_variable(variable_name)) | python | def neutralize_variable(self, variable_name):
"""
Neutralizes an OpenFisca variable existing in the tax and benefit system.
A neutralized variable always returns its default value when computed.
Trying to set inputs for a neutralized variable has no effect except raising a warning.
"""
self.variables[variable_name] = get_neutralized_variable(self.get_variable(variable_name)) | [
"def",
"neutralize_variable",
"(",
"self",
",",
"variable_name",
")",
":",
"self",
".",
"variables",
"[",
"variable_name",
"]",
"=",
"get_neutralized_variable",
"(",
"self",
".",
"get_variable",
"(",
"variable_name",
")",
")"
] | Neutralizes an OpenFisca variable existing in the tax and benefit system.
A neutralized variable always returns its default value when computed.
Trying to set inputs for a neutralized variable has no effect except raising a warning. | [
"Neutralizes",
"an",
"OpenFisca",
"variable",
"existing",
"in",
"the",
"tax",
"and",
"benefit",
"system",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L315-L323 | train | 206,255 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.load_parameters | def load_parameters(self, path_to_yaml_dir):
"""
Loads the legislation parameter for a directory containing YAML parameters files.
:param path_to_yaml_dir: Absolute path towards the YAML parameter directory.
Example:
>>> self.load_parameters('/path/to/yaml/parameters/dir')
"""
parameters = ParameterNode('', directory_path = path_to_yaml_dir)
if self.preprocess_parameters is not None:
parameters = self.preprocess_parameters(parameters)
self.parameters = parameters | python | def load_parameters(self, path_to_yaml_dir):
"""
Loads the legislation parameter for a directory containing YAML parameters files.
:param path_to_yaml_dir: Absolute path towards the YAML parameter directory.
Example:
>>> self.load_parameters('/path/to/yaml/parameters/dir')
"""
parameters = ParameterNode('', directory_path = path_to_yaml_dir)
if self.preprocess_parameters is not None:
parameters = self.preprocess_parameters(parameters)
self.parameters = parameters | [
"def",
"load_parameters",
"(",
"self",
",",
"path_to_yaml_dir",
")",
":",
"parameters",
"=",
"ParameterNode",
"(",
"''",
",",
"directory_path",
"=",
"path_to_yaml_dir",
")",
"if",
"self",
".",
"preprocess_parameters",
"is",
"not",
"None",
":",
"parameters",
"=",... | Loads the legislation parameter for a directory containing YAML parameters files.
:param path_to_yaml_dir: Absolute path towards the YAML parameter directory.
Example:
>>> self.load_parameters('/path/to/yaml/parameters/dir') | [
"Loads",
"the",
"legislation",
"parameter",
"for",
"a",
"directory",
"containing",
"YAML",
"parameters",
"files",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L325-L341 | train | 206,256 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.get_parameters_at_instant | def get_parameters_at_instant(self, instant):
"""
Get the parameters of the legislation at a given instant
:param instant: string of the format 'YYYY-MM-DD' or `openfisca_core.periods.Instant` instance.
:returns: The parameters of the legislation at a given instant.
:rtype: :any:`ParameterNodeAtInstant`
"""
if isinstance(instant, periods.Period):
instant = instant.start
elif isinstance(instant, (str, int)):
instant = periods.instant(instant)
else:
assert isinstance(instant, periods.Instant), "Expected an Instant (e.g. Instant((2017, 1, 1)) ). Got: {}.".format(instant)
parameters_at_instant = self._parameters_at_instant_cache.get(instant)
if parameters_at_instant is None and self.parameters is not None:
parameters_at_instant = self.parameters.get_at_instant(str(instant))
self._parameters_at_instant_cache[instant] = parameters_at_instant
return parameters_at_instant | python | def get_parameters_at_instant(self, instant):
"""
Get the parameters of the legislation at a given instant
:param instant: string of the format 'YYYY-MM-DD' or `openfisca_core.periods.Instant` instance.
:returns: The parameters of the legislation at a given instant.
:rtype: :any:`ParameterNodeAtInstant`
"""
if isinstance(instant, periods.Period):
instant = instant.start
elif isinstance(instant, (str, int)):
instant = periods.instant(instant)
else:
assert isinstance(instant, periods.Instant), "Expected an Instant (e.g. Instant((2017, 1, 1)) ). Got: {}.".format(instant)
parameters_at_instant = self._parameters_at_instant_cache.get(instant)
if parameters_at_instant is None and self.parameters is not None:
parameters_at_instant = self.parameters.get_at_instant(str(instant))
self._parameters_at_instant_cache[instant] = parameters_at_instant
return parameters_at_instant | [
"def",
"get_parameters_at_instant",
"(",
"self",
",",
"instant",
")",
":",
"if",
"isinstance",
"(",
"instant",
",",
"periods",
".",
"Period",
")",
":",
"instant",
"=",
"instant",
".",
"start",
"elif",
"isinstance",
"(",
"instant",
",",
"(",
"str",
",",
"... | Get the parameters of the legislation at a given instant
:param instant: string of the format 'YYYY-MM-DD' or `openfisca_core.periods.Instant` instance.
:returns: The parameters of the legislation at a given instant.
:rtype: :any:`ParameterNodeAtInstant` | [
"Get",
"the",
"parameters",
"of",
"the",
"legislation",
"at",
"a",
"given",
"instant"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L349-L368 | train | 206,257 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.get_package_metadata | def get_package_metadata(self):
"""
Gets metatada relative to the country package the tax and benefit system is built from.
:returns: Country package metadata
:rtype: dict
Example:
>>> tax_benefit_system.get_package_metadata()
>>> {
>>> 'location': '/path/to/dir/containing/package',
>>> 'name': 'openfisca-france',
>>> 'repository_url': 'https://github.com/openfisca/openfisca-france',
>>> 'version': '17.2.0'
>>> }
"""
# Handle reforms
if self.baseline:
return self.baseline.get_package_metadata()
fallback_metadata = {
'name': self.__class__.__name__,
'version': '',
'repository_url': '',
'location': '',
}
module = inspect.getmodule(self)
if not module.__package__:
return fallback_metadata
package_name = module.__package__.split('.')[0]
try:
distribution = pkg_resources.get_distribution(package_name)
except pkg_resources.DistributionNotFound:
return fallback_metadata
location = inspect.getsourcefile(module).split(package_name)[0].rstrip('/')
home_page_metadatas = [
metadata.split(':', 1)[1].strip(' ')
for metadata in distribution._get_metadata(distribution.PKG_INFO) if 'Home-page' in metadata
]
repository_url = home_page_metadatas[0] if home_page_metadatas else ''
return {
'name': distribution.key,
'version': distribution.version,
'repository_url': repository_url,
'location': location,
} | python | def get_package_metadata(self):
"""
Gets metatada relative to the country package the tax and benefit system is built from.
:returns: Country package metadata
:rtype: dict
Example:
>>> tax_benefit_system.get_package_metadata()
>>> {
>>> 'location': '/path/to/dir/containing/package',
>>> 'name': 'openfisca-france',
>>> 'repository_url': 'https://github.com/openfisca/openfisca-france',
>>> 'version': '17.2.0'
>>> }
"""
# Handle reforms
if self.baseline:
return self.baseline.get_package_metadata()
fallback_metadata = {
'name': self.__class__.__name__,
'version': '',
'repository_url': '',
'location': '',
}
module = inspect.getmodule(self)
if not module.__package__:
return fallback_metadata
package_name = module.__package__.split('.')[0]
try:
distribution = pkg_resources.get_distribution(package_name)
except pkg_resources.DistributionNotFound:
return fallback_metadata
location = inspect.getsourcefile(module).split(package_name)[0].rstrip('/')
home_page_metadatas = [
metadata.split(':', 1)[1].strip(' ')
for metadata in distribution._get_metadata(distribution.PKG_INFO) if 'Home-page' in metadata
]
repository_url = home_page_metadatas[0] if home_page_metadatas else ''
return {
'name': distribution.key,
'version': distribution.version,
'repository_url': repository_url,
'location': location,
} | [
"def",
"get_package_metadata",
"(",
"self",
")",
":",
"# Handle reforms",
"if",
"self",
".",
"baseline",
":",
"return",
"self",
".",
"baseline",
".",
"get_package_metadata",
"(",
")",
"fallback_metadata",
"=",
"{",
"'name'",
":",
"self",
".",
"__class__",
".",... | Gets metatada relative to the country package the tax and benefit system is built from.
:returns: Country package metadata
:rtype: dict
Example:
>>> tax_benefit_system.get_package_metadata()
>>> {
>>> 'location': '/path/to/dir/containing/package',
>>> 'name': 'openfisca-france',
>>> 'repository_url': 'https://github.com/openfisca/openfisca-france',
>>> 'version': '17.2.0'
>>> } | [
"Gets",
"metatada",
"relative",
"to",
"the",
"country",
"package",
"the",
"tax",
"and",
"benefit",
"system",
"is",
"built",
"from",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L370-L419 | train | 206,258 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | TaxBenefitSystem.get_variables | def get_variables(self, entity = None):
"""
Gets all variables contained in a tax and benefit system.
:param <Entity subclass> entity: If set, returns only the variable defined for the given entity.
:returns: A dictionnary, indexed by variable names.
:rtype: dict
"""
if not entity:
return self.variables
else:
return {
variable_name: variable
for variable_name, variable in self.variables.items()
# TODO - because entities are copied (see constructor) they can't be compared
if variable.entity.key == entity.key
} | python | def get_variables(self, entity = None):
"""
Gets all variables contained in a tax and benefit system.
:param <Entity subclass> entity: If set, returns only the variable defined for the given entity.
:returns: A dictionnary, indexed by variable names.
:rtype: dict
"""
if not entity:
return self.variables
else:
return {
variable_name: variable
for variable_name, variable in self.variables.items()
# TODO - because entities are copied (see constructor) they can't be compared
if variable.entity.key == entity.key
} | [
"def",
"get_variables",
"(",
"self",
",",
"entity",
"=",
"None",
")",
":",
"if",
"not",
"entity",
":",
"return",
"self",
".",
"variables",
"else",
":",
"return",
"{",
"variable_name",
":",
"variable",
"for",
"variable_name",
",",
"variable",
"in",
"self",
... | Gets all variables contained in a tax and benefit system.
:param <Entity subclass> entity: If set, returns only the variable defined for the given entity.
:returns: A dictionnary, indexed by variable names.
:rtype: dict | [
"Gets",
"all",
"variables",
"contained",
"in",
"a",
"tax",
"and",
"benefit",
"system",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L421-L439 | train | 206,259 |
openfisca/openfisca-core | openfisca_core/simulation_builder.py | SimulationBuilder.build_from_dict | def build_from_dict(self, tax_benefit_system, input_dict):
"""
Build a simulation from ``input_dict``
This method uses :any:`build_from_entities` if entities are fully specified, or :any:`build_from_variables` if not.
:param dict input_dict: A dict represeting the input of the simulation
:return: A :any:`Simulation`
"""
input_dict = self.explicit_singular_entities(tax_benefit_system, input_dict)
if any(key in tax_benefit_system.entities_plural() for key in input_dict.keys()):
return self.build_from_entities(tax_benefit_system, input_dict)
else:
return self.build_from_variables(tax_benefit_system, input_dict) | python | def build_from_dict(self, tax_benefit_system, input_dict):
"""
Build a simulation from ``input_dict``
This method uses :any:`build_from_entities` if entities are fully specified, or :any:`build_from_variables` if not.
:param dict input_dict: A dict represeting the input of the simulation
:return: A :any:`Simulation`
"""
input_dict = self.explicit_singular_entities(tax_benefit_system, input_dict)
if any(key in tax_benefit_system.entities_plural() for key in input_dict.keys()):
return self.build_from_entities(tax_benefit_system, input_dict)
else:
return self.build_from_variables(tax_benefit_system, input_dict) | [
"def",
"build_from_dict",
"(",
"self",
",",
"tax_benefit_system",
",",
"input_dict",
")",
":",
"input_dict",
"=",
"self",
".",
"explicit_singular_entities",
"(",
"tax_benefit_system",
",",
"input_dict",
")",
"if",
"any",
"(",
"key",
"in",
"tax_benefit_system",
"."... | Build a simulation from ``input_dict``
This method uses :any:`build_from_entities` if entities are fully specified, or :any:`build_from_variables` if not.
:param dict input_dict: A dict represeting the input of the simulation
:return: A :any:`Simulation` | [
"Build",
"a",
"simulation",
"from",
"input_dict"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulation_builder.py#L43-L57 | train | 206,260 |
openfisca/openfisca-core | openfisca_core/simulation_builder.py | SimulationBuilder.build_from_entities | def build_from_entities(self, tax_benefit_system, input_dict):
"""
Build a simulation from a Python dict ``input_dict`` fully specifying entities.
Examples:
>>> simulation_builder.build_from_entities({
'persons': {'Javier': { 'salary': {'2018-11': 2000}}},
'households': {'household': {'parents': ['Javier']}}
})
"""
input_dict = deepcopy(input_dict)
simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities())
# Register variables so get_variable_entity can find them
for (variable_name, _variable) in tax_benefit_system.variables.items():
self.register_variable(variable_name, simulation.get_variable_population(variable_name).entity)
check_type(input_dict, dict, ['error'])
axes = input_dict.pop('axes', None)
unexpected_entities = [entity for entity in input_dict if entity not in tax_benefit_system.entities_plural()]
if unexpected_entities:
unexpected_entity = unexpected_entities[0]
raise SituationParsingError([unexpected_entity],
''.join([
"Some entities in the situation are not defined in the loaded tax and benefit system.",
"These entities are not found: {0}.",
"The defined entities are: {1}."]
)
.format(
', '.join(unexpected_entities),
', '.join(tax_benefit_system.entities_plural())
)
)
persons_json = input_dict.get(tax_benefit_system.person_entity.plural, None)
if not persons_json:
raise SituationParsingError([tax_benefit_system.person_entity.plural],
'No {0} found. At least one {0} must be defined to run a simulation.'.format(tax_benefit_system.person_entity.key))
persons_ids = self.add_person_entity(simulation.persons.entity, persons_json)
for entity_class in tax_benefit_system.group_entities:
instances_json = input_dict.get(entity_class.plural)
if instances_json is not None:
self.add_group_entity(self.persons_plural, persons_ids, entity_class, instances_json)
else:
self.add_default_group_entity(persons_ids, entity_class)
if axes:
self.axes = axes
self.expand_axes()
try:
self.finalize_variables_init(simulation.persons)
except PeriodMismatchError as e:
self.raise_period_mismatch(simulation.persons.entity, persons_json, e)
for entity_class in tax_benefit_system.group_entities:
try:
population = simulation.populations[entity_class.key]
self.finalize_variables_init(population)
except PeriodMismatchError as e:
self.raise_period_mismatch(population.entity, instances_json, e)
return simulation | python | def build_from_entities(self, tax_benefit_system, input_dict):
"""
Build a simulation from a Python dict ``input_dict`` fully specifying entities.
Examples:
>>> simulation_builder.build_from_entities({
'persons': {'Javier': { 'salary': {'2018-11': 2000}}},
'households': {'household': {'parents': ['Javier']}}
})
"""
input_dict = deepcopy(input_dict)
simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities())
# Register variables so get_variable_entity can find them
for (variable_name, _variable) in tax_benefit_system.variables.items():
self.register_variable(variable_name, simulation.get_variable_population(variable_name).entity)
check_type(input_dict, dict, ['error'])
axes = input_dict.pop('axes', None)
unexpected_entities = [entity for entity in input_dict if entity not in tax_benefit_system.entities_plural()]
if unexpected_entities:
unexpected_entity = unexpected_entities[0]
raise SituationParsingError([unexpected_entity],
''.join([
"Some entities in the situation are not defined in the loaded tax and benefit system.",
"These entities are not found: {0}.",
"The defined entities are: {1}."]
)
.format(
', '.join(unexpected_entities),
', '.join(tax_benefit_system.entities_plural())
)
)
persons_json = input_dict.get(tax_benefit_system.person_entity.plural, None)
if not persons_json:
raise SituationParsingError([tax_benefit_system.person_entity.plural],
'No {0} found. At least one {0} must be defined to run a simulation.'.format(tax_benefit_system.person_entity.key))
persons_ids = self.add_person_entity(simulation.persons.entity, persons_json)
for entity_class in tax_benefit_system.group_entities:
instances_json = input_dict.get(entity_class.plural)
if instances_json is not None:
self.add_group_entity(self.persons_plural, persons_ids, entity_class, instances_json)
else:
self.add_default_group_entity(persons_ids, entity_class)
if axes:
self.axes = axes
self.expand_axes()
try:
self.finalize_variables_init(simulation.persons)
except PeriodMismatchError as e:
self.raise_period_mismatch(simulation.persons.entity, persons_json, e)
for entity_class in tax_benefit_system.group_entities:
try:
population = simulation.populations[entity_class.key]
self.finalize_variables_init(population)
except PeriodMismatchError as e:
self.raise_period_mismatch(population.entity, instances_json, e)
return simulation | [
"def",
"build_from_entities",
"(",
"self",
",",
"tax_benefit_system",
",",
"input_dict",
")",
":",
"input_dict",
"=",
"deepcopy",
"(",
"input_dict",
")",
"simulation",
"=",
"Simulation",
"(",
"tax_benefit_system",
",",
"tax_benefit_system",
".",
"instantiate_entities"... | Build a simulation from a Python dict ``input_dict`` fully specifying entities.
Examples:
>>> simulation_builder.build_from_entities({
'persons': {'Javier': { 'salary': {'2018-11': 2000}}},
'households': {'household': {'parents': ['Javier']}}
}) | [
"Build",
"a",
"simulation",
"from",
"a",
"Python",
"dict",
"input_dict",
"fully",
"specifying",
"entities",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulation_builder.py#L59-L126 | train | 206,261 |
openfisca/openfisca-core | openfisca_core/simulation_builder.py | SimulationBuilder.build_from_variables | def build_from_variables(self, tax_benefit_system, input_dict):
"""
Build a simulation from a Python dict ``input_dict`` describing variables values without expliciting entities.
This method uses :any:`build_default_simulation` to infer an entity structure
Example:
>>> simulation_builder.build_from_variables(
{'salary': {'2016-10': 12000}}
)
"""
count = _get_person_count(input_dict)
simulation = self.build_default_simulation(tax_benefit_system, count)
for variable, value in input_dict.items():
if not isinstance(value, dict):
if self.default_period is None:
raise SituationParsingError([variable],
"Can't deal with type: expected object. Input variables should be set for specific periods. For instance: {'salary': {'2017-01': 2000, '2017-02': 2500}}, or {'birth_date': {'ETERNITY': '1980-01-01'}}.")
simulation.set_input(variable, self.default_period, value)
else:
for period_str, dated_value in value.items():
simulation.set_input(variable, period_str, dated_value)
return simulation | python | def build_from_variables(self, tax_benefit_system, input_dict):
"""
Build a simulation from a Python dict ``input_dict`` describing variables values without expliciting entities.
This method uses :any:`build_default_simulation` to infer an entity structure
Example:
>>> simulation_builder.build_from_variables(
{'salary': {'2016-10': 12000}}
)
"""
count = _get_person_count(input_dict)
simulation = self.build_default_simulation(tax_benefit_system, count)
for variable, value in input_dict.items():
if not isinstance(value, dict):
if self.default_period is None:
raise SituationParsingError([variable],
"Can't deal with type: expected object. Input variables should be set for specific periods. For instance: {'salary': {'2017-01': 2000, '2017-02': 2500}}, or {'birth_date': {'ETERNITY': '1980-01-01'}}.")
simulation.set_input(variable, self.default_period, value)
else:
for period_str, dated_value in value.items():
simulation.set_input(variable, period_str, dated_value)
return simulation | [
"def",
"build_from_variables",
"(",
"self",
",",
"tax_benefit_system",
",",
"input_dict",
")",
":",
"count",
"=",
"_get_person_count",
"(",
"input_dict",
")",
"simulation",
"=",
"self",
".",
"build_default_simulation",
"(",
"tax_benefit_system",
",",
"count",
")",
... | Build a simulation from a Python dict ``input_dict`` describing variables values without expliciting entities.
This method uses :any:`build_default_simulation` to infer an entity structure
Example:
>>> simulation_builder.build_from_variables(
{'salary': {'2016-10': 12000}}
) | [
"Build",
"a",
"simulation",
"from",
"a",
"Python",
"dict",
"input_dict",
"describing",
"variables",
"values",
"without",
"expliciting",
"entities",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulation_builder.py#L128-L151 | train | 206,262 |
openfisca/openfisca-core | openfisca_core/simulation_builder.py | SimulationBuilder.explicit_singular_entities | def explicit_singular_entities(self, tax_benefit_system, input_dict):
"""
Preprocess ``input_dict`` to explicit entities defined using the single-entity shortcut
Example:
>>> simulation_builder.explicit_singular_entities(
{'persons': {'Javier': {}, }, 'household': {'parents': ['Javier']}}
)
>>> {'persons': {'Javier': {}}, 'households': {'household': {'parents': ['Javier']}}
"""
singular_keys = set(input_dict).intersection(tax_benefit_system.entities_by_singular())
if not singular_keys:
return input_dict
result = {
entity_id: entity_description
for (entity_id, entity_description) in input_dict.items()
if entity_id in tax_benefit_system.entities_plural()
} # filter out the singular entities
for singular in singular_keys:
plural = tax_benefit_system.entities_by_singular()[singular].plural
result[plural] = {singular: input_dict[singular]}
return result | python | def explicit_singular_entities(self, tax_benefit_system, input_dict):
"""
Preprocess ``input_dict`` to explicit entities defined using the single-entity shortcut
Example:
>>> simulation_builder.explicit_singular_entities(
{'persons': {'Javier': {}, }, 'household': {'parents': ['Javier']}}
)
>>> {'persons': {'Javier': {}}, 'households': {'household': {'parents': ['Javier']}}
"""
singular_keys = set(input_dict).intersection(tax_benefit_system.entities_by_singular())
if not singular_keys:
return input_dict
result = {
entity_id: entity_description
for (entity_id, entity_description) in input_dict.items()
if entity_id in tax_benefit_system.entities_plural()
} # filter out the singular entities
for singular in singular_keys:
plural = tax_benefit_system.entities_by_singular()[singular].plural
result[plural] = {singular: input_dict[singular]}
return result | [
"def",
"explicit_singular_entities",
"(",
"self",
",",
"tax_benefit_system",
",",
"input_dict",
")",
":",
"singular_keys",
"=",
"set",
"(",
"input_dict",
")",
".",
"intersection",
"(",
"tax_benefit_system",
".",
"entities_by_singular",
"(",
")",
")",
"if",
"not",
... | Preprocess ``input_dict`` to explicit entities defined using the single-entity shortcut
Example:
>>> simulation_builder.explicit_singular_entities(
{'persons': {'Javier': {}, }, 'household': {'parents': ['Javier']}}
)
>>> {'persons': {'Javier': {}}, 'households': {'household': {'parents': ['Javier']}} | [
"Preprocess",
"input_dict",
"to",
"explicit",
"entities",
"defined",
"using",
"the",
"single",
"-",
"entity",
"shortcut"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulation_builder.py#L198-L224 | train | 206,263 |
openfisca/openfisca-core | openfisca_core/simulation_builder.py | SimulationBuilder.add_person_entity | def add_person_entity(self, entity, instances_json):
"""
Add the simulation's instances of the persons entity as described in ``instances_json``.
"""
check_type(instances_json, dict, [entity.plural])
entity_ids = list(map(str, instances_json.keys()))
self.persons_plural = entity.plural
self.entity_ids[self.persons_plural] = entity_ids
self.entity_counts[self.persons_plural] = len(entity_ids)
for instance_id, instance_object in instances_json.items():
check_type(instance_object, dict, [entity.plural, instance_id])
self.init_variable_values(entity, instance_object, str(instance_id))
return self.get_ids(entity.plural) | python | def add_person_entity(self, entity, instances_json):
"""
Add the simulation's instances of the persons entity as described in ``instances_json``.
"""
check_type(instances_json, dict, [entity.plural])
entity_ids = list(map(str, instances_json.keys()))
self.persons_plural = entity.plural
self.entity_ids[self.persons_plural] = entity_ids
self.entity_counts[self.persons_plural] = len(entity_ids)
for instance_id, instance_object in instances_json.items():
check_type(instance_object, dict, [entity.plural, instance_id])
self.init_variable_values(entity, instance_object, str(instance_id))
return self.get_ids(entity.plural) | [
"def",
"add_person_entity",
"(",
"self",
",",
"entity",
",",
"instances_json",
")",
":",
"check_type",
"(",
"instances_json",
",",
"dict",
",",
"[",
"entity",
".",
"plural",
"]",
")",
"entity_ids",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"instances_json"... | Add the simulation's instances of the persons entity as described in ``instances_json``. | [
"Add",
"the",
"simulation",
"s",
"instances",
"of",
"the",
"persons",
"entity",
"as",
"described",
"in",
"instances_json",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulation_builder.py#L226-L240 | train | 206,264 |
openfisca/openfisca-core | openfisca_core/taxscales.py | combine_tax_scales | def combine_tax_scales(node):
"""
Combine all the MarginalRateTaxScales in the node into a single MarginalRateTaxScale.
"""
combined_tax_scales = None
for child_name in node:
child = node[child_name]
if not isinstance(child, AbstractTaxScale):
log.info('Skipping {} with value {} because it is not a tax scale'.format(child_name, child))
continue
if combined_tax_scales is None:
combined_tax_scales = MarginalRateTaxScale(name = child_name)
combined_tax_scales.add_bracket(0, 0)
combined_tax_scales.add_tax_scale(child)
return combined_tax_scales | python | def combine_tax_scales(node):
"""
Combine all the MarginalRateTaxScales in the node into a single MarginalRateTaxScale.
"""
combined_tax_scales = None
for child_name in node:
child = node[child_name]
if not isinstance(child, AbstractTaxScale):
log.info('Skipping {} with value {} because it is not a tax scale'.format(child_name, child))
continue
if combined_tax_scales is None:
combined_tax_scales = MarginalRateTaxScale(name = child_name)
combined_tax_scales.add_bracket(0, 0)
combined_tax_scales.add_tax_scale(child)
return combined_tax_scales | [
"def",
"combine_tax_scales",
"(",
"node",
")",
":",
"combined_tax_scales",
"=",
"None",
"for",
"child_name",
"in",
"node",
":",
"child",
"=",
"node",
"[",
"child_name",
"]",
"if",
"not",
"isinstance",
"(",
"child",
",",
"AbstractTaxScale",
")",
":",
"log",
... | Combine all the MarginalRateTaxScales in the node into a single MarginalRateTaxScale. | [
"Combine",
"all",
"the",
"MarginalRateTaxScales",
"in",
"the",
"node",
"into",
"a",
"single",
"MarginalRateTaxScale",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxscales.py#L298-L314 | train | 206,265 |
openfisca/openfisca-core | openfisca_core/taxscales.py | MarginalRateTaxScale.inverse | def inverse(self):
"""Returns a new instance of MarginalRateTaxScale
Invert a taxscale:
Assume tax_scale composed of bracket which thresholds are expressed in term of brut revenue.
The inverse is another MarginalTaxSclae which thresholds are expressed in terms of net revenue.
If net = revbrut - tax_scale.calc(revbrut) then brut = tax_scale.inverse().calc(net)
"""
# threshold : threshold of brut revenue
# net_threshold: threshold of net revenue
# theta : ordonnée à l'origine des segments des différents seuils dans une
# représentation du revenu imposable comme fonction linéaire par
# morceaux du revenu brut
# Actually 1 / (1- global_rate)
inverse = self.__class__(name = self.name + "'", option = self.option, unit = self.unit)
net_threshold = 0
for threshold, rate in zip(self.thresholds, self.rates):
if threshold == 0:
previous_rate = 0
theta = 0
# On calcule le seuil de revenu imposable de la tranche considérée.
net_threshold = (1 - previous_rate) * threshold + theta
inverse.add_bracket(net_threshold, 1 / (1 - rate))
theta = (rate - previous_rate) * threshold + theta
previous_rate = rate
return inverse | python | def inverse(self):
"""Returns a new instance of MarginalRateTaxScale
Invert a taxscale:
Assume tax_scale composed of bracket which thresholds are expressed in term of brut revenue.
The inverse is another MarginalTaxSclae which thresholds are expressed in terms of net revenue.
If net = revbrut - tax_scale.calc(revbrut) then brut = tax_scale.inverse().calc(net)
"""
# threshold : threshold of brut revenue
# net_threshold: threshold of net revenue
# theta : ordonnée à l'origine des segments des différents seuils dans une
# représentation du revenu imposable comme fonction linéaire par
# morceaux du revenu brut
# Actually 1 / (1- global_rate)
inverse = self.__class__(name = self.name + "'", option = self.option, unit = self.unit)
net_threshold = 0
for threshold, rate in zip(self.thresholds, self.rates):
if threshold == 0:
previous_rate = 0
theta = 0
# On calcule le seuil de revenu imposable de la tranche considérée.
net_threshold = (1 - previous_rate) * threshold + theta
inverse.add_bracket(net_threshold, 1 / (1 - rate))
theta = (rate - previous_rate) * threshold + theta
previous_rate = rate
return inverse | [
"def",
"inverse",
"(",
"self",
")",
":",
"# threshold : threshold of brut revenue",
"# net_threshold: threshold of net revenue",
"# theta : ordonnée à l'origine des segments des différents seuils dans une",
"# représentation du revenu imposable comme fonction linéaire par",
"# mo... | Returns a new instance of MarginalRateTaxScale
Invert a taxscale:
Assume tax_scale composed of bracket which thresholds are expressed in term of brut revenue.
The inverse is another MarginalTaxSclae which thresholds are expressed in terms of net revenue.
If net = revbrut - tax_scale.calc(revbrut) then brut = tax_scale.inverse().calc(net) | [
"Returns",
"a",
"new",
"instance",
"of",
"MarginalRateTaxScale"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxscales.py#L248-L273 | train | 206,266 |
openfisca/openfisca-core | openfisca_core/taxscales.py | MarginalRateTaxScale.scale_tax_scales | def scale_tax_scales(self, factor):
"""Scale all the MarginalRateTaxScales in the node."""
assert isinstance(factor, (float, int))
scaled_tax_scale = self.copy()
return scaled_tax_scale.multiply_thresholds(factor) | python | def scale_tax_scales(self, factor):
"""Scale all the MarginalRateTaxScales in the node."""
assert isinstance(factor, (float, int))
scaled_tax_scale = self.copy()
return scaled_tax_scale.multiply_thresholds(factor) | [
"def",
"scale_tax_scales",
"(",
"self",
",",
"factor",
")",
":",
"assert",
"isinstance",
"(",
"factor",
",",
"(",
"float",
",",
"int",
")",
")",
"scaled_tax_scale",
"=",
"self",
".",
"copy",
"(",
")",
"return",
"scaled_tax_scale",
".",
"multiply_thresholds",... | Scale all the MarginalRateTaxScales in the node. | [
"Scale",
"all",
"the",
"MarginalRateTaxScales",
"in",
"the",
"node",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxscales.py#L275-L279 | train | 206,267 |
openfisca/openfisca-core | openfisca_core/indexed_enums.py | EnumArray.decode | def decode(self):
"""
Return the array of enum items corresponding to self
>>> enum_array = household('housing_occupancy_status', period)
>>> enum_array[0]
>>> 2 # Encoded value
>>> enum_array.decode()[0]
>>> <HousingOccupancyStatus.free_lodger: 'Free lodger'> # Decoded value : enum item
"""
return np.select([self == item.index for item in self.possible_values], [item for item in self.possible_values]) | python | def decode(self):
"""
Return the array of enum items corresponding to self
>>> enum_array = household('housing_occupancy_status', period)
>>> enum_array[0]
>>> 2 # Encoded value
>>> enum_array.decode()[0]
>>> <HousingOccupancyStatus.free_lodger: 'Free lodger'> # Decoded value : enum item
"""
return np.select([self == item.index for item in self.possible_values], [item for item in self.possible_values]) | [
"def",
"decode",
"(",
"self",
")",
":",
"return",
"np",
".",
"select",
"(",
"[",
"self",
"==",
"item",
".",
"index",
"for",
"item",
"in",
"self",
".",
"possible_values",
"]",
",",
"[",
"item",
"for",
"item",
"in",
"self",
".",
"possible_values",
"]",... | Return the array of enum items corresponding to self
>>> enum_array = household('housing_occupancy_status', period)
>>> enum_array[0]
>>> 2 # Encoded value
>>> enum_array.decode()[0]
>>> <HousingOccupancyStatus.free_lodger: 'Free lodger'> # Decoded value : enum item | [
"Return",
"the",
"array",
"of",
"enum",
"items",
"corresponding",
"to",
"self"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/indexed_enums.py#L106-L116 | train | 206,268 |
openfisca/openfisca-core | openfisca_core/indexed_enums.py | EnumArray.decode_to_str | def decode_to_str(self):
"""
Return the array of string identifiers corresponding to self
>>> enum_array = household('housing_occupancy_status', period)
>>> enum_array[0]
>>> 2 # Encoded value
>>> enum_array.decode_to_str()[0]
>>> 'free_lodger' # String identifier
"""
return np.select([self == item.index for item in self.possible_values], [item.name for item in self.possible_values]) | python | def decode_to_str(self):
"""
Return the array of string identifiers corresponding to self
>>> enum_array = household('housing_occupancy_status', period)
>>> enum_array[0]
>>> 2 # Encoded value
>>> enum_array.decode_to_str()[0]
>>> 'free_lodger' # String identifier
"""
return np.select([self == item.index for item in self.possible_values], [item.name for item in self.possible_values]) | [
"def",
"decode_to_str",
"(",
"self",
")",
":",
"return",
"np",
".",
"select",
"(",
"[",
"self",
"==",
"item",
".",
"index",
"for",
"item",
"in",
"self",
".",
"possible_values",
"]",
",",
"[",
"item",
".",
"name",
"for",
"item",
"in",
"self",
".",
"... | Return the array of string identifiers corresponding to self
>>> enum_array = household('housing_occupancy_status', period)
>>> enum_array[0]
>>> 2 # Encoded value
>>> enum_array.decode_to_str()[0]
>>> 'free_lodger' # String identifier | [
"Return",
"the",
"array",
"of",
"string",
"identifiers",
"corresponding",
"to",
"self"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/indexed_enums.py#L118-L128 | train | 206,269 |
openfisca/openfisca-core | openfisca_core/tracers.py | Tracer.record_calculation_start | def record_calculation_start(self, variable_name, period, **parameters):
"""
Record that OpenFisca started computing a variable.
:param str variable_name: Name of the variable starting to be computed
:param Period period: Period for which the variable is being computed
:param list parameters: Parameter with which the variable is being computed
"""
key = self._get_key(variable_name, period, **parameters)
if self.stack: # The variable is a dependency of another variable
parent = self.stack[-1]
self.trace[parent]['dependencies'].append(key)
else: # The variable has been requested by the client
self.requested_calculations.add(key)
if not self.trace.get(key):
self.trace[key] = {'dependencies': [], 'parameters': {}}
self.stack.append(key)
self._computation_log.append((key, len(self.stack)))
self.usage_stats[variable_name]['nb_requests'] += 1 | python | def record_calculation_start(self, variable_name, period, **parameters):
"""
Record that OpenFisca started computing a variable.
:param str variable_name: Name of the variable starting to be computed
:param Period period: Period for which the variable is being computed
:param list parameters: Parameter with which the variable is being computed
"""
key = self._get_key(variable_name, period, **parameters)
if self.stack: # The variable is a dependency of another variable
parent = self.stack[-1]
self.trace[parent]['dependencies'].append(key)
else: # The variable has been requested by the client
self.requested_calculations.add(key)
if not self.trace.get(key):
self.trace[key] = {'dependencies': [], 'parameters': {}}
self.stack.append(key)
self._computation_log.append((key, len(self.stack)))
self.usage_stats[variable_name]['nb_requests'] += 1 | [
"def",
"record_calculation_start",
"(",
"self",
",",
"variable_name",
",",
"period",
",",
"*",
"*",
"parameters",
")",
":",
"key",
"=",
"self",
".",
"_get_key",
"(",
"variable_name",
",",
"period",
",",
"*",
"*",
"parameters",
")",
"if",
"self",
".",
"st... | Record that OpenFisca started computing a variable.
:param str variable_name: Name of the variable starting to be computed
:param Period period: Period for which the variable is being computed
:param list parameters: Parameter with which the variable is being computed | [
"Record",
"that",
"OpenFisca",
"started",
"computing",
"a",
"variable",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/tracers.py#L95-L116 | train | 206,270 |
openfisca/openfisca-core | openfisca_core/tracers.py | Tracer.record_calculation_end | def record_calculation_end(self, variable_name, period, result, **parameters):
"""
Record that OpenFisca finished computing a variable.
:param str variable_name: Name of the variable starting to be computed
:param Period period: Period for which the variable is being computed
:param numpy.ndarray result: Result of the computation
:param list parameters: Parameter with which the variable is being computed
"""
key = self._get_key(variable_name, period, **parameters)
expected_key = self.stack.pop()
if not key == expected_key:
raise ValueError(
"Something went wrong with the simulation tracer: result of '{0}' was expected, got results for '{1}' instead. This does not make sense as the last variable we started computing was '{0}'."
.format(expected_key, key)
)
self.trace[key]['value'] = result | python | def record_calculation_end(self, variable_name, period, result, **parameters):
"""
Record that OpenFisca finished computing a variable.
:param str variable_name: Name of the variable starting to be computed
:param Period period: Period for which the variable is being computed
:param numpy.ndarray result: Result of the computation
:param list parameters: Parameter with which the variable is being computed
"""
key = self._get_key(variable_name, period, **parameters)
expected_key = self.stack.pop()
if not key == expected_key:
raise ValueError(
"Something went wrong with the simulation tracer: result of '{0}' was expected, got results for '{1}' instead. This does not make sense as the last variable we started computing was '{0}'."
.format(expected_key, key)
)
self.trace[key]['value'] = result | [
"def",
"record_calculation_end",
"(",
"self",
",",
"variable_name",
",",
"period",
",",
"result",
",",
"*",
"*",
"parameters",
")",
":",
"key",
"=",
"self",
".",
"_get_key",
"(",
"variable_name",
",",
"period",
",",
"*",
"*",
"parameters",
")",
"expected_k... | Record that OpenFisca finished computing a variable.
:param str variable_name: Name of the variable starting to be computed
:param Period period: Period for which the variable is being computed
:param numpy.ndarray result: Result of the computation
:param list parameters: Parameter with which the variable is being computed | [
"Record",
"that",
"OpenFisca",
"finished",
"computing",
"a",
"variable",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/tracers.py#L131-L148 | train | 206,271 |
openfisca/openfisca-core | openfisca_core/tracers.py | Tracer.print_computation_log | def print_computation_log(self, aggregate = False):
"""
Print the computation log of a simulation.
If ``aggregate`` is ``False`` (default), print the value of each computed vector.
If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each computed vector.
This mode is more suited for simulations on a large population.
"""
for line in self.computation_log(aggregate):
print(line) | python | def print_computation_log(self, aggregate = False):
"""
Print the computation log of a simulation.
If ``aggregate`` is ``False`` (default), print the value of each computed vector.
If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each computed vector.
This mode is more suited for simulations on a large population.
"""
for line in self.computation_log(aggregate):
print(line) | [
"def",
"print_computation_log",
"(",
"self",
",",
"aggregate",
"=",
"False",
")",
":",
"for",
"line",
"in",
"self",
".",
"computation_log",
"(",
"aggregate",
")",
":",
"print",
"(",
"line",
")"
] | Print the computation log of a simulation.
If ``aggregate`` is ``False`` (default), print the value of each computed vector.
If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each computed vector.
This mode is more suited for simulations on a large population. | [
"Print",
"the",
"computation",
"log",
"of",
"a",
"simulation",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/tracers.py#L211-L221 | train | 206,272 |
openfisca/openfisca-core | openfisca_core/scripts/simulation_generator.py | make_simulation | def make_simulation(tax_benefit_system, nb_persons, nb_groups, **kwargs):
"""
Generate a simulation containing nb_persons persons spread in nb_groups groups.
Example:
>>> from openfisca_core.scripts.simulation_generator import make_simulation
>>> from openfisca_france import CountryTaxBenefitSystem
>>> tbs = CountryTaxBenefitSystem()
>>> simulation = make_simulation(tbs, 400, 100) # Create a simulation with 400 persons, spread among 100 families
>>> simulation.calculate('revenu_disponible', 2017)
"""
simulation = Simulation(tax_benefit_system = tax_benefit_system, **kwargs)
simulation.persons.ids = np.arange(nb_persons)
simulation.persons.count = nb_persons
adults = [0] + sorted(random.sample(range(1, nb_persons), nb_groups - 1))
members_entity_id = np.empty(nb_persons, dtype = int)
# A legacy role is an index that every person within an entity has. For instance, the 'demandeur' has legacy role 0, the 'conjoint' 1, the first 'child' 2, the second 3, etc.
members_legacy_role = np.empty(nb_persons, dtype = int)
id_group = -1
for id_person in range(nb_persons):
if id_person in adults:
id_group += 1
legacy_role = 0
else:
legacy_role = 2 if legacy_role == 0 else legacy_role + 1
members_legacy_role[id_person] = legacy_role
members_entity_id[id_person] = id_group
for entity in simulation.populations.values():
if not entity.is_person:
entity.members_entity_id = members_entity_id
entity.count = nb_groups
entity.members_role = np.where(members_legacy_role == 0, entity.flattened_roles[0], entity.flattened_roles[-1])
return simulation | python | def make_simulation(tax_benefit_system, nb_persons, nb_groups, **kwargs):
"""
Generate a simulation containing nb_persons persons spread in nb_groups groups.
Example:
>>> from openfisca_core.scripts.simulation_generator import make_simulation
>>> from openfisca_france import CountryTaxBenefitSystem
>>> tbs = CountryTaxBenefitSystem()
>>> simulation = make_simulation(tbs, 400, 100) # Create a simulation with 400 persons, spread among 100 families
>>> simulation.calculate('revenu_disponible', 2017)
"""
simulation = Simulation(tax_benefit_system = tax_benefit_system, **kwargs)
simulation.persons.ids = np.arange(nb_persons)
simulation.persons.count = nb_persons
adults = [0] + sorted(random.sample(range(1, nb_persons), nb_groups - 1))
members_entity_id = np.empty(nb_persons, dtype = int)
# A legacy role is an index that every person within an entity has. For instance, the 'demandeur' has legacy role 0, the 'conjoint' 1, the first 'child' 2, the second 3, etc.
members_legacy_role = np.empty(nb_persons, dtype = int)
id_group = -1
for id_person in range(nb_persons):
if id_person in adults:
id_group += 1
legacy_role = 0
else:
legacy_role = 2 if legacy_role == 0 else legacy_role + 1
members_legacy_role[id_person] = legacy_role
members_entity_id[id_person] = id_group
for entity in simulation.populations.values():
if not entity.is_person:
entity.members_entity_id = members_entity_id
entity.count = nb_groups
entity.members_role = np.where(members_legacy_role == 0, entity.flattened_roles[0], entity.flattened_roles[-1])
return simulation | [
"def",
"make_simulation",
"(",
"tax_benefit_system",
",",
"nb_persons",
",",
"nb_groups",
",",
"*",
"*",
"kwargs",
")",
":",
"simulation",
"=",
"Simulation",
"(",
"tax_benefit_system",
"=",
"tax_benefit_system",
",",
"*",
"*",
"kwargs",
")",
"simulation",
".",
... | Generate a simulation containing nb_persons persons spread in nb_groups groups.
Example:
>>> from openfisca_core.scripts.simulation_generator import make_simulation
>>> from openfisca_france import CountryTaxBenefitSystem
>>> tbs = CountryTaxBenefitSystem()
>>> simulation = make_simulation(tbs, 400, 100) # Create a simulation with 400 persons, spread among 100 families
>>> simulation.calculate('revenu_disponible', 2017) | [
"Generate",
"a",
"simulation",
"containing",
"nb_persons",
"persons",
"spread",
"in",
"nb_groups",
"groups",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/scripts/simulation_generator.py#L7-L44 | train | 206,273 |
openfisca/openfisca-core | openfisca_core/reforms.py | Reform.modify_parameters | def modify_parameters(self, modifier_function):
"""
Make modifications on the parameters of the legislation
Call this function in `apply()` if the reform asks for legislation parameter modifications.
:param modifier_function: A function that takes an object of type :any:`ParameterNode` and should return an object of the same type.
"""
baseline_parameters = self.baseline.parameters
baseline_parameters_copy = copy.deepcopy(baseline_parameters)
reform_parameters = modifier_function(baseline_parameters_copy)
if not isinstance(reform_parameters, ParameterNode):
return ValueError(
'modifier_function {} in module {} must return a ParameterNode'
.format(modifier_function.__name__, modifier_function.__module__,)
)
self.parameters = reform_parameters
self._parameters_at_instant_cache = {} | python | def modify_parameters(self, modifier_function):
"""
Make modifications on the parameters of the legislation
Call this function in `apply()` if the reform asks for legislation parameter modifications.
:param modifier_function: A function that takes an object of type :any:`ParameterNode` and should return an object of the same type.
"""
baseline_parameters = self.baseline.parameters
baseline_parameters_copy = copy.deepcopy(baseline_parameters)
reform_parameters = modifier_function(baseline_parameters_copy)
if not isinstance(reform_parameters, ParameterNode):
return ValueError(
'modifier_function {} in module {} must return a ParameterNode'
.format(modifier_function.__name__, modifier_function.__module__,)
)
self.parameters = reform_parameters
self._parameters_at_instant_cache = {} | [
"def",
"modify_parameters",
"(",
"self",
",",
"modifier_function",
")",
":",
"baseline_parameters",
"=",
"self",
".",
"baseline",
".",
"parameters",
"baseline_parameters_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"baseline_parameters",
")",
"reform_parameters",
"=",
... | Make modifications on the parameters of the legislation
Call this function in `apply()` if the reform asks for legislation parameter modifications.
:param modifier_function: A function that takes an object of type :any:`ParameterNode` and should return an object of the same type. | [
"Make",
"modifications",
"on",
"the",
"parameters",
"of",
"the",
"legislation"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/reforms.py#L68-L85 | train | 206,274 |
openfisca/openfisca-core | openfisca_core/periods.py | Instant.date | def date(self):
"""Convert instant to a date.
>>> instant(2014).date
datetime.date(2014, 1, 1)
>>> instant('2014-2').date
datetime.date(2014, 2, 1)
>>> instant('2014-2-3').date
datetime.date(2014, 2, 3)
"""
instant_date = date_by_instant_cache.get(self)
if instant_date is None:
date_by_instant_cache[self] = instant_date = datetime.date(*self)
return instant_date | python | def date(self):
"""Convert instant to a date.
>>> instant(2014).date
datetime.date(2014, 1, 1)
>>> instant('2014-2').date
datetime.date(2014, 2, 1)
>>> instant('2014-2-3').date
datetime.date(2014, 2, 3)
"""
instant_date = date_by_instant_cache.get(self)
if instant_date is None:
date_by_instant_cache[self] = instant_date = datetime.date(*self)
return instant_date | [
"def",
"date",
"(",
"self",
")",
":",
"instant_date",
"=",
"date_by_instant_cache",
".",
"get",
"(",
"self",
")",
"if",
"instant_date",
"is",
"None",
":",
"date_by_instant_cache",
"[",
"self",
"]",
"=",
"instant_date",
"=",
"datetime",
".",
"date",
"(",
"*... | Convert instant to a date.
>>> instant(2014).date
datetime.date(2014, 1, 1)
>>> instant('2014-2').date
datetime.date(2014, 2, 1)
>>> instant('2014-2-3').date
datetime.date(2014, 2, 3) | [
"Convert",
"instant",
"to",
"a",
"date",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/periods.py#L64-L77 | train | 206,275 |
openfisca/openfisca-core | openfisca_core/periods.py | Instant.period | def period(self, unit, size = 1):
"""Create a new period starting at instant.
>>> instant(2014).period('month')
Period(('month', Instant((2014, 1, 1)), 1))
>>> instant('2014-2').period('year', 2)
Period(('year', Instant((2014, 2, 1)), 2))
>>> instant('2014-2-3').period('day', size = 2)
Period(('day', Instant((2014, 2, 3)), 2))
"""
assert unit in (DAY, MONTH, YEAR), 'Invalid unit: {} of type {}'.format(unit, type(unit))
assert isinstance(size, int) and size >= 1, 'Invalid size: {} of type {}'.format(size, type(size))
return Period((unit, self, size)) | python | def period(self, unit, size = 1):
"""Create a new period starting at instant.
>>> instant(2014).period('month')
Period(('month', Instant((2014, 1, 1)), 1))
>>> instant('2014-2').period('year', 2)
Period(('year', Instant((2014, 2, 1)), 2))
>>> instant('2014-2-3').period('day', size = 2)
Period(('day', Instant((2014, 2, 3)), 2))
"""
assert unit in (DAY, MONTH, YEAR), 'Invalid unit: {} of type {}'.format(unit, type(unit))
assert isinstance(size, int) and size >= 1, 'Invalid size: {} of type {}'.format(size, type(size))
return Period((unit, self, size)) | [
"def",
"period",
"(",
"self",
",",
"unit",
",",
"size",
"=",
"1",
")",
":",
"assert",
"unit",
"in",
"(",
"DAY",
",",
"MONTH",
",",
"YEAR",
")",
",",
"'Invalid unit: {} of type {}'",
".",
"format",
"(",
"unit",
",",
"type",
"(",
"unit",
")",
")",
"a... | Create a new period starting at instant.
>>> instant(2014).period('month')
Period(('month', Instant((2014, 1, 1)), 1))
>>> instant('2014-2').period('year', 2)
Period(('year', Instant((2014, 2, 1)), 2))
>>> instant('2014-2-3').period('day', size = 2)
Period(('day', Instant((2014, 2, 3)), 2)) | [
"Create",
"a",
"new",
"period",
"starting",
"at",
"instant",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/periods.py#L105-L117 | train | 206,276 |
openfisca/openfisca-core | openfisca_core/periods.py | Period.get_subperiods | def get_subperiods(self, unit):
"""
Return the list of all the periods of unit ``unit`` contained in self.
Examples:
>>> period('2017').get_subperiods(MONTH)
>>> [period('2017-01'), period('2017-02'), ... period('2017-12')]
>>> period('year:2014:2').get_subperiods(YEAR)
>>> [period('2014'), period('2015')]
"""
if unit_weight(self.unit) < unit_weight(unit):
raise ValueError('Cannot subdivide {0} into {1}'.format(self.unit, unit))
if unit == YEAR:
return [self.this_year.offset(i, YEAR) for i in range(self.size)]
if unit == MONTH:
return [self.first_month.offset(i, MONTH) for i in range(self.size_in_months)]
if unit == DAY:
return [self.first_day.offset(i, DAY) for i in range(self.size_in_days)] | python | def get_subperiods(self, unit):
"""
Return the list of all the periods of unit ``unit`` contained in self.
Examples:
>>> period('2017').get_subperiods(MONTH)
>>> [period('2017-01'), period('2017-02'), ... period('2017-12')]
>>> period('year:2014:2').get_subperiods(YEAR)
>>> [period('2014'), period('2015')]
"""
if unit_weight(self.unit) < unit_weight(unit):
raise ValueError('Cannot subdivide {0} into {1}'.format(self.unit, unit))
if unit == YEAR:
return [self.this_year.offset(i, YEAR) for i in range(self.size)]
if unit == MONTH:
return [self.first_month.offset(i, MONTH) for i in range(self.size_in_months)]
if unit == DAY:
return [self.first_day.offset(i, DAY) for i in range(self.size_in_days)] | [
"def",
"get_subperiods",
"(",
"self",
",",
"unit",
")",
":",
"if",
"unit_weight",
"(",
"self",
".",
"unit",
")",
"<",
"unit_weight",
"(",
"unit",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot subdivide {0} into {1}'",
".",
"format",
"(",
"self",
".",
"uni... | Return the list of all the periods of unit ``unit`` contained in self.
Examples:
>>> period('2017').get_subperiods(MONTH)
>>> [period('2017-01'), period('2017-02'), ... period('2017-12')]
>>> period('year:2014:2').get_subperiods(YEAR)
>>> [period('2014'), period('2015')] | [
"Return",
"the",
"list",
"of",
"all",
"the",
"periods",
"of",
"unit",
"unit",
"contained",
"in",
"self",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/periods.py#L409-L431 | train | 206,277 |
openfisca/openfisca-core | openfisca_core/periods.py | Period.size_in_months | def size_in_months(self):
"""Return the size of the period in months.
>>> period('month', '2012-2-29', 4).size_in_months
4
>>> period('year', '2012', 1).size_in_months
12
"""
if (self[0] == MONTH):
return self[2]
if(self[0] == YEAR):
return self[2] * 12
raise ValueError("Cannot calculate number of months in {0}".format(self[0])) | python | def size_in_months(self):
"""Return the size of the period in months.
>>> period('month', '2012-2-29', 4).size_in_months
4
>>> period('year', '2012', 1).size_in_months
12
"""
if (self[0] == MONTH):
return self[2]
if(self[0] == YEAR):
return self[2] * 12
raise ValueError("Cannot calculate number of months in {0}".format(self[0])) | [
"def",
"size_in_months",
"(",
"self",
")",
":",
"if",
"(",
"self",
"[",
"0",
"]",
"==",
"MONTH",
")",
":",
"return",
"self",
"[",
"2",
"]",
"if",
"(",
"self",
"[",
"0",
"]",
"==",
"YEAR",
")",
":",
"return",
"self",
"[",
"2",
"]",
"*",
"12",
... | Return the size of the period in months.
>>> period('month', '2012-2-29', 4).size_in_months
4
>>> period('year', '2012', 1).size_in_months
12 | [
"Return",
"the",
"size",
"of",
"the",
"period",
"in",
"months",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/periods.py#L587-L599 | train | 206,278 |
openfisca/openfisca-core | openfisca_core/periods.py | Period.size_in_days | def size_in_days(self):
"""Return the size of the period in days.
>>> period('month', '2012-2-29', 4).size_in_days
28
>>> period('year', '2012', 1).size_in_days
366
"""
unit, instant, length = self
if unit == DAY:
return length
if unit in [MONTH, YEAR]:
last_day = self.start.offset(length, unit).offset(-1, DAY)
return (last_day.date - self.start.date).days + 1
raise ValueError("Cannot calculate number of days in {0}".format(unit)) | python | def size_in_days(self):
"""Return the size of the period in days.
>>> period('month', '2012-2-29', 4).size_in_days
28
>>> period('year', '2012', 1).size_in_days
366
"""
unit, instant, length = self
if unit == DAY:
return length
if unit in [MONTH, YEAR]:
last_day = self.start.offset(length, unit).offset(-1, DAY)
return (last_day.date - self.start.date).days + 1
raise ValueError("Cannot calculate number of days in {0}".format(unit)) | [
"def",
"size_in_days",
"(",
"self",
")",
":",
"unit",
",",
"instant",
",",
"length",
"=",
"self",
"if",
"unit",
"==",
"DAY",
":",
"return",
"length",
"if",
"unit",
"in",
"[",
"MONTH",
",",
"YEAR",
"]",
":",
"last_day",
"=",
"self",
".",
"start",
".... | Return the size of the period in days.
>>> period('month', '2012-2-29', 4).size_in_days
28
>>> period('year', '2012', 1).size_in_days
366 | [
"Return",
"the",
"size",
"of",
"the",
"period",
"in",
"days",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/periods.py#L602-L618 | train | 206,279 |
openfisca/openfisca-core | openfisca_core/periods.py | Period.stop | def stop(self):
"""Return the last day of the period as an Instant instance.
>>> period('year', 2014).stop
Instant((2014, 12, 31))
>>> period('month', 2014).stop
Instant((2014, 12, 31))
>>> period('day', 2014).stop
Instant((2014, 12, 31))
>>> period('year', '2012-2-29').stop
Instant((2013, 2, 28))
>>> period('month', '2012-2-29').stop
Instant((2012, 3, 28))
>>> period('day', '2012-2-29').stop
Instant((2012, 2, 29))
>>> period('year', '2012-2-29', 2).stop
Instant((2014, 2, 28))
>>> period('month', '2012-2-29', 2).stop
Instant((2012, 4, 28))
>>> period('day', '2012-2-29', 2).stop
Instant((2012, 3, 1))
"""
unit, start_instant, size = self
year, month, day = start_instant
if unit == ETERNITY:
return Instant((float("inf"), float("inf"), float("inf")))
if unit == 'day':
if size > 1:
day += size - 1
month_last_day = calendar.monthrange(year, month)[1]
while day > month_last_day:
month += 1
if month == 13:
year += 1
month = 1
day -= month_last_day
month_last_day = calendar.monthrange(year, month)[1]
else:
if unit == 'month':
month += size
while month > 12:
year += 1
month -= 12
else:
assert unit == 'year', 'Invalid unit: {} of type {}'.format(unit, type(unit))
year += size
day -= 1
if day < 1:
month -= 1
if month == 0:
year -= 1
month = 12
day += calendar.monthrange(year, month)[1]
else:
month_last_day = calendar.monthrange(year, month)[1]
if day > month_last_day:
month += 1
if month == 13:
year += 1
month = 1
day -= month_last_day
return Instant((year, month, day)) | python | def stop(self):
"""Return the last day of the period as an Instant instance.
>>> period('year', 2014).stop
Instant((2014, 12, 31))
>>> period('month', 2014).stop
Instant((2014, 12, 31))
>>> period('day', 2014).stop
Instant((2014, 12, 31))
>>> period('year', '2012-2-29').stop
Instant((2013, 2, 28))
>>> period('month', '2012-2-29').stop
Instant((2012, 3, 28))
>>> period('day', '2012-2-29').stop
Instant((2012, 2, 29))
>>> period('year', '2012-2-29', 2).stop
Instant((2014, 2, 28))
>>> period('month', '2012-2-29', 2).stop
Instant((2012, 4, 28))
>>> period('day', '2012-2-29', 2).stop
Instant((2012, 3, 1))
"""
unit, start_instant, size = self
year, month, day = start_instant
if unit == ETERNITY:
return Instant((float("inf"), float("inf"), float("inf")))
if unit == 'day':
if size > 1:
day += size - 1
month_last_day = calendar.monthrange(year, month)[1]
while day > month_last_day:
month += 1
if month == 13:
year += 1
month = 1
day -= month_last_day
month_last_day = calendar.monthrange(year, month)[1]
else:
if unit == 'month':
month += size
while month > 12:
year += 1
month -= 12
else:
assert unit == 'year', 'Invalid unit: {} of type {}'.format(unit, type(unit))
year += size
day -= 1
if day < 1:
month -= 1
if month == 0:
year -= 1
month = 12
day += calendar.monthrange(year, month)[1]
else:
month_last_day = calendar.monthrange(year, month)[1]
if day > month_last_day:
month += 1
if month == 13:
year += 1
month = 1
day -= month_last_day
return Instant((year, month, day)) | [
"def",
"stop",
"(",
"self",
")",
":",
"unit",
",",
"start_instant",
",",
"size",
"=",
"self",
"year",
",",
"month",
",",
"day",
"=",
"start_instant",
"if",
"unit",
"==",
"ETERNITY",
":",
"return",
"Instant",
"(",
"(",
"float",
"(",
"\"inf\"",
")",
",... | Return the last day of the period as an Instant instance.
>>> period('year', 2014).stop
Instant((2014, 12, 31))
>>> period('month', 2014).stop
Instant((2014, 12, 31))
>>> period('day', 2014).stop
Instant((2014, 12, 31))
>>> period('year', '2012-2-29').stop
Instant((2013, 2, 28))
>>> period('month', '2012-2-29').stop
Instant((2012, 3, 28))
>>> period('day', '2012-2-29').stop
Instant((2012, 2, 29))
>>> period('year', '2012-2-29', 2).stop
Instant((2014, 2, 28))
>>> period('month', '2012-2-29', 2).stop
Instant((2012, 4, 28))
>>> period('day', '2012-2-29', 2).stop
Instant((2012, 3, 1)) | [
"Return",
"the",
"last",
"day",
"of",
"the",
"period",
"as",
"an",
"Instant",
"instance",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/periods.py#L630-L693 | train | 206,280 |
openfisca/openfisca-core | openfisca_core/variables.py | Variable.parse_formula_name | def parse_formula_name(self, attribute_name):
"""
Returns the starting date of a formula based on its name.
Valid dated name formats are : 'formula', 'formula_YYYY', 'formula_YYYY_MM' and 'formula_YYYY_MM_DD' where YYYY, MM and DD are a year, month and day.
By convention, the starting date of:
- `formula` is `0001-01-01` (minimal date in Python)
- `formula_YYYY` is `YYYY-01-01`
- `formula_YYYY_MM` is `YYYY-MM-01`
"""
def raise_error():
raise ValueError(
'Unrecognized formula name in variable "{}". Expecting "formula_YYYY" or "formula_YYYY_MM" or "formula_YYYY_MM_DD where YYYY, MM and DD are year, month and day. Found: "{}".'
.format(self.name, attribute_name))
if attribute_name == FORMULA_NAME_PREFIX:
return date.min
FORMULA_REGEX = r'formula_(\d{4})(?:_(\d{2}))?(?:_(\d{2}))?$' # YYYY or YYYY_MM or YYYY_MM_DD
match = re.match(FORMULA_REGEX, attribute_name)
if not match:
raise_error()
date_str = '-'.join([match.group(1), match.group(2) or '01', match.group(3) or '01'])
try:
return datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
except ValueError: # formula_2005_99_99 for instance
raise_error() | python | def parse_formula_name(self, attribute_name):
"""
Returns the starting date of a formula based on its name.
Valid dated name formats are : 'formula', 'formula_YYYY', 'formula_YYYY_MM' and 'formula_YYYY_MM_DD' where YYYY, MM and DD are a year, month and day.
By convention, the starting date of:
- `formula` is `0001-01-01` (minimal date in Python)
- `formula_YYYY` is `YYYY-01-01`
- `formula_YYYY_MM` is `YYYY-MM-01`
"""
def raise_error():
raise ValueError(
'Unrecognized formula name in variable "{}". Expecting "formula_YYYY" or "formula_YYYY_MM" or "formula_YYYY_MM_DD where YYYY, MM and DD are year, month and day. Found: "{}".'
.format(self.name, attribute_name))
if attribute_name == FORMULA_NAME_PREFIX:
return date.min
FORMULA_REGEX = r'formula_(\d{4})(?:_(\d{2}))?(?:_(\d{2}))?$' # YYYY or YYYY_MM or YYYY_MM_DD
match = re.match(FORMULA_REGEX, attribute_name)
if not match:
raise_error()
date_str = '-'.join([match.group(1), match.group(2) or '01', match.group(3) or '01'])
try:
return datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
except ValueError: # formula_2005_99_99 for instance
raise_error() | [
"def",
"parse_formula_name",
"(",
"self",
",",
"attribute_name",
")",
":",
"def",
"raise_error",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Unrecognized formula name in variable \"{}\". Expecting \"formula_YYYY\" or \"formula_YYYY_MM\" or \"formula_YYYY_MM_DD where YYYY, MM and DD ... | Returns the starting date of a formula based on its name.
Valid dated name formats are : 'formula', 'formula_YYYY', 'formula_YYYY_MM' and 'formula_YYYY_MM_DD' where YYYY, MM and DD are a year, month and day.
By convention, the starting date of:
- `formula` is `0001-01-01` (minimal date in Python)
- `formula_YYYY` is `YYYY-01-01`
- `formula_YYYY_MM` is `YYYY-MM-01` | [
"Returns",
"the",
"starting",
"date",
"of",
"a",
"formula",
"based",
"on",
"its",
"name",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/variables.py#L290-L320 | train | 206,281 |
openfisca/openfisca-core | openfisca_core/variables.py | Variable.get_introspection_data | def get_introspection_data(cls, tax_benefit_system):
"""
Get instrospection data about the code of the variable.
:returns: (comments, source file path, source code, start line number)
:rtype: tuple
"""
comments = inspect.getcomments(cls)
# Handle dynamically generated variable classes or Jupyter Notebooks, which have no source.
try:
absolute_file_path = inspect.getsourcefile(cls)
except TypeError:
source_file_path = None
else:
source_file_path = absolute_file_path.replace(tax_benefit_system.get_package_metadata()['location'], '')
try:
source_lines, start_line_number = inspect.getsourcelines(cls)
source_code = textwrap.dedent(''.join(source_lines))
except (IOError, TypeError):
source_code, start_line_number = None, None
return comments, source_file_path, source_code, start_line_number | python | def get_introspection_data(cls, tax_benefit_system):
"""
Get instrospection data about the code of the variable.
:returns: (comments, source file path, source code, start line number)
:rtype: tuple
"""
comments = inspect.getcomments(cls)
# Handle dynamically generated variable classes or Jupyter Notebooks, which have no source.
try:
absolute_file_path = inspect.getsourcefile(cls)
except TypeError:
source_file_path = None
else:
source_file_path = absolute_file_path.replace(tax_benefit_system.get_package_metadata()['location'], '')
try:
source_lines, start_line_number = inspect.getsourcelines(cls)
source_code = textwrap.dedent(''.join(source_lines))
except (IOError, TypeError):
source_code, start_line_number = None, None
return comments, source_file_path, source_code, start_line_number | [
"def",
"get_introspection_data",
"(",
"cls",
",",
"tax_benefit_system",
")",
":",
"comments",
"=",
"inspect",
".",
"getcomments",
"(",
"cls",
")",
"# Handle dynamically generated variable classes or Jupyter Notebooks, which have no source.",
"try",
":",
"absolute_file_path",
... | Get instrospection data about the code of the variable.
:returns: (comments, source file path, source code, start line number)
:rtype: tuple | [
"Get",
"instrospection",
"data",
"about",
"the",
"code",
"of",
"the",
"variable",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/variables.py#L331-L354 | train | 206,282 |
openfisca/openfisca-core | openfisca_core/variables.py | Variable.get_formula | def get_formula(self, period = None):
"""
Returns the formula used to compute the variable at the given period.
If no period is given and the variable has several formula, return the oldest formula.
:returns: Formula used to compute the variable
:rtype: function
"""
if not self.formulas:
return None
if period is None:
return self.formulas.peekitem(index = 0)[1] # peekitem gets the 1st key-value tuple (the oldest start_date and formula). Return the formula.
if isinstance(period, periods.Period):
instant = period.start
else:
try:
instant = periods.period(period).start
except ValueError:
instant = periods.instant(period)
if self.end and instant.date > self.end:
return None
instant = str(instant)
for start_date in reversed(self.formulas):
if start_date <= instant:
return self.formulas[start_date]
return None | python | def get_formula(self, period = None):
"""
Returns the formula used to compute the variable at the given period.
If no period is given and the variable has several formula, return the oldest formula.
:returns: Formula used to compute the variable
:rtype: function
"""
if not self.formulas:
return None
if period is None:
return self.formulas.peekitem(index = 0)[1] # peekitem gets the 1st key-value tuple (the oldest start_date and formula). Return the formula.
if isinstance(period, periods.Period):
instant = period.start
else:
try:
instant = periods.period(period).start
except ValueError:
instant = periods.instant(period)
if self.end and instant.date > self.end:
return None
instant = str(instant)
for start_date in reversed(self.formulas):
if start_date <= instant:
return self.formulas[start_date]
return None | [
"def",
"get_formula",
"(",
"self",
",",
"period",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"formulas",
":",
"return",
"None",
"if",
"period",
"is",
"None",
":",
"return",
"self",
".",
"formulas",
".",
"peekitem",
"(",
"index",
"=",
"0",
")",
... | Returns the formula used to compute the variable at the given period.
If no period is given and the variable has several formula, return the oldest formula.
:returns: Formula used to compute the variable
:rtype: function | [
"Returns",
"the",
"formula",
"used",
"to",
"compute",
"the",
"variable",
"at",
"the",
"given",
"period",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/variables.py#L356-L388 | train | 206,283 |
openfisca/openfisca-core | openfisca_core/populations.py | Population.get_rank | def get_rank(self, entity, criteria, condition = True):
"""
Get the rank of a person within an entity according to a criteria.
The person with rank 0 has the minimum value of criteria.
If condition is specified, then the persons who don't respect it are not taken into account and their rank is -1.
Example:
>>> age = person('age', period) # e.g [32, 34, 2, 8, 1]
>>> person.get_rank(household, age)
>>> [3, 4, 0, 2, 1]
>>> is_child = person.has_role(Household.CHILD) # [False, False, True, True, True]
>>> person.get_rank(household, - age, condition = is_child) # Sort in reverse order so that the eldest child gets the rank 0.
>>> [-1, -1, 1, 0, 2]
"""
# If entity is for instance 'person.household', we get the reference entity 'household' behind the projector
entity = entity if not isinstance(entity, Projector) else entity.reference_entity
positions = entity.members_position
biggest_entity_size = np.max(positions) + 1
filtered_criteria = np.where(condition, criteria, np.inf)
ids = entity.members_entity_id
# Matrix: the value in line i and column j is the value of criteria for the jth person of the ith entity
matrix = np.asarray([
entity.value_nth_person(k, filtered_criteria, default = np.inf)
for k in range(biggest_entity_size)
]).transpose()
# We double-argsort all lines of the matrix.
# Double-argsorting gets the rank of each value once sorted
# For instance, if x = [3,1,6,4,0], y = np.argsort(x) is [4, 1, 0, 3, 2] (because the value with index 4 is the smallest one, the value with index 1 the second smallest, etc.) and z = np.argsort(y) is [2, 1, 4, 3, 0], the rank of each value.
sorted_matrix = np.argsort(np.argsort(matrix))
# Build the result vector by taking for each person the value in the right line (corresponding to its household id) and the right column (corresponding to its position)
result = sorted_matrix[ids, positions]
# Return -1 for the persons who don't respect the condition
return np.where(condition, result, -1) | python | def get_rank(self, entity, criteria, condition = True):
"""
Get the rank of a person within an entity according to a criteria.
The person with rank 0 has the minimum value of criteria.
If condition is specified, then the persons who don't respect it are not taken into account and their rank is -1.
Example:
>>> age = person('age', period) # e.g [32, 34, 2, 8, 1]
>>> person.get_rank(household, age)
>>> [3, 4, 0, 2, 1]
>>> is_child = person.has_role(Household.CHILD) # [False, False, True, True, True]
>>> person.get_rank(household, - age, condition = is_child) # Sort in reverse order so that the eldest child gets the rank 0.
>>> [-1, -1, 1, 0, 2]
"""
# If entity is for instance 'person.household', we get the reference entity 'household' behind the projector
entity = entity if not isinstance(entity, Projector) else entity.reference_entity
positions = entity.members_position
biggest_entity_size = np.max(positions) + 1
filtered_criteria = np.where(condition, criteria, np.inf)
ids = entity.members_entity_id
# Matrix: the value in line i and column j is the value of criteria for the jth person of the ith entity
matrix = np.asarray([
entity.value_nth_person(k, filtered_criteria, default = np.inf)
for k in range(biggest_entity_size)
]).transpose()
# We double-argsort all lines of the matrix.
# Double-argsorting gets the rank of each value once sorted
# For instance, if x = [3,1,6,4,0], y = np.argsort(x) is [4, 1, 0, 3, 2] (because the value with index 4 is the smallest one, the value with index 1 the second smallest, etc.) and z = np.argsort(y) is [2, 1, 4, 3, 0], the rank of each value.
sorted_matrix = np.argsort(np.argsort(matrix))
# Build the result vector by taking for each person the value in the right line (corresponding to its household id) and the right column (corresponding to its position)
result = sorted_matrix[ids, positions]
# Return -1 for the persons who don't respect the condition
return np.where(condition, result, -1) | [
"def",
"get_rank",
"(",
"self",
",",
"entity",
",",
"criteria",
",",
"condition",
"=",
"True",
")",
":",
"# If entity is for instance 'person.household', we get the reference entity 'household' behind the projector",
"entity",
"=",
"entity",
"if",
"not",
"isinstance",
"(",
... | Get the rank of a person within an entity according to a criteria.
The person with rank 0 has the minimum value of criteria.
If condition is specified, then the persons who don't respect it are not taken into account and their rank is -1.
Example:
>>> age = person('age', period) # e.g [32, 34, 2, 8, 1]
>>> person.get_rank(household, age)
>>> [3, 4, 0, 2, 1]
>>> is_child = person.has_role(Household.CHILD) # [False, False, True, True, True]
>>> person.get_rank(household, - age, condition = is_child) # Sort in reverse order so that the eldest child gets the rank 0.
>>> [-1, -1, 1, 0, 2] | [
"Get",
"the",
"rank",
"of",
"a",
"person",
"within",
"an",
"entity",
"according",
"to",
"a",
"criteria",
".",
"The",
"person",
"with",
"rank",
"0",
"has",
"the",
"minimum",
"value",
"of",
"criteria",
".",
"If",
"condition",
"is",
"specified",
"then",
"th... | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L165-L205 | train | 206,284 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.ordered_members_map | def ordered_members_map(self):
"""
Mask to group the persons by entity
This function only caches the map value, to see what the map is used for, see value_nth_person method.
"""
if self._ordered_members_map is None:
return np.argsort(self.members_entity_id)
return self._ordered_members_map | python | def ordered_members_map(self):
"""
Mask to group the persons by entity
This function only caches the map value, to see what the map is used for, see value_nth_person method.
"""
if self._ordered_members_map is None:
return np.argsort(self.members_entity_id)
return self._ordered_members_map | [
"def",
"ordered_members_map",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ordered_members_map",
"is",
"None",
":",
"return",
"np",
".",
"argsort",
"(",
"self",
".",
"members_entity_id",
")",
"return",
"self",
".",
"_ordered_members_map"
] | Mask to group the persons by entity
This function only caches the map value, to see what the map is used for, see value_nth_person method. | [
"Mask",
"to",
"group",
"the",
"persons",
"by",
"entity",
"This",
"function",
"only",
"caches",
"the",
"map",
"value",
"to",
"see",
"what",
"the",
"map",
"is",
"used",
"for",
"see",
"value_nth_person",
"method",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L265-L272 | train | 206,285 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.sum | def sum(self, array, role = None):
"""
Return the sum of ``array`` for the members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.sum(salaries)
>>> array([3500])
"""
self.entity.check_role_validity(role)
self.members.check_array_compatible_with_entity(array)
if role is not None:
role_filter = self.members.has_role(role)
return np.bincount(
self.members_entity_id[role_filter],
weights = array[role_filter],
minlength = self.count)
else:
return np.bincount(self.members_entity_id, weights = array) | python | def sum(self, array, role = None):
"""
Return the sum of ``array`` for the members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.sum(salaries)
>>> array([3500])
"""
self.entity.check_role_validity(role)
self.members.check_array_compatible_with_entity(array)
if role is not None:
role_filter = self.members.has_role(role)
return np.bincount(
self.members_entity_id[role_filter],
weights = array[role_filter],
minlength = self.count)
else:
return np.bincount(self.members_entity_id, weights = array) | [
"def",
"sum",
"(",
"self",
",",
"array",
",",
"role",
"=",
"None",
")",
":",
"self",
".",
"entity",
".",
"check_role_validity",
"(",
"role",
")",
"self",
".",
"members",
".",
"check_array_compatible_with_entity",
"(",
"array",
")",
"if",
"role",
"is",
"n... | Return the sum of ``array`` for the members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.sum(salaries)
>>> array([3500]) | [
"Return",
"the",
"sum",
"of",
"array",
"for",
"the",
"members",
"of",
"the",
"entity",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L284-L307 | train | 206,286 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.any | def any(self, array, role = None):
"""
Return ``True`` if ``array`` is ``True`` for any members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.any(salaries >= 1800)
>>> array([True])
"""
sum_in_entity = self.sum(array, role = role)
return (sum_in_entity > 0) | python | def any(self, array, role = None):
"""
Return ``True`` if ``array`` is ``True`` for any members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.any(salaries >= 1800)
>>> array([True])
"""
sum_in_entity = self.sum(array, role = role)
return (sum_in_entity > 0) | [
"def",
"any",
"(",
"self",
",",
"array",
",",
"role",
"=",
"None",
")",
":",
"sum_in_entity",
"=",
"self",
".",
"sum",
"(",
"array",
",",
"role",
"=",
"role",
")",
"return",
"(",
"sum_in_entity",
">",
"0",
")"
] | Return ``True`` if ``array`` is ``True`` for any members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.any(salaries >= 1800)
>>> array([True]) | [
"Return",
"True",
"if",
"array",
"is",
"True",
"for",
"any",
"members",
"of",
"the",
"entity",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L310-L325 | train | 206,287 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.all | def all(self, array, role = None):
"""
Return ``True`` if ``array`` is ``True`` for all members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.all(salaries >= 1800)
>>> array([False])
"""
return self.reduce(array, reducer = np.logical_and, neutral_element = True, role = role) | python | def all(self, array, role = None):
"""
Return ``True`` if ``array`` is ``True`` for all members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.all(salaries >= 1800)
>>> array([False])
"""
return self.reduce(array, reducer = np.logical_and, neutral_element = True, role = role) | [
"def",
"all",
"(",
"self",
",",
"array",
",",
"role",
"=",
"None",
")",
":",
"return",
"self",
".",
"reduce",
"(",
"array",
",",
"reducer",
"=",
"np",
".",
"logical_and",
",",
"neutral_element",
"=",
"True",
",",
"role",
"=",
"role",
")"
] | Return ``True`` if ``array`` is ``True`` for all members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.all(salaries >= 1800)
>>> array([False]) | [
"Return",
"True",
"if",
"array",
"is",
"True",
"for",
"all",
"members",
"of",
"the",
"entity",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L348-L362 | train | 206,288 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.max | def max(self, array, role = None):
"""
Return the maximum value of ``array`` for the entity members.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.max(salaries)
>>> array([2000])
"""
return self.reduce(array, reducer = np.maximum, neutral_element = - np.infty, role = role) | python | def max(self, array, role = None):
"""
Return the maximum value of ``array`` for the entity members.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.max(salaries)
>>> array([2000])
"""
return self.reduce(array, reducer = np.maximum, neutral_element = - np.infty, role = role) | [
"def",
"max",
"(",
"self",
",",
"array",
",",
"role",
"=",
"None",
")",
":",
"return",
"self",
".",
"reduce",
"(",
"array",
",",
"reducer",
"=",
"np",
".",
"maximum",
",",
"neutral_element",
"=",
"-",
"np",
".",
"infty",
",",
"role",
"=",
"role",
... | Return the maximum value of ``array`` for the entity members.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.max(salaries)
>>> array([2000]) | [
"Return",
"the",
"maximum",
"value",
"of",
"array",
"for",
"the",
"entity",
"members",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L365-L379 | train | 206,289 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.min | def min(self, array, role = None):
"""
Return the minimum value of ``array`` for the entity members.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.min(salaries)
>>> array([0])
>>> household.min(salaries, role = Household.PARENT) # Assuming the 1st two persons are parents
>>> array([1500])
"""
return self.reduce(array, reducer = np.minimum, neutral_element = np.infty, role = role) | python | def min(self, array, role = None):
"""
Return the minimum value of ``array`` for the entity members.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.min(salaries)
>>> array([0])
>>> household.min(salaries, role = Household.PARENT) # Assuming the 1st two persons are parents
>>> array([1500])
"""
return self.reduce(array, reducer = np.minimum, neutral_element = np.infty, role = role) | [
"def",
"min",
"(",
"self",
",",
"array",
",",
"role",
"=",
"None",
")",
":",
"return",
"self",
".",
"reduce",
"(",
"array",
",",
"reducer",
"=",
"np",
".",
"minimum",
",",
"neutral_element",
"=",
"np",
".",
"infty",
",",
"role",
"=",
"role",
")"
] | Return the minimum value of ``array`` for the entity members.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = household.members('salary', '2018-01') # e.g. [2000, 1500, 0, 0, 0]
>>> household.min(salaries)
>>> array([0])
>>> household.min(salaries, role = Household.PARENT) # Assuming the 1st two persons are parents
>>> array([1500]) | [
"Return",
"the",
"minimum",
"value",
"of",
"array",
"for",
"the",
"entity",
"members",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L382-L398 | train | 206,290 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.nb_persons | def nb_persons(self, role = None):
"""
Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account.
"""
if role:
if role.subroles:
role_condition = np.logical_or.reduce([self.members_role == subrole for subrole in role.subroles])
else:
role_condition = self.members_role == role
return self.sum(role_condition)
else:
return np.bincount(self.members_entity_id) | python | def nb_persons(self, role = None):
"""
Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account.
"""
if role:
if role.subroles:
role_condition = np.logical_or.reduce([self.members_role == subrole for subrole in role.subroles])
else:
role_condition = self.members_role == role
return self.sum(role_condition)
else:
return np.bincount(self.members_entity_id) | [
"def",
"nb_persons",
"(",
"self",
",",
"role",
"=",
"None",
")",
":",
"if",
"role",
":",
"if",
"role",
".",
"subroles",
":",
"role_condition",
"=",
"np",
".",
"logical_or",
".",
"reduce",
"(",
"[",
"self",
".",
"members_role",
"==",
"subrole",
"for",
... | Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account. | [
"Returns",
"the",
"number",
"of",
"persons",
"contained",
"in",
"the",
"entity",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L401-L414 | train | 206,291 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.value_from_person | def value_from_person(self, array, role, default = 0):
"""
Get the value of ``array`` for the person with the unique role ``role``.
``array`` must have the dimension of the number of persons in the simulation
If such a person does not exist, return ``default`` instead
The result is a vector which dimension is the number of entities
"""
self.entity.check_role_validity(role)
if role.max != 1:
raise Exception(
'You can only use value_from_person with a role that is unique in {}. Role {} is not unique.'
.format(self.key, role.key)
)
self.members.check_array_compatible_with_entity(array)
members_map = self.ordered_members_map
result = self.filled_array(default, dtype = array.dtype)
if isinstance(array, EnumArray):
result = EnumArray(result, array.possible_values)
role_filter = self.members.has_role(role)
entity_filter = self.any(role_filter)
result[entity_filter] = array[members_map][role_filter[members_map]]
return result | python | def value_from_person(self, array, role, default = 0):
"""
Get the value of ``array`` for the person with the unique role ``role``.
``array`` must have the dimension of the number of persons in the simulation
If such a person does not exist, return ``default`` instead
The result is a vector which dimension is the number of entities
"""
self.entity.check_role_validity(role)
if role.max != 1:
raise Exception(
'You can only use value_from_person with a role that is unique in {}. Role {} is not unique.'
.format(self.key, role.key)
)
self.members.check_array_compatible_with_entity(array)
members_map = self.ordered_members_map
result = self.filled_array(default, dtype = array.dtype)
if isinstance(array, EnumArray):
result = EnumArray(result, array.possible_values)
role_filter = self.members.has_role(role)
entity_filter = self.any(role_filter)
result[entity_filter] = array[members_map][role_filter[members_map]]
return result | [
"def",
"value_from_person",
"(",
"self",
",",
"array",
",",
"role",
",",
"default",
"=",
"0",
")",
":",
"self",
".",
"entity",
".",
"check_role_validity",
"(",
"role",
")",
"if",
"role",
".",
"max",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"'You can ... | Get the value of ``array`` for the person with the unique role ``role``.
``array`` must have the dimension of the number of persons in the simulation
If such a person does not exist, return ``default`` instead
The result is a vector which dimension is the number of entities | [
"Get",
"the",
"value",
"of",
"array",
"for",
"the",
"person",
"with",
"the",
"unique",
"role",
"role",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L419-L445 | train | 206,292 |
openfisca/openfisca-core | openfisca_core/populations.py | GroupPopulation.value_nth_person | def value_nth_person(self, n, array, default = 0):
"""
Get the value of array for the person whose position in the entity is n.
Note that this position is arbitrary, and that members are not sorted.
If the nth person does not exist, return ``default`` instead.
The result is a vector which dimension is the number of entities.
"""
self.members.check_array_compatible_with_entity(array)
positions = self.members_position
nb_persons_per_entity = self.nb_persons()
members_map = self.ordered_members_map
result = self.filled_array(default, dtype = array.dtype)
# For households that have at least n persons, set the result as the value of criteria for the person for which the position is n.
# The map is needed b/c the order of the nth persons of each household in the persons vector is not necessarily the same than the household order.
result[nb_persons_per_entity > n] = array[members_map][positions[members_map] == n]
return result | python | def value_nth_person(self, n, array, default = 0):
"""
Get the value of array for the person whose position in the entity is n.
Note that this position is arbitrary, and that members are not sorted.
If the nth person does not exist, return ``default`` instead.
The result is a vector which dimension is the number of entities.
"""
self.members.check_array_compatible_with_entity(array)
positions = self.members_position
nb_persons_per_entity = self.nb_persons()
members_map = self.ordered_members_map
result = self.filled_array(default, dtype = array.dtype)
# For households that have at least n persons, set the result as the value of criteria for the person for which the position is n.
# The map is needed b/c the order of the nth persons of each household in the persons vector is not necessarily the same than the household order.
result[nb_persons_per_entity > n] = array[members_map][positions[members_map] == n]
return result | [
"def",
"value_nth_person",
"(",
"self",
",",
"n",
",",
"array",
",",
"default",
"=",
"0",
")",
":",
"self",
".",
"members",
".",
"check_array_compatible_with_entity",
"(",
"array",
")",
"positions",
"=",
"self",
".",
"members_position",
"nb_persons_per_entity",
... | Get the value of array for the person whose position in the entity is n.
Note that this position is arbitrary, and that members are not sorted.
If the nth person does not exist, return ``default`` instead.
The result is a vector which dimension is the number of entities. | [
"Get",
"the",
"value",
"of",
"array",
"for",
"the",
"person",
"whose",
"position",
"in",
"the",
"entity",
"is",
"n",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L448-L467 | train | 206,293 |
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation.data_storage_dir | def data_storage_dir(self):
"""
Temporary folder used to store intermediate calculation data in case the memory is saturated
"""
if self._data_storage_dir is None:
self._data_storage_dir = tempfile.mkdtemp(prefix = "openfisca_")
log.warn((
"Intermediate results will be stored on disk in {} in case of memory overflow. "
"You should remove this directory once you're done with your simulation."
).format(self._data_storage_dir))
return self._data_storage_dir | python | def data_storage_dir(self):
"""
Temporary folder used to store intermediate calculation data in case the memory is saturated
"""
if self._data_storage_dir is None:
self._data_storage_dir = tempfile.mkdtemp(prefix = "openfisca_")
log.warn((
"Intermediate results will be stored on disk in {} in case of memory overflow. "
"You should remove this directory once you're done with your simulation."
).format(self._data_storage_dir))
return self._data_storage_dir | [
"def",
"data_storage_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_storage_dir",
"is",
"None",
":",
"self",
".",
"_data_storage_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"\"openfisca_\"",
")",
"log",
".",
"warn",
"(",
"(",
"\"Inte... | Temporary folder used to store intermediate calculation data in case the memory is saturated | [
"Temporary",
"folder",
"used",
"to",
"store",
"intermediate",
"calculation",
"data",
"in",
"case",
"the",
"memory",
"is",
"saturated"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L94-L104 | train | 206,294 |
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation.calculate | def calculate(self, variable_name, period, **parameters):
"""
Calculate the variable ``variable_name`` for the period ``period``, using the variable formula if it exists.
:returns: A numpy array containing the result of the calculation
"""
population = self.get_variable_population(variable_name)
holder = population.get_holder(variable_name)
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)
if period is not None and not isinstance(period, periods.Period):
period = periods.period(period)
if self.trace:
self.tracer.record_calculation_start(variable.name, period, **parameters)
self._check_period_consistency(period, variable)
# First look for a value already cached
cached_array = holder.get_array(period)
if cached_array is not None:
if self.trace:
self.tracer.record_calculation_end(variable.name, period, cached_array, **parameters)
return cached_array
array = None
# First, try to run a formula
try:
self._check_for_cycle(variable, period)
array = self._run_formula(variable, population, period)
# If no result, use the default value and cache it
if array is None:
array = holder.default_array()
array = self._cast_formula_result(array, variable)
holder.put_in_cache(array, period)
except SpiralError:
array = holder.default_array()
finally:
if self.trace:
self.tracer.record_calculation_end(variable.name, period, array, **parameters)
self._clean_cycle_detection_data(variable.name)
self.purge_cache_of_invalid_values()
return array | python | def calculate(self, variable_name, period, **parameters):
"""
Calculate the variable ``variable_name`` for the period ``period``, using the variable formula if it exists.
:returns: A numpy array containing the result of the calculation
"""
population = self.get_variable_population(variable_name)
holder = population.get_holder(variable_name)
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)
if period is not None and not isinstance(period, periods.Period):
period = periods.period(period)
if self.trace:
self.tracer.record_calculation_start(variable.name, period, **parameters)
self._check_period_consistency(period, variable)
# First look for a value already cached
cached_array = holder.get_array(period)
if cached_array is not None:
if self.trace:
self.tracer.record_calculation_end(variable.name, period, cached_array, **parameters)
return cached_array
array = None
# First, try to run a formula
try:
self._check_for_cycle(variable, period)
array = self._run_formula(variable, population, period)
# If no result, use the default value and cache it
if array is None:
array = holder.default_array()
array = self._cast_formula_result(array, variable)
holder.put_in_cache(array, period)
except SpiralError:
array = holder.default_array()
finally:
if self.trace:
self.tracer.record_calculation_end(variable.name, period, array, **parameters)
self._clean_cycle_detection_data(variable.name)
self.purge_cache_of_invalid_values()
return array | [
"def",
"calculate",
"(",
"self",
",",
"variable_name",
",",
"period",
",",
"*",
"*",
"parameters",
")",
":",
"population",
"=",
"self",
".",
"get_variable_population",
"(",
"variable_name",
")",
"holder",
"=",
"population",
".",
"get_holder",
"(",
"variable_na... | Calculate the variable ``variable_name`` for the period ``period``, using the variable formula if it exists.
:returns: A numpy array containing the result of the calculation | [
"Calculate",
"the",
"variable",
"variable_name",
"for",
"the",
"period",
"period",
"using",
"the",
"variable",
"formula",
"if",
"it",
"exists",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L108-L156 | train | 206,295 |
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation.calculate_output | def calculate_output(self, variable_name, period):
"""
Calculate the value of a variable using the ``calculate_output`` attribute of the variable.
"""
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)
if variable.calculate_output is None:
return self.calculate(variable_name, period)
return variable.calculate_output(self, variable_name, period) | python | def calculate_output(self, variable_name, period):
"""
Calculate the value of a variable using the ``calculate_output`` attribute of the variable.
"""
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)
if variable.calculate_output is None:
return self.calculate(variable_name, period)
return variable.calculate_output(self, variable_name, period) | [
"def",
"calculate_output",
"(",
"self",
",",
"variable_name",
",",
"period",
")",
":",
"variable",
"=",
"self",
".",
"tax_benefit_system",
".",
"get_variable",
"(",
"variable_name",
",",
"check_existence",
"=",
"True",
")",
"if",
"variable",
".",
"calculate_outp... | Calculate the value of a variable using the ``calculate_output`` attribute of the variable. | [
"Calculate",
"the",
"value",
"of",
"a",
"variable",
"using",
"the",
"calculate_output",
"attribute",
"of",
"the",
"variable",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L215-L225 | train | 206,296 |
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation._run_formula | def _run_formula(self, variable, population, period):
"""
Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``.
"""
formula = variable.get_formula(period)
if formula is None:
return None
if self.trace:
parameters_at = self.trace_parameters_at_instant
else:
parameters_at = self.tax_benefit_system.get_parameters_at_instant
if formula.__code__.co_argcount == 2:
array = formula(population, period)
else:
array = formula(population, period, parameters_at)
self._check_formula_result(array, variable, population, period)
return array | python | def _run_formula(self, variable, population, period):
"""
Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``.
"""
formula = variable.get_formula(period)
if formula is None:
return None
if self.trace:
parameters_at = self.trace_parameters_at_instant
else:
parameters_at = self.tax_benefit_system.get_parameters_at_instant
if formula.__code__.co_argcount == 2:
array = formula(population, period)
else:
array = formula(population, period, parameters_at)
self._check_formula_result(array, variable, population, period)
return array | [
"def",
"_run_formula",
"(",
"self",
",",
"variable",
",",
"population",
",",
"period",
")",
":",
"formula",
"=",
"variable",
".",
"get_formula",
"(",
"period",
")",
"if",
"formula",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"trace",
":",
... | Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``. | [
"Find",
"the",
"variable",
"formula",
"for",
"the",
"given",
"period",
"if",
"it",
"exists",
"and",
"apply",
"it",
"to",
"population",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L233-L253 | train | 206,297 |
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation._check_period_consistency | def _check_period_consistency(self, period, variable):
"""
Check that a period matches the variable definition_period
"""
if variable.definition_period == periods.ETERNITY:
return # For variables which values are constant in time, all periods are accepted
if variable.definition_period == periods.MONTH and period.unit != periods.MONTH:
raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole month. You can use the ADD option to sum '{0}' over the requested period, or change the requested period to 'period.first_month'.".format(
variable.name,
period
))
if variable.definition_period == periods.YEAR and period.unit != periods.YEAR:
raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole year. You can use the DIVIDE option to get an estimate of {0} by dividing the yearly value by 12, or change the requested period to 'period.this_year'.".format(
variable.name,
period
))
if period.size != 1:
raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole {2}. You can use the ADD option to sum '{0}' over the requested period.".format(
variable.name,
period,
'month' if variable.definition_period == periods.MONTH else 'year'
)) | python | def _check_period_consistency(self, period, variable):
"""
Check that a period matches the variable definition_period
"""
if variable.definition_period == periods.ETERNITY:
return # For variables which values are constant in time, all periods are accepted
if variable.definition_period == periods.MONTH and period.unit != periods.MONTH:
raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole month. You can use the ADD option to sum '{0}' over the requested period, or change the requested period to 'period.first_month'.".format(
variable.name,
period
))
if variable.definition_period == periods.YEAR and period.unit != periods.YEAR:
raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole year. You can use the DIVIDE option to get an estimate of {0} by dividing the yearly value by 12, or change the requested period to 'period.this_year'.".format(
variable.name,
period
))
if period.size != 1:
raise ValueError("Unable to compute variable '{0}' for period {1}: '{0}' must be computed for a whole {2}. You can use the ADD option to sum '{0}' over the requested period.".format(
variable.name,
period,
'month' if variable.definition_period == periods.MONTH else 'year'
)) | [
"def",
"_check_period_consistency",
"(",
"self",
",",
"period",
",",
"variable",
")",
":",
"if",
"variable",
".",
"definition_period",
"==",
"periods",
".",
"ETERNITY",
":",
"return",
"# For variables which values are constant in time, all periods are accepted",
"if",
"va... | Check that a period matches the variable definition_period | [
"Check",
"that",
"a",
"period",
"matches",
"the",
"variable",
"definition_period"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L255-L279 | train | 206,298 |
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation.get_memory_usage | def get_memory_usage(self, variables = None):
"""
Get data about the virtual memory usage of the simulation
"""
result = dict(
total_nb_bytes = 0,
by_variable = {}
)
for entity in self.populations.values():
entity_memory_usage = entity.get_memory_usage(variables = variables)
result['total_nb_bytes'] += entity_memory_usage['total_nb_bytes']
result['by_variable'].update(entity_memory_usage['by_variable'])
return result | python | def get_memory_usage(self, variables = None):
"""
Get data about the virtual memory usage of the simulation
"""
result = dict(
total_nb_bytes = 0,
by_variable = {}
)
for entity in self.populations.values():
entity_memory_usage = entity.get_memory_usage(variables = variables)
result['total_nb_bytes'] += entity_memory_usage['total_nb_bytes']
result['by_variable'].update(entity_memory_usage['by_variable'])
return result | [
"def",
"get_memory_usage",
"(",
"self",
",",
"variables",
"=",
"None",
")",
":",
"result",
"=",
"dict",
"(",
"total_nb_bytes",
"=",
"0",
",",
"by_variable",
"=",
"{",
"}",
")",
"for",
"entity",
"in",
"self",
".",
"populations",
".",
"values",
"(",
")",... | Get data about the virtual memory usage of the simulation | [
"Get",
"data",
"about",
"the",
"virtual",
"memory",
"usage",
"of",
"the",
"simulation"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L373-L385 | train | 206,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.