repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
aerogear/digger-build-cli | digger/parser.py | register_action | def register_action(action):
"""
Adds an action to the parser cli.
:param action(BaseAction): a subclass of the BaseAction class
"""
sub = _subparsers.add_parser(action.meta('cmd'), help=action.meta('help'))
sub.set_defaults(cmd=action.meta('cmd'))
for (name, arg) in action.props().items():
sub.add_argument(arg.name, arg.flag, **arg.options)
_actions[action.meta('cmd')] = action | python | def register_action(action):
"""
Adds an action to the parser cli.
:param action(BaseAction): a subclass of the BaseAction class
"""
sub = _subparsers.add_parser(action.meta('cmd'), help=action.meta('help'))
sub.set_defaults(cmd=action.meta('cmd'))
for (name, arg) in action.props().items():
sub.add_argument(arg.name, arg.flag, **arg.options)
_actions[action.meta('cmd')] = action | [
"def",
"register_action",
"(",
"action",
")",
":",
"sub",
"=",
"_subparsers",
".",
"add_parser",
"(",
"action",
".",
"meta",
"(",
"'cmd'",
")",
",",
"help",
"=",
"action",
".",
"meta",
"(",
"'help'",
")",
")",
"sub",
".",
"set_defaults",
"(",
"cmd",
... | Adds an action to the parser cli.
:param action(BaseAction): a subclass of the BaseAction class | [
"Adds",
"an",
"action",
"to",
"the",
"parser",
"cli",
"."
] | train | https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/parser.py#L12-L22 |
aerogear/digger-build-cli | digger/parser.py | run | def run(*args, **kwargs):
"""
Runs the parser and it executes the action handler with the provided arguments from the CLI.
Also catches the BaseError interrupting the execution and showing the error message to the user.
Default arguments comes from the cli args (sys.argv array) but we can force those arguments when writing tests:
.. code-block:: python
parser.run(['build', '--path', '/custom-app-path'].split())
.. code-block:: python
parser.run('build --path /custom-app-path')
"""
cmd = _parser.parse_args(*args, **kwargs)
if hasattr(cmd, 'cmd') is False:
return _parser.print_help()
Action = _actions.get(cmd.cmd)
action = Action()
try:
action(**{k:getattr(cmd, k) for k in action.props().keys()})
except errors.BaseError as e:
e.print_error() | python | def run(*args, **kwargs):
"""
Runs the parser and it executes the action handler with the provided arguments from the CLI.
Also catches the BaseError interrupting the execution and showing the error message to the user.
Default arguments comes from the cli args (sys.argv array) but we can force those arguments when writing tests:
.. code-block:: python
parser.run(['build', '--path', '/custom-app-path'].split())
.. code-block:: python
parser.run('build --path /custom-app-path')
"""
cmd = _parser.parse_args(*args, **kwargs)
if hasattr(cmd, 'cmd') is False:
return _parser.print_help()
Action = _actions.get(cmd.cmd)
action = Action()
try:
action(**{k:getattr(cmd, k) for k in action.props().keys()})
except errors.BaseError as e:
e.print_error() | [
"def",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"_parser",
".",
"parse_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"hasattr",
"(",
"cmd",
",",
"'cmd'",
")",
"is",
"False",
":",
"return",
"_parser",
... | Runs the parser and it executes the action handler with the provided arguments from the CLI.
Also catches the BaseError interrupting the execution and showing the error message to the user.
Default arguments comes from the cli args (sys.argv array) but we can force those arguments when writing tests:
.. code-block:: python
parser.run(['build', '--path', '/custom-app-path'].split())
.. code-block:: python
parser.run('build --path /custom-app-path') | [
"Runs",
"the",
"parser",
"and",
"it",
"executes",
"the",
"action",
"handler",
"with",
"the",
"provided",
"arguments",
"from",
"the",
"CLI",
"."
] | train | https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/parser.py#L34-L58 |
ActionAgile/trellostats | trellostats/cli.py | cli | def cli(ctx):
""" This is a command line app to get useful stats from a trello board
and report on them in useful ways.
Requires the following environment varilables:
TRELLOSTATS_APP_KEY=<your key here>
TRELLOSTATS_APP_TOKEN=<your token here>
"""
ctx.obj = dict()
ctx.obj['app_key'] = os.environ.get('TRELLOSTATS_APP_KEY')
ctx.obj['app_token'] = os.environ.get('TRELLOSTATS_APP_TOKEN')
init_db(db_proxy) | python | def cli(ctx):
""" This is a command line app to get useful stats from a trello board
and report on them in useful ways.
Requires the following environment varilables:
TRELLOSTATS_APP_KEY=<your key here>
TRELLOSTATS_APP_TOKEN=<your token here>
"""
ctx.obj = dict()
ctx.obj['app_key'] = os.environ.get('TRELLOSTATS_APP_KEY')
ctx.obj['app_token'] = os.environ.get('TRELLOSTATS_APP_TOKEN')
init_db(db_proxy) | [
"def",
"cli",
"(",
"ctx",
")",
":",
"ctx",
".",
"obj",
"=",
"dict",
"(",
")",
"ctx",
".",
"obj",
"[",
"'app_key'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TRELLOSTATS_APP_KEY'",
")",
"ctx",
".",
"obj",
"[",
"'app_token'",
"]",
"=",
"os... | This is a command line app to get useful stats from a trello board
and report on them in useful ways.
Requires the following environment varilables:
TRELLOSTATS_APP_KEY=<your key here>
TRELLOSTATS_APP_TOKEN=<your token here> | [
"This",
"is",
"a",
"command",
"line",
"app",
"to",
"get",
"useful",
"stats",
"from",
"a",
"trello",
"board",
"and",
"report",
"on",
"them",
"in",
"useful",
"ways",
"."
] | train | https://github.com/ActionAgile/trellostats/blob/695039ba9a787d0fdb71ec90cee52193ca98e489/trellostats/cli.py#L16-L28 |
ActionAgile/trellostats | trellostats/cli.py | snapshot | def snapshot(ctx, board, done):
"""
Recording mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done
"""
ctx.obj['board_id'] = board
ts = TrelloStats(ctx.obj)
Snapshot.create_table(fail_silently=True)
done_id = ts.get_list_id_from_name(done)
ct = cycle_time(ts, board, done)
env = get_env()
print render_text(env, **dict(cycle_time=ct))
# Create snapshot
print Snapshot.create(board_id=board, done_id=done_id, cycle_time=ct) | python | def snapshot(ctx, board, done):
"""
Recording mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done
"""
ctx.obj['board_id'] = board
ts = TrelloStats(ctx.obj)
Snapshot.create_table(fail_silently=True)
done_id = ts.get_list_id_from_name(done)
ct = cycle_time(ts, board, done)
env = get_env()
print render_text(env, **dict(cycle_time=ct))
# Create snapshot
print Snapshot.create(board_id=board, done_id=done_id, cycle_time=ct) | [
"def",
"snapshot",
"(",
"ctx",
",",
"board",
",",
"done",
")",
":",
"ctx",
".",
"obj",
"[",
"'board_id'",
"]",
"=",
"board",
"ts",
"=",
"TrelloStats",
"(",
"ctx",
".",
"obj",
")",
"Snapshot",
".",
"create_table",
"(",
"fail_silently",
"=",
"True",
")... | Recording mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done | [
"Recording",
"mode",
"-",
"Daily",
"snapshots",
"of",
"a",
"board",
"for",
"ongoing",
"reporting",
":",
"-",
">",
"trellis",
"report",
"--",
"board",
"=",
"87hiudhw",
"--",
"spend",
"--",
"revenue",
"--",
"done",
"=",
"Done"
] | train | https://github.com/ActionAgile/trellostats/blob/695039ba9a787d0fdb71ec90cee52193ca98e489/trellostats/cli.py#L52-L70 |
ActionAgile/trellostats | trellostats/cli.py | report | def report(ctx, board, done, output):
ctx.obj['board_id'] = board
ts = TrelloStats(ctx.obj)
"""
Reporting mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done
"""
ct = cycle_time(ts, board, done)
env = get_env()
# Get all render functions from the module and filter out the ones we don't want.
render_functions = [target for target in
dir(sys.modules['trellostats.reports'])
if target.startswith("render_") and
target.endswith(output)]
for render_func in render_functions:
print globals()[render_func](env, **dict(cycle_time=ct)) | python | def report(ctx, board, done, output):
ctx.obj['board_id'] = board
ts = TrelloStats(ctx.obj)
"""
Reporting mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done
"""
ct = cycle_time(ts, board, done)
env = get_env()
# Get all render functions from the module and filter out the ones we don't want.
render_functions = [target for target in
dir(sys.modules['trellostats.reports'])
if target.startswith("render_") and
target.endswith(output)]
for render_func in render_functions:
print globals()[render_func](env, **dict(cycle_time=ct)) | [
"def",
"report",
"(",
"ctx",
",",
"board",
",",
"done",
",",
"output",
")",
":",
"ctx",
".",
"obj",
"[",
"'board_id'",
"]",
"=",
"board",
"ts",
"=",
"TrelloStats",
"(",
"ctx",
".",
"obj",
")",
"ct",
"=",
"cycle_time",
"(",
"ts",
",",
"board",
","... | Reporting mode - Daily snapshots of a board for ongoing reporting:
-> trellis report --board=87hiudhw
--spend
--revenue
--done=Done | [
"Reporting",
"mode",
"-",
"Daily",
"snapshots",
"of",
"a",
"board",
"for",
"ongoing",
"reporting",
":",
"-",
">",
"trellis",
"report",
"--",
"board",
"=",
"87hiudhw",
"--",
"spend",
"--",
"revenue",
"--",
"done",
"=",
"Done"
] | train | https://github.com/ActionAgile/trellostats/blob/695039ba9a787d0fdb71ec90cee52193ca98e489/trellostats/cli.py#L79-L100 |
pyschool/story | story/translation.py | translation | def translation(language):
"""
Return a translation object in the default 'django' domain.
"""
global _translations
if language not in _translations:
_translations[language] = Translations(language)
return _translations[language] | python | def translation(language):
"""
Return a translation object in the default 'django' domain.
"""
global _translations
if language not in _translations:
_translations[language] = Translations(language)
return _translations[language] | [
"def",
"translation",
"(",
"language",
")",
":",
"global",
"_translations",
"if",
"language",
"not",
"in",
"_translations",
":",
"_translations",
"[",
"language",
"]",
"=",
"Translations",
"(",
"language",
")",
"return",
"_translations",
"[",
"language",
"]"
] | Return a translation object in the default 'django' domain. | [
"Return",
"a",
"translation",
"object",
"in",
"the",
"default",
"django",
"domain",
"."
] | train | https://github.com/pyschool/story/blob/c23daf4a187b0df4cbae88ef06b36c396f1ffd57/story/translation.py#L84-L91 |
pyschool/story | story/translation.py | gettext | def gettext(message):
"""
Translate the 'message' string. It uses the current thread to find the
translation object to use. If no current translation is activated, the
message will be run through the default translation object.
"""
global _default
_default = _default or translation(DEFAULT_LANGUAGE)
translation_object = getattr(_active, 'value', _default)
result = translation_object.gettext(message)
return result | python | def gettext(message):
"""
Translate the 'message' string. It uses the current thread to find the
translation object to use. If no current translation is activated, the
message will be run through the default translation object.
"""
global _default
_default = _default or translation(DEFAULT_LANGUAGE)
translation_object = getattr(_active, 'value', _default)
result = translation_object.gettext(message)
return result | [
"def",
"gettext",
"(",
"message",
")",
":",
"global",
"_default",
"_default",
"=",
"_default",
"or",
"translation",
"(",
"DEFAULT_LANGUAGE",
")",
"translation_object",
"=",
"getattr",
"(",
"_active",
",",
"'value'",
",",
"_default",
")",
"result",
"=",
"transl... | Translate the 'message' string. It uses the current thread to find the
translation object to use. If no current translation is activated, the
message will be run through the default translation object. | [
"Translate",
"the",
"message",
"string",
".",
"It",
"uses",
"the",
"current",
"thread",
"to",
"find",
"the",
"translation",
"object",
"to",
"use",
".",
"If",
"no",
"current",
"translation",
"is",
"activated",
"the",
"message",
"will",
"be",
"run",
"through",... | train | https://github.com/pyschool/story/blob/c23daf4a187b0df4cbae88ef06b36c396f1ffd57/story/translation.py#L134-L144 |
pyschool/story | story/translation.py | Translations._new_gnu_trans | def _new_gnu_trans(self, localedir, use_null_fallback=True):
"""
Return a mergeable gettext.GNUTranslations instance.
A convenience wrapper. By default gettext uses 'fallback=False'.
Using param `use_null_fallback` to avoid confusion with any other
references to 'fallback'.
"""
use_null_fallback = False
return gettext_module.translation(
domain=self.domain,
localedir=localedir,
languages=[self.language],
codeset='utf-8',
fallback=use_null_fallback) | python | def _new_gnu_trans(self, localedir, use_null_fallback=True):
"""
Return a mergeable gettext.GNUTranslations instance.
A convenience wrapper. By default gettext uses 'fallback=False'.
Using param `use_null_fallback` to avoid confusion with any other
references to 'fallback'.
"""
use_null_fallback = False
return gettext_module.translation(
domain=self.domain,
localedir=localedir,
languages=[self.language],
codeset='utf-8',
fallback=use_null_fallback) | [
"def",
"_new_gnu_trans",
"(",
"self",
",",
"localedir",
",",
"use_null_fallback",
"=",
"True",
")",
":",
"use_null_fallback",
"=",
"False",
"return",
"gettext_module",
".",
"translation",
"(",
"domain",
"=",
"self",
".",
"domain",
",",
"localedir",
"=",
"local... | Return a mergeable gettext.GNUTranslations instance.
A convenience wrapper. By default gettext uses 'fallback=False'.
Using param `use_null_fallback` to avoid confusion with any other
references to 'fallback'. | [
"Return",
"a",
"mergeable",
"gettext",
".",
"GNUTranslations",
"instance",
"."
] | train | https://github.com/pyschool/story/blob/c23daf4a187b0df4cbae88ef06b36c396f1ffd57/story/translation.py#L44-L58 |
pyschool/story | story/translation.py | Translations.add_localedir_translations | def add_localedir_translations(self, localedir):
"""Merge translations from localedir."""
global _localedirs
if localedir in self.localedirs:
return
self.localedirs.append(localedir)
full_localedir = os.path.join(localedir, 'locale')
if os.path.exists(full_localedir):
translation = self._new_gnu_trans(full_localedir)
self.merge(translation) | python | def add_localedir_translations(self, localedir):
"""Merge translations from localedir."""
global _localedirs
if localedir in self.localedirs:
return
self.localedirs.append(localedir)
full_localedir = os.path.join(localedir, 'locale')
if os.path.exists(full_localedir):
translation = self._new_gnu_trans(full_localedir)
self.merge(translation) | [
"def",
"add_localedir_translations",
"(",
"self",
",",
"localedir",
")",
":",
"global",
"_localedirs",
"if",
"localedir",
"in",
"self",
".",
"localedirs",
":",
"return",
"self",
".",
"localedirs",
".",
"append",
"(",
"localedir",
")",
"full_localedir",
"=",
"o... | Merge translations from localedir. | [
"Merge",
"translations",
"from",
"localedir",
"."
] | train | https://github.com/pyschool/story/blob/c23daf4a187b0df4cbae88ef06b36c396f1ffd57/story/translation.py#L60-L69 |
pyschool/story | story/translation.py | Translations.merge | def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found
self.plural = other.plural
self._info = other._info.copy()
self._catalog = other._catalog.copy()
else:
self._catalog.update(other._catalog) | python | def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found
self.plural = other.plural
self._info = other._info.copy()
self._catalog = other._catalog.copy()
else:
self._catalog.update(other._catalog) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"getattr",
"(",
"other",
",",
"'_catalog'",
",",
"None",
")",
":",
"return",
"# NullTranslations() has no _catalog",
"if",
"self",
".",
"_catalog",
"is",
"None",
":",
"# Take plural and _info fr... | Merge another translation into this catalog. | [
"Merge",
"another",
"translation",
"into",
"this",
"catalog",
"."
] | train | https://github.com/pyschool/story/blob/c23daf4a187b0df4cbae88ef06b36c396f1ffd57/story/translation.py#L71-L81 |
gr33ndata/dysl | dysl/utils.py | decode_input | def decode_input(text_in):
""" Decodes `text_in`
If text_in is is a string,
then decode it as utf-8 string.
If text_in is is a list of strings,
then decode each string of it,
then combine them into one outpust string.
"""
if type(text_in) == list:
text_out = u' '.join([t.decode('utf-8') for t in text_in])
else:
text_out = text_in.decode('utf-8')
return text_out | python | def decode_input(text_in):
""" Decodes `text_in`
If text_in is is a string,
then decode it as utf-8 string.
If text_in is is a list of strings,
then decode each string of it,
then combine them into one outpust string.
"""
if type(text_in) == list:
text_out = u' '.join([t.decode('utf-8') for t in text_in])
else:
text_out = text_in.decode('utf-8')
return text_out | [
"def",
"decode_input",
"(",
"text_in",
")",
":",
"if",
"type",
"(",
"text_in",
")",
"==",
"list",
":",
"text_out",
"=",
"u' '",
".",
"join",
"(",
"[",
"t",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"t",
"in",
"text_in",
"]",
")",
"else",
":",
"t... | Decodes `text_in`
If text_in is is a string,
then decode it as utf-8 string.
If text_in is is a list of strings,
then decode each string of it,
then combine them into one outpust string. | [
"Decodes",
"text_in",
"If",
"text_in",
"is",
"is",
"a",
"string",
"then",
"decode",
"it",
"as",
"utf",
"-",
"8",
"string",
".",
"If",
"text_in",
"is",
"is",
"a",
"list",
"of",
"strings",
"then",
"decode",
"each",
"string",
"of",
"it",
"then",
"combine"... | train | https://github.com/gr33ndata/dysl/blob/649c1d6a1761f47d49a9842e7389f6df52039155/dysl/utils.py#L1-L14 |
arrrlo/DB-Transfer | db_transfer/adapter_file.py | File._set_local_file_path | def _set_local_file_path(self):
"""
Take from environment variable, create dirs and
create file if doesn' exist.
"""
self.FILE_LOCAL = self._transfer.get_env('FILE_LOCAL')
if not self.FILE_LOCAL:
filename = '{}_{}.{}'.format(str(self._transfer.prefix),
str(self._transfer.namespace),
str(self.file_extension))
self.FILE_LOCAL = os.path.join(os.path.expanduser("~"), filename)
dirs = os.path.dirname(self.FILE_LOCAL)
if not os.path.exists(dirs):
os.makedirs(dirs)
try:
open(self.FILE_LOCAL, "rb+").close()
except:
open(self.FILE_LOCAL, "a").close() | python | def _set_local_file_path(self):
"""
Take from environment variable, create dirs and
create file if doesn' exist.
"""
self.FILE_LOCAL = self._transfer.get_env('FILE_LOCAL')
if not self.FILE_LOCAL:
filename = '{}_{}.{}'.format(str(self._transfer.prefix),
str(self._transfer.namespace),
str(self.file_extension))
self.FILE_LOCAL = os.path.join(os.path.expanduser("~"), filename)
dirs = os.path.dirname(self.FILE_LOCAL)
if not os.path.exists(dirs):
os.makedirs(dirs)
try:
open(self.FILE_LOCAL, "rb+").close()
except:
open(self.FILE_LOCAL, "a").close() | [
"def",
"_set_local_file_path",
"(",
"self",
")",
":",
"self",
".",
"FILE_LOCAL",
"=",
"self",
".",
"_transfer",
".",
"get_env",
"(",
"'FILE_LOCAL'",
")",
"if",
"not",
"self",
".",
"FILE_LOCAL",
":",
"filename",
"=",
"'{}_{}.{}'",
".",
"format",
"(",
"str",... | Take from environment variable, create dirs and
create file if doesn' exist. | [
"Take",
"from",
"environment",
"variable",
"create",
"dirs",
"and",
"create",
"file",
"if",
"doesn",
"exist",
"."
] | train | https://github.com/arrrlo/DB-Transfer/blob/a23103404e99bc9a82b9cf3c5a17b4ee0671b421/db_transfer/adapter_file.py#L14-L35 |
marteinn/AtomicPress | atomicpress/themes/minimal/helpers.py | gen_post_status | def gen_post_status():
"""
Show only published posts outside debug.
"""
if not app.config["DEBUG"]:
post_status = and_(Post.status == PostStatus.PUBLISH)
else:
post_status = or_(Post.status == PostStatus.PUBLISH,
Post.status == PostStatus.DRAFT)
return post_status | python | def gen_post_status():
"""
Show only published posts outside debug.
"""
if not app.config["DEBUG"]:
post_status = and_(Post.status == PostStatus.PUBLISH)
else:
post_status = or_(Post.status == PostStatus.PUBLISH,
Post.status == PostStatus.DRAFT)
return post_status | [
"def",
"gen_post_status",
"(",
")",
":",
"if",
"not",
"app",
".",
"config",
"[",
"\"DEBUG\"",
"]",
":",
"post_status",
"=",
"and_",
"(",
"Post",
".",
"status",
"==",
"PostStatus",
".",
"PUBLISH",
")",
"else",
":",
"post_status",
"=",
"or_",
"(",
"Post"... | Show only published posts outside debug. | [
"Show",
"only",
"published",
"posts",
"outside",
"debug",
"."
] | train | https://github.com/marteinn/AtomicPress/blob/b8a0ca9c9c327f062833fc4a401a8ac0baccf6d1/atomicpress/themes/minimal/helpers.py#L7-L17 |
cohorte/cohorte-herald | python/herald/remote/herald_jsonrpc.py | JsonRpcDispatcher._simple_dispatch | def _simple_dispatch(self, name, params):
"""
Dispatch method
"""
try:
# Internal method
func = self.funcs[name]
except KeyError:
# Other method
pass
else:
# Internal method found
if isinstance(params, (list, tuple)):
return func(*params)
else:
return func(**params)
# Call the other method outside the except block, to avoid messy logs
# in case of error
return self._dispatch_method(name, params) | python | def _simple_dispatch(self, name, params):
"""
Dispatch method
"""
try:
# Internal method
func = self.funcs[name]
except KeyError:
# Other method
pass
else:
# Internal method found
if isinstance(params, (list, tuple)):
return func(*params)
else:
return func(**params)
# Call the other method outside the except block, to avoid messy logs
# in case of error
return self._dispatch_method(name, params) | [
"def",
"_simple_dispatch",
"(",
"self",
",",
"name",
",",
"params",
")",
":",
"try",
":",
"# Internal method",
"func",
"=",
"self",
".",
"funcs",
"[",
"name",
"]",
"except",
"KeyError",
":",
"# Other method",
"pass",
"else",
":",
"# Internal method found",
"... | Dispatch method | [
"Dispatch",
"method"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/remote/herald_jsonrpc.py#L95-L114 |
fangpenlin/design-patterns | design_patterns/observer.py | Subject.subscribe | def subscribe(self, observer):
"""Subscribe an observer to this subject and return a subscription id
"""
sid = self._sn
self.observers[sid] = observer
self._sn += 1
return SubscribeID(self, sid) | python | def subscribe(self, observer):
"""Subscribe an observer to this subject and return a subscription id
"""
sid = self._sn
self.observers[sid] = observer
self._sn += 1
return SubscribeID(self, sid) | [
"def",
"subscribe",
"(",
"self",
",",
"observer",
")",
":",
"sid",
"=",
"self",
".",
"_sn",
"self",
".",
"observers",
"[",
"sid",
"]",
"=",
"observer",
"self",
".",
"_sn",
"+=",
"1",
"return",
"SubscribeID",
"(",
"self",
",",
"sid",
")"
] | Subscribe an observer to this subject and return a subscription id | [
"Subscribe",
"an",
"observer",
"to",
"this",
"subject",
"and",
"return",
"a",
"subscription",
"id"
] | train | https://github.com/fangpenlin/design-patterns/blob/5eaae370ac367e8a9bc5aff68e2325e6d510dbb1/design_patterns/observer.py#L25-L32 |
fangpenlin/design-patterns | design_patterns/observer.py | Subject.unsubscribe | def unsubscribe(self, sid):
"""Disconnect an observer from this subject
"""
if sid not in self.observers:
raise KeyError(
'Cannot disconnect a observer does not connected to subject'
)
del self.observers[sid] | python | def unsubscribe(self, sid):
"""Disconnect an observer from this subject
"""
if sid not in self.observers:
raise KeyError(
'Cannot disconnect a observer does not connected to subject'
)
del self.observers[sid] | [
"def",
"unsubscribe",
"(",
"self",
",",
"sid",
")",
":",
"if",
"sid",
"not",
"in",
"self",
".",
"observers",
":",
"raise",
"KeyError",
"(",
"'Cannot disconnect a observer does not connected to subject'",
")",
"del",
"self",
".",
"observers",
"[",
"sid",
"]"
] | Disconnect an observer from this subject | [
"Disconnect",
"an",
"observer",
"from",
"this",
"subject"
] | train | https://github.com/fangpenlin/design-patterns/blob/5eaae370ac367e8a9bc5aff68e2325e6d510dbb1/design_patterns/observer.py#L34-L42 |
concordusapps/alchemist | alchemist/utils.py | make_module_class | def make_module_class(name):
"""Takes the module referenced by name and make it a full class.
"""
source = sys.modules[name]
members = vars(source)
is_descriptor = lambda x: not isinstance(x, type) and hasattr(x, '__get__')
descriptors = {k: v for (k, v) in members.items() if is_descriptor(v)}
members = {k: v for (k, v) in members.items() if k not in descriptors}
descriptors['__source'] = source
target = type(name, (types.ModuleType,), descriptors)(name)
target.__dict__.update(members)
sys.modules[name] = target | python | def make_module_class(name):
"""Takes the module referenced by name and make it a full class.
"""
source = sys.modules[name]
members = vars(source)
is_descriptor = lambda x: not isinstance(x, type) and hasattr(x, '__get__')
descriptors = {k: v for (k, v) in members.items() if is_descriptor(v)}
members = {k: v for (k, v) in members.items() if k not in descriptors}
descriptors['__source'] = source
target = type(name, (types.ModuleType,), descriptors)(name)
target.__dict__.update(members)
sys.modules[name] = target | [
"def",
"make_module_class",
"(",
"name",
")",
":",
"source",
"=",
"sys",
".",
"modules",
"[",
"name",
"]",
"members",
"=",
"vars",
"(",
"source",
")",
"is_descriptor",
"=",
"lambda",
"x",
":",
"not",
"isinstance",
"(",
"x",
",",
"type",
")",
"and",
"... | Takes the module referenced by name and make it a full class. | [
"Takes",
"the",
"module",
"referenced",
"by",
"name",
"and",
"make",
"it",
"a",
"full",
"class",
"."
] | train | https://github.com/concordusapps/alchemist/blob/822571366271b5dca0ac8bf41df988c6a3b61432/alchemist/utils.py#L12-L27 |
hobson/pug-ann | pug/ann/util.py | build_ann | def build_ann(N_input=None, N_hidden=2, N_output=1, hidden_layer_type='Linear', verbosity=1):
"""Build a neural net with the indicated input, hidden, and outout dimensions
Arguments:
params (dict or PyBrainParams namedtuple):
default: {'N_hidden': 6}
(this is the only parameter that affects the NN build)
Returns:
FeedForwardNetwork with N_input + N_hidden + N_output nodes in 3 layers
"""
N_input = N_input or 1
N_output = N_output or 1
N_hidden = N_hidden or tuple()
if isinstance(N_hidden, (int, float, basestring)):
N_hidden = (int(N_hidden),)
hidden_layer_type = hidden_layer_type or tuple()
hidden_layer_type = tuplify(normalize_layer_type(hidden_layer_type))
if verbosity > 0:
print(N_hidden, ' layers of type ', hidden_layer_type)
assert(len(N_hidden) == len(hidden_layer_type))
nn = pb.structure.FeedForwardNetwork()
# layers
nn.addInputModule(pb.structure.BiasUnit(name='bias'))
nn.addInputModule(pb.structure.LinearLayer(N_input, name='input'))
for i, (Nhid, hidlaytype) in enumerate(zip(N_hidden, hidden_layer_type)):
Nhid = int(Nhid)
nn.addModule(hidlaytype(Nhid, name=('hidden-{}'.format(i) if i else 'hidden')))
nn.addOutputModule(pb.structure.LinearLayer(N_output, name='output'))
# connections
nn.addConnection(pb.structure.FullConnection(nn['bias'], nn['hidden'] if N_hidden else nn['output']))
nn.addConnection(pb.structure.FullConnection(nn['input'], nn['hidden'] if N_hidden else nn['output']))
for i, (Nhid, hidlaytype) in enumerate(zip(N_hidden[:-1], hidden_layer_type[:-1])):
Nhid = int(Nhid)
nn.addConnection(pb.structure.FullConnection(nn[('hidden-{}'.format(i) if i else 'hidden')],
nn['hidden-{}'.format(i + 1)]))
i = len(N_hidden) - 1
nn.addConnection(pb.structure.FullConnection(nn['hidden-{}'.format(i) if i else 'hidden'], nn['output']))
nn.sortModules()
if FAST:
try:
nn.convertToFastNetwork()
except:
if verbosity > 0:
print('Unable to convert slow PyBrain NN to a fast ARAC network...')
if verbosity > 0:
print(nn.connections)
return nn | python | def build_ann(N_input=None, N_hidden=2, N_output=1, hidden_layer_type='Linear', verbosity=1):
"""Build a neural net with the indicated input, hidden, and outout dimensions
Arguments:
params (dict or PyBrainParams namedtuple):
default: {'N_hidden': 6}
(this is the only parameter that affects the NN build)
Returns:
FeedForwardNetwork with N_input + N_hidden + N_output nodes in 3 layers
"""
N_input = N_input or 1
N_output = N_output or 1
N_hidden = N_hidden or tuple()
if isinstance(N_hidden, (int, float, basestring)):
N_hidden = (int(N_hidden),)
hidden_layer_type = hidden_layer_type or tuple()
hidden_layer_type = tuplify(normalize_layer_type(hidden_layer_type))
if verbosity > 0:
print(N_hidden, ' layers of type ', hidden_layer_type)
assert(len(N_hidden) == len(hidden_layer_type))
nn = pb.structure.FeedForwardNetwork()
# layers
nn.addInputModule(pb.structure.BiasUnit(name='bias'))
nn.addInputModule(pb.structure.LinearLayer(N_input, name='input'))
for i, (Nhid, hidlaytype) in enumerate(zip(N_hidden, hidden_layer_type)):
Nhid = int(Nhid)
nn.addModule(hidlaytype(Nhid, name=('hidden-{}'.format(i) if i else 'hidden')))
nn.addOutputModule(pb.structure.LinearLayer(N_output, name='output'))
# connections
nn.addConnection(pb.structure.FullConnection(nn['bias'], nn['hidden'] if N_hidden else nn['output']))
nn.addConnection(pb.structure.FullConnection(nn['input'], nn['hidden'] if N_hidden else nn['output']))
for i, (Nhid, hidlaytype) in enumerate(zip(N_hidden[:-1], hidden_layer_type[:-1])):
Nhid = int(Nhid)
nn.addConnection(pb.structure.FullConnection(nn[('hidden-{}'.format(i) if i else 'hidden')],
nn['hidden-{}'.format(i + 1)]))
i = len(N_hidden) - 1
nn.addConnection(pb.structure.FullConnection(nn['hidden-{}'.format(i) if i else 'hidden'], nn['output']))
nn.sortModules()
if FAST:
try:
nn.convertToFastNetwork()
except:
if verbosity > 0:
print('Unable to convert slow PyBrain NN to a fast ARAC network...')
if verbosity > 0:
print(nn.connections)
return nn | [
"def",
"build_ann",
"(",
"N_input",
"=",
"None",
",",
"N_hidden",
"=",
"2",
",",
"N_output",
"=",
"1",
",",
"hidden_layer_type",
"=",
"'Linear'",
",",
"verbosity",
"=",
"1",
")",
":",
"N_input",
"=",
"N_input",
"or",
"1",
"N_output",
"=",
"N_output",
"... | Build a neural net with the indicated input, hidden, and outout dimensions
Arguments:
params (dict or PyBrainParams namedtuple):
default: {'N_hidden': 6}
(this is the only parameter that affects the NN build)
Returns:
FeedForwardNetwork with N_input + N_hidden + N_output nodes in 3 layers | [
"Build",
"a",
"neural",
"net",
"with",
"the",
"indicated",
"input",
"hidden",
"and",
"outout",
"dimensions"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L62-L115 |
hobson/pug-ann | pug/ann/util.py | prepend_dataset_with_weather | def prepend_dataset_with_weather(samples, location='Fresno, CA', weather_columns=None, use_cache=True, verbosity=0):
""" Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors
samples[0..N]['target'] should have an index with the date timestamp
If you use_cache for the curent year, you may not get the most recent data.
Arguments:
samples (list of dict): {'input': np.array(), 'target': pandas.DataFrame}
"""
if verbosity > 1:
print('Prepending weather data for {} to dataset samples'.format(weather_columns))
if not weather_columns:
return samples
timestamps = pd.DatetimeIndex([s['target'].index[0] for s in samples])
years = range(timestamps.min().date().year, timestamps.max().date().year + 1)
weather_df = weather.daily(location=location, years=years, use_cache=use_cache)
# FIXME: weather_df.resample('D') fails
weather_df.index = [d.date() for d in weather_df.index]
if verbosity > 1:
print('Retrieved weather for years {}:'.format(years))
print(weather_df)
weather_columns = [label if label in weather_df.columns else weather_df.columns[int(label)]
for label in (weather_columns or [])]
for sampnum, sample in enumerate(samples):
timestamp = timestamps[sampnum]
try:
weather_day = weather_df.loc[timestamp.date()]
except:
from traceback import print_exc
print_exc()
weather_day = {}
if verbosity >= 0:
warnings.warn('Unable to find weather for the date {}'.format(timestamp.date()))
NaN = float('NaN')
sample['input'] = [weather_day.get(label, None) for label in weather_columns] + list(sample['input'])
if verbosity > 0 and NaN in sample['input']:
warnings.warn('Unable to find weather features {} in the weather for date {}'.format(
[label for i, label in enumerate(weather_columns) if sample['input'][i] == NaN], timestamp))
return samples | python | def prepend_dataset_with_weather(samples, location='Fresno, CA', weather_columns=None, use_cache=True, verbosity=0):
""" Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors
samples[0..N]['target'] should have an index with the date timestamp
If you use_cache for the curent year, you may not get the most recent data.
Arguments:
samples (list of dict): {'input': np.array(), 'target': pandas.DataFrame}
"""
if verbosity > 1:
print('Prepending weather data for {} to dataset samples'.format(weather_columns))
if not weather_columns:
return samples
timestamps = pd.DatetimeIndex([s['target'].index[0] for s in samples])
years = range(timestamps.min().date().year, timestamps.max().date().year + 1)
weather_df = weather.daily(location=location, years=years, use_cache=use_cache)
# FIXME: weather_df.resample('D') fails
weather_df.index = [d.date() for d in weather_df.index]
if verbosity > 1:
print('Retrieved weather for years {}:'.format(years))
print(weather_df)
weather_columns = [label if label in weather_df.columns else weather_df.columns[int(label)]
for label in (weather_columns or [])]
for sampnum, sample in enumerate(samples):
timestamp = timestamps[sampnum]
try:
weather_day = weather_df.loc[timestamp.date()]
except:
from traceback import print_exc
print_exc()
weather_day = {}
if verbosity >= 0:
warnings.warn('Unable to find weather for the date {}'.format(timestamp.date()))
NaN = float('NaN')
sample['input'] = [weather_day.get(label, None) for label in weather_columns] + list(sample['input'])
if verbosity > 0 and NaN in sample['input']:
warnings.warn('Unable to find weather features {} in the weather for date {}'.format(
[label for i, label in enumerate(weather_columns) if sample['input'][i] == NaN], timestamp))
return samples | [
"def",
"prepend_dataset_with_weather",
"(",
"samples",
",",
"location",
"=",
"'Fresno, CA'",
",",
"weather_columns",
"=",
"None",
",",
"use_cache",
"=",
"True",
",",
"verbosity",
"=",
"0",
")",
":",
"if",
"verbosity",
">",
"1",
":",
"print",
"(",
"'Prependin... | Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors
samples[0..N]['target'] should have an index with the date timestamp
If you use_cache for the curent year, you may not get the most recent data.
Arguments:
samples (list of dict): {'input': np.array(), 'target': pandas.DataFrame} | [
"Prepend",
"weather",
"the",
"values",
"specified",
"(",
"e",
".",
"g",
".",
"Max",
"TempF",
")",
"to",
"the",
"samples",
"[",
"0",
"..",
"N",
"]",
"[",
"input",
"]",
"vectors"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L127-L166 |
hobson/pug-ann | pug/ann/util.py | dataset_from_dataframe | def dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=(-1,), normalize=False, verbosity=1):
"""Compose a pybrain.dataset from a pandas DataFrame
Arguments:
delays (list of int): sample delays to use for the input tapped delay line
Positive and negative values are treated the same as sample counts into the past.
default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3
inputs (list of int or list of str): column indices or labels for the inputs
outputs (list of int or list of str): column indices or labels for the outputs
normalize (bool): whether to divide each input to be normally distributed about 0 with std 1
Returns:
3-tuple: tuple(dataset, list of means, list of stds)
means and stds allow normalization of new inputs and denormalization of the outputs
TODO:
Detect categorical variables with low dimensionality and split into separate bits
Vowpel Wabbit hashes strings into an int?
Detect ordinal variables and convert to continuous int sequence
SEE: http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
"""
if isinstance(delays, int):
if delays:
delays = range(1, delays + 1)
else:
delays = [0]
delays = np.abs(np.array([int(i) for i in delays]))
inputs = [df.columns[int(inp)] if isinstance(inp, (float, int)) else str(inp) for inp in inputs]
outputs = [df.columns[int(out)] if isinstance(out, (float, int)) else str(out) for out in (outputs or [])]
inputs = [fuzzy_get(df.columns, i) for i in inputs]
outputs = [fuzzy_get(df.columns, o) for o in outputs]
N_inp = len(inputs)
N_out = len(outputs)
inp_outs = inputs + outputs
if verbosity > 0:
print("inputs: {}\noutputs: {}\ndelays: {}\n".format(inputs, outputs, delays))
means, stds = np.zeros(len(inp_outs)), np.ones(len(inp_outs))
if normalize:
means, stds = df[inp_outs].mean(), df[inp_outs].std()
if normalize and verbosity > 0:
print("Input mean values (used to normalize input biases): {}".format(means[:N_inp]))
print("Output mean values (used to normalize output biases): {}".format(means[N_inp:]))
ds = pb.datasets.SupervisedDataSet(N_inp * len(delays), N_out)
if verbosity > 0:
print("Dataset dimensions are {}x{}x{} (records x indim x outdim) for {} delays, {} inputs, {} outputs".format(
len(df), ds.indim, ds.outdim, len(delays), len(inputs), len(outputs)))
# FIXME: normalize the whole matrix at once and add it quickly rather than one sample at a time
if delays == np.array([0]) and not normalize:
if verbosity > 0:
print("No tapped delay lines (delays) were requested, so using undelayed features for the dataset.")
assert(df[inputs].values.shape[0] == df[outputs].values.shape[0])
ds.setField('input', df[inputs].values)
ds.setField('target', df[outputs].values)
ds.linkFields(['input', 'target'])
# for inp, outp in zip(df[inputs].values, df[outputs].values):
# ds.appendLinked(inp, outp)
assert(len(ds['input']) == len(ds['target']))
else:
for i, out_vec in enumerate(df[outputs].values):
if verbosity > 0 and i % 100 == 0:
print("{}%".format(i / .01 / len(df)))
elif verbosity > 1:
print('sample[{i}].target={out_vec}'.format(i=i, out_vec=out_vec))
if i < max(delays):
continue
inp_vec = []
for delay in delays:
inp_vec += list((df[inputs].values[i - delay] - means[:N_inp]) / stds[:N_inp])
ds.addSample(inp_vec, (out_vec - means[N_inp:]) / stds[N_inp:])
if verbosity > 0:
print("Dataset now has {} samples".format(len(ds)))
if normalize:
return ds, means, stds
else:
return ds | python | def dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=(-1,), normalize=False, verbosity=1):
"""Compose a pybrain.dataset from a pandas DataFrame
Arguments:
delays (list of int): sample delays to use for the input tapped delay line
Positive and negative values are treated the same as sample counts into the past.
default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3
inputs (list of int or list of str): column indices or labels for the inputs
outputs (list of int or list of str): column indices or labels for the outputs
normalize (bool): whether to divide each input to be normally distributed about 0 with std 1
Returns:
3-tuple: tuple(dataset, list of means, list of stds)
means and stds allow normalization of new inputs and denormalization of the outputs
TODO:
Detect categorical variables with low dimensionality and split into separate bits
Vowpel Wabbit hashes strings into an int?
Detect ordinal variables and convert to continuous int sequence
SEE: http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
"""
if isinstance(delays, int):
if delays:
delays = range(1, delays + 1)
else:
delays = [0]
delays = np.abs(np.array([int(i) for i in delays]))
inputs = [df.columns[int(inp)] if isinstance(inp, (float, int)) else str(inp) for inp in inputs]
outputs = [df.columns[int(out)] if isinstance(out, (float, int)) else str(out) for out in (outputs or [])]
inputs = [fuzzy_get(df.columns, i) for i in inputs]
outputs = [fuzzy_get(df.columns, o) for o in outputs]
N_inp = len(inputs)
N_out = len(outputs)
inp_outs = inputs + outputs
if verbosity > 0:
print("inputs: {}\noutputs: {}\ndelays: {}\n".format(inputs, outputs, delays))
means, stds = np.zeros(len(inp_outs)), np.ones(len(inp_outs))
if normalize:
means, stds = df[inp_outs].mean(), df[inp_outs].std()
if normalize and verbosity > 0:
print("Input mean values (used to normalize input biases): {}".format(means[:N_inp]))
print("Output mean values (used to normalize output biases): {}".format(means[N_inp:]))
ds = pb.datasets.SupervisedDataSet(N_inp * len(delays), N_out)
if verbosity > 0:
print("Dataset dimensions are {}x{}x{} (records x indim x outdim) for {} delays, {} inputs, {} outputs".format(
len(df), ds.indim, ds.outdim, len(delays), len(inputs), len(outputs)))
# FIXME: normalize the whole matrix at once and add it quickly rather than one sample at a time
if delays == np.array([0]) and not normalize:
if verbosity > 0:
print("No tapped delay lines (delays) were requested, so using undelayed features for the dataset.")
assert(df[inputs].values.shape[0] == df[outputs].values.shape[0])
ds.setField('input', df[inputs].values)
ds.setField('target', df[outputs].values)
ds.linkFields(['input', 'target'])
# for inp, outp in zip(df[inputs].values, df[outputs].values):
# ds.appendLinked(inp, outp)
assert(len(ds['input']) == len(ds['target']))
else:
for i, out_vec in enumerate(df[outputs].values):
if verbosity > 0 and i % 100 == 0:
print("{}%".format(i / .01 / len(df)))
elif verbosity > 1:
print('sample[{i}].target={out_vec}'.format(i=i, out_vec=out_vec))
if i < max(delays):
continue
inp_vec = []
for delay in delays:
inp_vec += list((df[inputs].values[i - delay] - means[:N_inp]) / stds[:N_inp])
ds.addSample(inp_vec, (out_vec - means[N_inp:]) / stds[N_inp:])
if verbosity > 0:
print("Dataset now has {} samples".format(len(ds)))
if normalize:
return ds, means, stds
else:
return ds | [
"def",
"dataset_from_dataframe",
"(",
"df",
",",
"delays",
"=",
"(",
"1",
",",
"2",
",",
"3",
")",
",",
"inputs",
"=",
"(",
"1",
",",
"2",
",",
"-",
"1",
")",
",",
"outputs",
"=",
"(",
"-",
"1",
",",
")",
",",
"normalize",
"=",
"False",
",",
... | Compose a pybrain.dataset from a pandas DataFrame
Arguments:
delays (list of int): sample delays to use for the input tapped delay line
Positive and negative values are treated the same as sample counts into the past.
default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3
inputs (list of int or list of str): column indices or labels for the inputs
outputs (list of int or list of str): column indices or labels for the outputs
normalize (bool): whether to divide each input to be normally distributed about 0 with std 1
Returns:
3-tuple: tuple(dataset, list of means, list of stds)
means and stds allow normalization of new inputs and denormalization of the outputs
TODO:
Detect categorical variables with low dimensionality and split into separate bits
Vowpel Wabbit hashes strings into an int?
Detect ordinal variables and convert to continuous int sequence
SEE: http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm | [
"Compose",
"a",
"pybrain",
".",
"dataset",
"from",
"a",
"pandas",
"DataFrame"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L169-L248 |
hobson/pug-ann | pug/ann/util.py | input_dataset_from_dataframe | def input_dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1):
""" Build a dataset with an empty output/target vector
Identical to `dataset_from_dataframe`, except that default values for 2 arguments:
outputs: None
"""
return dataset_from_dataframe(df=df, delays=delays, inputs=inputs, outputs=outputs,
normalize=normalize, verbosity=verbosity) | python | def input_dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1):
""" Build a dataset with an empty output/target vector
Identical to `dataset_from_dataframe`, except that default values for 2 arguments:
outputs: None
"""
return dataset_from_dataframe(df=df, delays=delays, inputs=inputs, outputs=outputs,
normalize=normalize, verbosity=verbosity) | [
"def",
"input_dataset_from_dataframe",
"(",
"df",
",",
"delays",
"=",
"(",
"1",
",",
"2",
",",
"3",
")",
",",
"inputs",
"=",
"(",
"1",
",",
"2",
",",
"-",
"1",
")",
",",
"outputs",
"=",
"None",
",",
"normalize",
"=",
"True",
",",
"verbosity",
"="... | Build a dataset with an empty output/target vector
Identical to `dataset_from_dataframe`, except that default values for 2 arguments:
outputs: None | [
"Build",
"a",
"dataset",
"with",
"an",
"empty",
"output",
"/",
"target",
"vector"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L348-L355 |
hobson/pug-ann | pug/ann/util.py | inputs_from_dataframe | def inputs_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1):
""" Build a sequence of vectors suitable for "activation" by a neural net
Identical to `dataset_from_dataframe`, except that only the input vectors are
returned (not a full DataSet instance) and default values for 2 arguments are changed:
outputs: None
And only the input vectors are return
"""
ds = input_dataset_from_dataframe(df=df, delays=delays, inputs=inputs, outputs=outputs,
normalize=normalize, verbosity=verbosity)
return ds['input'] | python | def inputs_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1):
""" Build a sequence of vectors suitable for "activation" by a neural net
Identical to `dataset_from_dataframe`, except that only the input vectors are
returned (not a full DataSet instance) and default values for 2 arguments are changed:
outputs: None
And only the input vectors are return
"""
ds = input_dataset_from_dataframe(df=df, delays=delays, inputs=inputs, outputs=outputs,
normalize=normalize, verbosity=verbosity)
return ds['input'] | [
"def",
"inputs_from_dataframe",
"(",
"df",
",",
"delays",
"=",
"(",
"1",
",",
"2",
",",
"3",
")",
",",
"inputs",
"=",
"(",
"1",
",",
"2",
",",
"-",
"1",
")",
",",
"outputs",
"=",
"None",
",",
"normalize",
"=",
"True",
",",
"verbosity",
"=",
"1"... | Build a sequence of vectors suitable for "activation" by a neural net
Identical to `dataset_from_dataframe`, except that only the input vectors are
returned (not a full DataSet instance) and default values for 2 arguments are changed:
outputs: None
And only the input vectors are return | [
"Build",
"a",
"sequence",
"of",
"vectors",
"suitable",
"for",
"activation",
"by",
"a",
"neural",
"net"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L358-L369 |
hobson/pug-ann | pug/ann/util.py | build_trainer | def build_trainer(nn, ds, verbosity=1):
"""Configure neural net trainer from a pybrain dataset"""
return pb.supervised.trainers.rprop.RPropMinusTrainer(nn, dataset=ds, batchlearning=True, verbose=bool(verbosity)) | python | def build_trainer(nn, ds, verbosity=1):
"""Configure neural net trainer from a pybrain dataset"""
return pb.supervised.trainers.rprop.RPropMinusTrainer(nn, dataset=ds, batchlearning=True, verbose=bool(verbosity)) | [
"def",
"build_trainer",
"(",
"nn",
",",
"ds",
",",
"verbosity",
"=",
"1",
")",
":",
"return",
"pb",
".",
"supervised",
".",
"trainers",
".",
"rprop",
".",
"RPropMinusTrainer",
"(",
"nn",
",",
"dataset",
"=",
"ds",
",",
"batchlearning",
"=",
"True",
","... | Configure neural net trainer from a pybrain dataset | [
"Configure",
"neural",
"net",
"trainer",
"from",
"a",
"pybrain",
"dataset"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L372-L374 |
hobson/pug-ann | pug/ann/util.py | weight_matrices | def weight_matrices(nn):
""" Extract list of weight matrices from a Network, Layer (module), Trainer, Connection or other pybrain object"""
if isinstance(nn, ndarray):
return nn
try:
return weight_matrices(nn.connections)
except:
pass
try:
return weight_matrices(nn.module)
except:
pass
# Network objects are ParameterContainer's too, but won't reshape into a single matrix,
# so this must come after try nn.connections
if isinstance(nn, (ParameterContainer, Connection)):
return reshape(nn.params, (nn.outdim, nn.indim))
if isinstance(nn, basestring):
try:
fn = nn
nn = NetworkReader(fn, newfile=False)
return weight_matrices(nn.readFrom(fn))
except:
pass
# FIXME: what does NetworkReader output? (Module? Layer?) need to handle it's type here
try:
return [weight_matrices(v) for (k, v) in nn.iteritems()]
except:
try:
connections = nn.module.connections.values()
nn = []
for conlist in connections:
nn += conlist
return weight_matrices(nn)
except:
return [weight_matrices(v) for v in nn] | python | def weight_matrices(nn):
""" Extract list of weight matrices from a Network, Layer (module), Trainer, Connection or other pybrain object"""
if isinstance(nn, ndarray):
return nn
try:
return weight_matrices(nn.connections)
except:
pass
try:
return weight_matrices(nn.module)
except:
pass
# Network objects are ParameterContainer's too, but won't reshape into a single matrix,
# so this must come after try nn.connections
if isinstance(nn, (ParameterContainer, Connection)):
return reshape(nn.params, (nn.outdim, nn.indim))
if isinstance(nn, basestring):
try:
fn = nn
nn = NetworkReader(fn, newfile=False)
return weight_matrices(nn.readFrom(fn))
except:
pass
# FIXME: what does NetworkReader output? (Module? Layer?) need to handle it's type here
try:
return [weight_matrices(v) for (k, v) in nn.iteritems()]
except:
try:
connections = nn.module.connections.values()
nn = []
for conlist in connections:
nn += conlist
return weight_matrices(nn)
except:
return [weight_matrices(v) for v in nn] | [
"def",
"weight_matrices",
"(",
"nn",
")",
":",
"if",
"isinstance",
"(",
"nn",
",",
"ndarray",
")",
":",
"return",
"nn",
"try",
":",
"return",
"weight_matrices",
"(",
"nn",
".",
"connections",
")",
"except",
":",
"pass",
"try",
":",
"return",
"weight_matr... | Extract list of weight matrices from a Network, Layer (module), Trainer, Connection or other pybrain object | [
"Extract",
"list",
"of",
"weight",
"matrices",
"from",
"a",
"Network",
"Layer",
"(",
"module",
")",
"Trainer",
"Connection",
"or",
"other",
"pybrain",
"object"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L377-L417 |
hobson/pug-ann | pug/ann/util.py | dataset_nan_locs | def dataset_nan_locs(ds):
"""
from http://stackoverflow.com/a/14033137/623735
# gets the indices of the rows with nan values in a dataframe
pd.isnull(df).any(1).nonzero()[0]
"""
ans = []
for sampnum, sample in enumerate(ds):
if pd.isnull(sample).any():
ans += [{
'sample': sampnum,
'input': pd.isnull(sample[0]).nonzero()[0],
'output': pd.isnull(sample[1]).nonzero()[0],
}]
return ans | python | def dataset_nan_locs(ds):
"""
from http://stackoverflow.com/a/14033137/623735
# gets the indices of the rows with nan values in a dataframe
pd.isnull(df).any(1).nonzero()[0]
"""
ans = []
for sampnum, sample in enumerate(ds):
if pd.isnull(sample).any():
ans += [{
'sample': sampnum,
'input': pd.isnull(sample[0]).nonzero()[0],
'output': pd.isnull(sample[1]).nonzero()[0],
}]
return ans | [
"def",
"dataset_nan_locs",
"(",
"ds",
")",
":",
"ans",
"=",
"[",
"]",
"for",
"sampnum",
",",
"sample",
"in",
"enumerate",
"(",
"ds",
")",
":",
"if",
"pd",
".",
"isnull",
"(",
"sample",
")",
".",
"any",
"(",
")",
":",
"ans",
"+=",
"[",
"{",
"'sa... | from http://stackoverflow.com/a/14033137/623735
# gets the indices of the rows with nan values in a dataframe
pd.isnull(df).any(1).nonzero()[0] | [
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"14033137",
"/",
"623735",
"#",
"gets",
"the",
"indices",
"of",
"the",
"rows",
"with",
"nan",
"values",
"in",
"a",
"dataframe",
"pd",
".",
"isnull",
"(",
"df",
")",
".",
"any",
... | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L535-L549 |
hobson/pug-ann | pug/ann/util.py | table_nan_locs | def table_nan_locs(table):
"""
from http://stackoverflow.com/a/14033137/623735
# gets the indices of the rows with nan values in a dataframe
pd.isnull(df).any(1).nonzero()[0]
"""
ans = []
for rownum, row in enumerate(table):
try:
if pd.isnull(row).any():
colnums = pd.isnull(row).nonzero()[0]
ans += [(rownum, colnum) for colnum in colnums]
except AttributeError: # table is really just a sequence of scalars
if pd.isnull(row):
ans += [(rownum, 0)]
return ans | python | def table_nan_locs(table):
"""
from http://stackoverflow.com/a/14033137/623735
# gets the indices of the rows with nan values in a dataframe
pd.isnull(df).any(1).nonzero()[0]
"""
ans = []
for rownum, row in enumerate(table):
try:
if pd.isnull(row).any():
colnums = pd.isnull(row).nonzero()[0]
ans += [(rownum, colnum) for colnum in colnums]
except AttributeError: # table is really just a sequence of scalars
if pd.isnull(row):
ans += [(rownum, 0)]
return ans | [
"def",
"table_nan_locs",
"(",
"table",
")",
":",
"ans",
"=",
"[",
"]",
"for",
"rownum",
",",
"row",
"in",
"enumerate",
"(",
"table",
")",
":",
"try",
":",
"if",
"pd",
".",
"isnull",
"(",
"row",
")",
".",
"any",
"(",
")",
":",
"colnums",
"=",
"p... | from http://stackoverflow.com/a/14033137/623735
# gets the indices of the rows with nan values in a dataframe
pd.isnull(df).any(1).nonzero()[0] | [
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"14033137",
"/",
"623735",
"#",
"gets",
"the",
"indices",
"of",
"the",
"rows",
"with",
"nan",
"values",
"in",
"a",
"dataframe",
"pd",
".",
"isnull",
"(",
"df",
")",
".",
"any",
... | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L552-L567 |
hobson/pug-ann | pug/ann/util.py | plot_network_results | def plot_network_results(network, ds=None, mean=0, std=1, title='', show=True, save=True):
"""Identical to plot_trainer except `network` and `ds` must be provided separately"""
df = sim_network(network=network, ds=ds, mean=mean, std=std)
df.plot()
plt.xlabel('Date')
plt.ylabel('Threshold (kW)')
plt.title(title)
if show:
try:
# ipython notebook overrides plt.show and doesn't have a block kwarg
plt.show(block=False)
except TypeError:
plt.show()
if save:
filename = 'ann_performance_for_{0}.png'.format(title).replace(' ', '_')
if isinstance(save, basestring) and os.path.isdir(save):
filename = os.path.join(save, filename)
plt.savefig(filename)
if not show:
plt.clf()
return network, mean, std | python | def plot_network_results(network, ds=None, mean=0, std=1, title='', show=True, save=True):
"""Identical to plot_trainer except `network` and `ds` must be provided separately"""
df = sim_network(network=network, ds=ds, mean=mean, std=std)
df.plot()
plt.xlabel('Date')
plt.ylabel('Threshold (kW)')
plt.title(title)
if show:
try:
# ipython notebook overrides plt.show and doesn't have a block kwarg
plt.show(block=False)
except TypeError:
plt.show()
if save:
filename = 'ann_performance_for_{0}.png'.format(title).replace(' ', '_')
if isinstance(save, basestring) and os.path.isdir(save):
filename = os.path.join(save, filename)
plt.savefig(filename)
if not show:
plt.clf()
return network, mean, std | [
"def",
"plot_network_results",
"(",
"network",
",",
"ds",
"=",
"None",
",",
"mean",
"=",
"0",
",",
"std",
"=",
"1",
",",
"title",
"=",
"''",
",",
"show",
"=",
"True",
",",
"save",
"=",
"True",
")",
":",
"df",
"=",
"sim_network",
"(",
"network",
"... | Identical to plot_trainer except `network` and `ds` must be provided separately | [
"Identical",
"to",
"plot_trainer",
"except",
"network",
"and",
"ds",
"must",
"be",
"provided",
"separately"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L570-L592 |
hobson/pug-ann | pug/ann/util.py | trainer_results | def trainer_results(trainer, mean=0, std=1, title='', show=True, save=True):
"""Plot the performance of the Network and SupervisedDataSet in a pybrain Trainer
DataSet target and output values are denormalized before plotting with:
output * std + mean
Which inverses the normalization
(output - mean) / std
Args:
trainer (Trainer): a pybrain Trainer instance containing a valid Network and DataSet
ds (DataSet): a pybrain DataSet to override the one contained in `trainer`.
Required if trainer is a Network instance rather than a Trainer instance.
mean (float): mean of the denormalized dataset (default: 0)
Only affects the scale of the plot
std (float): std (standard deviation) of the denormalized dataset (default: 1)
title (str): title to display on the plot.
Returns:
3-tuple: (trainer, mean, std), A trainer/dataset along with denormalization info
"""
return plot_network_results(network=trainer.module, ds=trainer.ds, mean=mean, std=std, title=title,
show=show, save=save) | python | def trainer_results(trainer, mean=0, std=1, title='', show=True, save=True):
"""Plot the performance of the Network and SupervisedDataSet in a pybrain Trainer
DataSet target and output values are denormalized before plotting with:
output * std + mean
Which inverses the normalization
(output - mean) / std
Args:
trainer (Trainer): a pybrain Trainer instance containing a valid Network and DataSet
ds (DataSet): a pybrain DataSet to override the one contained in `trainer`.
Required if trainer is a Network instance rather than a Trainer instance.
mean (float): mean of the denormalized dataset (default: 0)
Only affects the scale of the plot
std (float): std (standard deviation) of the denormalized dataset (default: 1)
title (str): title to display on the plot.
Returns:
3-tuple: (trainer, mean, std), A trainer/dataset along with denormalization info
"""
return plot_network_results(network=trainer.module, ds=trainer.ds, mean=mean, std=std, title=title,
show=show, save=save) | [
"def",
"trainer_results",
"(",
"trainer",
",",
"mean",
"=",
"0",
",",
"std",
"=",
"1",
",",
"title",
"=",
"''",
",",
"show",
"=",
"True",
",",
"save",
"=",
"True",
")",
":",
"return",
"plot_network_results",
"(",
"network",
"=",
"trainer",
".",
"modu... | Plot the performance of the Network and SupervisedDataSet in a pybrain Trainer
DataSet target and output values are denormalized before plotting with:
output * std + mean
Which inverses the normalization
(output - mean) / std
Args:
trainer (Trainer): a pybrain Trainer instance containing a valid Network and DataSet
ds (DataSet): a pybrain DataSet to override the one contained in `trainer`.
Required if trainer is a Network instance rather than a Trainer instance.
mean (float): mean of the denormalized dataset (default: 0)
Only affects the scale of the plot
std (float): std (standard deviation) of the denormalized dataset (default: 1)
title (str): title to display on the plot.
Returns:
3-tuple: (trainer, mean, std), A trainer/dataset along with denormalization info | [
"Plot",
"the",
"performance",
"of",
"the",
"Network",
"and",
"SupervisedDataSet",
"in",
"a",
"pybrain",
"Trainer"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L595-L619 |
hobson/pug-ann | pug/ann/util.py | sim_trainer | def sim_trainer(trainer, mean=0, std=1):
"""Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target'])
"""
return sim_network(network=trainer.module, ds=trainer.ds, mean=mean, std=std) | python | def sim_trainer(trainer, mean=0, std=1):
"""Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target'])
"""
return sim_network(network=trainer.module, ds=trainer.ds, mean=mean, std=std) | [
"def",
"sim_trainer",
"(",
"trainer",
",",
"mean",
"=",
"0",
",",
"std",
"=",
"1",
")",
":",
"return",
"sim_network",
"(",
"network",
"=",
"trainer",
".",
"module",
",",
"ds",
"=",
"trainer",
".",
"ds",
",",
"mean",
"=",
"mean",
",",
"std",
"=",
... | Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target']) | [
"Simulate",
"a",
"trainer",
"by",
"activating",
"its",
"DataSet",
"and",
"returning",
"DataFrame",
"(",
"columns",
"=",
"[",
"Output",
"Target",
"]",
")"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L622-L625 |
hobson/pug-ann | pug/ann/util.py | sim_network | def sim_network(network, ds=None, index=None, mean=0, std=1):
"""Simulate/activate a Network on a SupervisedDataSet and return DataFrame(columns=['Output','Target'])
The DataSet's target and output values are denormalized before populating the dataframe columns:
denormalized_output = normalized_output * std + mean
Which inverses the normalization that produced the normalized output in the first place: \
normalized_output = (denormalzied_output - mean) / std
Args:
network (Network): a pybrain Network instance to activate with the provided DataSet, `ds`
ds (DataSet): a pybrain DataSet to activate the Network on to produce an output sequence
mean (float): mean of the denormalized dataset (default: 0)
Output is scaled
std (float): std (standard deviation) of the denormalized dataset (default: 1)
title (str): title to display on the plot.
Returns:
DataFrame: DataFrame with columns "Output" and "Target" suitable for df.plot-ting
"""
# just in case network is a trainer or has a Module-derived instance as one of it's attribute
# isinstance(network.module, (networks.Network, modules.Module))
if hasattr(network, 'module') and hasattr(network.module, 'activate'):
# may want to also check: isinstance(network.module, (networks.Network, modules.Module))
network = network.module
ds = ds or network.ds
if not ds:
raise RuntimeError("Unable to find a `pybrain.datasets.DataSet` instance to activate the Network with, "
" to plot the outputs. A dataset can be provided as part of a network instance or "
"as a separate kwarg if `network` is used to provide the `pybrain.Network`"
" instance directly.")
results_generator = ((network.activate(ds['input'][i])[0] * std + mean, ds['target'][i][0] * std + mean)
for i in xrange(len(ds['input'])))
return pd.DataFrame(results_generator, columns=['Output', 'Target'], index=index or range(len(ds['input']))) | python | def sim_network(network, ds=None, index=None, mean=0, std=1):
"""Simulate/activate a Network on a SupervisedDataSet and return DataFrame(columns=['Output','Target'])
The DataSet's target and output values are denormalized before populating the dataframe columns:
denormalized_output = normalized_output * std + mean
Which inverses the normalization that produced the normalized output in the first place: \
normalized_output = (denormalzied_output - mean) / std
Args:
network (Network): a pybrain Network instance to activate with the provided DataSet, `ds`
ds (DataSet): a pybrain DataSet to activate the Network on to produce an output sequence
mean (float): mean of the denormalized dataset (default: 0)
Output is scaled
std (float): std (standard deviation) of the denormalized dataset (default: 1)
title (str): title to display on the plot.
Returns:
DataFrame: DataFrame with columns "Output" and "Target" suitable for df.plot-ting
"""
# just in case network is a trainer or has a Module-derived instance as one of it's attribute
# isinstance(network.module, (networks.Network, modules.Module))
if hasattr(network, 'module') and hasattr(network.module, 'activate'):
# may want to also check: isinstance(network.module, (networks.Network, modules.Module))
network = network.module
ds = ds or network.ds
if not ds:
raise RuntimeError("Unable to find a `pybrain.datasets.DataSet` instance to activate the Network with, "
" to plot the outputs. A dataset can be provided as part of a network instance or "
"as a separate kwarg if `network` is used to provide the `pybrain.Network`"
" instance directly.")
results_generator = ((network.activate(ds['input'][i])[0] * std + mean, ds['target'][i][0] * std + mean)
for i in xrange(len(ds['input'])))
return pd.DataFrame(results_generator, columns=['Output', 'Target'], index=index or range(len(ds['input']))) | [
"def",
"sim_network",
"(",
"network",
",",
"ds",
"=",
"None",
",",
"index",
"=",
"None",
",",
"mean",
"=",
"0",
",",
"std",
"=",
"1",
")",
":",
"# just in case network is a trainer or has a Module-derived instance as one of it's attribute",
"# isinstance(network.module,... | Simulate/activate a Network on a SupervisedDataSet and return DataFrame(columns=['Output','Target'])
The DataSet's target and output values are denormalized before populating the dataframe columns:
denormalized_output = normalized_output * std + mean
Which inverses the normalization that produced the normalized output in the first place: \
normalized_output = (denormalzied_output - mean) / std
Args:
network (Network): a pybrain Network instance to activate with the provided DataSet, `ds`
ds (DataSet): a pybrain DataSet to activate the Network on to produce an output sequence
mean (float): mean of the denormalized dataset (default: 0)
Output is scaled
std (float): std (standard deviation) of the denormalized dataset (default: 1)
title (str): title to display on the plot.
Returns:
DataFrame: DataFrame with columns "Output" and "Target" suitable for df.plot-ting | [
"Simulate",
"/",
"activate",
"a",
"Network",
"on",
"a",
"SupervisedDataSet",
"and",
"return",
"DataFrame",
"(",
"columns",
"=",
"[",
"Output",
"Target",
"]",
")"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/util.py#L628-L664 |
pulseenergy/vacation | vacation/lexer.py | lex | def lex(args):
""" Lex input and return a list of actions to perform. """
if len(args) == 0 or args[0] == SHOW:
return [(SHOW, None)]
elif args[0] == LOG:
return [(LOG, None)]
elif args[0] == ECHO:
return [(ECHO, None)]
elif args[0] == SET and args[1] == RATE:
return tokenizeSetRate(args[2:])
elif args[0] == SET and args[1] == DAYS:
return tokenizeSetDays(args[2:])
elif args[0] == TAKE:
return tokenizeTake(args[1:])
elif args[0] == CANCEL:
return tokenizeCancel(args[1:])
elif isMonth(args[0]):
return tokenizeTake(args)
else:
print('Unknown commands: {}'.format(' '.join(args)))
return [] | python | def lex(args):
""" Lex input and return a list of actions to perform. """
if len(args) == 0 or args[0] == SHOW:
return [(SHOW, None)]
elif args[0] == LOG:
return [(LOG, None)]
elif args[0] == ECHO:
return [(ECHO, None)]
elif args[0] == SET and args[1] == RATE:
return tokenizeSetRate(args[2:])
elif args[0] == SET and args[1] == DAYS:
return tokenizeSetDays(args[2:])
elif args[0] == TAKE:
return tokenizeTake(args[1:])
elif args[0] == CANCEL:
return tokenizeCancel(args[1:])
elif isMonth(args[0]):
return tokenizeTake(args)
else:
print('Unknown commands: {}'.format(' '.join(args)))
return [] | [
"def",
"lex",
"(",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"or",
"args",
"[",
"0",
"]",
"==",
"SHOW",
":",
"return",
"[",
"(",
"SHOW",
",",
"None",
")",
"]",
"elif",
"args",
"[",
"0",
"]",
"==",
"LOG",
":",
"return",
"["... | Lex input and return a list of actions to perform. | [
"Lex",
"input",
"and",
"return",
"a",
"list",
"of",
"actions",
"to",
"perform",
"."
] | train | https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/lexer.py#L19-L39 |
reflexsc/reflex | dev/action.py | Action.run_svc_action | def run_svc_action(self, name, replace=None, svc=None):
"""
backwards compatible to reflex service object. This looks for hooks on
current object as well as in the actions sub-object.
"""
actions = svc.get('actions')
if actions and actions.get(name):
return self.run(name, actions=actions, replace=replace)
if svc.get(name + "-hook"):
return self.run(name, actions={
name: {
"type": "hook",
"url": svc.get(name + "-hook")
}
}, replace=replace)
self.die("Unable to find action {name} on service {svc}",
name=name, svc=svc.get('name', '')) | python | def run_svc_action(self, name, replace=None, svc=None):
"""
backwards compatible to reflex service object. This looks for hooks on
current object as well as in the actions sub-object.
"""
actions = svc.get('actions')
if actions and actions.get(name):
return self.run(name, actions=actions, replace=replace)
if svc.get(name + "-hook"):
return self.run(name, actions={
name: {
"type": "hook",
"url": svc.get(name + "-hook")
}
}, replace=replace)
self.die("Unable to find action {name} on service {svc}",
name=name, svc=svc.get('name', '')) | [
"def",
"run_svc_action",
"(",
"self",
",",
"name",
",",
"replace",
"=",
"None",
",",
"svc",
"=",
"None",
")",
":",
"actions",
"=",
"svc",
".",
"get",
"(",
"'actions'",
")",
"if",
"actions",
"and",
"actions",
".",
"get",
"(",
"name",
")",
":",
"retu... | backwards compatible to reflex service object. This looks for hooks on
current object as well as in the actions sub-object. | [
"backwards",
"compatible",
"to",
"reflex",
"service",
"object",
".",
"This",
"looks",
"for",
"hooks",
"on",
"current",
"object",
"as",
"well",
"as",
"in",
"the",
"actions",
"sub",
"-",
"object",
"."
] | train | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/action.py#L105-L121 |
reflexsc/reflex | dev/action.py | Action.run | def run(self, name, replace=None, actions=None):
"""
Do an action.
If `replace` is provided as a dictionary, do a search/replace using
%{} templates on content of action (unique to action type)
"""
self.actions = actions # incase we use group
action = actions.get(name)
if not action:
self.die("Action not found: {}", name)
action['name'] = name
action_type = action.get('type', "none")
try:
func = getattr(self, '_run__' + action_type)
except AttributeError:
self.die("Unsupported action type " + action_type)
try:
return func(action, replace)
except Exception as err: # pylint: disable=broad-except
if self._debug:
self.debug(traceback.format_exc())
self.die("Error running action name={} type={} error={}",
name, action_type, err) | python | def run(self, name, replace=None, actions=None):
"""
Do an action.
If `replace` is provided as a dictionary, do a search/replace using
%{} templates on content of action (unique to action type)
"""
self.actions = actions # incase we use group
action = actions.get(name)
if not action:
self.die("Action not found: {}", name)
action['name'] = name
action_type = action.get('type', "none")
try:
func = getattr(self, '_run__' + action_type)
except AttributeError:
self.die("Unsupported action type " + action_type)
try:
return func(action, replace)
except Exception as err: # pylint: disable=broad-except
if self._debug:
self.debug(traceback.format_exc())
self.die("Error running action name={} type={} error={}",
name, action_type, err) | [
"def",
"run",
"(",
"self",
",",
"name",
",",
"replace",
"=",
"None",
",",
"actions",
"=",
"None",
")",
":",
"self",
".",
"actions",
"=",
"actions",
"# incase we use group",
"action",
"=",
"actions",
".",
"get",
"(",
"name",
")",
"if",
"not",
"action",
... | Do an action.
If `replace` is provided as a dictionary, do a search/replace using
%{} templates on content of action (unique to action type) | [
"Do",
"an",
"action",
"."
] | train | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/action.py#L124-L149 |
reflexsc/reflex | dev/action.py | Action._run__group | def _run__group(self, action, replace):
"""
Run a group of actions in sequence.
>>> Action().run("several", actions={
... "several": {
... "type": "group",
... "actions": ["hello","call","then"]
... }, "hello": {
... "type": "exec",
... "cmd": "echo version=%{version}"
... }, "call": {
... "type": "hook",
... "url": "http://reflex.cold.org"
... }, "then": {
... "type": "exec",
... "cmd": "echo finished"
... }}, replace={
... "version": "1712.10"
... })
version=1712.10
"""
for target in action.get('actions', []):
Action().run(target, actions=self.actions, replace=replace) | python | def _run__group(self, action, replace):
"""
Run a group of actions in sequence.
>>> Action().run("several", actions={
... "several": {
... "type": "group",
... "actions": ["hello","call","then"]
... }, "hello": {
... "type": "exec",
... "cmd": "echo version=%{version}"
... }, "call": {
... "type": "hook",
... "url": "http://reflex.cold.org"
... }, "then": {
... "type": "exec",
... "cmd": "echo finished"
... }}, replace={
... "version": "1712.10"
... })
version=1712.10
"""
for target in action.get('actions', []):
Action().run(target, actions=self.actions, replace=replace) | [
"def",
"_run__group",
"(",
"self",
",",
"action",
",",
"replace",
")",
":",
"for",
"target",
"in",
"action",
".",
"get",
"(",
"'actions'",
",",
"[",
"]",
")",
":",
"Action",
"(",
")",
".",
"run",
"(",
"target",
",",
"actions",
"=",
"self",
".",
"... | Run a group of actions in sequence.
>>> Action().run("several", actions={
... "several": {
... "type": "group",
... "actions": ["hello","call","then"]
... }, "hello": {
... "type": "exec",
... "cmd": "echo version=%{version}"
... }, "call": {
... "type": "hook",
... "url": "http://reflex.cold.org"
... }, "then": {
... "type": "exec",
... "cmd": "echo finished"
... }}, replace={
... "version": "1712.10"
... })
version=1712.10 | [
"Run",
"a",
"group",
"of",
"actions",
"in",
"sequence",
"."
] | train | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/action.py#L152-L176 |
reflexsc/reflex | dev/action.py | Action._run__hook | def _run__hook(self, action, replace):
"""Simple webhook"""
url = action.get("url")
expected = action.get("expect", {}).get("response-codes", (200, 201, 202, 204))
if replace and action.get("template", True):
url = self.rfxcfg.macro_expand(url, replace)
self.logf("Action {} hook\n", action['name'])
self.logf("{}\n", url, level=common.log_msg)
result = requests.get(url)
self.debug("Result={}\n", result.status_code)
if result.status_code not in expected:
self.die("Hook failed name={} result={}", action['name'], result.status_code)
self.logf("Success\n", level=common.log_good) | python | def _run__hook(self, action, replace):
"""Simple webhook"""
url = action.get("url")
expected = action.get("expect", {}).get("response-codes", (200, 201, 202, 204))
if replace and action.get("template", True):
url = self.rfxcfg.macro_expand(url, replace)
self.logf("Action {} hook\n", action['name'])
self.logf("{}\n", url, level=common.log_msg)
result = requests.get(url)
self.debug("Result={}\n", result.status_code)
if result.status_code not in expected:
self.die("Hook failed name={} result={}", action['name'], result.status_code)
self.logf("Success\n", level=common.log_good) | [
"def",
"_run__hook",
"(",
"self",
",",
"action",
",",
"replace",
")",
":",
"url",
"=",
"action",
".",
"get",
"(",
"\"url\"",
")",
"expected",
"=",
"action",
".",
"get",
"(",
"\"expect\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"response-codes\"",
","... | Simple webhook | [
"Simple",
"webhook"
] | train | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/action.py#L179-L191 |
reflexsc/reflex | dev/action.py | Action._run__exec | def _run__exec(self, action, replace):
"""
Run a system command
>>> Action().run("hello", actions={
... "hello": {
... "type": "exec",
... "cmd": "echo version=%{version}"
... }}, replace={
... "version": "1712.10"
... })
version=1712.10
"""
cmd = action.get('cmd')
shell = False
if isinstance(cmd, str):
shell = True
if replace and action.get("template", True):
if shell:
cmd = self.rfxcfg.macro_expand(cmd, replace)
else:
cmd = [self.rfxcfg.macro_expand(x, replace) for x in cmd]
self.logf("Action {} exec\n", action['name'])
self.logf("{}\n", cmd, level=common.log_cmd)
if self.sys(cmd):
self.logf("Success\n", level=common.log_good)
return
self.die("Failure\n", level=common.log_err) | python | def _run__exec(self, action, replace):
"""
Run a system command
>>> Action().run("hello", actions={
... "hello": {
... "type": "exec",
... "cmd": "echo version=%{version}"
... }}, replace={
... "version": "1712.10"
... })
version=1712.10
"""
cmd = action.get('cmd')
shell = False
if isinstance(cmd, str):
shell = True
if replace and action.get("template", True):
if shell:
cmd = self.rfxcfg.macro_expand(cmd, replace)
else:
cmd = [self.rfxcfg.macro_expand(x, replace) for x in cmd]
self.logf("Action {} exec\n", action['name'])
self.logf("{}\n", cmd, level=common.log_cmd)
if self.sys(cmd):
self.logf("Success\n", level=common.log_good)
return
self.die("Failure\n", level=common.log_err) | [
"def",
"_run__exec",
"(",
"self",
",",
"action",
",",
"replace",
")",
":",
"cmd",
"=",
"action",
".",
"get",
"(",
"'cmd'",
")",
"shell",
"=",
"False",
"if",
"isinstance",
"(",
"cmd",
",",
"str",
")",
":",
"shell",
"=",
"True",
"if",
"replace",
"and... | Run a system command
>>> Action().run("hello", actions={
... "hello": {
... "type": "exec",
... "cmd": "echo version=%{version}"
... }}, replace={
... "version": "1712.10"
... })
version=1712.10 | [
"Run",
"a",
"system",
"command"
] | train | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/action.py#L200-L230 |
reflexsc/reflex | dev/action.py | Action._run__http | def _run__http(self, action, replace):
"""More complex HTTP query."""
query = action['query']
# self._debug = True
url = '{type}://{host}{path}'.format(path=query['path'], **action)
content = None
method = query.get('method', "get").lower()
self.debug("{} {} url={}\n", action['type'], method, url)
if method == "post":
content = query['content']
headers = query.get('headers', {})
if replace and action.get('template'):
self.rfxcfg.macro_expand(url, replace)
if content:
if isinstance(content, dict):
for key, value in content.items():
content[key] = self.rfxcfg.macro_expand(value, replace)
else:
content = self.rfxcfg.macro_expand(content, replace)
newhdrs = dict()
for key, value in headers.items():
newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
headers = newhdrs
self.debug("{} headers={}\n", action['type'], headers)
self.debug("{} content={}\n", action['type'], content)
if content and isinstance(content, dict):
content = json.dumps(content)
self.logf("Action {name} {type}\n", **action)
result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
expect = action.get('expect', {})
expected_codes = expect.get("response-codes", (200, 201, 202, 204))
self.debug("{} expect codes={}\n", action['type'], expected_codes)
self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
if result.status_code not in expected_codes:
self.die("Unable to make {} call, unexpected result ({})",
action['type'], result.status_code)
if 'content' in expect:
self.debug("{} expect content={}\n", action['type'], expect['content'])
if expect['content'] not in result.text:
self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
action['type'], url, expect['content'], result.text)
if 'regex' in expect:
self.debug("{} expect regex={}\n", action['type'], expect['regex'])
if not re.search(expect['regex'], result.text):
self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
action['type'], url, expect['regex'], result.text)
self.log(result.text, level=common.log_msg)
self.logf("Success, status={}\n", result.status_code, level=common.log_good)
return True | python | def _run__http(self, action, replace):
"""More complex HTTP query."""
query = action['query']
# self._debug = True
url = '{type}://{host}{path}'.format(path=query['path'], **action)
content = None
method = query.get('method', "get").lower()
self.debug("{} {} url={}\n", action['type'], method, url)
if method == "post":
content = query['content']
headers = query.get('headers', {})
if replace and action.get('template'):
self.rfxcfg.macro_expand(url, replace)
if content:
if isinstance(content, dict):
for key, value in content.items():
content[key] = self.rfxcfg.macro_expand(value, replace)
else:
content = self.rfxcfg.macro_expand(content, replace)
newhdrs = dict()
for key, value in headers.items():
newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
headers = newhdrs
self.debug("{} headers={}\n", action['type'], headers)
self.debug("{} content={}\n", action['type'], content)
if content and isinstance(content, dict):
content = json.dumps(content)
self.logf("Action {name} {type}\n", **action)
result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
expect = action.get('expect', {})
expected_codes = expect.get("response-codes", (200, 201, 202, 204))
self.debug("{} expect codes={}\n", action['type'], expected_codes)
self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
if result.status_code not in expected_codes:
self.die("Unable to make {} call, unexpected result ({})",
action['type'], result.status_code)
if 'content' in expect:
self.debug("{} expect content={}\n", action['type'], expect['content'])
if expect['content'] not in result.text:
self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
action['type'], url, expect['content'], result.text)
if 'regex' in expect:
self.debug("{} expect regex={}\n", action['type'], expect['regex'])
if not re.search(expect['regex'], result.text):
self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
action['type'], url, expect['regex'], result.text)
self.log(result.text, level=common.log_msg)
self.logf("Success, status={}\n", result.status_code, level=common.log_good)
return True | [
"def",
"_run__http",
"(",
"self",
",",
"action",
",",
"replace",
")",
":",
"query",
"=",
"action",
"[",
"'query'",
"]",
"# self._debug = True",
"url",
"=",
"'{type}://{host}{path}'",
".",
"format",
"(",
"path",
"=",
"query",
"[",
"'path'",
"]",
",",
... | More complex HTTP query. | [
"More",
"complex",
"HTTP",
"query",
"."
] | train | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/action.py#L236-L294 |
duniter/duniter-python-api | examples/request_web_socket_block.py | main | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
try:
# Create Web Socket connection on block path
ws_connection = client(bma.ws.block)
# From the documentation ws_connection should be a ClientWebSocketResponse object...
#
# https://docs.aiohttp.org/en/stable/client_quickstart.html#websockets
#
# In reality, aiohttp.session.ws_connect() returns a aiohttp.client._WSRequestContextManager instance.
# It must be used in a with statement to get the ClientWebSocketResponse instance from it (__aenter__).
# At the end of the with statement, aiohttp.client._WSRequestContextManager.__aexit__ is called
# and close the ClientWebSocketResponse in it.
# Mandatory to get the "for msg in ws" to work !
async with ws_connection as ws:
print("Connected successfully to web socket block path")
# Iterate on each message received...
async for msg in ws:
# if message type is text...
if msg.type == aiohttp.WSMsgType.TEXT:
print("Received a block")
# Validate jsonschema and return a the json dict
block_data = parse_text(msg.data, bma.ws.WS_BLOCK_SCHEMA)
print(block_data)
elif msg.type == aiohttp.WSMsgType.CLOSED:
# Connection is closed
print("Web socket connection closed !")
elif msg.type == aiohttp.WSMsgType.ERROR:
# Connection error
print("Web socket connection error !")
# Close session
await client.close()
except (aiohttp.WSServerHandshakeError, ValueError) as e:
print("Websocket block {0} : {1}".format(type(e).__name__, str(e)))
except (aiohttp.ClientError, gaierror, TimeoutError) as e:
print("{0} : {1}".format(str(e), BMAS_ENDPOINT))
except jsonschema.ValidationError as e:
print("{:}:{:}".format(str(e.__class__.__name__), str(e))) | python | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
try:
# Create Web Socket connection on block path
ws_connection = client(bma.ws.block)
# From the documentation ws_connection should be a ClientWebSocketResponse object...
#
# https://docs.aiohttp.org/en/stable/client_quickstart.html#websockets
#
# In reality, aiohttp.session.ws_connect() returns a aiohttp.client._WSRequestContextManager instance.
# It must be used in a with statement to get the ClientWebSocketResponse instance from it (__aenter__).
# At the end of the with statement, aiohttp.client._WSRequestContextManager.__aexit__ is called
# and close the ClientWebSocketResponse in it.
# Mandatory to get the "for msg in ws" to work !
async with ws_connection as ws:
print("Connected successfully to web socket block path")
# Iterate on each message received...
async for msg in ws:
# if message type is text...
if msg.type == aiohttp.WSMsgType.TEXT:
print("Received a block")
# Validate jsonschema and return a the json dict
block_data = parse_text(msg.data, bma.ws.WS_BLOCK_SCHEMA)
print(block_data)
elif msg.type == aiohttp.WSMsgType.CLOSED:
# Connection is closed
print("Web socket connection closed !")
elif msg.type == aiohttp.WSMsgType.ERROR:
# Connection error
print("Web socket connection error !")
# Close session
await client.close()
except (aiohttp.WSServerHandshakeError, ValueError) as e:
print("Websocket block {0} : {1}".format(type(e).__name__, str(e)))
except (aiohttp.ClientError, gaierror, TimeoutError) as e:
print("{0} : {1}".format(str(e), BMAS_ENDPOINT))
except jsonschema.ValidationError as e:
print("{:}:{:}".format(str(e.__class__.__name__), str(e))) | [
"async",
"def",
"main",
"(",
")",
":",
"# Create Client from endpoint string in Duniter format",
"client",
"=",
"Client",
"(",
"BMAS_ENDPOINT",
")",
"try",
":",
"# Create Web Socket connection on block path",
"ws_connection",
"=",
"client",
"(",
"bma",
".",
"ws",
".",
... | Main code | [
"Main",
"code"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/request_web_socket_block.py#L21-L67 |
CodyKochmann/strict_functions | strict_functions/strict_defaults.py | _get_default_args | def _get_default_args(func):
"""
returns a dictionary of arg_name:default_values for the input function
"""
args, varargs, keywords, defaults = inspect.getargspec(func)
print(args)
return dict(zip(reversed(args), reversed(defaults))) | python | def _get_default_args(func):
"""
returns a dictionary of arg_name:default_values for the input function
"""
args, varargs, keywords, defaults = inspect.getargspec(func)
print(args)
return dict(zip(reversed(args), reversed(defaults))) | [
"def",
"_get_default_args",
"(",
"func",
")",
":",
"args",
",",
"varargs",
",",
"keywords",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"print",
"(",
"args",
")",
"return",
"dict",
"(",
"zip",
"(",
"reversed",
"(",
"args",
")"... | returns a dictionary of arg_name:default_values for the input function | [
"returns",
"a",
"dictionary",
"of",
"arg_name",
":",
"default_values",
"for",
"the",
"input",
"function"
] | train | https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/strict_defaults.py#L10-L16 |
CodyKochmann/strict_functions | strict_functions/strict_defaults.py | _get_arg_names | def _get_arg_names(func):
''' this returns the arg names since dictionaries dont guarantee order '''
args, varargs, keywords, defaults = inspect.getargspec(func)
return(tuple(args)) | python | def _get_arg_names(func):
''' this returns the arg names since dictionaries dont guarantee order '''
args, varargs, keywords, defaults = inspect.getargspec(func)
return(tuple(args)) | [
"def",
"_get_arg_names",
"(",
"func",
")",
":",
"args",
",",
"varargs",
",",
"keywords",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"return",
"(",
"tuple",
"(",
"args",
")",
")"
] | this returns the arg names since dictionaries dont guarantee order | [
"this",
"returns",
"the",
"arg",
"names",
"since",
"dictionaries",
"dont",
"guarantee",
"order"
] | train | https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/strict_defaults.py#L18-L21 |
CodyKochmann/strict_functions | strict_functions/strict_defaults.py | strict_defaults | def strict_defaults(fn):
''' use this decorator to enforce type checking on functions based on the function's defaults '''
@wraps(fn)
def wrapper(*args, **kwargs):
defaults = _get_default_args(fn)
# dictionary that holds each default type
needed_types={
key:type(defaults[key]) for key in defaults
}
# ordered tuple of the function's argument names
arg_names=_get_arg_names(fn)
assert not len(arg_names) - len(fn.__defaults__), '{} needs default variables on all arguments'.format(fn.__name__)
# merge args to kwargs for easy parsing
for i in range(len(args)):
if args[i] not in kwargs.keys():
kwargs[arg_names[i]]=args[i]
# assert that theyre all the correct type
for name in needed_types:
# do them all seperately so you can show what went wrong
assert isinstance(kwargs[name],needed_types[name]), 'got {} and expected a {}'.format(kwargs[name],needed_types[name])
# return the refined results
return fn(**kwargs)
return wrapper | python | def strict_defaults(fn):
''' use this decorator to enforce type checking on functions based on the function's defaults '''
@wraps(fn)
def wrapper(*args, **kwargs):
defaults = _get_default_args(fn)
# dictionary that holds each default type
needed_types={
key:type(defaults[key]) for key in defaults
}
# ordered tuple of the function's argument names
arg_names=_get_arg_names(fn)
assert not len(arg_names) - len(fn.__defaults__), '{} needs default variables on all arguments'.format(fn.__name__)
# merge args to kwargs for easy parsing
for i in range(len(args)):
if args[i] not in kwargs.keys():
kwargs[arg_names[i]]=args[i]
# assert that theyre all the correct type
for name in needed_types:
# do them all seperately so you can show what went wrong
assert isinstance(kwargs[name],needed_types[name]), 'got {} and expected a {}'.format(kwargs[name],needed_types[name])
# return the refined results
return fn(**kwargs)
return wrapper | [
"def",
"strict_defaults",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"_get_default_args",
"(",
"fn",
")",
"# dictionary that holds each default type",
"needed_typ... | use this decorator to enforce type checking on functions based on the function's defaults | [
"use",
"this",
"decorator",
"to",
"enforce",
"type",
"checking",
"on",
"functions",
"based",
"on",
"the",
"function",
"s",
"defaults"
] | train | https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/strict_defaults.py#L23-L45 |
clinicedc/edc-notification | edc_notification/update_mailing_lists_in_m2m.py | update_mailing_lists_in_m2m | def update_mailing_lists_in_m2m(
sender=None,
userprofile=None,
pk_set=None,
subscribe=None,
unsubscribe=None,
verbose=None,
email_enabled=None,
):
"""
m2m_model = m2m model class for 'email_notifications' or
'sms_notifications'.
"""
response = None
email_enabled = email_enabled or settings.EMAIL_ENABLED
if email_enabled and site_notifications.loaded:
if userprofile.email_notifications.through == sender:
NotificationModel = django_apps.get_model("edc_notification.Notification")
for notification_obj in NotificationModel.objects.filter(
pk__in=list(pk_set), enabled=True
):
notification_cls = site_notifications.get(notification_obj.name)
notification = notification_cls()
manager = MailingListManager(
address=notification.email_to[0],
display_name=notification.display_name,
name=notification.name,
)
response = manager.create(verbose=verbose)
if subscribe:
response = manager.subscribe(userprofile.user, verbose=verbose)
elif unsubscribe:
response = manager.unsubscribe(userprofile.user, verbose=verbose)
return response | python | def update_mailing_lists_in_m2m(
sender=None,
userprofile=None,
pk_set=None,
subscribe=None,
unsubscribe=None,
verbose=None,
email_enabled=None,
):
"""
m2m_model = m2m model class for 'email_notifications' or
'sms_notifications'.
"""
response = None
email_enabled = email_enabled or settings.EMAIL_ENABLED
if email_enabled and site_notifications.loaded:
if userprofile.email_notifications.through == sender:
NotificationModel = django_apps.get_model("edc_notification.Notification")
for notification_obj in NotificationModel.objects.filter(
pk__in=list(pk_set), enabled=True
):
notification_cls = site_notifications.get(notification_obj.name)
notification = notification_cls()
manager = MailingListManager(
address=notification.email_to[0],
display_name=notification.display_name,
name=notification.name,
)
response = manager.create(verbose=verbose)
if subscribe:
response = manager.subscribe(userprofile.user, verbose=verbose)
elif unsubscribe:
response = manager.unsubscribe(userprofile.user, verbose=verbose)
return response | [
"def",
"update_mailing_lists_in_m2m",
"(",
"sender",
"=",
"None",
",",
"userprofile",
"=",
"None",
",",
"pk_set",
"=",
"None",
",",
"subscribe",
"=",
"None",
",",
"unsubscribe",
"=",
"None",
",",
"verbose",
"=",
"None",
",",
"email_enabled",
"=",
"None",
"... | m2m_model = m2m model class for 'email_notifications' or
'sms_notifications'. | [
"m2m_model",
"=",
"m2m",
"model",
"class",
"for",
"email_notifications",
"or",
"sms_notifications",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/update_mailing_lists_in_m2m.py#L8-L41 |
hangyan/shaw | shaw/types/d.py | superdict | def superdict(arg=()):
"""Recursive defaultdict which can init with other dict """
def update(obj, arg):
return obj.update(arg) or obj
return update(defaultdict(superdict), arg) | python | def superdict(arg=()):
"""Recursive defaultdict which can init with other dict """
def update(obj, arg):
return obj.update(arg) or obj
return update(defaultdict(superdict), arg) | [
"def",
"superdict",
"(",
"arg",
"=",
"(",
")",
")",
":",
"def",
"update",
"(",
"obj",
",",
"arg",
")",
":",
"return",
"obj",
".",
"update",
"(",
"arg",
")",
"or",
"obj",
"return",
"update",
"(",
"defaultdict",
"(",
"superdict",
")",
",",
"arg",
"... | Recursive defaultdict which can init with other dict | [
"Recursive",
"defaultdict",
"which",
"can",
"init",
"with",
"other",
"dict"
] | train | https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/types/d.py#L34-L38 |
hangyan/shaw | shaw/types/d.py | rget | def rget(d, key):
"""Recursively get keys from dict, for example:
'a.b.c' --> d['a']['b']['c'], return None if not exist.
"""
if not isinstance(d, dict):
return None
assert isinstance(key, str) or isinstance(key, list)
keys = key.split('.') if isinstance(key, str) else key
cdrs = cdr(keys)
cars = car(keys)
return rget(d.get(cars), cdrs) if cdrs else d.get(cars) | python | def rget(d, key):
"""Recursively get keys from dict, for example:
'a.b.c' --> d['a']['b']['c'], return None if not exist.
"""
if not isinstance(d, dict):
return None
assert isinstance(key, str) or isinstance(key, list)
keys = key.split('.') if isinstance(key, str) else key
cdrs = cdr(keys)
cars = car(keys)
return rget(d.get(cars), cdrs) if cdrs else d.get(cars) | [
"def",
"rget",
"(",
"d",
",",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"return",
"None",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"or",
"isinstance",
"(",
"key",
",",
"list",
")",
"keys",
"=",
"key"... | Recursively get keys from dict, for example:
'a.b.c' --> d['a']['b']['c'], return None if not exist. | [
"Recursively",
"get",
"keys",
"from",
"dict",
"for",
"example",
":",
"a",
".",
"b",
".",
"c",
"--",
">",
"d",
"[",
"a",
"]",
"[",
"b",
"]",
"[",
"c",
"]",
"return",
"None",
"if",
"not",
"exist",
"."
] | train | https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/types/d.py#L41-L52 |
hangyan/shaw | shaw/types/d.py | deepcopy | def deepcopy(data):
"""Use pickle to do deep_copy"""
try:
return pickle.loads(pickle.dumps(data))
except TypeError:
return copy.deepcopy(data) | python | def deepcopy(data):
"""Use pickle to do deep_copy"""
try:
return pickle.loads(pickle.dumps(data))
except TypeError:
return copy.deepcopy(data) | [
"def",
"deepcopy",
"(",
"data",
")",
":",
"try",
":",
"return",
"pickle",
".",
"loads",
"(",
"pickle",
".",
"dumps",
"(",
"data",
")",
")",
"except",
"TypeError",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"data",
")"
] | Use pickle to do deep_copy | [
"Use",
"pickle",
"to",
"do",
"deep_copy"
] | train | https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/types/d.py#L55-L60 |
hangyan/shaw | shaw/types/d.py | deepcp | def deepcp(data):
"""Use ujson to do deep_copy"""
import ujson
try:
return ujson.loads(ujson.dumps(data))
except Exception:
return copy.deepcopy(data) | python | def deepcp(data):
"""Use ujson to do deep_copy"""
import ujson
try:
return ujson.loads(ujson.dumps(data))
except Exception:
return copy.deepcopy(data) | [
"def",
"deepcp",
"(",
"data",
")",
":",
"import",
"ujson",
"try",
":",
"return",
"ujson",
".",
"loads",
"(",
"ujson",
".",
"dumps",
"(",
"data",
")",
")",
"except",
"Exception",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"data",
")"
] | Use ujson to do deep_copy | [
"Use",
"ujson",
"to",
"do",
"deep_copy"
] | train | https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/types/d.py#L63-L69 |
mozilla/socorrolib | socorrolib/lib/ver_tools.py | _memoizeArgsOnly | def _memoizeArgsOnly (max_cache_size=1000):
"""Python 2.4 compatible memoize decorator.
It creates a cache that has a maximum size. If the cache exceeds the max,
it is thrown out and a new one made. With such behavior, it is wise to set
the cache just a little larger that the maximum expected need.
Parameters:
max_cache_size - the size to which a cache can grow
Limitations:
The cache works only on args, not kwargs
"""
def wrapper (f):
def fn (*args):
try:
return fn.cache[args]
except KeyError:
if fn.count >= max_cache_size:
fn.cache = {}
fn.count = 0
fn.cache[args] = result = f(*args)
fn.count += 1
return result
fn.cache = {}
fn.count = 0
return fn
return wrapper | python | def _memoizeArgsOnly (max_cache_size=1000):
"""Python 2.4 compatible memoize decorator.
It creates a cache that has a maximum size. If the cache exceeds the max,
it is thrown out and a new one made. With such behavior, it is wise to set
the cache just a little larger that the maximum expected need.
Parameters:
max_cache_size - the size to which a cache can grow
Limitations:
The cache works only on args, not kwargs
"""
def wrapper (f):
def fn (*args):
try:
return fn.cache[args]
except KeyError:
if fn.count >= max_cache_size:
fn.cache = {}
fn.count = 0
fn.cache[args] = result = f(*args)
fn.count += 1
return result
fn.cache = {}
fn.count = 0
return fn
return wrapper | [
"def",
"_memoizeArgsOnly",
"(",
"max_cache_size",
"=",
"1000",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"def",
"fn",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"fn",
".",
"cache",
"[",
"args",
"]",
"except",
"KeyError",
":",
"if",
"fn... | Python 2.4 compatible memoize decorator.
It creates a cache that has a maximum size. If the cache exceeds the max,
it is thrown out and a new one made. With such behavior, it is wise to set
the cache just a little larger that the maximum expected need.
Parameters:
max_cache_size - the size to which a cache can grow
Limitations:
The cache works only on args, not kwargs | [
"Python",
"2",
".",
"4",
"compatible",
"memoize",
"decorator",
".",
"It",
"creates",
"a",
"cache",
"that",
"has",
"a",
"maximum",
"size",
".",
"If",
"the",
"cache",
"exceeds",
"the",
"max",
"it",
"is",
"thrown",
"out",
"and",
"a",
"new",
"one",
"made",... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/ver_tools.py#L27-L53 |
mozilla/socorrolib | socorrolib/lib/ver_tools.py | normalize | def normalize(version_string, max_version_parts=4):
"""turn a string representing a version into a normalized version list.
Version lists are directly comparable using standard operators such as
>, <, ==, etc.
Parameters:
version_string - such as '3.5' or '3.6.3plugin3'
max_version_parts - version strings are comprised of a series of 4 tuples.
This should be set to the maximum number of 4 tuples
in a version string.
"""
version_list = []
for part_count, version_part in enumerate(version_string.split('.')):
try:
groups = _version_part_re.match(version_part).groups()
except Exception, x:
raise NotAVersionException(version_string)
version_list.extend(t(x) for x, t in zip(groups, _normalize_fn_list))
version_list.extend(_padding_list * (max_version_parts - part_count - 1))
return version_list | python | def normalize(version_string, max_version_parts=4):
"""turn a string representing a version into a normalized version list.
Version lists are directly comparable using standard operators such as
>, <, ==, etc.
Parameters:
version_string - such as '3.5' or '3.6.3plugin3'
max_version_parts - version strings are comprised of a series of 4 tuples.
This should be set to the maximum number of 4 tuples
in a version string.
"""
version_list = []
for part_count, version_part in enumerate(version_string.split('.')):
try:
groups = _version_part_re.match(version_part).groups()
except Exception, x:
raise NotAVersionException(version_string)
version_list.extend(t(x) for x, t in zip(groups, _normalize_fn_list))
version_list.extend(_padding_list * (max_version_parts - part_count - 1))
return version_list | [
"def",
"normalize",
"(",
"version_string",
",",
"max_version_parts",
"=",
"4",
")",
":",
"version_list",
"=",
"[",
"]",
"for",
"part_count",
",",
"version_part",
"in",
"enumerate",
"(",
"version_string",
".",
"split",
"(",
"'.'",
")",
")",
":",
"try",
":",... | turn a string representing a version into a normalized version list.
Version lists are directly comparable using standard operators such as
>, <, ==, etc.
Parameters:
version_string - such as '3.5' or '3.6.3plugin3'
max_version_parts - version strings are comprised of a series of 4 tuples.
This should be set to the maximum number of 4 tuples
in a version string. | [
"turn",
"a",
"string",
"representing",
"a",
"version",
"into",
"a",
"normalized",
"version",
"list",
".",
"Version",
"lists",
"are",
"directly",
"comparable",
"using",
"standard",
"operators",
"such",
"as",
">",
"<",
"==",
"etc",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/ver_tools.py#L116-L135 |
mozilla/socorrolib | socorrolib/lib/ver_tools.py | _do_denormalize | def _do_denormalize (version_tuple):
"""separate action function to allow for the memoize decorator. Lists,
the most common thing passed in to the 'denormalize' below are not hashable.
"""
version_parts_list = []
for parts_tuple in itertools.imap(None,*([iter(version_tuple)]*4)):
version_part = ''.join(fn(x) for fn, x in
zip(_denormalize_fn_list, parts_tuple))
if version_part:
version_parts_list.append(version_part)
return '.'.join(version_parts_list) | python | def _do_denormalize (version_tuple):
"""separate action function to allow for the memoize decorator. Lists,
the most common thing passed in to the 'denormalize' below are not hashable.
"""
version_parts_list = []
for parts_tuple in itertools.imap(None,*([iter(version_tuple)]*4)):
version_part = ''.join(fn(x) for fn, x in
zip(_denormalize_fn_list, parts_tuple))
if version_part:
version_parts_list.append(version_part)
return '.'.join(version_parts_list) | [
"def",
"_do_denormalize",
"(",
"version_tuple",
")",
":",
"version_parts_list",
"=",
"[",
"]",
"for",
"parts_tuple",
"in",
"itertools",
".",
"imap",
"(",
"None",
",",
"*",
"(",
"[",
"iter",
"(",
"version_tuple",
")",
"]",
"*",
"4",
")",
")",
":",
"vers... | separate action function to allow for the memoize decorator. Lists,
the most common thing passed in to the 'denormalize' below are not hashable. | [
"separate",
"action",
"function",
"to",
"allow",
"for",
"the",
"memoize",
"decorator",
".",
"Lists",
"the",
"most",
"common",
"thing",
"passed",
"in",
"to",
"the",
"denormalize",
"below",
"are",
"not",
"hashable",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/ver_tools.py#L138-L148 |
mozilla/socorrolib | socorrolib/lib/ver_tools.py | compare | def compare (v1, v2):
"""old style __cmp__ function returning -1, 0, 1"""
v1_norm = normalize(v1)
v2_norm = normalize(v2)
if v1_norm < v2_norm:
return -1
if v1_norm > v2_norm:
return 1
return 0 | python | def compare (v1, v2):
"""old style __cmp__ function returning -1, 0, 1"""
v1_norm = normalize(v1)
v2_norm = normalize(v2)
if v1_norm < v2_norm:
return -1
if v1_norm > v2_norm:
return 1
return 0 | [
"def",
"compare",
"(",
"v1",
",",
"v2",
")",
":",
"v1_norm",
"=",
"normalize",
"(",
"v1",
")",
"v2_norm",
"=",
"normalize",
"(",
"v2",
")",
"if",
"v1_norm",
"<",
"v2_norm",
":",
"return",
"-",
"1",
"if",
"v1_norm",
">",
"v2_norm",
":",
"return",
"1... | old style __cmp__ function returning -1, 0, 1 | [
"old",
"style",
"__cmp__",
"function",
"returning",
"-",
"1",
"0",
"1"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/ver_tools.py#L164-L172 |
COLORFULBOARD/revision | revision/history.py | History.current_revision | def current_revision(self):
"""
:return: The current :class:`revision.data.Revision`.
:rtype: :class:`revision.data.Revision`
"""
if self.current_index is None:
return None
if len(self.revisions) > self.current_index:
return self.revisions[self.current_index]
return None | python | def current_revision(self):
"""
:return: The current :class:`revision.data.Revision`.
:rtype: :class:`revision.data.Revision`
"""
if self.current_index is None:
return None
if len(self.revisions) > self.current_index:
return self.revisions[self.current_index]
return None | [
"def",
"current_revision",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_index",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"self",
".",
"revisions",
")",
">",
"self",
".",
"current_index",
":",
"return",
"self",
".",
"revisions",
"[",
... | :return: The current :class:`revision.data.Revision`.
:rtype: :class:`revision.data.Revision` | [
":",
"return",
":",
"The",
"current",
":",
"class",
":",
"revision",
".",
"data",
".",
"Revision",
".",
":",
"rtype",
":",
":",
"class",
":",
"revision",
".",
"data",
".",
"Revision"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/history.py#L34-L45 |
COLORFULBOARD/revision | revision/history.py | History.load | def load(self, revision_path):
"""
Load revision file.
:param revision_path:
:type revision_path: str
"""
if not os.path.exists(revision_path):
raise RuntimeError("revision file does not exist.")
with open(revision_path, mode='r') as f:
text = f.read()
rev_strings = text.split("## ")
for rev_string in rev_strings:
if len(rev_string) == 0 or rev_string[:2] == "# ":
continue
try:
revision = Revision()
revision.parse(rev_string)
except RuntimeError:
raise RuntimeError("")
self.insert(revision, len(self.revisions)) | python | def load(self, revision_path):
"""
Load revision file.
:param revision_path:
:type revision_path: str
"""
if not os.path.exists(revision_path):
raise RuntimeError("revision file does not exist.")
with open(revision_path, mode='r') as f:
text = f.read()
rev_strings = text.split("## ")
for rev_string in rev_strings:
if len(rev_string) == 0 or rev_string[:2] == "# ":
continue
try:
revision = Revision()
revision.parse(rev_string)
except RuntimeError:
raise RuntimeError("")
self.insert(revision, len(self.revisions)) | [
"def",
"load",
"(",
"self",
",",
"revision_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"revision_path",
")",
":",
"raise",
"RuntimeError",
"(",
"\"revision file does not exist.\"",
")",
"with",
"open",
"(",
"revision_path",
",",
"mod... | Load revision file.
:param revision_path:
:type revision_path: str | [
"Load",
"revision",
"file",
"."
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/history.py#L47-L71 |
COLORFULBOARD/revision | revision/history.py | History.checkout | def checkout(self, revision_id):
"""
:param revision_id: :class:`revision.data.Revision` ID.
:type revision_id: str
"""
index = 0
found = False
for revision in self.revisions:
if revision.revision_id == revision_id:
self.current_index = index
found = True
index += 1
if not found:
raise RuntimeError("") | python | def checkout(self, revision_id):
"""
:param revision_id: :class:`revision.data.Revision` ID.
:type revision_id: str
"""
index = 0
found = False
for revision in self.revisions:
if revision.revision_id == revision_id:
self.current_index = index
found = True
index += 1
if not found:
raise RuntimeError("") | [
"def",
"checkout",
"(",
"self",
",",
"revision_id",
")",
":",
"index",
"=",
"0",
"found",
"=",
"False",
"for",
"revision",
"in",
"self",
".",
"revisions",
":",
"if",
"revision",
".",
"revision_id",
"==",
"revision_id",
":",
"self",
".",
"current_index",
... | :param revision_id: :class:`revision.data.Revision` ID.
:type revision_id: str | [
":",
"param",
"revision_id",
":",
":",
"class",
":",
"revision",
".",
"data",
".",
"Revision",
"ID",
".",
":",
"type",
"revision_id",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/history.py#L82-L97 |
COLORFULBOARD/revision | revision/history.py | History.insert | def insert(self, revision, index):
"""
Insert a :class:`revision.data.Revision` at a given index.
:param revision:
:type revision: :class:`revision.data.Revision`
:param index:
:type index: int
"""
if not isinstance(revision, Revision):
raise InvalidArgType()
for rev in self.revisions:
if rev == revision:
return self
self.revisions.insert(index, revision)
return self | python | def insert(self, revision, index):
"""
Insert a :class:`revision.data.Revision` at a given index.
:param revision:
:type revision: :class:`revision.data.Revision`
:param index:
:type index: int
"""
if not isinstance(revision, Revision):
raise InvalidArgType()
for rev in self.revisions:
if rev == revision:
return self
self.revisions.insert(index, revision)
return self | [
"def",
"insert",
"(",
"self",
",",
"revision",
",",
"index",
")",
":",
"if",
"not",
"isinstance",
"(",
"revision",
",",
"Revision",
")",
":",
"raise",
"InvalidArgType",
"(",
")",
"for",
"rev",
"in",
"self",
".",
"revisions",
":",
"if",
"rev",
"==",
"... | Insert a :class:`revision.data.Revision` at a given index.
:param revision:
:type revision: :class:`revision.data.Revision`
:param index:
:type index: int | [
"Insert",
"a",
":",
"class",
":",
"revision",
".",
"data",
".",
"Revision",
"at",
"a",
"given",
"index",
"."
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/history.py#L109-L127 |
twneale/visitors | visitors/ext/pyast.py | from_ast | def from_ast(
pyast_node, node=None, node_cls=None, Node=Node,
iter_fields=ast.iter_fields, AST=ast.AST):
'''Convert the ast tree to a tater tree.
'''
node_cls = node_cls or Node
node = node or node_cls()
name = pyast_node.__class__.__name__
attrs = []
for field, value in iter_fields(pyast_node):
if name == 'Dict':
for key, value in zip(pyast_node.keys, pyast_node.values):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
value = from_ast(item)
elif isinstance(value, AST):
value = from_ast(value)
attrs.append((key.s, value))
else:
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
value = from_ast(item)
elif isinstance(value, AST):
value = from_ast(value)
attrs.append((field, value))
node.update(attrs, type=name)
return node | python | def from_ast(
pyast_node, node=None, node_cls=None, Node=Node,
iter_fields=ast.iter_fields, AST=ast.AST):
'''Convert the ast tree to a tater tree.
'''
node_cls = node_cls or Node
node = node or node_cls()
name = pyast_node.__class__.__name__
attrs = []
for field, value in iter_fields(pyast_node):
if name == 'Dict':
for key, value in zip(pyast_node.keys, pyast_node.values):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
value = from_ast(item)
elif isinstance(value, AST):
value = from_ast(value)
attrs.append((key.s, value))
else:
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
value = from_ast(item)
elif isinstance(value, AST):
value = from_ast(value)
attrs.append((field, value))
node.update(attrs, type=name)
return node | [
"def",
"from_ast",
"(",
"pyast_node",
",",
"node",
"=",
"None",
",",
"node_cls",
"=",
"None",
",",
"Node",
"=",
"Node",
",",
"iter_fields",
"=",
"ast",
".",
"iter_fields",
",",
"AST",
"=",
"ast",
".",
"AST",
")",
":",
"node_cls",
"=",
"node_cls",
"or... | Convert the ast tree to a tater tree. | [
"Convert",
"the",
"ast",
"tree",
"to",
"a",
"tater",
"tree",
"."
] | train | https://github.com/twneale/visitors/blob/17a2759fb0ddc0a039cf42e1bbb053295b3b2445/visitors/ext/pyast.py#L26-L55 |
twneale/visitors | visitors/ext/pyast.py | _AstConverter.generic_visit | def generic_visit(self, node, iter_fields=ast.iter_fields, AST=ast.AST):
"""Called if no explicit visitor function exists for a node.
"""
for field, value in iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value) | python | def generic_visit(self, node, iter_fields=ast.iter_fields, AST=ast.AST):
"""Called if no explicit visitor function exists for a node.
"""
for field, value in iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(value) | [
"def",
"generic_visit",
"(",
"self",
",",
"node",
",",
"iter_fields",
"=",
"ast",
".",
"iter_fields",
",",
"AST",
"=",
"ast",
".",
"AST",
")",
":",
"for",
"field",
",",
"value",
"in",
"iter_fields",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"va... | Called if no explicit visitor function exists for a node. | [
"Called",
"if",
"no",
"explicit",
"visitor",
"function",
"exists",
"for",
"a",
"node",
"."
] | train | https://github.com/twneale/visitors/blob/17a2759fb0ddc0a039cf42e1bbb053295b3b2445/visitors/ext/pyast.py#L14-L23 |
ttinies/sc2ladderMgmt | sc2ladderMgmt/ladders.py | Ladder._validateAttrs | def _validateAttrs(self, keys):
"""prove that all attributes are defined appropriately"""
badAttrsMsg = ""
for k in keys:
if k not in self.attrs:
badAttrsMsg += "Attribute key '%s' is not a valid attribute"%(k)
if badAttrsMsg:
raise ValueError("Encountered invalid attributes. ALLOWED: %s%s%s"\
%(list(self.attrs), os.linesep, badAttrsMsg)) | python | def _validateAttrs(self, keys):
"""prove that all attributes are defined appropriately"""
badAttrsMsg = ""
for k in keys:
if k not in self.attrs:
badAttrsMsg += "Attribute key '%s' is not a valid attribute"%(k)
if badAttrsMsg:
raise ValueError("Encountered invalid attributes. ALLOWED: %s%s%s"\
%(list(self.attrs), os.linesep, badAttrsMsg)) | [
"def",
"_validateAttrs",
"(",
"self",
",",
"keys",
")",
":",
"badAttrsMsg",
"=",
"\"\"",
"for",
"k",
"in",
"keys",
":",
"if",
"k",
"not",
"in",
"self",
".",
"attrs",
":",
"badAttrsMsg",
"+=",
"\"Attribute key '%s' is not a valid attribute\"",
"%",
"(",
"k",
... | prove that all attributes are defined appropriately | [
"prove",
"that",
"all",
"attributes",
"are",
"defined",
"appropriately"
] | train | https://github.com/ttinies/sc2ladderMgmt/blob/230292e18c54e43129c162116bbdf743b3e9dcf1/sc2ladderMgmt/ladders.py#L54-L62 |
ttinies/sc2ladderMgmt | sc2ladderMgmt/ladders.py | Ladder.load | def load(self, ladderName):
"""retrieve the ladder settings from saved disk file"""
self.name = ladderName # preset value to load self.filename
with open(self.filename, "rb") as f:
data = f.read()
self.__dict__.update( json.loads(data) ) | python | def load(self, ladderName):
"""retrieve the ladder settings from saved disk file"""
self.name = ladderName # preset value to load self.filename
with open(self.filename, "rb") as f:
data = f.read()
self.__dict__.update( json.loads(data) ) | [
"def",
"load",
"(",
"self",
",",
"ladderName",
")",
":",
"self",
".",
"name",
"=",
"ladderName",
"# preset value to load self.filename",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",... | retrieve the ladder settings from saved disk file | [
"retrieve",
"the",
"ladder",
"settings",
"from",
"saved",
"disk",
"file"
] | train | https://github.com/ttinies/sc2ladderMgmt/blob/230292e18c54e43129c162116bbdf743b3e9dcf1/sc2ladderMgmt/ladders.py#L64-L69 |
ttinies/sc2ladderMgmt | sc2ladderMgmt/ladders.py | Ladder.update | def update(self, attrs):
"""update attributes initialized with the proper type"""
self._validateAttrs(attrs)
for k,v in attrs.items():
typecast = type( getattr(self, k) )
if typecast==bool and v=="False": newval = False # "False" evalued as boolean is True because its length > 0
else: newval = typecast(v.lower())
setattr(self, k, newval) | python | def update(self, attrs):
"""update attributes initialized with the proper type"""
self._validateAttrs(attrs)
for k,v in attrs.items():
typecast = type( getattr(self, k) )
if typecast==bool and v=="False": newval = False # "False" evalued as boolean is True because its length > 0
else: newval = typecast(v.lower())
setattr(self, k, newval) | [
"def",
"update",
"(",
"self",
",",
"attrs",
")",
":",
"self",
".",
"_validateAttrs",
"(",
"attrs",
")",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"typecast",
"=",
"type",
"(",
"getattr",
"(",
"self",
",",
"k",
")",
")",
... | update attributes initialized with the proper type | [
"update",
"attributes",
"initialized",
"with",
"the",
"proper",
"type"
] | train | https://github.com/ttinies/sc2ladderMgmt/blob/230292e18c54e43129c162116bbdf743b3e9dcf1/sc2ladderMgmt/ladders.py#L77-L84 |
alexhayes/django-geopostcodes | django_geopostcodes/helpers.py | import_localities | def import_localities(path, delimiter=';'):
"""
Import localities from a CSV file.
:param path: Path to the CSV file containing the localities.
"""
creates = []
updates = []
with open(path, mode="r") as infile:
reader = csv.DictReader(infile, delimiter=str(delimiter))
with atomic():
for row in reader:
row['point'] = Point(float(row['longitude']),
float(row['latitude']))
locality, created = Locality.objects.update_or_create(
id=row['id'],
defaults=row
)
if created:
creates.append(locality)
else:
updates.append(locality)
return creates, updates | python | def import_localities(path, delimiter=';'):
"""
Import localities from a CSV file.
:param path: Path to the CSV file containing the localities.
"""
creates = []
updates = []
with open(path, mode="r") as infile:
reader = csv.DictReader(infile, delimiter=str(delimiter))
with atomic():
for row in reader:
row['point'] = Point(float(row['longitude']),
float(row['latitude']))
locality, created = Locality.objects.update_or_create(
id=row['id'],
defaults=row
)
if created:
creates.append(locality)
else:
updates.append(locality)
return creates, updates | [
"def",
"import_localities",
"(",
"path",
",",
"delimiter",
"=",
"';'",
")",
":",
"creates",
"=",
"[",
"]",
"updates",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
",",
"mode",
"=",
"\"r\"",
")",
"as",
"infile",
":",
"reader",
"=",
"csv",
".",
"DictR... | Import localities from a CSV file.
:param path: Path to the CSV file containing the localities. | [
"Import",
"localities",
"from",
"a",
"CSV",
"file",
"."
] | train | https://github.com/alexhayes/django-geopostcodes/blob/325c7306e5939a576571e49b0889d08a0d138dfa/django_geopostcodes/helpers.py#L18-L44 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription.py | get_netid_subscriptions | def get_netid_subscriptions(netid, subscription_codes):
"""
Returns a list of uwnetid.subscription objects
corresponding to the netid and subscription code or list provided
"""
url = _netid_subscription_url(netid, subscription_codes)
response = get_resource(url)
return _json_to_subscriptions(response) | python | def get_netid_subscriptions(netid, subscription_codes):
"""
Returns a list of uwnetid.subscription objects
corresponding to the netid and subscription code or list provided
"""
url = _netid_subscription_url(netid, subscription_codes)
response = get_resource(url)
return _json_to_subscriptions(response) | [
"def",
"get_netid_subscriptions",
"(",
"netid",
",",
"subscription_codes",
")",
":",
"url",
"=",
"_netid_subscription_url",
"(",
"netid",
",",
"subscription_codes",
")",
"response",
"=",
"get_resource",
"(",
"url",
")",
"return",
"_json_to_subscriptions",
"(",
"resp... | Returns a list of uwnetid.subscription objects
corresponding to the netid and subscription code or list provided | [
"Returns",
"a",
"list",
"of",
"uwnetid",
".",
"subscription",
"objects",
"corresponding",
"to",
"the",
"netid",
"and",
"subscription",
"code",
"or",
"list",
"provided"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription.py#L36-L43 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription.py | select_subscription | def select_subscription(subs_code, subscriptions):
"""
Return the uwnetid.subscription object with the subs_code.
"""
if subs_code and subscriptions:
for subs in subscriptions:
if (subs.subscription_code == subs_code):
return subs
return None | python | def select_subscription(subs_code, subscriptions):
"""
Return the uwnetid.subscription object with the subs_code.
"""
if subs_code and subscriptions:
for subs in subscriptions:
if (subs.subscription_code == subs_code):
return subs
return None | [
"def",
"select_subscription",
"(",
"subs_code",
",",
"subscriptions",
")",
":",
"if",
"subs_code",
"and",
"subscriptions",
":",
"for",
"subs",
"in",
"subscriptions",
":",
"if",
"(",
"subs",
".",
"subscription_code",
"==",
"subs_code",
")",
":",
"return",
"subs... | Return the uwnetid.subscription object with the subs_code. | [
"Return",
"the",
"uwnetid",
".",
"subscription",
"object",
"with",
"the",
"subs_code",
"."
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription.py#L46-L54 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription.py | modify_subscription_status | def modify_subscription_status(netid, subscription_code, status):
"""
Post a subscription 'modify' action for the given netid
and subscription_code
"""
url = _netid_subscription_url(netid, subscription_code)
body = {
'action': 'modify',
'value': str(status)
}
response = post_resource(url, json.dumps(body))
return _json_to_subscriptions(response) | python | def modify_subscription_status(netid, subscription_code, status):
"""
Post a subscription 'modify' action for the given netid
and subscription_code
"""
url = _netid_subscription_url(netid, subscription_code)
body = {
'action': 'modify',
'value': str(status)
}
response = post_resource(url, json.dumps(body))
return _json_to_subscriptions(response) | [
"def",
"modify_subscription_status",
"(",
"netid",
",",
"subscription_code",
",",
"status",
")",
":",
"url",
"=",
"_netid_subscription_url",
"(",
"netid",
",",
"subscription_code",
")",
"body",
"=",
"{",
"'action'",
":",
"'modify'",
",",
"'value'",
":",
"str",
... | Post a subscription 'modify' action for the given netid
and subscription_code | [
"Post",
"a",
"subscription",
"modify",
"action",
"for",
"the",
"given",
"netid",
"and",
"subscription_code"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription.py#L57-L69 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription.py | update_subscription | def update_subscription(netid, action, subscription_code, data_field=None):
"""
Post a subscription action for the given netid and subscription_code
"""
url = '{0}/subscription.json'.format(url_version())
action_list = []
if isinstance(subscription_code, list):
for code in subscription_code:
action_list.append(_set_action(
netid, action, code, data_field))
else:
action_list.append(_set_action(
netid, action, subscription_code, data_field))
body = {'actionList': action_list}
response = post_resource(url, json.dumps(body))
return _json_to_subscription_post_response(response) | python | def update_subscription(netid, action, subscription_code, data_field=None):
"""
Post a subscription action for the given netid and subscription_code
"""
url = '{0}/subscription.json'.format(url_version())
action_list = []
if isinstance(subscription_code, list):
for code in subscription_code:
action_list.append(_set_action(
netid, action, code, data_field))
else:
action_list.append(_set_action(
netid, action, subscription_code, data_field))
body = {'actionList': action_list}
response = post_resource(url, json.dumps(body))
return _json_to_subscription_post_response(response) | [
"def",
"update_subscription",
"(",
"netid",
",",
"action",
",",
"subscription_code",
",",
"data_field",
"=",
"None",
")",
":",
"url",
"=",
"'{0}/subscription.json'",
".",
"format",
"(",
"url_version",
"(",
")",
")",
"action_list",
"=",
"[",
"]",
"if",
"isins... | Post a subscription action for the given netid and subscription_code | [
"Post",
"a",
"subscription",
"action",
"for",
"the",
"given",
"netid",
"and",
"subscription_code"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription.py#L72-L89 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription.py | _netid_subscription_url | def _netid_subscription_url(netid, subscription_codes):
"""
Return UWNetId resource for provided netid and subscription
code or code list
"""
return "{0}/{1}/subscription/{2}".format(
url_base(), netid,
(','.join([str(n) for n in subscription_codes])
if isinstance(subscription_codes, (list, tuple))
else subscription_codes)) | python | def _netid_subscription_url(netid, subscription_codes):
"""
Return UWNetId resource for provided netid and subscription
code or code list
"""
return "{0}/{1}/subscription/{2}".format(
url_base(), netid,
(','.join([str(n) for n in subscription_codes])
if isinstance(subscription_codes, (list, tuple))
else subscription_codes)) | [
"def",
"_netid_subscription_url",
"(",
"netid",
",",
"subscription_codes",
")",
":",
"return",
"\"{0}/{1}/subscription/{2}\"",
".",
"format",
"(",
"url_base",
"(",
")",
",",
"netid",
",",
"(",
"','",
".",
"join",
"(",
"[",
"str",
"(",
"n",
")",
"for",
"n",... | Return UWNetId resource for provided netid and subscription
code or code list | [
"Return",
"UWNetId",
"resource",
"for",
"provided",
"netid",
"and",
"subscription",
"code",
"or",
"code",
"list"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription.py#L108-L117 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription.py | _json_to_subscriptions | def _json_to_subscriptions(response_body):
"""
Returns a list of Subscription objects
"""
data = json.loads(response_body)
subscriptions = []
for subscription_data in data.get("subscriptionList", []):
subscriptions.append(Subscription().from_json(
data.get('uwNetID'), subscription_data))
return subscriptions | python | def _json_to_subscriptions(response_body):
"""
Returns a list of Subscription objects
"""
data = json.loads(response_body)
subscriptions = []
for subscription_data in data.get("subscriptionList", []):
subscriptions.append(Subscription().from_json(
data.get('uwNetID'), subscription_data))
return subscriptions | [
"def",
"_json_to_subscriptions",
"(",
"response_body",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"response_body",
")",
"subscriptions",
"=",
"[",
"]",
"for",
"subscription_data",
"in",
"data",
".",
"get",
"(",
"\"subscriptionList\"",
",",
"[",
"]",
"... | Returns a list of Subscription objects | [
"Returns",
"a",
"list",
"of",
"Subscription",
"objects"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription.py#L120-L130 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription.py | _json_to_subscription_post_response | def _json_to_subscription_post_response(response_body):
"""
Returns a list of SubscriptionPostResponse objects
"""
data = json.loads(response_body)
response_list = []
for response_data in data.get("responseList", []):
response_list.append(SubscriptionPostResponse().from_json(
data.get('uwNetID'), response_data))
return response_list | python | def _json_to_subscription_post_response(response_body):
"""
Returns a list of SubscriptionPostResponse objects
"""
data = json.loads(response_body)
response_list = []
for response_data in data.get("responseList", []):
response_list.append(SubscriptionPostResponse().from_json(
data.get('uwNetID'), response_data))
return response_list | [
"def",
"_json_to_subscription_post_response",
"(",
"response_body",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"response_body",
")",
"response_list",
"=",
"[",
"]",
"for",
"response_data",
"in",
"data",
".",
"get",
"(",
"\"responseList\"",
",",
"[",
"]"... | Returns a list of SubscriptionPostResponse objects | [
"Returns",
"a",
"list",
"of",
"SubscriptionPostResponse",
"objects"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription.py#L133-L143 |
chewse/djangorestframework-signed-permissions | signedpermissions/permissions.py | SignedPermission.has_permission | def has_permission(self, request, view):
"""Check list and create permissions based on sign and filters."""
if view.suffix == 'Instance':
return True
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
'{}.{}'.format(
view.queryset.model._meta.app_label,
view.queryset.model._meta.model_name
)
)
if not filter_and_actions:
return False
if request.method == 'POST':
for key, value in request.data.iteritems():
# Do unicode conversion because value will always be a
# string
if (key in filter_and_actions['filters'] and not
unicode(filter_and_actions['filters'][key]) == unicode(value)):
return False
return True | python | def has_permission(self, request, view):
"""Check list and create permissions based on sign and filters."""
if view.suffix == 'Instance':
return True
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
'{}.{}'.format(
view.queryset.model._meta.app_label,
view.queryset.model._meta.model_name
)
)
if not filter_and_actions:
return False
if request.method == 'POST':
for key, value in request.data.iteritems():
# Do unicode conversion because value will always be a
# string
if (key in filter_and_actions['filters'] and not
unicode(filter_and_actions['filters'][key]) == unicode(value)):
return False
return True | [
"def",
"has_permission",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"if",
"view",
".",
"suffix",
"==",
"'Instance'",
":",
"return",
"True",
"filter_and_actions",
"=",
"self",
".",
"_get_filter_and_actions",
"(",
"request",
".",
"query_params",
".",
... | Check list and create permissions based on sign and filters. | [
"Check",
"list",
"and",
"create",
"permissions",
"based",
"on",
"sign",
"and",
"filters",
"."
] | train | https://github.com/chewse/djangorestframework-signed-permissions/blob/b1cc4c57999fc5be8361f60f0ada1d777b27feab/signedpermissions/permissions.py#L19-L41 |
chewse/djangorestframework-signed-permissions | signedpermissions/permissions.py | SignedPermission.has_object_permission | def has_object_permission(self, request, view, obj=None):
"""Check object permissions based on filters."""
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
'{}.{}'.format(obj._meta.app_label, obj._meta.model_name))
if not filter_and_actions:
return False
qs = view.queryset.filter(**filter_and_actions['filters'])
return qs.filter(id=obj.id).exists() | python | def has_object_permission(self, request, view, obj=None):
"""Check object permissions based on filters."""
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
'{}.{}'.format(obj._meta.app_label, obj._meta.model_name))
if not filter_and_actions:
return False
qs = view.queryset.filter(**filter_and_actions['filters'])
return qs.filter(id=obj.id).exists() | [
"def",
"has_object_permission",
"(",
"self",
",",
"request",
",",
"view",
",",
"obj",
"=",
"None",
")",
":",
"filter_and_actions",
"=",
"self",
".",
"_get_filter_and_actions",
"(",
"request",
".",
"query_params",
".",
"get",
"(",
"'sign'",
")",
",",
"view",
... | Check object permissions based on filters. | [
"Check",
"object",
"permissions",
"based",
"on",
"filters",
"."
] | train | https://github.com/chewse/djangorestframework-signed-permissions/blob/b1cc4c57999fc5be8361f60f0ada1d777b27feab/signedpermissions/permissions.py#L43-L52 |
BD2KOnFHIR/i2b2model | i2b2model/sqlsupport/file_aware_parser.py | FileAwareParser.add_file_argument | def add_file_argument(self, *args, **kwargs):
""" Add an argument that represents the location of a file
:param args:
:param kwargs:
:return:
"""
rval = self.add_argument(*args, **kwargs)
self.file_args.append(rval)
return rval | python | def add_file_argument(self, *args, **kwargs):
""" Add an argument that represents the location of a file
:param args:
:param kwargs:
:return:
"""
rval = self.add_argument(*args, **kwargs)
self.file_args.append(rval)
return rval | [
"def",
"add_file_argument",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rval",
"=",
"self",
".",
"add_argument",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"file_args",
".",
"append",
"(",
"rval",
")",
"retu... | Add an argument that represents the location of a file
:param args:
:param kwargs:
:return: | [
"Add",
"an",
"argument",
"that",
"represents",
"the",
"location",
"of",
"a",
"file"
] | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/sqlsupport/file_aware_parser.py#L21-L30 |
BD2KOnFHIR/i2b2model | i2b2model/sqlsupport/file_aware_parser.py | FileAwareParser.add_argument | def add_argument(self, *args, **kwargs):
""" Add an argument incorporating the default value into the help string
:param args:
:param kwargs:
:return:
"""
defhelp = kwargs.pop("help", None)
defaults = kwargs.pop("default", None)
default = defaults if self.use_defaults else None
if not defhelp or default is None or kwargs.get('action') == 'help':
return super().add_argument(*args, help=defhelp, default=default, **kwargs)
else:
return super().add_argument(*args, help=defhelp + " (default: {})".format(default),
default=default, **kwargs) | python | def add_argument(self, *args, **kwargs):
""" Add an argument incorporating the default value into the help string
:param args:
:param kwargs:
:return:
"""
defhelp = kwargs.pop("help", None)
defaults = kwargs.pop("default", None)
default = defaults if self.use_defaults else None
if not defhelp or default is None or kwargs.get('action') == 'help':
return super().add_argument(*args, help=defhelp, default=default, **kwargs)
else:
return super().add_argument(*args, help=defhelp + " (default: {})".format(default),
default=default, **kwargs) | [
"def",
"add_argument",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"defhelp",
"=",
"kwargs",
".",
"pop",
"(",
"\"help\"",
",",
"None",
")",
"defaults",
"=",
"kwargs",
".",
"pop",
"(",
"\"default\"",
",",
"None",
")",
"default",
... | Add an argument incorporating the default value into the help string
:param args:
:param kwargs:
:return: | [
"Add",
"an",
"argument",
"incorporating",
"the",
"default",
"value",
"into",
"the",
"help",
"string"
] | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/sqlsupport/file_aware_parser.py#L32-L46 |
BD2KOnFHIR/i2b2model | i2b2model/sqlsupport/file_aware_parser.py | FileAwareParser.decode_file_args | def decode_file_args(self, argv: List[str]) -> List[str]:
"""
Preprocess a configuration file. The location of the configuration file is stored in the parser so that the
FileOrURI action can add relative locations.
:param argv: raw options list
:return: options list with '--conf' references replaced with file contents
"""
for i in range(0, len(argv) - 1):
# TODO: take prefix into account
if argv[i] == '--conf':
del argv[i]
conf_file = argv[i]
del (argv[i])
with open(conf_file) as config_file:
conf_args = shlex.split(config_file.read())
# We take advantage of a poential bug in the parser where you can say "foo -u 1 -u 2" and get
# 2 as a result
argv = self.fix_rel_paths(conf_args, conf_file) + argv
return self.decode_file_args(argv)
return argv | python | def decode_file_args(self, argv: List[str]) -> List[str]:
"""
Preprocess a configuration file. The location of the configuration file is stored in the parser so that the
FileOrURI action can add relative locations.
:param argv: raw options list
:return: options list with '--conf' references replaced with file contents
"""
for i in range(0, len(argv) - 1):
# TODO: take prefix into account
if argv[i] == '--conf':
del argv[i]
conf_file = argv[i]
del (argv[i])
with open(conf_file) as config_file:
conf_args = shlex.split(config_file.read())
# We take advantage of a poential bug in the parser where you can say "foo -u 1 -u 2" and get
# 2 as a result
argv = self.fix_rel_paths(conf_args, conf_file) + argv
return self.decode_file_args(argv)
return argv | [
"def",
"decode_file_args",
"(",
"self",
",",
"argv",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"argv",
")",
"-",
"1",
")",
":",
"# TODO: take prefix into account",
"... | Preprocess a configuration file. The location of the configuration file is stored in the parser so that the
FileOrURI action can add relative locations.
:param argv: raw options list
:return: options list with '--conf' references replaced with file contents | [
"Preprocess",
"a",
"configuration",
"file",
".",
"The",
"location",
"of",
"the",
"configuration",
"file",
"is",
"stored",
"in",
"the",
"parser",
"so",
"that",
"the",
"FileOrURI",
"action",
"can",
"add",
"relative",
"locations",
".",
":",
"param",
"argv",
":"... | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/sqlsupport/file_aware_parser.py#L48-L67 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_Interface | def p_Interface(p):
"""Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";"
"""
p[0] = model.Interface(name=p[2], parent=p[3], members=p[5]) | python | def p_Interface(p):
"""Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";"
"""
p[0] = model.Interface(name=p[2], parent=p[3], members=p[5]) | [
"def",
"p_Interface",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Interface",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"parent",
"=",
"p",
"[",
"3",
"]",
",",
"members",
"=",
"p",
"[",
"5",
"]",
")"
] | Interface : interface IDENTIFIER Inheritance "{" InterfaceMembers "}" ";" | [
"Interface",
":",
"interface",
"IDENTIFIER",
"Inheritance",
"{",
"InterfaceMembers",
"}",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L72-L75 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_Dictionary | def p_Dictionary(p):
"""Dictionary : dictionary IDENTIFIER Inheritance "{" DictionaryMembers "}" ";"
"""
p[0] = model.Dictionary(name=p[2], parent=p[3], members=p[5]) | python | def p_Dictionary(p):
"""Dictionary : dictionary IDENTIFIER Inheritance "{" DictionaryMembers "}" ";"
"""
p[0] = model.Dictionary(name=p[2], parent=p[3], members=p[5]) | [
"def",
"p_Dictionary",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Dictionary",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"parent",
"=",
"p",
"[",
"3",
"]",
",",
"members",
"=",
"p",
"[",
"5",
"]",
")"
] | Dictionary : dictionary IDENTIFIER Inheritance "{" DictionaryMembers "}" ";" | [
"Dictionary",
":",
"dictionary",
"IDENTIFIER",
"Inheritance",
"{",
"DictionaryMembers",
"}",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L112-L115 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_DictionaryMember | def p_DictionaryMember(p):
"""DictionaryMember : Type IDENTIFIER Default ";"
"""
p[0] = model.DictionaryMember(type=p[1], name=p[2], default=p[3]) | python | def p_DictionaryMember(p):
"""DictionaryMember : Type IDENTIFIER Default ";"
"""
p[0] = model.DictionaryMember(type=p[1], name=p[2], default=p[3]) | [
"def",
"p_DictionaryMember",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"DictionaryMember",
"(",
"type",
"=",
"p",
"[",
"1",
"]",
",",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"default",
"=",
"p",
"[",
"3",
"]",
")"
] | DictionaryMember : Type IDENTIFIER Default ";" | [
"DictionaryMember",
":",
"Type",
"IDENTIFIER",
"Default",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L135-L138 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_DefaultValue_string | def p_DefaultValue_string(p):
"""DefaultValue : STRING"""
p[0] = model.Value(type=model.Value.STRING, value=p[1]) | python | def p_DefaultValue_string(p):
"""DefaultValue : STRING"""
p[0] = model.Value(type=model.Value.STRING, value=p[1]) | [
"def",
"p_DefaultValue_string",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"STRING",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | DefaultValue : STRING | [
"DefaultValue",
":",
"STRING"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L165-L167 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_Exception | def p_Exception(p):
"""Exception : exception IDENTIFIER Inheritance "{" ExceptionMembers "}" ";"
"""
p[0] = model.Exception(name=p[2], parent=p[3], members=p[5]) | python | def p_Exception(p):
"""Exception : exception IDENTIFIER Inheritance "{" ExceptionMembers "}" ";"
"""
p[0] = model.Exception(name=p[2], parent=p[3], members=p[5]) | [
"def",
"p_Exception",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Exception",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"parent",
"=",
"p",
"[",
"3",
"]",
",",
"members",
"=",
"p",
"[",
"5",
"]",
")"
] | Exception : exception IDENTIFIER Inheritance "{" ExceptionMembers "}" ";" | [
"Exception",
":",
"exception",
"IDENTIFIER",
"Inheritance",
"{",
"ExceptionMembers",
"}",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L179-L182 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_CallbackRest | def p_CallbackRest(p):
"""CallbackRest : IDENTIFIER "=" ReturnType "(" ArgumentList ")" ";"
"""
p[0] = model.Callback(name=p[1], return_type=p[3], arguments=p[5]) | python | def p_CallbackRest(p):
"""CallbackRest : IDENTIFIER "=" ReturnType "(" ArgumentList ")" ";"
"""
p[0] = model.Callback(name=p[1], return_type=p[3], arguments=p[5]) | [
"def",
"p_CallbackRest",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Callback",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"return_type",
"=",
"p",
"[",
"3",
"]",
",",
"arguments",
"=",
"p",
"[",
"5",
"]",
")"
] | CallbackRest : IDENTIFIER "=" ReturnType "(" ArgumentList ")" ";" | [
"CallbackRest",
":",
"IDENTIFIER",
"=",
"ReturnType",
"(",
"ArgumentList",
")",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L245-L248 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_Typedef | def p_Typedef(p):
"""Typedef : typedef ExtendedAttributeList Type IDENTIFIER ";"
"""
p[0] = model.Typedef(type_extended_attributes=p[2], type=p[3], name=p[4]) | python | def p_Typedef(p):
"""Typedef : typedef ExtendedAttributeList Type IDENTIFIER ";"
"""
p[0] = model.Typedef(type_extended_attributes=p[2], type=p[3], name=p[4]) | [
"def",
"p_Typedef",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Typedef",
"(",
"type_extended_attributes",
"=",
"p",
"[",
"2",
"]",
",",
"type",
"=",
"p",
"[",
"3",
"]",
",",
"name",
"=",
"p",
"[",
"4",
"]",
")"
] | Typedef : typedef ExtendedAttributeList Type IDENTIFIER ";" | [
"Typedef",
":",
"typedef",
"ExtendedAttributeList",
"Type",
"IDENTIFIER",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L253-L256 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_Const | def p_Const(p):
"""Const : const ConstType IDENTIFIER "=" ConstValue ";"
"""
p[0] = model.Const(type=p[2], name=p[3], value=p[5]) | python | def p_Const(p):
"""Const : const ConstType IDENTIFIER "=" ConstValue ";"
"""
p[0] = model.Const(type=p[2], name=p[3], value=p[5]) | [
"def",
"p_Const",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Const",
"(",
"type",
"=",
"p",
"[",
"2",
"]",
",",
"name",
"=",
"p",
"[",
"3",
"]",
",",
"value",
"=",
"p",
"[",
"5",
"]",
")"
] | Const : const ConstType IDENTIFIER "=" ConstValue ";" | [
"Const",
":",
"const",
"ConstType",
"IDENTIFIER",
"=",
"ConstValue",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L269-L272 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ConstValue_boolean | def p_ConstValue_boolean(p):
"""ConstValue : BooleanLiteral"""
p[0] = model.Value(type=model.Value.BOOLEAN, value=p[1]) | python | def p_ConstValue_boolean(p):
"""ConstValue : BooleanLiteral"""
p[0] = model.Value(type=model.Value.BOOLEAN, value=p[1]) | [
"def",
"p_ConstValue_boolean",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"BOOLEAN",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | ConstValue : BooleanLiteral | [
"ConstValue",
":",
"BooleanLiteral"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L277-L279 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ConstValue_integer | def p_ConstValue_integer(p):
"""ConstValue : INTEGER"""
p[0] = model.Value(type=model.Value.INTEGER, value=p[1]) | python | def p_ConstValue_integer(p):
"""ConstValue : INTEGER"""
p[0] = model.Value(type=model.Value.INTEGER, value=p[1]) | [
"def",
"p_ConstValue_integer",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"INTEGER",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | ConstValue : INTEGER | [
"ConstValue",
":",
"INTEGER"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L284-L286 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ConstValue_float | def p_ConstValue_float(p):
"""ConstValue : FLOAT"""
p[0] = model.Value(type=model.Value.FLOAT, value=p[1]) | python | def p_ConstValue_float(p):
"""ConstValue : FLOAT"""
p[0] = model.Value(type=model.Value.FLOAT, value=p[1]) | [
"def",
"p_ConstValue_float",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"FLOAT",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | ConstValue : FLOAT | [
"ConstValue",
":",
"FLOAT"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L291-L293 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ConstValue_null | def p_ConstValue_null(p):
"""ConstValue : null"""
p[0] = model.Value(type=model.Value.NULL, value=p[1]) | python | def p_ConstValue_null(p):
"""ConstValue : null"""
p[0] = model.Value(type=model.Value.NULL, value=p[1]) | [
"def",
"p_ConstValue_null",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"NULL",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | ConstValue : null | [
"ConstValue",
":",
"null"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L298-L300 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_Attribute | def p_Attribute(p):
"""Attribute : Inherit ReadOnly attribute Type IDENTIFIER ";"
"""
p[0] = model.Attribute(inherit=p[1], readonly=p[2], type=p[4], name=p[5]) | python | def p_Attribute(p):
"""Attribute : Inherit ReadOnly attribute Type IDENTIFIER ";"
"""
p[0] = model.Attribute(inherit=p[1], readonly=p[2], type=p[4], name=p[5]) | [
"def",
"p_Attribute",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Attribute",
"(",
"inherit",
"=",
"p",
"[",
"1",
"]",
",",
"readonly",
"=",
"p",
"[",
"2",
"]",
",",
"type",
"=",
"p",
"[",
"4",
"]",
",",
"name",
"=",
"p",
... | Attribute : Inherit ReadOnly attribute Type IDENTIFIER ";" | [
"Attribute",
":",
"Inherit",
"ReadOnly",
"attribute",
"Type",
"IDENTIFIER",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L346-L349 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_OperationRest | def p_OperationRest(p):
"""OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";"
"""
p[0] = model.Operation(return_type=p[1], name=p[2], arguments=p[4]) | python | def p_OperationRest(p):
"""OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";"
"""
p[0] = model.Operation(return_type=p[1], name=p[2], arguments=p[4]) | [
"def",
"p_OperationRest",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Operation",
"(",
"return_type",
"=",
"p",
"[",
"1",
"]",
",",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"arguments",
"=",
"p",
"[",
"4",
"]",
")"
] | OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";" | [
"OperationRest",
":",
"ReturnType",
"OptionalIdentifier",
"(",
"ArgumentList",
")",
";"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L452-L455 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_OptionalOrRequiredArgument_optional | def p_OptionalOrRequiredArgument_optional(p):
"""OptionalOrRequiredArgument : optional Type IDENTIFIER Default"""
p[0] = model.OperationArgument(
type=p[2], name=p[3], optional=True, default=p[4]) | python | def p_OptionalOrRequiredArgument_optional(p):
"""OptionalOrRequiredArgument : optional Type IDENTIFIER Default"""
p[0] = model.OperationArgument(
type=p[2], name=p[3], optional=True, default=p[4]) | [
"def",
"p_OptionalOrRequiredArgument_optional",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"OperationArgument",
"(",
"type",
"=",
"p",
"[",
"2",
"]",
",",
"name",
"=",
"p",
"[",
"3",
"]",
",",
"optional",
"=",
"True",
",",
"default",
... | OptionalOrRequiredArgument : optional Type IDENTIFIER Default | [
"OptionalOrRequiredArgument",
":",
"optional",
"Type",
"IDENTIFIER",
"Default"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L510-L513 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_OptionalOrRequiredArgument | def p_OptionalOrRequiredArgument(p):
"""OptionalOrRequiredArgument : Type Ellipsis IDENTIFIER"""
p[0] = model.OperationArgument(type=p[1], ellipsis=p[2], name=p[3]) | python | def p_OptionalOrRequiredArgument(p):
"""OptionalOrRequiredArgument : Type Ellipsis IDENTIFIER"""
p[0] = model.OperationArgument(type=p[1], ellipsis=p[2], name=p[3]) | [
"def",
"p_OptionalOrRequiredArgument",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"OperationArgument",
"(",
"type",
"=",
"p",
"[",
"1",
"]",
",",
"ellipsis",
"=",
"p",
"[",
"2",
"]",
",",
"name",
"=",
"p",
"[",
"3",
"]",
")"
] | OptionalOrRequiredArgument : Type Ellipsis IDENTIFIER | [
"OptionalOrRequiredArgument",
":",
"Type",
"Ellipsis",
"IDENTIFIER"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L518-L520 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_SingleType_any | def p_SingleType_any(p):
"""SingleType : any TypeSuffixStartingWithArray"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
model.SimpleType.ANY), p[2]) | python | def p_SingleType_any(p):
"""SingleType : any TypeSuffixStartingWithArray"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
model.SimpleType.ANY), p[2]) | [
"def",
"p_SingleType_any",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"helper",
".",
"unwrapTypeSuffix",
"(",
"model",
".",
"SimpleType",
"(",
"model",
".",
"SimpleType",
".",
"ANY",
")",
",",
"p",
"[",
"2",
"]",
")"
] | SingleType : any TypeSuffixStartingWithArray | [
"SingleType",
":",
"any",
"TypeSuffixStartingWithArray"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L714-L717 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_UnionType | def p_UnionType(p):
"""UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")"
"""
t = [p[2]] + [p[4]] + p[5]
p[0] = model.UnionType(t=t) | python | def p_UnionType(p):
"""UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")"
"""
t = [p[2]] + [p[4]] + p[5]
p[0] = model.UnionType(t=t) | [
"def",
"p_UnionType",
"(",
"p",
")",
":",
"t",
"=",
"[",
"p",
"[",
"2",
"]",
"]",
"+",
"[",
"p",
"[",
"4",
"]",
"]",
"+",
"p",
"[",
"5",
"]",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"UnionType",
"(",
"t",
"=",
"t",
")"
] | UnionType : "(" UnionMemberType or UnionMemberType UnionMemberTypes ")" | [
"UnionType",
":",
"(",
"UnionMemberType",
"or",
"UnionMemberType",
"UnionMemberTypes",
")"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L722-L726 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_UnionMemberType_anyType | def p_UnionMemberType_anyType(p):
"""UnionMemberType : any "[" "]" TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.Array(t=model.SimpleType(
type=model.SimpleType.ANY)), p[4]) | python | def p_UnionMemberType_anyType(p):
"""UnionMemberType : any "[" "]" TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.Array(t=model.SimpleType(
type=model.SimpleType.ANY)), p[4]) | [
"def",
"p_UnionMemberType_anyType",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"helper",
".",
"unwrapTypeSuffix",
"(",
"model",
".",
"Array",
"(",
"t",
"=",
"model",
".",
"SimpleType",
"(",
"type",
"=",
"model",
".",
"SimpleType",
".",
"ANY",
")",
... | UnionMemberType : any "[" "]" TypeSuffix | [
"UnionMemberType",
":",
"any",
"[",
"]",
"TypeSuffix"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L745-L748 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_NonAnyType_domString | def p_NonAnyType_domString(p):
"""NonAnyType : DOMString TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
type=model.SimpleType.DOMSTRING), p[2]) | python | def p_NonAnyType_domString(p):
"""NonAnyType : DOMString TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
type=model.SimpleType.DOMSTRING), p[2]) | [
"def",
"p_NonAnyType_domString",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"helper",
".",
"unwrapTypeSuffix",
"(",
"model",
".",
"SimpleType",
"(",
"type",
"=",
"model",
".",
"SimpleType",
".",
"DOMSTRING",
")",
",",
"p",
"[",
"2",
"]",
")"
] | NonAnyType : DOMString TypeSuffix | [
"NonAnyType",
":",
"DOMString",
"TypeSuffix"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L774-L777 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_NonAnyType_interface | def p_NonAnyType_interface(p):
"""NonAnyType : IDENTIFIER TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.InterfaceType(name=p[1]), p[2]) | python | def p_NonAnyType_interface(p):
"""NonAnyType : IDENTIFIER TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.InterfaceType(name=p[1]), p[2]) | [
"def",
"p_NonAnyType_interface",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"helper",
".",
"unwrapTypeSuffix",
"(",
"model",
".",
"InterfaceType",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
")",
",",
"p",
"[",
"2",
"]",
")"
] | NonAnyType : IDENTIFIER TypeSuffix | [
"NonAnyType",
":",
"IDENTIFIER",
"TypeSuffix"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L782-L784 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_NonAnyType_object | def p_NonAnyType_object(p):
"""NonAnyType : object TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
type=model.SimpleType.OBJECT), p[2]) | python | def p_NonAnyType_object(p):
"""NonAnyType : object TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
type=model.SimpleType.OBJECT), p[2]) | [
"def",
"p_NonAnyType_object",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"helper",
".",
"unwrapTypeSuffix",
"(",
"model",
".",
"SimpleType",
"(",
"type",
"=",
"model",
".",
"SimpleType",
".",
"OBJECT",
")",
",",
"p",
"[",
"2",
"]",
")"
] | NonAnyType : object TypeSuffix | [
"NonAnyType",
":",
"object",
"TypeSuffix"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L796-L799 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_NonAnyType | def p_NonAnyType(p):
"""NonAnyType : Date TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
type=model.SimpleType.DATE), p[2]) | python | def p_NonAnyType(p):
"""NonAnyType : Date TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.SimpleType(
type=model.SimpleType.DATE), p[2]) | [
"def",
"p_NonAnyType",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"helper",
".",
"unwrapTypeSuffix",
"(",
"model",
".",
"SimpleType",
"(",
"type",
"=",
"model",
".",
"SimpleType",
".",
"DATE",
")",
",",
"p",
"[",
"2",
"]",
")"
] | NonAnyType : Date TypeSuffix | [
"NonAnyType",
":",
"Date",
"TypeSuffix"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L804-L807 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ExtendedAttributeNoArgs | def p_ExtendedAttributeNoArgs(p):
"""ExtendedAttributeNoArgs : IDENTIFIER"""
p[0] = model.ExtendedAttribute(
value=model.ExtendedAttributeValue(name=p[1])) | python | def p_ExtendedAttributeNoArgs(p):
"""ExtendedAttributeNoArgs : IDENTIFIER"""
p[0] = model.ExtendedAttribute(
value=model.ExtendedAttributeValue(name=p[1])) | [
"def",
"p_ExtendedAttributeNoArgs",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"ExtendedAttribute",
"(",
"value",
"=",
"model",
".",
"ExtendedAttributeValue",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
")",
")"
] | ExtendedAttributeNoArgs : IDENTIFIER | [
"ExtendedAttributeNoArgs",
":",
"IDENTIFIER"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L971-L974 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ExtendedAttributeArgList | def p_ExtendedAttributeArgList(p):
"""ExtendedAttributeArgList : IDENTIFIER "(" ArgumentList ")"
"""
p[0] = model.ExtendedAttribute(
value=model.ExtendedAttributeValue(name=p[1], arguments=p[3])) | python | def p_ExtendedAttributeArgList(p):
"""ExtendedAttributeArgList : IDENTIFIER "(" ArgumentList ")"
"""
p[0] = model.ExtendedAttribute(
value=model.ExtendedAttributeValue(name=p[1], arguments=p[3])) | [
"def",
"p_ExtendedAttributeArgList",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"ExtendedAttribute",
"(",
"value",
"=",
"model",
".",
"ExtendedAttributeValue",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"arguments",
"=",
"p",
"[",
"3",
... | ExtendedAttributeArgList : IDENTIFIER "(" ArgumentList ")" | [
"ExtendedAttributeArgList",
":",
"IDENTIFIER",
"(",
"ArgumentList",
")"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L979-L983 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ExtendedAttributeIdent | def p_ExtendedAttributeIdent(p):
"""ExtendedAttributeIdent : IDENTIFIER "=" IDENTIFIER"""
p[0] = model.ExtendedAttribute(
name=p[1],
value=model.ExtendedAttributeValue(name=p[3])) | python | def p_ExtendedAttributeIdent(p):
"""ExtendedAttributeIdent : IDENTIFIER "=" IDENTIFIER"""
p[0] = model.ExtendedAttribute(
name=p[1],
value=model.ExtendedAttributeValue(name=p[3])) | [
"def",
"p_ExtendedAttributeIdent",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"ExtendedAttribute",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"value",
"=",
"model",
".",
"ExtendedAttributeValue",
"(",
"name",
"=",
"p",
"[",
"3",
"]",
... | ExtendedAttributeIdent : IDENTIFIER "=" IDENTIFIER | [
"ExtendedAttributeIdent",
":",
"IDENTIFIER",
"=",
"IDENTIFIER"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L988-L992 |
VasilyStepanov/pywidl | pywidl/grammar.py | p_ExtendedAttributeNamedArgList | def p_ExtendedAttributeNamedArgList(p):
"""ExtendedAttributeNamedArgList : IDENTIFIER "=" IDENTIFIER "(" ArgumentList ")"
"""
p[0] = model.ExtendedAttribute(
name=p[1],
value=model.ExtendedAttributeValue(name=p[3], arguments=p[5])) | python | def p_ExtendedAttributeNamedArgList(p):
"""ExtendedAttributeNamedArgList : IDENTIFIER "=" IDENTIFIER "(" ArgumentList ")"
"""
p[0] = model.ExtendedAttribute(
name=p[1],
value=model.ExtendedAttributeValue(name=p[3], arguments=p[5])) | [
"def",
"p_ExtendedAttributeNamedArgList",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"ExtendedAttribute",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"value",
"=",
"model",
".",
"ExtendedAttributeValue",
"(",
"name",
"=",
"p",
"[",
"3",
... | ExtendedAttributeNamedArgList : IDENTIFIER "=" IDENTIFIER "(" ArgumentList ")" | [
"ExtendedAttributeNamedArgList",
":",
"IDENTIFIER",
"=",
"IDENTIFIER",
"(",
"ArgumentList",
")"
] | train | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L997-L1002 |
FNNDSC/pfdicom | pfdicom/pfdicom.py | pfdicom.declare_selfvars | def declare_selfvars(self):
"""
A block to declare self variables
"""
#
# Object desc block
#
self.str_desc = ''
self.__name__ = "pfdicom"
self.str_version = '1.6.0'
# Directory and filenames
self.str_workingDir = ''
self.str_inputDir = ''
self.str_inputFile = ''
self.str_extension = ''
self.str_outputFileStem = ''
self.str_ouptutDir = ''
self.str_outputLeafDir = ''
self.maxDepth = -1
# pftree dictionary
self.pf_tree = None
self.numThreads = 1
self.str_stdout = ''
self.str_stderr = ''
self.exitCode = 0
self.b_json = False
self.b_followLinks = False
# The actual data volume and slice
# are numpy ndarrays
self.dcm = None
self.d_dcm = {} # dict convert of raw dcm
self.strRaw = ""
self.l_tagRaw = []
# Simpler dictionary representations of DICOM tags
# NB -- the pixel data is not read into the dictionary
# by default
self.d_dicom = {} # values directly from dcm ojbect
self.d_dicomSimple = {} # formatted dict convert
# Convenience vars
self.tic_start = None
self.dp = None
self.log = None
self.tic_start = 0.0
self.pp = pprint.PrettyPrinter(indent=4)
self.verbosityLevel = 1 | python | def declare_selfvars(self):
"""
A block to declare self variables
"""
#
# Object desc block
#
self.str_desc = ''
self.__name__ = "pfdicom"
self.str_version = '1.6.0'
# Directory and filenames
self.str_workingDir = ''
self.str_inputDir = ''
self.str_inputFile = ''
self.str_extension = ''
self.str_outputFileStem = ''
self.str_ouptutDir = ''
self.str_outputLeafDir = ''
self.maxDepth = -1
# pftree dictionary
self.pf_tree = None
self.numThreads = 1
self.str_stdout = ''
self.str_stderr = ''
self.exitCode = 0
self.b_json = False
self.b_followLinks = False
# The actual data volume and slice
# are numpy ndarrays
self.dcm = None
self.d_dcm = {} # dict convert of raw dcm
self.strRaw = ""
self.l_tagRaw = []
# Simpler dictionary representations of DICOM tags
# NB -- the pixel data is not read into the dictionary
# by default
self.d_dicom = {} # values directly from dcm ojbect
self.d_dicomSimple = {} # formatted dict convert
# Convenience vars
self.tic_start = None
self.dp = None
self.log = None
self.tic_start = 0.0
self.pp = pprint.PrettyPrinter(indent=4)
self.verbosityLevel = 1 | [
"def",
"declare_selfvars",
"(",
"self",
")",
":",
"#",
"# Object desc block",
"#",
"self",
".",
"str_desc",
"=",
"''",
"self",
".",
"__name__",
"=",
"\"pfdicom\"",
"self",
".",
"str_version",
"=",
"'1.6.0'",
"# Directory and filenames",
"self",
".",
"str_working... | A block to declare self variables | [
"A",
"block",
"to",
"declare",
"self",
"variables"
] | train | https://github.com/FNNDSC/pfdicom/blob/91a0426c514a3496cb2e0576481055a47afee8d8/pfdicom/pfdicom.py#L46-L99 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.