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 |
|---|---|---|---|---|---|---|---|---|---|---|
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.format_epilog_section | def format_epilog_section(self, section, text):
"""Format a section for the epilog by inserting a format"""
try:
func = self._epilog_formatters[self.epilog_formatter]
except KeyError:
if not callable(self.epilog_formatter):
raise
func = self.epilog_formatter
return func(section, text) | python | def format_epilog_section(self, section, text):
"""Format a section for the epilog by inserting a format"""
try:
func = self._epilog_formatters[self.epilog_formatter]
except KeyError:
if not callable(self.epilog_formatter):
raise
func = self.epilog_formatter
return func(section, text) | [
"def",
"format_epilog_section",
"(",
"self",
",",
"section",
",",
"text",
")",
":",
"try",
":",
"func",
"=",
"self",
".",
"_epilog_formatters",
"[",
"self",
".",
"epilog_formatter",
"]",
"except",
"KeyError",
":",
"if",
"not",
"callable",
"(",
"self",
".",... | Format a section for the epilog by inserting a format | [
"Format",
"a",
"section",
"for",
"the",
"epilog",
"by",
"inserting",
"a",
"format"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L578-L586 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.extract_as_epilog | def extract_as_epilog(self, text, sections=None, overwrite=False,
append=True):
"""Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog
append: bool
If True, append to the existing epilog"""
if sections is None:
sections = self.epilog_sections
if ((not self.epilog or overwrite or append) and sections):
epilog_parts = []
for sec in sections:
text = docstrings._get_section(text, sec).strip()
if text:
epilog_parts.append(
self.format_epilog_section(sec, text))
if epilog_parts:
epilog = '\n\n'.join(epilog_parts)
if overwrite or not self.epilog:
self.epilog = epilog
else:
self.epilog += '\n\n' + epilog | python | def extract_as_epilog(self, text, sections=None, overwrite=False,
append=True):
"""Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog
append: bool
If True, append to the existing epilog"""
if sections is None:
sections = self.epilog_sections
if ((not self.epilog or overwrite or append) and sections):
epilog_parts = []
for sec in sections:
text = docstrings._get_section(text, sec).strip()
if text:
epilog_parts.append(
self.format_epilog_section(sec, text))
if epilog_parts:
epilog = '\n\n'.join(epilog_parts)
if overwrite or not self.epilog:
self.epilog = epilog
else:
self.epilog += '\n\n' + epilog | [
"def",
"extract_as_epilog",
"(",
"self",
",",
"text",
",",
"sections",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"append",
"=",
"True",
")",
":",
"if",
"sections",
"is",
"None",
":",
"sections",
"=",
"self",
".",
"epilog_sections",
"if",
"(",
"... | Extract epilog sections from the a docstring
Parameters
----------
text
The docstring to use
sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog
append: bool
If True, append to the existing epilog | [
"Extract",
"epilog",
"sections",
"from",
"the",
"a",
"docstring"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L588-L617 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.grouparg | def grouparg(self, arg, my_arg=None, parent_cmds=[]):
"""
Grouper function for chaining subcommands
Parameters
----------
arg: str
The current command line argument that is parsed
my_arg: str
The name of this subparser. If None, this parser is the main
parser and has no parent parser
parent_cmds: list of str
The available commands of the parent parsers
Returns
-------
str or None
The grouping key for the given `arg` or None if the key does
not correspond to this parser or this parser is the main parser
and does not have seen a subparser yet
Notes
-----
Quite complicated, there is no real need to deal with this function
"""
if self._subparsers_action is None:
return None
commands = self._subparsers_action.choices
currentarg = self.__currentarg
# the default return value is the current argument we are in or the
# name of the subparser itself
ret = currentarg or my_arg
if currentarg is not None:
# if we are already in a sub command, we use the sub parser
sp_key = commands[currentarg].grouparg(arg, currentarg, chain(
commands, parent_cmds))
if sp_key is None and arg in commands:
# if the subparser did not recognize the command, we use the
# command the corresponds to this parser or (of this parser
# is the parent parser) the current subparser
self.__currentarg = currentarg = arg
ret = my_arg or currentarg
elif sp_key not in commands and arg in parent_cmds:
# otherwise, if the subparser recognizes the commmand but it is
# not in the known command of this parser, it must be another
# command of the subparser and this parser can ignore it
ret = None
else:
# otherwise the command belongs to this subparser (if this one
# is not the subparser) or the current subparser
ret = my_arg or currentarg
elif arg in commands:
# if the argument is a valid subparser, we return this one
self.__currentarg = arg
ret = arg
elif arg in parent_cmds:
# if the argument is not a valid subparser but in one of our
# parents, we return None to signalize that we cannot categorize
# it
ret = None
return ret | python | def grouparg(self, arg, my_arg=None, parent_cmds=[]):
"""
Grouper function for chaining subcommands
Parameters
----------
arg: str
The current command line argument that is parsed
my_arg: str
The name of this subparser. If None, this parser is the main
parser and has no parent parser
parent_cmds: list of str
The available commands of the parent parsers
Returns
-------
str or None
The grouping key for the given `arg` or None if the key does
not correspond to this parser or this parser is the main parser
and does not have seen a subparser yet
Notes
-----
Quite complicated, there is no real need to deal with this function
"""
if self._subparsers_action is None:
return None
commands = self._subparsers_action.choices
currentarg = self.__currentarg
# the default return value is the current argument we are in or the
# name of the subparser itself
ret = currentarg or my_arg
if currentarg is not None:
# if we are already in a sub command, we use the sub parser
sp_key = commands[currentarg].grouparg(arg, currentarg, chain(
commands, parent_cmds))
if sp_key is None and arg in commands:
# if the subparser did not recognize the command, we use the
# command the corresponds to this parser or (of this parser
# is the parent parser) the current subparser
self.__currentarg = currentarg = arg
ret = my_arg or currentarg
elif sp_key not in commands and arg in parent_cmds:
# otherwise, if the subparser recognizes the commmand but it is
# not in the known command of this parser, it must be another
# command of the subparser and this parser can ignore it
ret = None
else:
# otherwise the command belongs to this subparser (if this one
# is not the subparser) or the current subparser
ret = my_arg or currentarg
elif arg in commands:
# if the argument is a valid subparser, we return this one
self.__currentarg = arg
ret = arg
elif arg in parent_cmds:
# if the argument is not a valid subparser but in one of our
# parents, we return None to signalize that we cannot categorize
# it
ret = None
return ret | [
"def",
"grouparg",
"(",
"self",
",",
"arg",
",",
"my_arg",
"=",
"None",
",",
"parent_cmds",
"=",
"[",
"]",
")",
":",
"if",
"self",
".",
"_subparsers_action",
"is",
"None",
":",
"return",
"None",
"commands",
"=",
"self",
".",
"_subparsers_action",
".",
... | Grouper function for chaining subcommands
Parameters
----------
arg: str
The current command line argument that is parsed
my_arg: str
The name of this subparser. If None, this parser is the main
parser and has no parent parser
parent_cmds: list of str
The available commands of the parent parsers
Returns
-------
str or None
The grouping key for the given `arg` or None if the key does
not correspond to this parser or this parser is the main parser
and does not have seen a subparser yet
Notes
-----
Quite complicated, there is no real need to deal with this function | [
"Grouper",
"function",
"for",
"chaining",
"subcommands"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L619-L679 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.__parse_main | def __parse_main(self, args):
"""Parse the main arguments only. This is a work around for python 2.7
because argparse does not allow to parse arguments without subparsers
"""
if six.PY2:
self._subparsers_action.add_parser("__dummy")
return super(FuncArgParser, self).parse_known_args(
list(args) + ['__dummy'])
return super(FuncArgParser, self).parse_known_args(args) | python | def __parse_main(self, args):
"""Parse the main arguments only. This is a work around for python 2.7
because argparse does not allow to parse arguments without subparsers
"""
if six.PY2:
self._subparsers_action.add_parser("__dummy")
return super(FuncArgParser, self).parse_known_args(
list(args) + ['__dummy'])
return super(FuncArgParser, self).parse_known_args(args) | [
"def",
"__parse_main",
"(",
"self",
",",
"args",
")",
":",
"if",
"six",
".",
"PY2",
":",
"self",
".",
"_subparsers_action",
".",
"add_parser",
"(",
"\"__dummy\"",
")",
"return",
"super",
"(",
"FuncArgParser",
",",
"self",
")",
".",
"parse_known_args",
"(",... | Parse the main arguments only. This is a work around for python 2.7
because argparse does not allow to parse arguments without subparsers | [
"Parse",
"the",
"main",
"arguments",
"only",
".",
"This",
"is",
"a",
"work",
"around",
"for",
"python",
"2",
".",
"7",
"because",
"argparse",
"does",
"not",
"allow",
"to",
"parse",
"arguments",
"without",
"subparsers"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L709-L717 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.update_short | def update_short(self, **kwargs):
"""
Update the short optional arguments (those with one leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinished_arguments`
dictionary (i.e. keywords of the root functions), values the short
argument names
Examples
--------
Setting::
>>> parser.update_short(something='s', something_else='se')
is basically the same as::
>>> parser.update_arg('something', short='s')
>>> parser.update_arg('something_else', short='se')
which in turn is basically comparable to::
>>> parser.add_argument('-s', '--something', ...)
>>> parser.add_argument('-se', '--something_else', ...)
See Also
--------
update_shortf, update_long"""
for key, val in six.iteritems(kwargs):
self.update_arg(key, short=val) | python | def update_short(self, **kwargs):
"""
Update the short optional arguments (those with one leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinished_arguments`
dictionary (i.e. keywords of the root functions), values the short
argument names
Examples
--------
Setting::
>>> parser.update_short(something='s', something_else='se')
is basically the same as::
>>> parser.update_arg('something', short='s')
>>> parser.update_arg('something_else', short='se')
which in turn is basically comparable to::
>>> parser.add_argument('-s', '--something', ...)
>>> parser.add_argument('-se', '--something_else', ...)
See Also
--------
update_shortf, update_long"""
for key, val in six.iteritems(kwargs):
self.update_arg(key, short=val) | [
"def",
"update_short",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"self",
".",
"update_arg",
"(",
"key",
",",
"short",
"=",
"val",
")"
] | Update the short optional arguments (those with one leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinished_arguments`
dictionary (i.e. keywords of the root functions), values the short
argument names
Examples
--------
Setting::
>>> parser.update_short(something='s', something_else='se')
is basically the same as::
>>> parser.update_arg('something', short='s')
>>> parser.update_arg('something_else', short='se')
which in turn is basically comparable to::
>>> parser.add_argument('-s', '--something', ...)
>>> parser.add_argument('-se', '--something_else', ...)
See Also
--------
update_shortf, update_long | [
"Update",
"the",
"short",
"optional",
"arguments",
"(",
"those",
"with",
"one",
"leading",
"-",
")"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L721-L755 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.update_long | def update_long(self, **kwargs):
"""
Update the long optional arguments (those with two leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinished_arguments`
dictionary (i.e. keywords of the root functions), values the long
argument names
Examples
--------
Setting::
>>> parser.update_long(something='s', something_else='se')
is basically the same as::
>>> parser.update_arg('something', long='s')
>>> parser.update_arg('something_else', long='se')
which in turn is basically comparable to::
>>> parser.add_argument('--s', dest='something', ...)
>>> parser.add_argument('--se', dest='something_else', ...)
See Also
--------
update_short, update_longf"""
for key, val in six.iteritems(kwargs):
self.update_arg(key, long=val) | python | def update_long(self, **kwargs):
"""
Update the long optional arguments (those with two leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinished_arguments`
dictionary (i.e. keywords of the root functions), values the long
argument names
Examples
--------
Setting::
>>> parser.update_long(something='s', something_else='se')
is basically the same as::
>>> parser.update_arg('something', long='s')
>>> parser.update_arg('something_else', long='se')
which in turn is basically comparable to::
>>> parser.add_argument('--s', dest='something', ...)
>>> parser.add_argument('--se', dest='something_else', ...)
See Also
--------
update_short, update_longf"""
for key, val in six.iteritems(kwargs):
self.update_arg(key, long=val) | [
"def",
"update_long",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"self",
".",
"update_arg",
"(",
"key",
",",
"long",
"=",
"val",
")"
] | Update the long optional arguments (those with two leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinished_arguments`
dictionary (i.e. keywords of the root functions), values the long
argument names
Examples
--------
Setting::
>>> parser.update_long(something='s', something_else='se')
is basically the same as::
>>> parser.update_arg('something', long='s')
>>> parser.update_arg('something_else', long='se')
which in turn is basically comparable to::
>>> parser.add_argument('--s', dest='something', ...)
>>> parser.add_argument('--se', dest='something_else', ...)
See Also
--------
update_short, update_longf | [
"Update",
"the",
"long",
"optional",
"arguments",
"(",
"those",
"with",
"two",
"leading",
"-",
")"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L792-L826 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.parse2func | def parse2func(self, args=None, func=None):
"""Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list
The list of command line arguments
func: function
An alternative function to use. If None, the last function or the
one specified through the `setup_as` parameter in the
:meth:`setup_args` is used.
Returns
-------
object
What ever is returned by the called function
Note
----
This method does not cover subparsers!"""
kws = vars(self.parse_args(args))
if func is None:
if self._setup_as:
func = kws.pop(self._setup_as)
else:
func = self._used_functions[-1]
return func(**kws) | python | def parse2func(self, args=None, func=None):
"""Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list
The list of command line arguments
func: function
An alternative function to use. If None, the last function or the
one specified through the `setup_as` parameter in the
:meth:`setup_args` is used.
Returns
-------
object
What ever is returned by the called function
Note
----
This method does not cover subparsers!"""
kws = vars(self.parse_args(args))
if func is None:
if self._setup_as:
func = kws.pop(self._setup_as)
else:
func = self._used_functions[-1]
return func(**kws) | [
"def",
"parse2func",
"(",
"self",
",",
"args",
"=",
"None",
",",
"func",
"=",
"None",
")",
":",
"kws",
"=",
"vars",
"(",
"self",
".",
"parse_args",
"(",
"args",
")",
")",
"if",
"func",
"is",
"None",
":",
"if",
"self",
".",
"_setup_as",
":",
"func... | Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list
The list of command line arguments
func: function
An alternative function to use. If None, the last function or the
one specified through the `setup_as` parameter in the
:meth:`setup_args` is used.
Returns
-------
object
What ever is returned by the called function
Note
----
This method does not cover subparsers! | [
"Parse",
"the",
"command",
"line",
"arguments",
"to",
"the",
"setup",
"function"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L861-L890 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.parse_known2func | def parse_known2func(self, args=None, func=None):
"""Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list
The list of command line arguments
func: function or str
An alternative function to use. If None, the last function or the
one specified through the `setup_as` parameter in the
:meth:`setup_args` is used.
Returns
-------
object
What ever is returned by the called function
list
The remaining command line arguments that could not be interpreted
Note
----
This method does not cover subparsers!"""
ns, remainder = self.parse_known_args(args)
kws = vars(ns)
if func is None:
if self._setup_as:
func = kws.pop(self._setup_as)
else:
func = self._used_functions[-1]
return func(**kws), remainder | python | def parse_known2func(self, args=None, func=None):
"""Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list
The list of command line arguments
func: function or str
An alternative function to use. If None, the last function or the
one specified through the `setup_as` parameter in the
:meth:`setup_args` is used.
Returns
-------
object
What ever is returned by the called function
list
The remaining command line arguments that could not be interpreted
Note
----
This method does not cover subparsers!"""
ns, remainder = self.parse_known_args(args)
kws = vars(ns)
if func is None:
if self._setup_as:
func = kws.pop(self._setup_as)
else:
func = self._used_functions[-1]
return func(**kws), remainder | [
"def",
"parse_known2func",
"(",
"self",
",",
"args",
"=",
"None",
",",
"func",
"=",
"None",
")",
":",
"ns",
",",
"remainder",
"=",
"self",
".",
"parse_known_args",
"(",
"args",
")",
"kws",
"=",
"vars",
"(",
"ns",
")",
"if",
"func",
"is",
"None",
":... | Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list
The list of command line arguments
func: function or str
An alternative function to use. If None, the last function or the
one specified through the `setup_as` parameter in the
:meth:`setup_args` is used.
Returns
-------
object
What ever is returned by the called function
list
The remaining command line arguments that could not be interpreted
Note
----
This method does not cover subparsers! | [
"Parse",
"the",
"command",
"line",
"arguments",
"to",
"the",
"setup",
"function"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L892-L924 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.parse_chained | def parse_chained(self, args=None):
"""
Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args`.
Parameters
----------
args: list
The arguments parsed to the :meth:`parse_args` function
Returns
-------
argparse.Namespace
The namespace with mapping from command name to the function
return
See also
--------
parse_known_chained
"""
kws = vars(self.parse_args(args))
return self._parse2subparser_funcs(kws) | python | def parse_chained(self, args=None):
"""
Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args`.
Parameters
----------
args: list
The arguments parsed to the :meth:`parse_args` function
Returns
-------
argparse.Namespace
The namespace with mapping from command name to the function
return
See also
--------
parse_known_chained
"""
kws = vars(self.parse_args(args))
return self._parse2subparser_funcs(kws) | [
"def",
"parse_chained",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"kws",
"=",
"vars",
"(",
"self",
".",
"parse_args",
"(",
"args",
")",
")",
"return",
"self",
".",
"_parse2subparser_funcs",
"(",
"kws",
")"
] | Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args`.
Parameters
----------
args: list
The arguments parsed to the :meth:`parse_args` function
Returns
-------
argparse.Namespace
The namespace with mapping from command name to the function
return
See also
--------
parse_known_chained | [
"Parse",
"the",
"argument",
"directly",
"to",
"the",
"function",
"used",
"for",
"setup"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L926-L950 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.parse_known_chained | def parse_known_chained(self, args=None):
"""
Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args` method.
Parameters
----------
args: list
The arguments parsed to the :meth:`parse_args` function
Returns
-------
argparse.Namespace
The namespace with mapping from command name to the function
return
list
The remaining arguments that could not be interpreted
See also
--------
parse_known
"""
ns, remainder = self.parse_known_args(args)
kws = vars(ns)
return self._parse2subparser_funcs(kws), remainder | python | def parse_known_chained(self, args=None):
"""
Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args` method.
Parameters
----------
args: list
The arguments parsed to the :meth:`parse_args` function
Returns
-------
argparse.Namespace
The namespace with mapping from command name to the function
return
list
The remaining arguments that could not be interpreted
See also
--------
parse_known
"""
ns, remainder = self.parse_known_args(args)
kws = vars(ns)
return self._parse2subparser_funcs(kws), remainder | [
"def",
"parse_known_chained",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"ns",
",",
"remainder",
"=",
"self",
".",
"parse_known_args",
"(",
"args",
")",
"kws",
"=",
"vars",
"(",
"ns",
")",
"return",
"self",
".",
"_parse2subparser_funcs",
"(",
"kws"... | Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args` method.
Parameters
----------
args: list
The arguments parsed to the :meth:`parse_args` function
Returns
-------
argparse.Namespace
The namespace with mapping from command name to the function
return
list
The remaining arguments that could not be interpreted
See also
--------
parse_known | [
"Parse",
"the",
"argument",
"directly",
"to",
"the",
"function",
"used",
"for",
"setup"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L952-L979 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser._parse2subparser_funcs | def _parse2subparser_funcs(self, kws):
"""
Recursive function to parse arguments to chained parsers
"""
choices = getattr(self._subparsers_action, 'choices', {})
replaced = {key.replace('-', '_'): key for key in choices}
sp_commands = set(replaced).intersection(kws)
if not sp_commands:
if self._setup_as is not None:
func = kws.pop(self._setup_as)
else:
try:
func = self._used_functions[-1]
except IndexError:
return None
return func(**{
key: kws[key] for key in set(kws).difference(choices)})
else:
ret = {}
for key in sp_commands:
ret[key.replace('-', '_')] = \
choices[replaced[key]]._parse2subparser_funcs(
vars(kws[key]))
return Namespace(**ret) | python | def _parse2subparser_funcs(self, kws):
"""
Recursive function to parse arguments to chained parsers
"""
choices = getattr(self._subparsers_action, 'choices', {})
replaced = {key.replace('-', '_'): key for key in choices}
sp_commands = set(replaced).intersection(kws)
if not sp_commands:
if self._setup_as is not None:
func = kws.pop(self._setup_as)
else:
try:
func = self._used_functions[-1]
except IndexError:
return None
return func(**{
key: kws[key] for key in set(kws).difference(choices)})
else:
ret = {}
for key in sp_commands:
ret[key.replace('-', '_')] = \
choices[replaced[key]]._parse2subparser_funcs(
vars(kws[key]))
return Namespace(**ret) | [
"def",
"_parse2subparser_funcs",
"(",
"self",
",",
"kws",
")",
":",
"choices",
"=",
"getattr",
"(",
"self",
".",
"_subparsers_action",
",",
"'choices'",
",",
"{",
"}",
")",
"replaced",
"=",
"{",
"key",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
":",
... | Recursive function to parse arguments to chained parsers | [
"Recursive",
"function",
"to",
"parse",
"arguments",
"to",
"chained",
"parsers"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L981-L1004 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.get_subparser | def get_subparser(self, name):
"""
Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name`
"""
if self._subparsers_action is None:
raise ValueError("%s has no subparsers defined!" % self)
return self._subparsers_action.choices[name] | python | def get_subparser(self, name):
"""
Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name`
"""
if self._subparsers_action is None:
raise ValueError("%s has no subparsers defined!" % self)
return self._subparsers_action.choices[name] | [
"def",
"get_subparser",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_subparsers_action",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"%s has no subparsers defined!\"",
"%",
"self",
")",
"return",
"self",
".",
"_subparsers_action",
".",
"choices"... | Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name` | [
"Convenience",
"method",
"to",
"get",
"a",
"certain",
"subparser"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L1006-L1022 |
coded-by-hand/mass | mass/parse.py | parse_file | def parse_file(src):
"""
find file in config and output to dest dir
"""
#clear the stack between parses
if config.dest_dir == None:
dest = src.dir
else:
dest = config.dest_dir
output = get_output(src)
output_file = dest + '/' + src.basename + '.min.js'
f = open(output_file,'w')
f.write(jsmin.jsmin(output))
f.close()
print "Wrote combined and minified file to: %s" % (output_file) | python | def parse_file(src):
"""
find file in config and output to dest dir
"""
#clear the stack between parses
if config.dest_dir == None:
dest = src.dir
else:
dest = config.dest_dir
output = get_output(src)
output_file = dest + '/' + src.basename + '.min.js'
f = open(output_file,'w')
f.write(jsmin.jsmin(output))
f.close()
print "Wrote combined and minified file to: %s" % (output_file) | [
"def",
"parse_file",
"(",
"src",
")",
":",
"#clear the stack between parses",
"if",
"config",
".",
"dest_dir",
"==",
"None",
":",
"dest",
"=",
"src",
".",
"dir",
"else",
":",
"dest",
"=",
"config",
".",
"dest_dir",
"output",
"=",
"get_output",
"(",
"src",
... | find file in config and output to dest dir | [
"find",
"file",
"in",
"config",
"and",
"output",
"to",
"dest",
"dir"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/mass/parse.py#L12-L26 |
coded-by-hand/mass | mass/parse.py | get_output | def get_output(src):
"""
parse lines looking for commands
"""
output = ''
lines = open(src.path, 'rU').readlines()
for line in lines:
m = re.match(config.import_regex,line)
if m:
include_path = os.path.abspath(src.dir + '/' + m.group('script'));
if include_path not in config.sources:
script = Script(include_path)
script.parents.append(src)
config.sources[script.path] = script
include_file = config.sources[include_path]
#require statements dont include if the file has already been included
if include_file not in config.stack or m.group('command') == 'import':
config.stack.append(include_file)
output += get_output(include_file)
else:
output += line
return output | python | def get_output(src):
"""
parse lines looking for commands
"""
output = ''
lines = open(src.path, 'rU').readlines()
for line in lines:
m = re.match(config.import_regex,line)
if m:
include_path = os.path.abspath(src.dir + '/' + m.group('script'));
if include_path not in config.sources:
script = Script(include_path)
script.parents.append(src)
config.sources[script.path] = script
include_file = config.sources[include_path]
#require statements dont include if the file has already been included
if include_file not in config.stack or m.group('command') == 'import':
config.stack.append(include_file)
output += get_output(include_file)
else:
output += line
return output | [
"def",
"get_output",
"(",
"src",
")",
":",
"output",
"=",
"''",
"lines",
"=",
"open",
"(",
"src",
".",
"path",
",",
"'rU'",
")",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"m",
"=",
"re",
".",
"match",
"(",
"config",
".",
"i... | parse lines looking for commands | [
"parse",
"lines",
"looking",
"for",
"commands"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/mass/parse.py#L28-L49 |
duniter/duniter-python-api | examples/save_revoke_document.py | get_signed_raw_revocation_document | def get_signed_raw_revocation_document(identity: Identity, salt: str, password: str) -> str:
"""
Generate account revocation document for given identity
:param identity: Self Certification of the identity
:param salt: Salt
:param password: Password
:rtype: str
"""
revocation = Revocation(PROTOCOL_VERSION, identity.currency, identity, "")
key = SigningKey.from_credentials(salt, password)
revocation.sign([key])
return revocation.signed_raw() | python | def get_signed_raw_revocation_document(identity: Identity, salt: str, password: str) -> str:
"""
Generate account revocation document for given identity
:param identity: Self Certification of the identity
:param salt: Salt
:param password: Password
:rtype: str
"""
revocation = Revocation(PROTOCOL_VERSION, identity.currency, identity, "")
key = SigningKey.from_credentials(salt, password)
revocation.sign([key])
return revocation.signed_raw() | [
"def",
"get_signed_raw_revocation_document",
"(",
"identity",
":",
"Identity",
",",
"salt",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"str",
":",
"revocation",
"=",
"Revocation",
"(",
"PROTOCOL_VERSION",
",",
"identity",
".",
"currency",
",",
"identi... | Generate account revocation document for given identity
:param identity: Self Certification of the identity
:param salt: Salt
:param password: Password
:rtype: str | [
"Generate",
"account",
"revocation",
"document",
"for",
"given",
"identity"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/save_revoke_document.py#L77-L91 |
duniter/duniter-python-api | examples/save_revoke_document.py | main | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection
response = await client(bma.node.summary)
print(response)
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
# prompt hidden user entry
password = getpass.getpass("Enter your password: ")
# prompt public key
pubkey = input("Enter your public key: ")
# init signer instance
signer = SigningKey.from_credentials(salt, password)
# check public key
if signer.pubkey != pubkey:
print("Bad credentials!")
exit(0)
# capture current block to get currency name
current_block = await client(bma.blockchain.current)
# create our Identity document to sign the revoke document
identity_document = await get_identity_document(client, current_block['currency'], pubkey)
# get the revoke document
revocation_signed_raw_document = get_signed_raw_revocation_document(identity_document, salt, password)
# save revoke document in a file
fp = open(REVOCATION_DOCUMENT_FILE_PATH, 'w')
fp.write(revocation_signed_raw_document)
fp.close()
# document saved
print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH)
# Close client aiohttp session
await client.close() | python | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection
response = await client(bma.node.summary)
print(response)
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
# prompt hidden user entry
password = getpass.getpass("Enter your password: ")
# prompt public key
pubkey = input("Enter your public key: ")
# init signer instance
signer = SigningKey.from_credentials(salt, password)
# check public key
if signer.pubkey != pubkey:
print("Bad credentials!")
exit(0)
# capture current block to get currency name
current_block = await client(bma.blockchain.current)
# create our Identity document to sign the revoke document
identity_document = await get_identity_document(client, current_block['currency'], pubkey)
# get the revoke document
revocation_signed_raw_document = get_signed_raw_revocation_document(identity_document, salt, password)
# save revoke document in a file
fp = open(REVOCATION_DOCUMENT_FILE_PATH, 'w')
fp.write(revocation_signed_raw_document)
fp.close()
# document saved
print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH)
# Close client aiohttp session
await client.close() | [
"async",
"def",
"main",
"(",
")",
":",
"# Create Client from endpoint string in Duniter format",
"client",
"=",
"Client",
"(",
"BMAS_ENDPOINT",
")",
"# Get the node summary infos to test the connection",
"response",
"=",
"await",
"client",
"(",
"bma",
".",
"node",
".",
... | Main code | [
"Main",
"code"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/save_revoke_document.py#L94-L140 |
azraq27/neural | neural/alignment.py | align_epi | def align_epi(anatomy,epis,suffix='_al',base=3,skull_strip=True):
'''[[currently in progress]]: a simple replacement for the ``align_epi_anat.py`` script, because I've found it to be unreliable, in my usage'''
for epi in epis:
nl.tshift(epi,suffix='_tshift')
nl.affine_align(nl.suffix(epi,'_tshift'),'%s[%d]'%(epis[0],base),skull_strip=False,epi=True,cost='crM',resample='wsinc5',grid_size=nl.dset_info(epi).voxel_size[0],suffix='_al')
ss = [anatomy] if skull_strip else False
nl.affine_align(anatomy,'%s[%d]'%(epis[0],base),skull_strip=ss,cost='lpa',grid_size=1,opts=['-interp','cubic'],suffix='_al-to-EPI') | python | def align_epi(anatomy,epis,suffix='_al',base=3,skull_strip=True):
'''[[currently in progress]]: a simple replacement for the ``align_epi_anat.py`` script, because I've found it to be unreliable, in my usage'''
for epi in epis:
nl.tshift(epi,suffix='_tshift')
nl.affine_align(nl.suffix(epi,'_tshift'),'%s[%d]'%(epis[0],base),skull_strip=False,epi=True,cost='crM',resample='wsinc5',grid_size=nl.dset_info(epi).voxel_size[0],suffix='_al')
ss = [anatomy] if skull_strip else False
nl.affine_align(anatomy,'%s[%d]'%(epis[0],base),skull_strip=ss,cost='lpa',grid_size=1,opts=['-interp','cubic'],suffix='_al-to-EPI') | [
"def",
"align_epi",
"(",
"anatomy",
",",
"epis",
",",
"suffix",
"=",
"'_al'",
",",
"base",
"=",
"3",
",",
"skull_strip",
"=",
"True",
")",
":",
"for",
"epi",
"in",
"epis",
":",
"nl",
".",
"tshift",
"(",
"epi",
",",
"suffix",
"=",
"'_tshift'",
")",
... | [[currently in progress]]: a simple replacement for the ``align_epi_anat.py`` script, because I've found it to be unreliable, in my usage | [
"[[",
"currently",
"in",
"progress",
"]]",
":",
"a",
"simple",
"replacement",
"for",
"the",
"align_epi_anat",
".",
"py",
"script",
"because",
"I",
"ve",
"found",
"it",
"to",
"be",
"unreliable",
"in",
"my",
"usage"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L7-L13 |
azraq27/neural | neural/alignment.py | motion_from_params | def motion_from_params(param_file,motion_file,individual=True,rms=True):
'''calculate a motion regressor from the params file given by 3dAllineate
Basically just calculates the rms change in the translation and rotation components. Returns the 6 motion vector (if ``individual`` is ``True``) and the RMS difference (if ``rms`` is ``True``).'''
with open(param_file) as inf:
translate_rotate = np.array([[float(y) for y in x.strip().split()[:6]] for x in inf.readlines() if x[0]!='#'])
motion = np.array([])
if individual:
motion = np.vstack((np.zeros(translate_rotate.shape[1]),np.diff(translate_rotate,axis=0)))
if rms:
translate = [sqrt(sum([x**2 for x in y[:3]])) for y in translate_rotate]
rotate = [sqrt(sum([x**2 for x in y[3:]])) for y in translate_rotate]
translate_rotate = np.array(map(add,translate,rotate))
translate_rotate_diff = np.hstack(([0],np.diff(translate_rotate,axis=0)))
if motion.shape==(0,):
motion = rms_motion
else:
motion = np.column_stack((motion,translate_rotate_diff))
with open(motion_file,'w') as outf:
outf.write('\n'.join(['\t'.join([str(y) for y in x]) for x in motion])) | python | def motion_from_params(param_file,motion_file,individual=True,rms=True):
'''calculate a motion regressor from the params file given by 3dAllineate
Basically just calculates the rms change in the translation and rotation components. Returns the 6 motion vector (if ``individual`` is ``True``) and the RMS difference (if ``rms`` is ``True``).'''
with open(param_file) as inf:
translate_rotate = np.array([[float(y) for y in x.strip().split()[:6]] for x in inf.readlines() if x[0]!='#'])
motion = np.array([])
if individual:
motion = np.vstack((np.zeros(translate_rotate.shape[1]),np.diff(translate_rotate,axis=0)))
if rms:
translate = [sqrt(sum([x**2 for x in y[:3]])) for y in translate_rotate]
rotate = [sqrt(sum([x**2 for x in y[3:]])) for y in translate_rotate]
translate_rotate = np.array(map(add,translate,rotate))
translate_rotate_diff = np.hstack(([0],np.diff(translate_rotate,axis=0)))
if motion.shape==(0,):
motion = rms_motion
else:
motion = np.column_stack((motion,translate_rotate_diff))
with open(motion_file,'w') as outf:
outf.write('\n'.join(['\t'.join([str(y) for y in x]) for x in motion])) | [
"def",
"motion_from_params",
"(",
"param_file",
",",
"motion_file",
",",
"individual",
"=",
"True",
",",
"rms",
"=",
"True",
")",
":",
"with",
"open",
"(",
"param_file",
")",
"as",
"inf",
":",
"translate_rotate",
"=",
"np",
".",
"array",
"(",
"[",
"[",
... | calculate a motion regressor from the params file given by 3dAllineate
Basically just calculates the rms change in the translation and rotation components. Returns the 6 motion vector (if ``individual`` is ``True``) and the RMS difference (if ``rms`` is ``True``). | [
"calculate",
"a",
"motion",
"regressor",
"from",
"the",
"params",
"file",
"given",
"by",
"3dAllineate"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L15-L34 |
azraq27/neural | neural/alignment.py | volreg | def volreg(dset,suffix='_volreg',base=3,tshift=3,dfile_suffix='_volreg.1D'):
'''simple interface to 3dvolreg
:suffix: suffix to add to ``dset`` for volreg'ed file
:base: either a number or ``dset[#]`` of the base image to register to
:tshift: if a number, then tshift ignoring that many images, if ``None``
then don't tshift
:dfile_suffix: suffix to add to ``dset`` to save the motion parameters to
'''
cmd = ['3dvolreg','-prefix',nl.suffix(dset,suffix),'-base',base,'-dfile',nl.prefix(dset)+dfile_suffix]
if tshift:
cmd += ['-tshift',tshift]
cmd += [dset]
nl.run(cmd,products=nl.suffix(dset,suffix)) | python | def volreg(dset,suffix='_volreg',base=3,tshift=3,dfile_suffix='_volreg.1D'):
'''simple interface to 3dvolreg
:suffix: suffix to add to ``dset`` for volreg'ed file
:base: either a number or ``dset[#]`` of the base image to register to
:tshift: if a number, then tshift ignoring that many images, if ``None``
then don't tshift
:dfile_suffix: suffix to add to ``dset`` to save the motion parameters to
'''
cmd = ['3dvolreg','-prefix',nl.suffix(dset,suffix),'-base',base,'-dfile',nl.prefix(dset)+dfile_suffix]
if tshift:
cmd += ['-tshift',tshift]
cmd += [dset]
nl.run(cmd,products=nl.suffix(dset,suffix)) | [
"def",
"volreg",
"(",
"dset",
",",
"suffix",
"=",
"'_volreg'",
",",
"base",
"=",
"3",
",",
"tshift",
"=",
"3",
",",
"dfile_suffix",
"=",
"'_volreg.1D'",
")",
":",
"cmd",
"=",
"[",
"'3dvolreg'",
",",
"'-prefix'",
",",
"nl",
".",
"suffix",
"(",
"dset",... | simple interface to 3dvolreg
:suffix: suffix to add to ``dset`` for volreg'ed file
:base: either a number or ``dset[#]`` of the base image to register to
:tshift: if a number, then tshift ignoring that many images, if ``None``
then don't tshift
:dfile_suffix: suffix to add to ``dset`` to save the motion parameters to | [
"simple",
"interface",
"to",
"3dvolreg"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L36-L49 |
azraq27/neural | neural/alignment.py | affine_align | def affine_align(dset_from,dset_to,skull_strip=True,mask=None,suffix='_aff',prefix=None,cost=None,epi=False,resample='wsinc5',grid_size=None,opts=[]):
''' interface to 3dAllineate to align anatomies and EPIs '''
dset_ss = lambda dset: os.path.split(nl.suffix(dset,'_ns'))[1]
def dset_source(dset):
if skull_strip==True or skull_strip==dset:
return dset_ss(dset)
else:
return dset
dset_affine = prefix
if dset_affine==None:
dset_affine = os.path.split(nl.suffix(dset_from,suffix))[1]
dset_affine_mat_1D = nl.prefix(dset_affine) + '_matrix.1D'
dset_affine_par_1D = nl.prefix(dset_affine) + '_params.1D'
if os.path.exists(dset_affine):
# final product already exists
return
for dset in [dset_from,dset_to]:
if skull_strip==True or skull_strip==dset:
nl.skull_strip(dset,'_ns')
mask_use = mask
if mask:
# the mask was probably made in the space of the original dset_to anatomy,
# which has now been cropped from the skull stripping. So the lesion mask
# needs to be resampled to match the corresponding mask
if skull_strip==True or skull_strip==dset_to:
nl.run(['3dresample','-master',dset_u(dset_ss(dset)),'-inset',mask,'-prefix',nl.suffix(mask,'_resam')],products=nl.suffix(mask,'_resam'))
mask_use = nl.suffix(mask,'_resam')
all_cmd = [
'3dAllineate',
'-prefix', dset_affine,
'-base', dset_source(dset_to),
'-source', dset_source(dset_from),
'-source_automask',
'-1Dmatrix_save', dset_affine_mat_1D,
'-1Dparam_save',dset_affine_par_1D,
'-autoweight',
'-final',resample,
'-cmass'
] + opts
if grid_size:
all_cmd += ['-newgrid',grid_size]
if cost:
all_cmd += ['-cost',cost]
if epi:
all_cmd += ['-EPI']
if mask:
all_cmd += ['-emask', mask_use]
nl.run(all_cmd,products=dset_affine) | python | def affine_align(dset_from,dset_to,skull_strip=True,mask=None,suffix='_aff',prefix=None,cost=None,epi=False,resample='wsinc5',grid_size=None,opts=[]):
''' interface to 3dAllineate to align anatomies and EPIs '''
dset_ss = lambda dset: os.path.split(nl.suffix(dset,'_ns'))[1]
def dset_source(dset):
if skull_strip==True or skull_strip==dset:
return dset_ss(dset)
else:
return dset
dset_affine = prefix
if dset_affine==None:
dset_affine = os.path.split(nl.suffix(dset_from,suffix))[1]
dset_affine_mat_1D = nl.prefix(dset_affine) + '_matrix.1D'
dset_affine_par_1D = nl.prefix(dset_affine) + '_params.1D'
if os.path.exists(dset_affine):
# final product already exists
return
for dset in [dset_from,dset_to]:
if skull_strip==True or skull_strip==dset:
nl.skull_strip(dset,'_ns')
mask_use = mask
if mask:
# the mask was probably made in the space of the original dset_to anatomy,
# which has now been cropped from the skull stripping. So the lesion mask
# needs to be resampled to match the corresponding mask
if skull_strip==True or skull_strip==dset_to:
nl.run(['3dresample','-master',dset_u(dset_ss(dset)),'-inset',mask,'-prefix',nl.suffix(mask,'_resam')],products=nl.suffix(mask,'_resam'))
mask_use = nl.suffix(mask,'_resam')
all_cmd = [
'3dAllineate',
'-prefix', dset_affine,
'-base', dset_source(dset_to),
'-source', dset_source(dset_from),
'-source_automask',
'-1Dmatrix_save', dset_affine_mat_1D,
'-1Dparam_save',dset_affine_par_1D,
'-autoweight',
'-final',resample,
'-cmass'
] + opts
if grid_size:
all_cmd += ['-newgrid',grid_size]
if cost:
all_cmd += ['-cost',cost]
if epi:
all_cmd += ['-EPI']
if mask:
all_cmd += ['-emask', mask_use]
nl.run(all_cmd,products=dset_affine) | [
"def",
"affine_align",
"(",
"dset_from",
",",
"dset_to",
",",
"skull_strip",
"=",
"True",
",",
"mask",
"=",
"None",
",",
"suffix",
"=",
"'_aff'",
",",
"prefix",
"=",
"None",
",",
"cost",
"=",
"None",
",",
"epi",
"=",
"False",
",",
"resample",
"=",
"'... | interface to 3dAllineate to align anatomies and EPIs | [
"interface",
"to",
"3dAllineate",
"to",
"align",
"anatomies",
"and",
"EPIs"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L51-L105 |
azraq27/neural | neural/alignment.py | affine_apply | def affine_apply(dset_from,affine_1D,master,affine_suffix='_aff',interp='NN',inverse=False,prefix=None):
'''apply the 1D file from a previously aligned dataset
Applies the matrix in ``affine_1D`` to ``dset_from`` and makes the final grid look like the dataset ``master``
using the interpolation method ``interp``. If ``inverse`` is True, will apply the inverse of ``affine_1D`` instead'''
affine_1D_use = affine_1D
if inverse:
with tempfile.NamedTemporaryFile(delete=False) as temp:
temp.write(subprocess.check_output(['cat_matvec',affine_1D,'-I']))
affine_1D_use = temp.name
if prefix==None:
prefix = nl.suffix(dset_from,affine_suffix)
nl.run(['3dAllineate','-1Dmatrix_apply',affine_1D_use,'-input',dset_from,'-prefix',prefix,'-master',master,'-final',interp],products=prefix) | python | def affine_apply(dset_from,affine_1D,master,affine_suffix='_aff',interp='NN',inverse=False,prefix=None):
'''apply the 1D file from a previously aligned dataset
Applies the matrix in ``affine_1D`` to ``dset_from`` and makes the final grid look like the dataset ``master``
using the interpolation method ``interp``. If ``inverse`` is True, will apply the inverse of ``affine_1D`` instead'''
affine_1D_use = affine_1D
if inverse:
with tempfile.NamedTemporaryFile(delete=False) as temp:
temp.write(subprocess.check_output(['cat_matvec',affine_1D,'-I']))
affine_1D_use = temp.name
if prefix==None:
prefix = nl.suffix(dset_from,affine_suffix)
nl.run(['3dAllineate','-1Dmatrix_apply',affine_1D_use,'-input',dset_from,'-prefix',prefix,'-master',master,'-final',interp],products=prefix) | [
"def",
"affine_apply",
"(",
"dset_from",
",",
"affine_1D",
",",
"master",
",",
"affine_suffix",
"=",
"'_aff'",
",",
"interp",
"=",
"'NN'",
",",
"inverse",
"=",
"False",
",",
"prefix",
"=",
"None",
")",
":",
"affine_1D_use",
"=",
"affine_1D",
"if",
"inverse... | apply the 1D file from a previously aligned dataset
Applies the matrix in ``affine_1D`` to ``dset_from`` and makes the final grid look like the dataset ``master``
using the interpolation method ``interp``. If ``inverse`` is True, will apply the inverse of ``affine_1D`` instead | [
"apply",
"the",
"1D",
"file",
"from",
"a",
"previously",
"aligned",
"dataset",
"Applies",
"the",
"matrix",
"in",
"affine_1D",
"to",
"dset_from",
"and",
"makes",
"the",
"final",
"grid",
"look",
"like",
"the",
"dataset",
"master",
"using",
"the",
"interpolation"... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L107-L118 |
azraq27/neural | neural/alignment.py | convert_coord | def convert_coord(coord_from,matrix_file,base_to_aligned=True):
'''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False``'''
with open(matrix_file) as f:
try:
values = [float(y) for y in ' '.join([x for x in f.readlines() if x.strip()[0]!='#']).strip().split()]
except:
nl.notify('Error reading values from matrix file %s' % matrix_file, level=nl.level.error)
return False
if len(values)!=12:
nl.notify('Error: found %d values in matrix file %s (expecting 12)' % (len(values),matrix_file), level=nl.level.error)
return False
matrix = np.vstack((np.array(values).reshape((3,-1)),[0,0,0,1]))
if not base_to_aligned:
matrix = np.linalg.inv(matrix)
return np.dot(matrix,list(coord_from) + [1])[:3] | python | def convert_coord(coord_from,matrix_file,base_to_aligned=True):
'''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False``'''
with open(matrix_file) as f:
try:
values = [float(y) for y in ' '.join([x for x in f.readlines() if x.strip()[0]!='#']).strip().split()]
except:
nl.notify('Error reading values from matrix file %s' % matrix_file, level=nl.level.error)
return False
if len(values)!=12:
nl.notify('Error: found %d values in matrix file %s (expecting 12)' % (len(values),matrix_file), level=nl.level.error)
return False
matrix = np.vstack((np.array(values).reshape((3,-1)),[0,0,0,1]))
if not base_to_aligned:
matrix = np.linalg.inv(matrix)
return np.dot(matrix,list(coord_from) + [1])[:3] | [
"def",
"convert_coord",
"(",
"coord_from",
",",
"matrix_file",
",",
"base_to_aligned",
"=",
"True",
")",
":",
"with",
"open",
"(",
"matrix_file",
")",
"as",
"f",
":",
"try",
":",
"values",
"=",
"[",
"float",
"(",
"y",
")",
"for",
"y",
"in",
"' '",
".... | Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False`` | [
"Takes",
"an",
"XYZ",
"array",
"(",
"in",
"DICOM",
"coordinates",
")",
"and",
"uses",
"the",
"matrix",
"file",
"produced",
"by",
"3dAllineate",
"to",
"transform",
"it",
".",
"By",
"default",
"the",
"3dAllineate",
"matrix",
"transforms",
"from",
"base",
"to",... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L120-L135 |
azraq27/neural | neural/alignment.py | qwarp_align | def qwarp_align(dset_from,dset_to,skull_strip=True,mask=None,affine_suffix='_aff',suffix='_qwarp',prefix=None):
'''aligns ``dset_from`` to ``dset_to`` using 3dQwarp
Will run ``3dSkullStrip`` (unless ``skull_strip`` is ``False``), ``3dUnifize``,
``3dAllineate``, and then ``3dQwarp``. This method will add suffixes to the input
dataset for the intermediate files (e.g., ``_ss``, ``_u``). If those files already
exist, it will assume they were intelligently named, and use them as is
:skull_strip: If True/False, turns skull-stripping of both datasets on/off.
If a string matching ``dset_from`` or ``dset_to``, will only
skull-strip the given dataset
:mask: Applies the given mask to the alignment. Because of the nature
of the alignment algorithms, the mask is **always** applied to
the ``dset_to``. If this isn't what you want, you need to reverse
the transform and re-apply it (e.g., using :meth:`qwarp_invert`
and :meth:`qwarp_apply`). If the ``dset_to`` dataset is skull-stripped,
the mask will also be resampled to match the ``dset_to`` grid.
:affine_suffix: Suffix applied to ``dset_from`` to name the new dataset, as well as
the ``.1D`` file.
:suffix: Suffix applied to the final ``dset_from`` dataset. An additional file
with the additional suffix ``_WARP`` will be created containing the parameters
(e.g., with the default ``_qwarp`` suffix, the parameters will be in a file with
the suffix ``_qwarp_WARP``)
:prefix: Alternatively to ``suffix``, explicitly give the full output filename
The output affine dataset and 1D, as well as the output of qwarp are named by adding
the given suffixes (``affine_suffix`` and ``qwarp_suffix``) to the ``dset_from`` file
If ``skull_strip`` is a string instead of ``True``/``False``, it will only skull strip the given
dataset instead of both of them
# TODO: currently does not work with +tlrc datasets because the filenames get mangled
'''
dset_ss = lambda dset: os.path.split(nl.suffix(dset,'_ns'))[1]
dset_u = lambda dset: os.path.split(nl.suffix(dset,'_u'))[1]
def dset_source(dset):
if skull_strip==True or skull_strip==dset:
return dset_ss(dset)
else:
return dset
dset_affine = os.path.split(nl.suffix(dset_from,affine_suffix))[1]
dset_affine_1D = nl.prefix(dset_affine) + '.1D'
dset_qwarp = prefix
if dset_qwarp==None:
dset_qwarp = os.path.split(nl.suffix(dset_from,suffix))[1]
if os.path.exists(dset_qwarp):
# final product already exists
return
affine_align(dset_from,dset_to,skull_strip,mask,affine_suffix)
for dset in [dset_from,dset_to]:
nl.run([
'3dUnifize',
'-prefix', dset_u(dset_source(dset)),
'-input', dset_source(dset)
],products=[dset_u(dset_source(dset))])
mask_use = mask
if mask:
# the mask was probably made in the space of the original dset_to anatomy,
# which has now been cropped from the skull stripping. So the lesion mask
# needs to be resampled to match the corresponding mask
if skull_strip==True or skull_strip==dset_to:
nl.run(['3dresample','-master',dset_u(dset_ss(dset)),'-inset',mask,'-prefix',nl.suffix(mask,'_resam')],products=nl.suffix(mask,'_resam'))
mask_use = nl.suffix(mask,'_resam')
warp_cmd = [
'3dQwarp',
'-prefix', dset_qwarp,
'-duplo', '-useweight', '-blur', '0', '3',
'-iwarp',
'-base', dset_u(dset_source(dset_to)),
'-source', dset_affine
]
if mask:
warp_cmd += ['-emask', mask_use]
nl.run(warp_cmd,products=dset_qwarp) | python | def qwarp_align(dset_from,dset_to,skull_strip=True,mask=None,affine_suffix='_aff',suffix='_qwarp',prefix=None):
'''aligns ``dset_from`` to ``dset_to`` using 3dQwarp
Will run ``3dSkullStrip`` (unless ``skull_strip`` is ``False``), ``3dUnifize``,
``3dAllineate``, and then ``3dQwarp``. This method will add suffixes to the input
dataset for the intermediate files (e.g., ``_ss``, ``_u``). If those files already
exist, it will assume they were intelligently named, and use them as is
:skull_strip: If True/False, turns skull-stripping of both datasets on/off.
If a string matching ``dset_from`` or ``dset_to``, will only
skull-strip the given dataset
:mask: Applies the given mask to the alignment. Because of the nature
of the alignment algorithms, the mask is **always** applied to
the ``dset_to``. If this isn't what you want, you need to reverse
the transform and re-apply it (e.g., using :meth:`qwarp_invert`
and :meth:`qwarp_apply`). If the ``dset_to`` dataset is skull-stripped,
the mask will also be resampled to match the ``dset_to`` grid.
:affine_suffix: Suffix applied to ``dset_from`` to name the new dataset, as well as
the ``.1D`` file.
:suffix: Suffix applied to the final ``dset_from`` dataset. An additional file
with the additional suffix ``_WARP`` will be created containing the parameters
(e.g., with the default ``_qwarp`` suffix, the parameters will be in a file with
the suffix ``_qwarp_WARP``)
:prefix: Alternatively to ``suffix``, explicitly give the full output filename
The output affine dataset and 1D, as well as the output of qwarp are named by adding
the given suffixes (``affine_suffix`` and ``qwarp_suffix``) to the ``dset_from`` file
If ``skull_strip`` is a string instead of ``True``/``False``, it will only skull strip the given
dataset instead of both of them
# TODO: currently does not work with +tlrc datasets because the filenames get mangled
'''
dset_ss = lambda dset: os.path.split(nl.suffix(dset,'_ns'))[1]
dset_u = lambda dset: os.path.split(nl.suffix(dset,'_u'))[1]
def dset_source(dset):
if skull_strip==True or skull_strip==dset:
return dset_ss(dset)
else:
return dset
dset_affine = os.path.split(nl.suffix(dset_from,affine_suffix))[1]
dset_affine_1D = nl.prefix(dset_affine) + '.1D'
dset_qwarp = prefix
if dset_qwarp==None:
dset_qwarp = os.path.split(nl.suffix(dset_from,suffix))[1]
if os.path.exists(dset_qwarp):
# final product already exists
return
affine_align(dset_from,dset_to,skull_strip,mask,affine_suffix)
for dset in [dset_from,dset_to]:
nl.run([
'3dUnifize',
'-prefix', dset_u(dset_source(dset)),
'-input', dset_source(dset)
],products=[dset_u(dset_source(dset))])
mask_use = mask
if mask:
# the mask was probably made in the space of the original dset_to anatomy,
# which has now been cropped from the skull stripping. So the lesion mask
# needs to be resampled to match the corresponding mask
if skull_strip==True or skull_strip==dset_to:
nl.run(['3dresample','-master',dset_u(dset_ss(dset)),'-inset',mask,'-prefix',nl.suffix(mask,'_resam')],products=nl.suffix(mask,'_resam'))
mask_use = nl.suffix(mask,'_resam')
warp_cmd = [
'3dQwarp',
'-prefix', dset_qwarp,
'-duplo', '-useweight', '-blur', '0', '3',
'-iwarp',
'-base', dset_u(dset_source(dset_to)),
'-source', dset_affine
]
if mask:
warp_cmd += ['-emask', mask_use]
nl.run(warp_cmd,products=dset_qwarp) | [
"def",
"qwarp_align",
"(",
"dset_from",
",",
"dset_to",
",",
"skull_strip",
"=",
"True",
",",
"mask",
"=",
"None",
",",
"affine_suffix",
"=",
"'_aff'",
",",
"suffix",
"=",
"'_qwarp'",
",",
"prefix",
"=",
"None",
")",
":",
"dset_ss",
"=",
"lambda",
"dset"... | aligns ``dset_from`` to ``dset_to`` using 3dQwarp
Will run ``3dSkullStrip`` (unless ``skull_strip`` is ``False``), ``3dUnifize``,
``3dAllineate``, and then ``3dQwarp``. This method will add suffixes to the input
dataset for the intermediate files (e.g., ``_ss``, ``_u``). If those files already
exist, it will assume they were intelligently named, and use them as is
:skull_strip: If True/False, turns skull-stripping of both datasets on/off.
If a string matching ``dset_from`` or ``dset_to``, will only
skull-strip the given dataset
:mask: Applies the given mask to the alignment. Because of the nature
of the alignment algorithms, the mask is **always** applied to
the ``dset_to``. If this isn't what you want, you need to reverse
the transform and re-apply it (e.g., using :meth:`qwarp_invert`
and :meth:`qwarp_apply`). If the ``dset_to`` dataset is skull-stripped,
the mask will also be resampled to match the ``dset_to`` grid.
:affine_suffix: Suffix applied to ``dset_from`` to name the new dataset, as well as
the ``.1D`` file.
:suffix: Suffix applied to the final ``dset_from`` dataset. An additional file
with the additional suffix ``_WARP`` will be created containing the parameters
(e.g., with the default ``_qwarp`` suffix, the parameters will be in a file with
the suffix ``_qwarp_WARP``)
:prefix: Alternatively to ``suffix``, explicitly give the full output filename
The output affine dataset and 1D, as well as the output of qwarp are named by adding
the given suffixes (``affine_suffix`` and ``qwarp_suffix``) to the ``dset_from`` file
If ``skull_strip`` is a string instead of ``True``/``False``, it will only skull strip the given
dataset instead of both of them
# TODO: currently does not work with +tlrc datasets because the filenames get mangled | [
"aligns",
"dset_from",
"to",
"dset_to",
"using",
"3dQwarp"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L138-L220 |
azraq27/neural | neural/alignment.py | qwarp_apply | def qwarp_apply(dset_from,dset_warp,affine=None,warp_suffix='_warp',master='WARP',interp=None,prefix=None):
'''applies the transform from a previous qwarp
Uses the warp parameters from the dataset listed in
``dset_warp`` (usually the dataset name ends in ``_WARP``)
to the dataset ``dset_from``. If a ``.1D`` file is given
in the ``affine`` parameter, it will be applied simultaneously
with the qwarp.
If the parameter ``interp`` is given, will use as interpolation method,
otherwise it will just use the default (currently wsinc5)
Output dataset with have the ``warp_suffix`` suffix added to its name
'''
out_dset = prefix
if out_dset==None:
out_dset = os.path.split(nl.suffix(dset_from,warp_suffix))[1]
dset_from_info = nl.dset_info(dset_from)
dset_warp_info = nl.dset_info(dset_warp)
if(dset_from_info.orient!=dset_warp_info.orient):
# If the datasets are different orientations, the transform won't be applied correctly
nl.run(['3dresample','-orient',dset_warp_info.orient,'-prefix',nl.suffix(dset_from,'_reorient'),'-inset',dset_from],products=nl.suffix(dset_from,'_reorient'))
dset_from = nl.suffix(dset_from,'_reorient')
warp_opt = str(dset_warp)
if affine:
warp_opt += ' ' + affine
cmd = [
'3dNwarpApply',
'-nwarp', warp_opt]
cmd += [
'-source', dset_from,
'-master',master,
'-prefix', out_dset
]
if interp:
cmd += ['-interp',interp]
nl.run(cmd,products=out_dset) | python | def qwarp_apply(dset_from,dset_warp,affine=None,warp_suffix='_warp',master='WARP',interp=None,prefix=None):
'''applies the transform from a previous qwarp
Uses the warp parameters from the dataset listed in
``dset_warp`` (usually the dataset name ends in ``_WARP``)
to the dataset ``dset_from``. If a ``.1D`` file is given
in the ``affine`` parameter, it will be applied simultaneously
with the qwarp.
If the parameter ``interp`` is given, will use as interpolation method,
otherwise it will just use the default (currently wsinc5)
Output dataset with have the ``warp_suffix`` suffix added to its name
'''
out_dset = prefix
if out_dset==None:
out_dset = os.path.split(nl.suffix(dset_from,warp_suffix))[1]
dset_from_info = nl.dset_info(dset_from)
dset_warp_info = nl.dset_info(dset_warp)
if(dset_from_info.orient!=dset_warp_info.orient):
# If the datasets are different orientations, the transform won't be applied correctly
nl.run(['3dresample','-orient',dset_warp_info.orient,'-prefix',nl.suffix(dset_from,'_reorient'),'-inset',dset_from],products=nl.suffix(dset_from,'_reorient'))
dset_from = nl.suffix(dset_from,'_reorient')
warp_opt = str(dset_warp)
if affine:
warp_opt += ' ' + affine
cmd = [
'3dNwarpApply',
'-nwarp', warp_opt]
cmd += [
'-source', dset_from,
'-master',master,
'-prefix', out_dset
]
if interp:
cmd += ['-interp',interp]
nl.run(cmd,products=out_dset) | [
"def",
"qwarp_apply",
"(",
"dset_from",
",",
"dset_warp",
",",
"affine",
"=",
"None",
",",
"warp_suffix",
"=",
"'_warp'",
",",
"master",
"=",
"'WARP'",
",",
"interp",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"out_dset",
"=",
"prefix",
"if",
"... | applies the transform from a previous qwarp
Uses the warp parameters from the dataset listed in
``dset_warp`` (usually the dataset name ends in ``_WARP``)
to the dataset ``dset_from``. If a ``.1D`` file is given
in the ``affine`` parameter, it will be applied simultaneously
with the qwarp.
If the parameter ``interp`` is given, will use as interpolation method,
otherwise it will just use the default (currently wsinc5)
Output dataset with have the ``warp_suffix`` suffix added to its name | [
"applies",
"the",
"transform",
"from",
"a",
"previous",
"qwarp"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L222-L260 |
azraq27/neural | neural/alignment.py | qwarp_invert | def qwarp_invert(warp_param_dset,output_dset,affine_1Dfile=None):
'''inverts a qwarp (defined in ``warp_param_dset``) (and concatenates affine matrix ``affine_1Dfile`` if given)
outputs the inverted warp + affine to ``output_dset``'''
cmd = ['3dNwarpCat','-prefix',output_dset]
if affine_1Dfile:
cmd += ['-warp1','INV(%s)' % affine_1Dfile, '-warp2','INV(%s)' % warp_param_dset]
else:
cmd += ['-warp1','INV(%s)' % warp_param_dset]
nl.run(cmd,products=output_dset) | python | def qwarp_invert(warp_param_dset,output_dset,affine_1Dfile=None):
'''inverts a qwarp (defined in ``warp_param_dset``) (and concatenates affine matrix ``affine_1Dfile`` if given)
outputs the inverted warp + affine to ``output_dset``'''
cmd = ['3dNwarpCat','-prefix',output_dset]
if affine_1Dfile:
cmd += ['-warp1','INV(%s)' % affine_1Dfile, '-warp2','INV(%s)' % warp_param_dset]
else:
cmd += ['-warp1','INV(%s)' % warp_param_dset]
nl.run(cmd,products=output_dset) | [
"def",
"qwarp_invert",
"(",
"warp_param_dset",
",",
"output_dset",
",",
"affine_1Dfile",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'3dNwarpCat'",
",",
"'-prefix'",
",",
"output_dset",
"]",
"if",
"affine_1Dfile",
":",
"cmd",
"+=",
"[",
"'-warp1'",
",",
"'INV(%... | inverts a qwarp (defined in ``warp_param_dset``) (and concatenates affine matrix ``affine_1Dfile`` if given)
outputs the inverted warp + affine to ``output_dset`` | [
"inverts",
"a",
"qwarp",
"(",
"defined",
"in",
"warp_param_dset",
")",
"(",
"and",
"concatenates",
"affine",
"matrix",
"affine_1Dfile",
"if",
"given",
")",
"outputs",
"the",
"inverted",
"warp",
"+",
"affine",
"to",
"output_dset"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L262-L273 |
azraq27/neural | neural/alignment.py | qwarp_epi | def qwarp_epi(dset,align_subbrick=5,suffix='_qwal',prefix=None):
'''aligns an EPI time-series using 3dQwarp
Very expensive and not efficient at all, but it can produce pretty impressive alignment for EPI time-series with significant
distortions due to motion'''
info = nl.dset_info(dset)
if info==None:
nl.notify('Error reading dataset "%s"' % (dset),level=nl.level.error)
return False
if prefix==None:
prefix = nl.suffix(dset,suffix)
dset_sub = lambda x: '_tmp_qwarp_epi-%s_%d.nii.gz' % (nl.prefix(dset),x)
try:
align_dset = nl.suffix(dset_sub(align_subbrick),'_warp')
nl.calc('%s[%d]' % (dset,align_subbrick),expr='a',prefix=align_dset,datum='float')
for i in xrange(info.reps):
if i != align_subbrick:
nl.calc('%s[%d]' % (dset,i),expr='a',prefix=dset_sub(i),datum='float')
nl.run([
'3dQwarp', '-nowarp',
'-workhard', '-superhard', '-minpatch', '9', '-blur', '0',
'-pear', '-nopenalty',
'-base', align_dset,
'-source', dset_sub(i),
'-prefix', nl.suffix(dset_sub(i),'_warp')
],quiet=True)
cmd = ['3dTcat','-prefix',prefix]
if info.TR:
cmd += ['-tr',info.TR]
if info.slice_timing:
cmd += ['-tpattern',info.slice_timing]
cmd += [nl.suffix(dset_sub(i),'_warp') for i in xrange(info.reps)]
nl.run(cmd,quiet=True)
except Exception as e:
raise e
finally:
for i in xrange(info.reps):
for suffix in ['','warp']:
try:
os.remove(nl.suffix(dset_sub(i),suffix))
except:
pass | python | def qwarp_epi(dset,align_subbrick=5,suffix='_qwal',prefix=None):
'''aligns an EPI time-series using 3dQwarp
Very expensive and not efficient at all, but it can produce pretty impressive alignment for EPI time-series with significant
distortions due to motion'''
info = nl.dset_info(dset)
if info==None:
nl.notify('Error reading dataset "%s"' % (dset),level=nl.level.error)
return False
if prefix==None:
prefix = nl.suffix(dset,suffix)
dset_sub = lambda x: '_tmp_qwarp_epi-%s_%d.nii.gz' % (nl.prefix(dset),x)
try:
align_dset = nl.suffix(dset_sub(align_subbrick),'_warp')
nl.calc('%s[%d]' % (dset,align_subbrick),expr='a',prefix=align_dset,datum='float')
for i in xrange(info.reps):
if i != align_subbrick:
nl.calc('%s[%d]' % (dset,i),expr='a',prefix=dset_sub(i),datum='float')
nl.run([
'3dQwarp', '-nowarp',
'-workhard', '-superhard', '-minpatch', '9', '-blur', '0',
'-pear', '-nopenalty',
'-base', align_dset,
'-source', dset_sub(i),
'-prefix', nl.suffix(dset_sub(i),'_warp')
],quiet=True)
cmd = ['3dTcat','-prefix',prefix]
if info.TR:
cmd += ['-tr',info.TR]
if info.slice_timing:
cmd += ['-tpattern',info.slice_timing]
cmd += [nl.suffix(dset_sub(i),'_warp') for i in xrange(info.reps)]
nl.run(cmd,quiet=True)
except Exception as e:
raise e
finally:
for i in xrange(info.reps):
for suffix in ['','warp']:
try:
os.remove(nl.suffix(dset_sub(i),suffix))
except:
pass | [
"def",
"qwarp_epi",
"(",
"dset",
",",
"align_subbrick",
"=",
"5",
",",
"suffix",
"=",
"'_qwal'",
",",
"prefix",
"=",
"None",
")",
":",
"info",
"=",
"nl",
".",
"dset_info",
"(",
"dset",
")",
"if",
"info",
"==",
"None",
":",
"nl",
".",
"notify",
"(",... | aligns an EPI time-series using 3dQwarp
Very expensive and not efficient at all, but it can produce pretty impressive alignment for EPI time-series with significant
distortions due to motion | [
"aligns",
"an",
"EPI",
"time",
"-",
"series",
"using",
"3dQwarp"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L276-L317 |
azraq27/neural | neural/alignment.py | align_epi_anat | def align_epi_anat(anatomy,epi_dsets,skull_strip_anat=True):
''' aligns epis to anatomy using ``align_epi_anat.py`` script
:epi_dsets: can be either a string or list of strings of the epi child datasets
:skull_strip_anat: if ``True``, ``anatomy`` will be skull-stripped using the default method
The default output suffix is "_al"
'''
if isinstance(epi_dsets,basestring):
epi_dsets = [epi_dsets]
if len(epi_dsets)==0:
nl.notify('Warning: no epi alignment datasets given for anatomy %s!' % anatomy,level=nl.level.warning)
return
if all(os.path.exists(nl.suffix(x,'_al')) for x in epi_dsets):
return
anatomy_use = anatomy
if skull_strip_anat:
nl.skull_strip(anatomy,'_ns')
anatomy_use = nl.suffix(anatomy,'_ns')
inputs = [anatomy_use] + epi_dsets
dset_products = lambda dset: [nl.suffix(dset,'_al'), nl.prefix(dset)+'_al_mat.aff12.1D', nl.prefix(dset)+'_tsh_vr_motion.1D']
products = nl.flatten([dset_products(dset) for dset in epi_dsets])
with nl.run_in_tmp(inputs,products):
if nl.is_nifti(anatomy_use):
anatomy_use = nl.afni_copy(anatomy_use)
epi_dsets_use = []
for dset in epi_dsets:
if nl.is_nifti(dset):
epi_dsets_use.append(nl.afni_copy(dset))
else:
epi_dsets_use.append(dset)
cmd = ["align_epi_anat.py", "-epi2anat", "-anat_has_skull", "no", "-epi_strip", "3dAutomask","-anat", anatomy_use, "-epi_base", "5", "-epi", epi_dsets_use[0]]
if len(epi_dsets_use)>1:
cmd += ['-child_epi'] + epi_dsets_use[1:]
out = nl.run(cmd)
for dset in epi_dsets:
if nl.is_nifti(dset):
dset_nifti = nl.nifti_copy(nl.prefix(dset)+'_al+orig')
if dset_nifti and os.path.exists(dset_nifti) and dset_nifti.endswith('.nii') and dset.endswith('.gz'):
nl.run(['gzip',dset_nifti]) | python | def align_epi_anat(anatomy,epi_dsets,skull_strip_anat=True):
''' aligns epis to anatomy using ``align_epi_anat.py`` script
:epi_dsets: can be either a string or list of strings of the epi child datasets
:skull_strip_anat: if ``True``, ``anatomy`` will be skull-stripped using the default method
The default output suffix is "_al"
'''
if isinstance(epi_dsets,basestring):
epi_dsets = [epi_dsets]
if len(epi_dsets)==0:
nl.notify('Warning: no epi alignment datasets given for anatomy %s!' % anatomy,level=nl.level.warning)
return
if all(os.path.exists(nl.suffix(x,'_al')) for x in epi_dsets):
return
anatomy_use = anatomy
if skull_strip_anat:
nl.skull_strip(anatomy,'_ns')
anatomy_use = nl.suffix(anatomy,'_ns')
inputs = [anatomy_use] + epi_dsets
dset_products = lambda dset: [nl.suffix(dset,'_al'), nl.prefix(dset)+'_al_mat.aff12.1D', nl.prefix(dset)+'_tsh_vr_motion.1D']
products = nl.flatten([dset_products(dset) for dset in epi_dsets])
with nl.run_in_tmp(inputs,products):
if nl.is_nifti(anatomy_use):
anatomy_use = nl.afni_copy(anatomy_use)
epi_dsets_use = []
for dset in epi_dsets:
if nl.is_nifti(dset):
epi_dsets_use.append(nl.afni_copy(dset))
else:
epi_dsets_use.append(dset)
cmd = ["align_epi_anat.py", "-epi2anat", "-anat_has_skull", "no", "-epi_strip", "3dAutomask","-anat", anatomy_use, "-epi_base", "5", "-epi", epi_dsets_use[0]]
if len(epi_dsets_use)>1:
cmd += ['-child_epi'] + epi_dsets_use[1:]
out = nl.run(cmd)
for dset in epi_dsets:
if nl.is_nifti(dset):
dset_nifti = nl.nifti_copy(nl.prefix(dset)+'_al+orig')
if dset_nifti and os.path.exists(dset_nifti) and dset_nifti.endswith('.nii') and dset.endswith('.gz'):
nl.run(['gzip',dset_nifti]) | [
"def",
"align_epi_anat",
"(",
"anatomy",
",",
"epi_dsets",
",",
"skull_strip_anat",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"epi_dsets",
",",
"basestring",
")",
":",
"epi_dsets",
"=",
"[",
"epi_dsets",
"]",
"if",
"len",
"(",
"epi_dsets",
")",
"==",... | aligns epis to anatomy using ``align_epi_anat.py`` script
:epi_dsets: can be either a string or list of strings of the epi child datasets
:skull_strip_anat: if ``True``, ``anatomy`` will be skull-stripped using the default method
The default output suffix is "_al" | [
"aligns",
"epis",
"to",
"anatomy",
"using",
"align_epi_anat",
".",
"py",
"script"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L319-L365 |
azraq27/neural | neural/alignment.py | skullstrip_template | def skullstrip_template(dset,template,prefix=None,suffix=None,dilate=0):
'''Takes the raw anatomy ``dset``, aligns it to a template brain, and applies a templated skullstrip. Should produce fairly reliable skullstrips as long
as there is a decent amount of normal brain and the overall shape of the brain is normal-ish'''
if suffix==None:
suffix = '_sstemplate'
if prefix==None:
prefix = nl.suffix(dset,suffix)
if not os.path.exists(prefix):
with nl.notify('Running template-based skull-strip on %s' % dset):
dset = os.path.abspath(dset)
template = os.path.abspath(template)
tmp_dir = tempfile.mkdtemp()
cwd = os.getcwd()
with nl.run_in(tmp_dir):
nl.affine_align(template,dset,skull_strip=None,cost='mi',opts=['-nmatch','100%'])
nl.run(['3dQwarp','-minpatch','20','-penfac','10','-noweight','-source',nl.suffix(template,'_aff'),'-base',dset,'-prefix',nl.suffix(template,'_qwarp')],products=nl.suffix(template,'_qwarp'))
info = nl.dset_info(nl.suffix(template,'_qwarp'))
max_value = info.subbricks[0]['max']
nl.calc([dset,nl.suffix(template,'_qwarp')],'a*step(b-%f*0.05)'%max_value,prefix)
shutil.move(prefix,cwd)
shutil.rmtree(tmp_dir) | python | def skullstrip_template(dset,template,prefix=None,suffix=None,dilate=0):
'''Takes the raw anatomy ``dset``, aligns it to a template brain, and applies a templated skullstrip. Should produce fairly reliable skullstrips as long
as there is a decent amount of normal brain and the overall shape of the brain is normal-ish'''
if suffix==None:
suffix = '_sstemplate'
if prefix==None:
prefix = nl.suffix(dset,suffix)
if not os.path.exists(prefix):
with nl.notify('Running template-based skull-strip on %s' % dset):
dset = os.path.abspath(dset)
template = os.path.abspath(template)
tmp_dir = tempfile.mkdtemp()
cwd = os.getcwd()
with nl.run_in(tmp_dir):
nl.affine_align(template,dset,skull_strip=None,cost='mi',opts=['-nmatch','100%'])
nl.run(['3dQwarp','-minpatch','20','-penfac','10','-noweight','-source',nl.suffix(template,'_aff'),'-base',dset,'-prefix',nl.suffix(template,'_qwarp')],products=nl.suffix(template,'_qwarp'))
info = nl.dset_info(nl.suffix(template,'_qwarp'))
max_value = info.subbricks[0]['max']
nl.calc([dset,nl.suffix(template,'_qwarp')],'a*step(b-%f*0.05)'%max_value,prefix)
shutil.move(prefix,cwd)
shutil.rmtree(tmp_dir) | [
"def",
"skullstrip_template",
"(",
"dset",
",",
"template",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"dilate",
"=",
"0",
")",
":",
"if",
"suffix",
"==",
"None",
":",
"suffix",
"=",
"'_sstemplate'",
"if",
"prefix",
"==",
"None",
":",... | Takes the raw anatomy ``dset``, aligns it to a template brain, and applies a templated skullstrip. Should produce fairly reliable skullstrips as long
as there is a decent amount of normal brain and the overall shape of the brain is normal-ish | [
"Takes",
"the",
"raw",
"anatomy",
"dset",
"aligns",
"it",
"to",
"a",
"template",
"brain",
"and",
"applies",
"a",
"templated",
"skullstrip",
".",
"Should",
"produce",
"fairly",
"reliable",
"skullstrips",
"as",
"long",
"as",
"there",
"is",
"a",
"decent",
"amou... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L367-L387 |
Kraymer/high | high/__init__.py | printmp | def printmp(msg):
"""Print temporarily, until next print overrides it.
"""
filler = (80 - len(msg)) * ' '
print(msg + filler, end='\r')
sys.stdout.flush() | python | def printmp(msg):
"""Print temporarily, until next print overrides it.
"""
filler = (80 - len(msg)) * ' '
print(msg + filler, end='\r')
sys.stdout.flush() | [
"def",
"printmp",
"(",
"msg",
")",
":",
"filler",
"=",
"(",
"80",
"-",
"len",
"(",
"msg",
")",
")",
"*",
"' '",
"print",
"(",
"msg",
"+",
"filler",
",",
"end",
"=",
"'\\r'",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | Print temporarily, until next print overrides it. | [
"Print",
"temporarily",
"until",
"next",
"print",
"overrides",
"it",
"."
] | train | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/high/__init__.py#L29-L34 |
Kraymer/high | high/__init__.py | contacts | def contacts(github, logins):
"""Extract public contact info from users.
"""
printmp('Fetching contacts')
users = [github.user(login).as_dict() for login in logins]
mails = set()
blogs = set()
for user in users:
contact = user.get('name', 'login')
if user['email']:
contact += ' <%s>' % user['email']
mails.add(contact)
elif user['blog']:
contact += ' <%s>' % user['blog']
blogs.add(contact)
else:
continue
return mails, blogs | python | def contacts(github, logins):
"""Extract public contact info from users.
"""
printmp('Fetching contacts')
users = [github.user(login).as_dict() for login in logins]
mails = set()
blogs = set()
for user in users:
contact = user.get('name', 'login')
if user['email']:
contact += ' <%s>' % user['email']
mails.add(contact)
elif user['blog']:
contact += ' <%s>' % user['blog']
blogs.add(contact)
else:
continue
return mails, blogs | [
"def",
"contacts",
"(",
"github",
",",
"logins",
")",
":",
"printmp",
"(",
"'Fetching contacts'",
")",
"users",
"=",
"[",
"github",
".",
"user",
"(",
"login",
")",
".",
"as_dict",
"(",
")",
"for",
"login",
"in",
"logins",
"]",
"mails",
"=",
"set",
"(... | Extract public contact info from users. | [
"Extract",
"public",
"contact",
"info",
"from",
"users",
"."
] | train | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/high/__init__.py#L37-L54 |
Kraymer/high | high/__init__.py | extract_mail | def extract_mail(issues):
"""Extract mails that sometimes leak from issue comments.
"""
contacts = set()
for idx, issue in enumerate(issues):
printmp('Fetching issue #%s' % idx)
for comment in issue.comments():
comm = comment.as_dict()
emails = list(email[0] for email in re.findall(MAIL_REGEX, comm['body'])
if not email[0].startswith('//') and not email[0].endswith('github.com') and
'@' in email[0])
contacts |= set(emails)
return contacts | python | def extract_mail(issues):
"""Extract mails that sometimes leak from issue comments.
"""
contacts = set()
for idx, issue in enumerate(issues):
printmp('Fetching issue #%s' % idx)
for comment in issue.comments():
comm = comment.as_dict()
emails = list(email[0] for email in re.findall(MAIL_REGEX, comm['body'])
if not email[0].startswith('//') and not email[0].endswith('github.com') and
'@' in email[0])
contacts |= set(emails)
return contacts | [
"def",
"extract_mail",
"(",
"issues",
")",
":",
"contacts",
"=",
"set",
"(",
")",
"for",
"idx",
",",
"issue",
"in",
"enumerate",
"(",
"issues",
")",
":",
"printmp",
"(",
"'Fetching issue #%s'",
"%",
"idx",
")",
"for",
"comment",
"in",
"issue",
".",
"co... | Extract mails that sometimes leak from issue comments. | [
"Extract",
"mails",
"that",
"sometimes",
"leak",
"from",
"issue",
"comments",
"."
] | train | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/high/__init__.py#L57-L69 |
Kraymer/high | high/__init__.py | fetch_logins | def fetch_logins(roles, repo):
"""Fetch logins for users with given roles.
"""
users = set()
if 'stargazer' in roles:
printmp('Fetching stargazers')
users |= set(repo.stargazers())
if 'collaborator' in roles:
printmp('Fetching collaborators')
users |= set(repo.collaborators())
if 'issue' in roles:
printmp('Fetching issues creators')
users |= set([i.user for i in repo.issues(state='all')])
return users | python | def fetch_logins(roles, repo):
"""Fetch logins for users with given roles.
"""
users = set()
if 'stargazer' in roles:
printmp('Fetching stargazers')
users |= set(repo.stargazers())
if 'collaborator' in roles:
printmp('Fetching collaborators')
users |= set(repo.collaborators())
if 'issue' in roles:
printmp('Fetching issues creators')
users |= set([i.user for i in repo.issues(state='all')])
return users | [
"def",
"fetch_logins",
"(",
"roles",
",",
"repo",
")",
":",
"users",
"=",
"set",
"(",
")",
"if",
"'stargazer'",
"in",
"roles",
":",
"printmp",
"(",
"'Fetching stargazers'",
")",
"users",
"|=",
"set",
"(",
"repo",
".",
"stargazers",
"(",
")",
")",
"if",... | Fetch logins for users with given roles. | [
"Fetch",
"logins",
"for",
"users",
"with",
"given",
"roles",
"."
] | train | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/high/__init__.py#L72-L85 |
Kraymer/high | high/__init__.py | high_cli | def high_cli(repo_name, login, with_blog, as_list, role):
"""Extract mails from stargazers, collaborators and people involved with issues of given
repository.
"""
passw = getpass.getpass()
github = gh_login(login, passw)
repo = github.repository(login, repo_name)
role = [ROLES[k] for k in role]
users = fetch_logins(role, repo)
mails, blogs = contacts(github, users)
if 'issue' in role:
mails |= extract_mail(repo.issues(state='all'))
# Print results
sep = ', ' if as_list else '\n'
print(sep.join(mails))
if with_blog:
print(sep.join(blogs)) | python | def high_cli(repo_name, login, with_blog, as_list, role):
"""Extract mails from stargazers, collaborators and people involved with issues of given
repository.
"""
passw = getpass.getpass()
github = gh_login(login, passw)
repo = github.repository(login, repo_name)
role = [ROLES[k] for k in role]
users = fetch_logins(role, repo)
mails, blogs = contacts(github, users)
if 'issue' in role:
mails |= extract_mail(repo.issues(state='all'))
# Print results
sep = ', ' if as_list else '\n'
print(sep.join(mails))
if with_blog:
print(sep.join(blogs)) | [
"def",
"high_cli",
"(",
"repo_name",
",",
"login",
",",
"with_blog",
",",
"as_list",
",",
"role",
")",
":",
"passw",
"=",
"getpass",
".",
"getpass",
"(",
")",
"github",
"=",
"gh_login",
"(",
"login",
",",
"passw",
")",
"repo",
"=",
"github",
".",
"re... | Extract mails from stargazers, collaborators and people involved with issues of given
repository. | [
"Extract",
"mails",
"from",
"stargazers",
"collaborators",
"and",
"people",
"involved",
"with",
"issues",
"of",
"given",
"repository",
"."
] | train | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/high/__init__.py#L100-L118 |
cohorte/cohorte-herald | python/herald/transports/xmpp/bot.py | HeraldBot.__callback | def __callback(self, data):
"""
Safely calls back a method
:param data: Associated stanza
"""
method = self.__cb_message
if method is not None:
try:
method(data)
except Exception as ex:
_logger.exception("Error calling method: %s", ex) | python | def __callback(self, data):
"""
Safely calls back a method
:param data: Associated stanza
"""
method = self.__cb_message
if method is not None:
try:
method(data)
except Exception as ex:
_logger.exception("Error calling method: %s", ex) | [
"def",
"__callback",
"(",
"self",
",",
"data",
")",
":",
"method",
"=",
"self",
".",
"__cb_message",
"if",
"method",
"is",
"not",
"None",
":",
"try",
":",
"method",
"(",
"data",
")",
"except",
"Exception",
"as",
"ex",
":",
"_logger",
".",
"exception",
... | Safely calls back a method
:param data: Associated stanza | [
"Safely",
"calls",
"back",
"a",
"method"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/transports/xmpp/bot.py#L81-L92 |
cohorte/cohorte-herald | python/herald/transports/xmpp/bot.py | HeraldBot.__on_message | def __on_message(self, msg):
"""
XMPP message received
"""
msgtype = msg['type']
msgfrom = msg['from']
if msgtype == 'groupchat':
# MUC Room chat
if self._nick == msgfrom.resource:
# Loopback message
return
elif msgtype not in ('normal', 'chat'):
# Ignore non-chat messages
return
# Callback
self.__callback(msg) | python | def __on_message(self, msg):
"""
XMPP message received
"""
msgtype = msg['type']
msgfrom = msg['from']
if msgtype == 'groupchat':
# MUC Room chat
if self._nick == msgfrom.resource:
# Loopback message
return
elif msgtype not in ('normal', 'chat'):
# Ignore non-chat messages
return
# Callback
self.__callback(msg) | [
"def",
"__on_message",
"(",
"self",
",",
"msg",
")",
":",
"msgtype",
"=",
"msg",
"[",
"'type'",
"]",
"msgfrom",
"=",
"msg",
"[",
"'from'",
"]",
"if",
"msgtype",
"==",
"'groupchat'",
":",
"# MUC Room chat",
"if",
"self",
".",
"_nick",
"==",
"msgfrom",
"... | XMPP message received | [
"XMPP",
"message",
"received"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/transports/xmpp/bot.py#L94-L110 |
etcher-be/epab | epab/cmd/_freeze.py | freeze | def freeze(ctx, version: str, clean: bool):
"""
Freeze current package into a single file
"""
if clean:
_clean_spec()
ctx.invoke(epab.cmd.compile_qt_resources)
_freeze(version) | python | def freeze(ctx, version: str, clean: bool):
"""
Freeze current package into a single file
"""
if clean:
_clean_spec()
ctx.invoke(epab.cmd.compile_qt_resources)
_freeze(version) | [
"def",
"freeze",
"(",
"ctx",
",",
"version",
":",
"str",
",",
"clean",
":",
"bool",
")",
":",
"if",
"clean",
":",
"_clean_spec",
"(",
")",
"ctx",
".",
"invoke",
"(",
"epab",
".",
"cmd",
".",
"compile_qt_resources",
")",
"_freeze",
"(",
"version",
")"... | Freeze current package into a single file | [
"Freeze",
"current",
"package",
"into",
"a",
"single",
"file"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_freeze.py#L120-L127 |
scivision/gridaurora | gridaurora/ztanh.py | setupz | def setupz(Np: int, zmin: float, gridmin: float, gridmax: float) -> np.ndarray:
"""
np: number of grid points
zmin: minimum STEP SIZE at minimum grid altitude [km]
gridmin: minimum altitude of grid [km]
gridmax: maximum altitude of grid [km]
"""
dz = _ztanh(Np, gridmin, gridmax)
return np.insert(np.cumsum(dz)+zmin, 0, zmin)[:-1] | python | def setupz(Np: int, zmin: float, gridmin: float, gridmax: float) -> np.ndarray:
"""
np: number of grid points
zmin: minimum STEP SIZE at minimum grid altitude [km]
gridmin: minimum altitude of grid [km]
gridmax: maximum altitude of grid [km]
"""
dz = _ztanh(Np, gridmin, gridmax)
return np.insert(np.cumsum(dz)+zmin, 0, zmin)[:-1] | [
"def",
"setupz",
"(",
"Np",
":",
"int",
",",
"zmin",
":",
"float",
",",
"gridmin",
":",
"float",
",",
"gridmax",
":",
"float",
")",
"->",
"np",
".",
"ndarray",
":",
"dz",
"=",
"_ztanh",
"(",
"Np",
",",
"gridmin",
",",
"gridmax",
")",
"return",
"n... | np: number of grid points
zmin: minimum STEP SIZE at minimum grid altitude [km]
gridmin: minimum altitude of grid [km]
gridmax: maximum altitude of grid [km] | [
"np",
":",
"number",
"of",
"grid",
"points",
"zmin",
":",
"minimum",
"STEP",
"SIZE",
"at",
"minimum",
"grid",
"altitude",
"[",
"km",
"]",
"gridmin",
":",
"minimum",
"altitude",
"of",
"grid",
"[",
"km",
"]",
"gridmax",
":",
"maximum",
"altitude",
"of",
... | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/ztanh.py#L9-L19 |
scivision/gridaurora | gridaurora/ztanh.py | _ztanh | def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray:
"""
typically call via setupz instead
"""
x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote
return np.tanh(x0)*gridmax+gridmin | python | def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray:
"""
typically call via setupz instead
"""
x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote
return np.tanh(x0)*gridmax+gridmin | [
"def",
"_ztanh",
"(",
"Np",
":",
"int",
",",
"gridmin",
":",
"float",
",",
"gridmax",
":",
"float",
")",
"->",
"np",
".",
"ndarray",
":",
"x0",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"3.14",
",",
"Np",
")",
"# arbitrarily picking 3.14 as where tanh... | typically call via setupz instead | [
"typically",
"call",
"via",
"setupz",
"instead"
] | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/ztanh.py#L22-L27 |
clinicedc/edc-notification | edc_notification/site_notifications.py | SiteNotifications.get | def get(self, name):
"""Returns a Notification by name.
"""
if not self.loaded:
raise RegistryNotLoaded(self)
if not self._registry.get(name):
raise NotificationNotRegistered(
f"Notification not registered. Got '{name}'."
)
return self._registry.get(name) | python | def get(self, name):
"""Returns a Notification by name.
"""
if not self.loaded:
raise RegistryNotLoaded(self)
if not self._registry.get(name):
raise NotificationNotRegistered(
f"Notification not registered. Got '{name}'."
)
return self._registry.get(name) | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"self",
".",
"loaded",
":",
"raise",
"RegistryNotLoaded",
"(",
"self",
")",
"if",
"not",
"self",
".",
"_registry",
".",
"get",
"(",
"name",
")",
":",
"raise",
"NotificationNotRegistered",
"... | Returns a Notification by name. | [
"Returns",
"a",
"Notification",
"by",
"name",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L47-L56 |
clinicedc/edc-notification | edc_notification/site_notifications.py | SiteNotifications.register | def register(self, notification_cls=None):
"""Registers a Notification class unique by name.
"""
self.loaded = True
display_names = [n.display_name for n in self.registry.values()]
if (
notification_cls.name not in self.registry
and notification_cls.display_name not in display_names
):
self.registry.update({notification_cls.name: notification_cls})
models = getattr(notification_cls, "models", [])
if not models and getattr(notification_cls, "model", None):
models = [getattr(notification_cls, "model")]
for model in models:
try:
if notification_cls.name not in [
n.name for n in self.models[model]
]:
self.models[model].append(notification_cls)
except KeyError:
self.models.update({model: [notification_cls]})
else:
raise AlreadyRegistered(
f"Notification {notification_cls.name}: "
f"{notification_cls.display_name} is already registered."
) | python | def register(self, notification_cls=None):
"""Registers a Notification class unique by name.
"""
self.loaded = True
display_names = [n.display_name for n in self.registry.values()]
if (
notification_cls.name not in self.registry
and notification_cls.display_name not in display_names
):
self.registry.update({notification_cls.name: notification_cls})
models = getattr(notification_cls, "models", [])
if not models and getattr(notification_cls, "model", None):
models = [getattr(notification_cls, "model")]
for model in models:
try:
if notification_cls.name not in [
n.name for n in self.models[model]
]:
self.models[model].append(notification_cls)
except KeyError:
self.models.update({model: [notification_cls]})
else:
raise AlreadyRegistered(
f"Notification {notification_cls.name}: "
f"{notification_cls.display_name} is already registered."
) | [
"def",
"register",
"(",
"self",
",",
"notification_cls",
"=",
"None",
")",
":",
"self",
".",
"loaded",
"=",
"True",
"display_names",
"=",
"[",
"n",
".",
"display_name",
"for",
"n",
"in",
"self",
".",
"registry",
".",
"values",
"(",
")",
"]",
"if",
"(... | Registers a Notification class unique by name. | [
"Registers",
"a",
"Notification",
"class",
"unique",
"by",
"name",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L58-L84 |
clinicedc/edc-notification | edc_notification/site_notifications.py | SiteNotifications.notify | def notify(self, instance=None, **kwargs):
"""A wrapper to call notification.notify for each notification
class associated with the given model instance.
Returns a dictionary of {notification.name: model, ...}
including only notifications sent.
"""
notified = {}
for notification_cls in self.registry.values():
notification = notification_cls()
if notification.notify(instance=instance, **kwargs):
notified.update({notification_cls.name: instance._meta.label_lower})
return notified | python | def notify(self, instance=None, **kwargs):
"""A wrapper to call notification.notify for each notification
class associated with the given model instance.
Returns a dictionary of {notification.name: model, ...}
including only notifications sent.
"""
notified = {}
for notification_cls in self.registry.values():
notification = notification_cls()
if notification.notify(instance=instance, **kwargs):
notified.update({notification_cls.name: instance._meta.label_lower})
return notified | [
"def",
"notify",
"(",
"self",
",",
"instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"notified",
"=",
"{",
"}",
"for",
"notification_cls",
"in",
"self",
".",
"registry",
".",
"values",
"(",
")",
":",
"notification",
"=",
"notification_cls",
"... | A wrapper to call notification.notify for each notification
class associated with the given model instance.
Returns a dictionary of {notification.name: model, ...}
including only notifications sent. | [
"A",
"wrapper",
"to",
"call",
"notification",
".",
"notify",
"for",
"each",
"notification",
"class",
"associated",
"with",
"the",
"given",
"model",
"instance",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L86-L98 |
clinicedc/edc-notification | edc_notification/site_notifications.py | SiteNotifications.update_notification_list | def update_notification_list(self, apps=None, schema_editor=None, verbose=False):
"""Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notification does not exist. See notification.notify()
"""
Notification = (apps or django_apps).get_model("edc_notification.notification")
# flag all notifications as disabled and re-enable as required
Notification.objects.all().update(enabled=False)
if site_notifications.loaded:
if verbose:
sys.stdout.write(
style.MIGRATE_HEADING("Populating Notification model:\n")
)
self.delete_unregistered_notifications(apps=apps)
for name, notification_cls in site_notifications.registry.items():
if verbose:
sys.stdout.write(
f" * Adding '{name}': '{notification_cls().display_name}'\n"
)
try:
obj = Notification.objects.get(name=name)
except ObjectDoesNotExist:
Notification.objects.create(
name=name,
display_name=notification_cls().display_name,
enabled=True,
)
else:
obj.display_name = notification_cls().display_name
obj.enabled = True
obj.save() | python | def update_notification_list(self, apps=None, schema_editor=None, verbose=False):
"""Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notification does not exist. See notification.notify()
"""
Notification = (apps or django_apps).get_model("edc_notification.notification")
# flag all notifications as disabled and re-enable as required
Notification.objects.all().update(enabled=False)
if site_notifications.loaded:
if verbose:
sys.stdout.write(
style.MIGRATE_HEADING("Populating Notification model:\n")
)
self.delete_unregistered_notifications(apps=apps)
for name, notification_cls in site_notifications.registry.items():
if verbose:
sys.stdout.write(
f" * Adding '{name}': '{notification_cls().display_name}'\n"
)
try:
obj = Notification.objects.get(name=name)
except ObjectDoesNotExist:
Notification.objects.create(
name=name,
display_name=notification_cls().display_name,
enabled=True,
)
else:
obj.display_name = notification_cls().display_name
obj.enabled = True
obj.save() | [
"def",
"update_notification_list",
"(",
"self",
",",
"apps",
"=",
"None",
",",
"schema_editor",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"Notification",
"=",
"(",
"apps",
"or",
"django_apps",
")",
".",
"get_model",
"(",
"\"edc_notification.notifica... | Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notification does not exist. See notification.notify() | [
"Updates",
"the",
"notification",
"model",
"to",
"ensure",
"all",
"registered",
"notifications",
"classes",
"are",
"listed",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L100-L136 |
clinicedc/edc-notification | edc_notification/site_notifications.py | SiteNotifications.delete_unregistered_notifications | def delete_unregistered_notifications(self, apps=None):
"""Delete orphaned notification model instances.
"""
Notification = (apps or django_apps).get_model("edc_notification.notification")
return Notification.objects.exclude(
name__in=[n.name for n in site_notifications.registry.values()]
).delete() | python | def delete_unregistered_notifications(self, apps=None):
"""Delete orphaned notification model instances.
"""
Notification = (apps or django_apps).get_model("edc_notification.notification")
return Notification.objects.exclude(
name__in=[n.name for n in site_notifications.registry.values()]
).delete() | [
"def",
"delete_unregistered_notifications",
"(",
"self",
",",
"apps",
"=",
"None",
")",
":",
"Notification",
"=",
"(",
"apps",
"or",
"django_apps",
")",
".",
"get_model",
"(",
"\"edc_notification.notification\"",
")",
"return",
"Notification",
".",
"objects",
".",... | Delete orphaned notification model instances. | [
"Delete",
"orphaned",
"notification",
"model",
"instances",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L138-L144 |
clinicedc/edc-notification | edc_notification/site_notifications.py | SiteNotifications.create_mailing_lists | def create_mailing_lists(self, verbose=True):
"""Creates the mailing list for each registered notification.
"""
responses = {}
if (
settings.EMAIL_ENABLED
and self.loaded
and settings.EMAIL_BACKEND
!= "django.core.mail.backends.locmem.EmailBackend"
):
sys.stdout.write(style.MIGRATE_HEADING(f"Creating mailing lists:\n"))
for name, notification_cls in self.registry.items():
message = None
notification = notification_cls()
manager = MailingListManager(
address=notification.email_to,
name=notification.name,
display_name=notification.display_name,
)
try:
response = manager.create()
except ConnectionError as e:
sys.stdout.write(
style.ERROR(
f" * Failed to create mailing list {name}. " f"Got {e}\n"
)
)
else:
if verbose:
try:
message = response.json().get("message")
except JSONDecodeError:
message = response.text
sys.stdout.write(
f" * Creating mailing list {name}. "
f'Got {response.status_code}: "{message}"\n'
)
responses.update({name: response})
return responses | python | def create_mailing_lists(self, verbose=True):
"""Creates the mailing list for each registered notification.
"""
responses = {}
if (
settings.EMAIL_ENABLED
and self.loaded
and settings.EMAIL_BACKEND
!= "django.core.mail.backends.locmem.EmailBackend"
):
sys.stdout.write(style.MIGRATE_HEADING(f"Creating mailing lists:\n"))
for name, notification_cls in self.registry.items():
message = None
notification = notification_cls()
manager = MailingListManager(
address=notification.email_to,
name=notification.name,
display_name=notification.display_name,
)
try:
response = manager.create()
except ConnectionError as e:
sys.stdout.write(
style.ERROR(
f" * Failed to create mailing list {name}. " f"Got {e}\n"
)
)
else:
if verbose:
try:
message = response.json().get("message")
except JSONDecodeError:
message = response.text
sys.stdout.write(
f" * Creating mailing list {name}. "
f'Got {response.status_code}: "{message}"\n'
)
responses.update({name: response})
return responses | [
"def",
"create_mailing_lists",
"(",
"self",
",",
"verbose",
"=",
"True",
")",
":",
"responses",
"=",
"{",
"}",
"if",
"(",
"settings",
".",
"EMAIL_ENABLED",
"and",
"self",
".",
"loaded",
"and",
"settings",
".",
"EMAIL_BACKEND",
"!=",
"\"django.core.mail.backend... | Creates the mailing list for each registered notification. | [
"Creates",
"the",
"mailing",
"list",
"for",
"each",
"registered",
"notification",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L146-L184 |
clinicedc/edc-notification | edc_notification/site_notifications.py | SiteNotifications.autodiscover | def autodiscover(self, module_name=None, verbose=False):
"""Autodiscovers classes in the notifications.py file of any
INSTALLED_APP.
"""
module_name = module_name or "notifications"
verbose = True if verbose is None else verbose
sys.stdout.write(f" * checking for {module_name} ...\n")
for app in django_apps.app_configs:
try:
mod = import_module(app)
try:
before_import_registry = copy.copy(site_notifications._registry)
import_module(f"{app}.{module_name}")
if verbose:
sys.stdout.write(
f" * registered notifications from application '{app}'\n"
)
except Exception as e:
if f"No module named '{app}.{module_name}'" not in str(e):
site_notifications._registry = before_import_registry
if module_has_submodule(mod, module_name):
raise
except ModuleNotFoundError:
pass | python | def autodiscover(self, module_name=None, verbose=False):
"""Autodiscovers classes in the notifications.py file of any
INSTALLED_APP.
"""
module_name = module_name or "notifications"
verbose = True if verbose is None else verbose
sys.stdout.write(f" * checking for {module_name} ...\n")
for app in django_apps.app_configs:
try:
mod = import_module(app)
try:
before_import_registry = copy.copy(site_notifications._registry)
import_module(f"{app}.{module_name}")
if verbose:
sys.stdout.write(
f" * registered notifications from application '{app}'\n"
)
except Exception as e:
if f"No module named '{app}.{module_name}'" not in str(e):
site_notifications._registry = before_import_registry
if module_has_submodule(mod, module_name):
raise
except ModuleNotFoundError:
pass | [
"def",
"autodiscover",
"(",
"self",
",",
"module_name",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"module_name",
"=",
"module_name",
"or",
"\"notifications\"",
"verbose",
"=",
"True",
"if",
"verbose",
"is",
"None",
"else",
"verbose",
"sys",
".",
... | Autodiscovers classes in the notifications.py file of any
INSTALLED_APP. | [
"Autodiscovers",
"classes",
"in",
"the",
"notifications",
".",
"py",
"file",
"of",
"any",
"INSTALLED_APP",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L186-L209 |
six8/corona-cipr | src/cipr/commands/cfg.py | CiprCfg.add_package | def add_package(self, package):
"""
Add a package to this project
"""
self._data.setdefault('packages', {})
self._data['packages'][package.name] = package.source
for package in package.deploy_packages:
self.add_package(package)
self._save() | python | def add_package(self, package):
"""
Add a package to this project
"""
self._data.setdefault('packages', {})
self._data['packages'][package.name] = package.source
for package in package.deploy_packages:
self.add_package(package)
self._save() | [
"def",
"add_package",
"(",
"self",
",",
"package",
")",
":",
"self",
".",
"_data",
".",
"setdefault",
"(",
"'packages'",
",",
"{",
"}",
")",
"self",
".",
"_data",
"[",
"'packages'",
"]",
"[",
"package",
".",
"name",
"]",
"=",
"package",
".",
"source"... | Add a package to this project | [
"Add",
"a",
"package",
"to",
"this",
"project"
] | train | https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/cfg.py#L73-L84 |
Gr1N/copypaste | copypaste/unix.py | copy | def copy(string, cmd=copy_cmd, stdin=PIPE):
"""Copy given string into system clipboard.
"""
Popen(cmd, stdin=stdin).communicate(string.encode('utf-8')) | python | def copy(string, cmd=copy_cmd, stdin=PIPE):
"""Copy given string into system clipboard.
"""
Popen(cmd, stdin=stdin).communicate(string.encode('utf-8')) | [
"def",
"copy",
"(",
"string",
",",
"cmd",
"=",
"copy_cmd",
",",
"stdin",
"=",
"PIPE",
")",
":",
"Popen",
"(",
"cmd",
",",
"stdin",
"=",
"stdin",
")",
".",
"communicate",
"(",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | Copy given string into system clipboard. | [
"Copy",
"given",
"string",
"into",
"system",
"clipboard",
"."
] | train | https://github.com/Gr1N/copypaste/blob/7d515d1d31db5ae686378b60e4c8717d7f6834de/copypaste/unix.py#L24-L27 |
Gr1N/copypaste | copypaste/unix.py | paste | def paste(cmd=paste_cmd, stdout=PIPE):
"""Returns system clipboard contents.
"""
return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8') | python | def paste(cmd=paste_cmd, stdout=PIPE):
"""Returns system clipboard contents.
"""
return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8') | [
"def",
"paste",
"(",
"cmd",
"=",
"paste_cmd",
",",
"stdout",
"=",
"PIPE",
")",
":",
"return",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"stdout",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"'utf-8'",
")"
] | Returns system clipboard contents. | [
"Returns",
"system",
"clipboard",
"contents",
"."
] | train | https://github.com/Gr1N/copypaste/blob/7d515d1d31db5ae686378b60e4c8717d7f6834de/copypaste/unix.py#L30-L33 |
victorfsf/djurls | djurls/decorators.py | umap | def umap(path, name=None, include=None, namespace=None, priority=None):
"""
Maps a given URL path, name and namespace to a view.
Arguments:
- path: the URL regex, e.g.: '^teste/(?P<pk>[0-9])/$'.
Optional arguments:
- name: the URL name, which Django uses to identify the URL;
- include: A custom URL list, previously
set on the module's urls.py;
- namespace: the URL's namespace;
- priority: the URL's priority;
"""
def url_wrapper(view):
# gets the module name
module = _find_urls_module(view)
# gets the view function (checking if it's a class-based view)
fn = view.as_view() if hasattr(view, 'as_view') else view
if namespace and include:
raise TypeError(
'You can\'t use \'namespace\' and \'include\''
' at the same time!'
)
if namespace:
# imports the urlpatterns object
base = import_string('{}.urls.urlpatterns'.format(module))
# searchs for the namespace
urlpatterns_list = [
x for x in base
if getattr(x, 'namespace', None) == namespace
]
# if the list length is different than 1,
# then the namespace is either duplicated or doesn't exist
if len(urlpatterns_list) != 1:
raise ValueError(
'Namespace \'{}\' not in list.'.format(namespace)
)
# if the namespace was found, get its object
urlpatterns = urlpatterns_list.pop(0).url_patterns
else:
# imports the urlpatterns object
urlpatterns = import_string('{}.urls.{}'.format(
module,
include or 'urlpatterns'
))
# appends the url with its given name
call = (
urlpatterns.append if priority is None
else partial(urlpatterns.insert, priority)
)
call(url(path, fn, name=name))
return view
return url_wrapper | python | def umap(path, name=None, include=None, namespace=None, priority=None):
"""
Maps a given URL path, name and namespace to a view.
Arguments:
- path: the URL regex, e.g.: '^teste/(?P<pk>[0-9])/$'.
Optional arguments:
- name: the URL name, which Django uses to identify the URL;
- include: A custom URL list, previously
set on the module's urls.py;
- namespace: the URL's namespace;
- priority: the URL's priority;
"""
def url_wrapper(view):
# gets the module name
module = _find_urls_module(view)
# gets the view function (checking if it's a class-based view)
fn = view.as_view() if hasattr(view, 'as_view') else view
if namespace and include:
raise TypeError(
'You can\'t use \'namespace\' and \'include\''
' at the same time!'
)
if namespace:
# imports the urlpatterns object
base = import_string('{}.urls.urlpatterns'.format(module))
# searchs for the namespace
urlpatterns_list = [
x for x in base
if getattr(x, 'namespace', None) == namespace
]
# if the list length is different than 1,
# then the namespace is either duplicated or doesn't exist
if len(urlpatterns_list) != 1:
raise ValueError(
'Namespace \'{}\' not in list.'.format(namespace)
)
# if the namespace was found, get its object
urlpatterns = urlpatterns_list.pop(0).url_patterns
else:
# imports the urlpatterns object
urlpatterns = import_string('{}.urls.{}'.format(
module,
include or 'urlpatterns'
))
# appends the url with its given name
call = (
urlpatterns.append if priority is None
else partial(urlpatterns.insert, priority)
)
call(url(path, fn, name=name))
return view
return url_wrapper | [
"def",
"umap",
"(",
"path",
",",
"name",
"=",
"None",
",",
"include",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"priority",
"=",
"None",
")",
":",
"def",
"url_wrapper",
"(",
"view",
")",
":",
"# gets the module name",
"module",
"=",
"_find_urls_mo... | Maps a given URL path, name and namespace to a view.
Arguments:
- path: the URL regex, e.g.: '^teste/(?P<pk>[0-9])/$'.
Optional arguments:
- name: the URL name, which Django uses to identify the URL;
- include: A custom URL list, previously
set on the module's urls.py;
- namespace: the URL's namespace;
- priority: the URL's priority; | [
"Maps",
"a",
"given",
"URL",
"path",
"name",
"and",
"namespace",
"to",
"a",
"view",
".",
"Arguments",
":",
"-",
"path",
":",
"the",
"URL",
"regex",
"e",
".",
"g",
".",
":",
"^teste",
"/",
"(",
"?P<pk",
">",
"[",
"0",
"-",
"9",
"]",
")",
"/",
... | train | https://github.com/victorfsf/djurls/blob/c90a46e5e17c12dd6920100419a89e428baf4711/djurls/decorators.py#L8-L62 |
pulseenergy/vacation | vacation/rc.py | touch | def touch():
""" Create a .vacationrc file if none exists. """
if not os.path.isfile(get_rc_path()):
open(get_rc_path(), 'a').close()
print('Created file: {}'.format(get_rc_path())) | python | def touch():
""" Create a .vacationrc file if none exists. """
if not os.path.isfile(get_rc_path()):
open(get_rc_path(), 'a').close()
print('Created file: {}'.format(get_rc_path())) | [
"def",
"touch",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"get_rc_path",
"(",
")",
")",
":",
"open",
"(",
"get_rc_path",
"(",
")",
",",
"'a'",
")",
".",
"close",
"(",
")",
"print",
"(",
"'Created file: {}'",
".",
"format",
... | Create a .vacationrc file if none exists. | [
"Create",
"a",
".",
"vacationrc",
"file",
"if",
"none",
"exists",
"."
] | train | https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/rc.py#L9-L13 |
pulseenergy/vacation | vacation/rc.py | write | def write(entries):
""" Write an entire rc file. """
try:
with open(get_rc_path(), 'w') as rc:
rc.writelines(entries)
except IOError:
print('Error writing your ~/.vacationrc file!') | python | def write(entries):
""" Write an entire rc file. """
try:
with open(get_rc_path(), 'w') as rc:
rc.writelines(entries)
except IOError:
print('Error writing your ~/.vacationrc file!') | [
"def",
"write",
"(",
"entries",
")",
":",
"try",
":",
"with",
"open",
"(",
"get_rc_path",
"(",
")",
",",
"'w'",
")",
"as",
"rc",
":",
"rc",
".",
"writelines",
"(",
"entries",
")",
"except",
"IOError",
":",
"print",
"(",
"'Error writing your ~/.vacationrc... | Write an entire rc file. | [
"Write",
"an",
"entire",
"rc",
"file",
"."
] | train | https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/rc.py#L26-L32 |
pulseenergy/vacation | vacation/rc.py | append | def append(entry):
""" Append either a list of strings or a string to our file. """
if not entry:
return
try:
with open(get_rc_path(), 'a') as f:
if isinstance(entry, list):
f.writelines(entry)
else:
f.write(entry + '\n')
except IOError:
print('Error writing your ~/.vacationrc file!') | python | def append(entry):
""" Append either a list of strings or a string to our file. """
if not entry:
return
try:
with open(get_rc_path(), 'a') as f:
if isinstance(entry, list):
f.writelines(entry)
else:
f.write(entry + '\n')
except IOError:
print('Error writing your ~/.vacationrc file!') | [
"def",
"append",
"(",
"entry",
")",
":",
"if",
"not",
"entry",
":",
"return",
"try",
":",
"with",
"open",
"(",
"get_rc_path",
"(",
")",
",",
"'a'",
")",
"as",
"f",
":",
"if",
"isinstance",
"(",
"entry",
",",
"list",
")",
":",
"f",
".",
"writeline... | Append either a list of strings or a string to our file. | [
"Append",
"either",
"a",
"list",
"of",
"strings",
"or",
"a",
"string",
"to",
"our",
"file",
"."
] | train | https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/rc.py#L44-L55 |
pulseenergy/vacation | vacation/rc.py | delete | def delete(bad_entry):
""" Removes an entry from rc file. """
entries = read()
kept_entries = [x for x in entries if x.rstrip() != bad_entry]
write(kept_entries) | python | def delete(bad_entry):
""" Removes an entry from rc file. """
entries = read()
kept_entries = [x for x in entries if x.rstrip() != bad_entry]
write(kept_entries) | [
"def",
"delete",
"(",
"bad_entry",
")",
":",
"entries",
"=",
"read",
"(",
")",
"kept_entries",
"=",
"[",
"x",
"for",
"x",
"in",
"entries",
"if",
"x",
".",
"rstrip",
"(",
")",
"!=",
"bad_entry",
"]",
"write",
"(",
"kept_entries",
")"
] | Removes an entry from rc file. | [
"Removes",
"an",
"entry",
"from",
"rc",
"file",
"."
] | train | https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/rc.py#L58-L62 |
ulif/dinsort | dinsort.py | normalize | def normalize(text, variant=VARIANT1, case_sensitive=False):
"""Create a normalized version of `text`.
With `variant` set to ``VARIANT1`` (default), german umlauts are
transformed to plain chars: ``ä`` -> ``a``, ``ö`` -> ``o``, ...::
>>> print(normalize("mäßig"))
massig
With `variant` set to ``VARIANT2``, german umlauts are transformed
``ä`` -> ``ae``, etc.::
>>> print(normalize("mäßig", variant=VARIANT2))
maessig
All words are turned to lower-case.::
>>> print(normalize("Maße"))
masse
except if `case_sensitive` is set to `True`::
>>> print(normalize("Maße", case_sensitive=True))
Masse
Other chars with diacritics will be returned with the diacritics
stripped off::
>>> print(normalize("Česká"))
ceska
"""
text = text.replace("ß", "ss")
if not case_sensitive:
text = text.lower()
if variant == VARIANT2:
for char, repl in (
('ä', 'ae'), ('ö', 'oe'), ('ü', 'ue'),
('Ä', 'AE'), ('Ö', 'OE'), ('Ü', 'UE')):
text = text.replace(char, repl)
text = unicodedata.normalize("NFKD", text).encode("ASCII", "ignore")
return text.decode() | python | def normalize(text, variant=VARIANT1, case_sensitive=False):
"""Create a normalized version of `text`.
With `variant` set to ``VARIANT1`` (default), german umlauts are
transformed to plain chars: ``ä`` -> ``a``, ``ö`` -> ``o``, ...::
>>> print(normalize("mäßig"))
massig
With `variant` set to ``VARIANT2``, german umlauts are transformed
``ä`` -> ``ae``, etc.::
>>> print(normalize("mäßig", variant=VARIANT2))
maessig
All words are turned to lower-case.::
>>> print(normalize("Maße"))
masse
except if `case_sensitive` is set to `True`::
>>> print(normalize("Maße", case_sensitive=True))
Masse
Other chars with diacritics will be returned with the diacritics
stripped off::
>>> print(normalize("Česká"))
ceska
"""
text = text.replace("ß", "ss")
if not case_sensitive:
text = text.lower()
if variant == VARIANT2:
for char, repl in (
('ä', 'ae'), ('ö', 'oe'), ('ü', 'ue'),
('Ä', 'AE'), ('Ö', 'OE'), ('Ü', 'UE')):
text = text.replace(char, repl)
text = unicodedata.normalize("NFKD", text).encode("ASCII", "ignore")
return text.decode() | [
"def",
"normalize",
"(",
"text",
",",
"variant",
"=",
"VARIANT1",
",",
"case_sensitive",
"=",
"False",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"\"ß\",",
" ",
"ss\")",
"",
"if",
"not",
"case_sensitive",
":",
"text",
"=",
"text",
".",
"lower"... | Create a normalized version of `text`.
With `variant` set to ``VARIANT1`` (default), german umlauts are
transformed to plain chars: ``ä`` -> ``a``, ``ö`` -> ``o``, ...::
>>> print(normalize("mäßig"))
massig
With `variant` set to ``VARIANT2``, german umlauts are transformed
``ä`` -> ``ae``, etc.::
>>> print(normalize("mäßig", variant=VARIANT2))
maessig
All words are turned to lower-case.::
>>> print(normalize("Maße"))
masse
except if `case_sensitive` is set to `True`::
>>> print(normalize("Maße", case_sensitive=True))
Masse
Other chars with diacritics will be returned with the diacritics
stripped off::
>>> print(normalize("Česká"))
ceska | [
"Create",
"a",
"normalized",
"version",
"of",
"text",
"."
] | train | https://github.com/ulif/dinsort/blob/06c95323dfbe5e536a72a7a58789e61b38fcebc4/dinsort.py#L31-L73 |
ulif/dinsort | dinsort.py | sort_func | def sort_func(variant=VARIANT1, case_sensitive=False):
"""A function generator that can be used for sorting.
All keywords are passed to `normalize()` and generate keywords that
can be passed to `sorted()`::
>>> key = sort_func()
>>> print(sorted(["fur", "far"], key=key))
[u'far', u'fur']
Please note, that `sort_func` returns a function.
"""
return lambda x: normalize(
x, variant=variant, case_sensitive=case_sensitive) | python | def sort_func(variant=VARIANT1, case_sensitive=False):
"""A function generator that can be used for sorting.
All keywords are passed to `normalize()` and generate keywords that
can be passed to `sorted()`::
>>> key = sort_func()
>>> print(sorted(["fur", "far"], key=key))
[u'far', u'fur']
Please note, that `sort_func` returns a function.
"""
return lambda x: normalize(
x, variant=variant, case_sensitive=case_sensitive) | [
"def",
"sort_func",
"(",
"variant",
"=",
"VARIANT1",
",",
"case_sensitive",
"=",
"False",
")",
":",
"return",
"lambda",
"x",
":",
"normalize",
"(",
"x",
",",
"variant",
"=",
"variant",
",",
"case_sensitive",
"=",
"case_sensitive",
")"
] | A function generator that can be used for sorting.
All keywords are passed to `normalize()` and generate keywords that
can be passed to `sorted()`::
>>> key = sort_func()
>>> print(sorted(["fur", "far"], key=key))
[u'far', u'fur']
Please note, that `sort_func` returns a function. | [
"A",
"function",
"generator",
"that",
"can",
"be",
"used",
"for",
"sorting",
"."
] | train | https://github.com/ulif/dinsort/blob/06c95323dfbe5e536a72a7a58789e61b38fcebc4/dinsort.py#L76-L89 |
onjin/ntv | ntv/web.py | fetcher | def fetcher(date=datetime.today(), url_pattern=URL_PATTERN):
"""
Fetch json data from n.pl
Args:
date (date) - default today
url_patter (string) - default URL_PATTERN
Returns:
dict - data from api
"""
api_url = url_pattern % date.strftime('%Y-%m-%d')
headers = {'Referer': 'http://n.pl/program-tv'}
raw_result = requests.get(api_url, headers=headers).json()
return raw_result | python | def fetcher(date=datetime.today(), url_pattern=URL_PATTERN):
"""
Fetch json data from n.pl
Args:
date (date) - default today
url_patter (string) - default URL_PATTERN
Returns:
dict - data from api
"""
api_url = url_pattern % date.strftime('%Y-%m-%d')
headers = {'Referer': 'http://n.pl/program-tv'}
raw_result = requests.get(api_url, headers=headers).json()
return raw_result | [
"def",
"fetcher",
"(",
"date",
"=",
"datetime",
".",
"today",
"(",
")",
",",
"url_pattern",
"=",
"URL_PATTERN",
")",
":",
"api_url",
"=",
"url_pattern",
"%",
"date",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"headers",
"=",
"{",
"'Referer'",
":",
"'http:/... | Fetch json data from n.pl
Args:
date (date) - default today
url_patter (string) - default URL_PATTERN
Returns:
dict - data from api | [
"Fetch",
"json",
"data",
"from",
"n",
".",
"pl"
] | train | https://github.com/onjin/ntv/blob/9baa9cfdff9eca0ebd12b6c456951345a269039f/ntv/web.py#L13-L28 |
onjin/ntv | ntv/web.py | result_to_dict | def result_to_dict(raw_result):
"""
Parse raw result from fetcher into readable dictionary
Args:
raw_result (dict) - raw data from `fetcher`
Returns:
dict - readable dictionary
"""
result = {}
for channel_index, channel in enumerate(raw_result):
channel_id, channel_name = channel[0], channel[1]
channel_result = {
'id': channel_id,
'name': channel_name,
'movies': []
}
for movie in channel[2]:
channel_result['movies'].append({
'title': movie[1],
'start_time': datetime.fromtimestamp(movie[2]),
'end_time': datetime.fromtimestamp(movie[2] + movie[3]),
'inf': True if movie[3] else False,
})
result[channel_id] = channel_result
return result | python | def result_to_dict(raw_result):
"""
Parse raw result from fetcher into readable dictionary
Args:
raw_result (dict) - raw data from `fetcher`
Returns:
dict - readable dictionary
"""
result = {}
for channel_index, channel in enumerate(raw_result):
channel_id, channel_name = channel[0], channel[1]
channel_result = {
'id': channel_id,
'name': channel_name,
'movies': []
}
for movie in channel[2]:
channel_result['movies'].append({
'title': movie[1],
'start_time': datetime.fromtimestamp(movie[2]),
'end_time': datetime.fromtimestamp(movie[2] + movie[3]),
'inf': True if movie[3] else False,
})
result[channel_id] = channel_result
return result | [
"def",
"result_to_dict",
"(",
"raw_result",
")",
":",
"result",
"=",
"{",
"}",
"for",
"channel_index",
",",
"channel",
"in",
"enumerate",
"(",
"raw_result",
")",
":",
"channel_id",
",",
"channel_name",
"=",
"channel",
"[",
"0",
"]",
",",
"channel",
"[",
... | Parse raw result from fetcher into readable dictionary
Args:
raw_result (dict) - raw data from `fetcher`
Returns:
dict - readable dictionary | [
"Parse",
"raw",
"result",
"from",
"fetcher",
"into",
"readable",
"dictionary"
] | train | https://github.com/onjin/ntv/blob/9baa9cfdff9eca0ebd12b6c456951345a269039f/ntv/web.py#L31-L60 |
mozilla/socorrolib | socorrolib/lib/threadlib.py | TaskManager.waitForCompletion | def waitForCompletion (self):
"""Wait for all threads to complete their work
The worker threads are told to quit when they receive a task
that is a tuple of (None, None). This routine puts as many of
those tuples in the task queue as there are threads. As soon as
a thread receives one of these tuples, it dies.
"""
for x in range(self.numberOfThreads):
self.taskQueue.put((None, None))
for t in self.threadList:
# print "attempting to join %s" % t.getName()
t.join() | python | def waitForCompletion (self):
"""Wait for all threads to complete their work
The worker threads are told to quit when they receive a task
that is a tuple of (None, None). This routine puts as many of
those tuples in the task queue as there are threads. As soon as
a thread receives one of these tuples, it dies.
"""
for x in range(self.numberOfThreads):
self.taskQueue.put((None, None))
for t in self.threadList:
# print "attempting to join %s" % t.getName()
t.join() | [
"def",
"waitForCompletion",
"(",
"self",
")",
":",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"numberOfThreads",
")",
":",
"self",
".",
"taskQueue",
".",
"put",
"(",
"(",
"None",
",",
"None",
")",
")",
"for",
"t",
"in",
"self",
".",
"threadList",
... | Wait for all threads to complete their work
The worker threads are told to quit when they receive a task
that is a tuple of (None, None). This routine puts as many of
those tuples in the task queue as there are threads. As soon as
a thread receives one of these tuples, it dies. | [
"Wait",
"for",
"all",
"threads",
"to",
"complete",
"their",
"work"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/threadlib.py#L84-L96 |
mozilla/socorrolib | socorrolib/lib/threadlib.py | TaskManagerThread.run | def run(self):
"""The main routine for a thread's work.
The thread pulls tasks from the manager's task queue and executes
them until it encounters a task with a function that is None.
"""
try:
while True:
aFunction, arguments = self.manager.taskQueue.get()
if aFunction is None:
break
aFunction(arguments)
except KeyboardInterrupt:
import thread
print >>sys.stderr, "%s caught KeyboardInterrupt" % threading.currentThread().getName()
thread.interrupt_main()
except Exception, x:
print >>sys.stderr, "Something BAD happened in %s:" % threading.currentThread().getName()
traceback.print_exc(file=sys.stderr)
print >>sys.stderr, x | python | def run(self):
"""The main routine for a thread's work.
The thread pulls tasks from the manager's task queue and executes
them until it encounters a task with a function that is None.
"""
try:
while True:
aFunction, arguments = self.manager.taskQueue.get()
if aFunction is None:
break
aFunction(arguments)
except KeyboardInterrupt:
import thread
print >>sys.stderr, "%s caught KeyboardInterrupt" % threading.currentThread().getName()
thread.interrupt_main()
except Exception, x:
print >>sys.stderr, "Something BAD happened in %s:" % threading.currentThread().getName()
traceback.print_exc(file=sys.stderr)
print >>sys.stderr, x | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"aFunction",
",",
"arguments",
"=",
"self",
".",
"manager",
".",
"taskQueue",
".",
"get",
"(",
")",
"if",
"aFunction",
"is",
"None",
":",
"break",
"aFunction",
"(",
"arguments",
"... | The main routine for a thread's work.
The thread pulls tasks from the manager's task queue and executes
them until it encounters a task with a function that is None. | [
"The",
"main",
"routine",
"for",
"a",
"thread",
"s",
"work",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/threadlib.py#L117-L136 |
henzk/ape | ape/container_mode/tasks.py | info | def info():
"""
List information about this productive environment
:return:
"""
print()
print('root directory :', tasks.conf.APE_ROOT)
print()
print('active container :', os.environ.get('CONTAINER_NAME', ''))
print()
print('active product :', os.environ.get('PRODUCT_NAME', ''))
print()
print('ape feature selection :', tasks.FEATURE_SELECTION)
print()
print('containers and products:')
print('-' * 30)
print()
for container_name in tasks.get_containers():
print(container_name)
for product_name in tasks.get_products(container_name):
print(' ' + product_name)
print() | python | def info():
"""
List information about this productive environment
:return:
"""
print()
print('root directory :', tasks.conf.APE_ROOT)
print()
print('active container :', os.environ.get('CONTAINER_NAME', ''))
print()
print('active product :', os.environ.get('PRODUCT_NAME', ''))
print()
print('ape feature selection :', tasks.FEATURE_SELECTION)
print()
print('containers and products:')
print('-' * 30)
print()
for container_name in tasks.get_containers():
print(container_name)
for product_name in tasks.get_products(container_name):
print(' ' + product_name)
print() | [
"def",
"info",
"(",
")",
":",
"print",
"(",
")",
"print",
"(",
"'root directory :'",
",",
"tasks",
".",
"conf",
".",
"APE_ROOT",
")",
"print",
"(",
")",
"print",
"(",
"'active container :'",
",",
"os",
".",
"environ",
".",
"get",
"(",
"'CON... | List information about this productive environment
:return: | [
"List",
"information",
"about",
"this",
"productive",
"environment",
":",
"return",
":"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L54-L75 |
henzk/ape | ape/container_mode/tasks.py | cd | def cd(doi):
"""
cd to directory of interest(doi)
a doi can be:
herbert - the container named "herbert"
sdox:dev - product "website" located in container "herbert"
:param doi:
:return:
"""
parts = doi.split(':')
if len(parts) == 2:
container_name, product_name = parts[0], parts[1]
elif len(parts) == 1 and os.environ.get('CONTAINER_NAME'):
# interpret poi as product name if already zapped into a product in order
# to enable simply switching products by doing ape zap prod.
product_name = parts[0]
container_name = os.environ.get('CONTAINER_NAME')
else:
print('unable to parse context - format: <container_name>:<product_name>')
sys.exit(1)
if container_name not in tasks.get_containers():
print('No such container')
else:
if product_name:
if product_name not in tasks.get_products(container_name):
print('No such product')
else:
print(tasks.conf.SOURCE_HEADER)
print('cd ' + tasks.get_product_dir(container_name, product_name))
else:
print(tasks.conf.SOURCE_HEADER)
print('cd ' + tasks.get_container_dir(container_name)) | python | def cd(doi):
"""
cd to directory of interest(doi)
a doi can be:
herbert - the container named "herbert"
sdox:dev - product "website" located in container "herbert"
:param doi:
:return:
"""
parts = doi.split(':')
if len(parts) == 2:
container_name, product_name = parts[0], parts[1]
elif len(parts) == 1 and os.environ.get('CONTAINER_NAME'):
# interpret poi as product name if already zapped into a product in order
# to enable simply switching products by doing ape zap prod.
product_name = parts[0]
container_name = os.environ.get('CONTAINER_NAME')
else:
print('unable to parse context - format: <container_name>:<product_name>')
sys.exit(1)
if container_name not in tasks.get_containers():
print('No such container')
else:
if product_name:
if product_name not in tasks.get_products(container_name):
print('No such product')
else:
print(tasks.conf.SOURCE_HEADER)
print('cd ' + tasks.get_product_dir(container_name, product_name))
else:
print(tasks.conf.SOURCE_HEADER)
print('cd ' + tasks.get_container_dir(container_name)) | [
"def",
"cd",
"(",
"doi",
")",
":",
"parts",
"=",
"doi",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"container_name",
",",
"product_name",
"=",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
"]",
"elif",
"len... | cd to directory of interest(doi)
a doi can be:
herbert - the container named "herbert"
sdox:dev - product "website" located in container "herbert"
:param doi:
:return: | [
"cd",
"to",
"directory",
"of",
"interest",
"(",
"doi",
")"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L79-L115 |
henzk/ape | ape/container_mode/tasks.py | switch | def switch(poi):
"""
Zaps into a specific product specified by switch context to the product of interest(poi)
A poi is:
sdox:dev - for product "dev" located in container "sdox"
If poi does not contain a ":" it is interpreted as product name implying that a product within this
container is already active. So if this task is called with ape zap prod (and the corresponding container is
already zapped in), than only the product is switched.
After the context has been switched to sdox:dev additional commands may be available
that are relevant to sdox:dev
:param poi: product of interest, string: <container_name>:<product_name> or <product_name>.
"""
parts = poi.split(':')
if len(parts) == 2:
container_name, product_name = parts
elif len(parts) == 1 and os.environ.get('CONTAINER_NAME'):
# interpret poi as product name if already zapped into a product in order
# to enable simply switching products by doing ape zap prod.
container_name = os.environ.get('CONTAINER_NAME')
product_name = parts[0]
else:
print('unable to find poi: ', poi)
sys.exit(1)
if container_name not in tasks.get_containers():
raise ContainerNotFound('No such container %s' % container_name)
elif product_name not in tasks.get_products(container_name):
raise ProductNotFound('No such product %s' % product_name)
else:
print(SWITCH_TEMPLATE.format(
source_header=tasks.conf.SOURCE_HEADER,
container_name=container_name,
product_name=product_name
)) | python | def switch(poi):
"""
Zaps into a specific product specified by switch context to the product of interest(poi)
A poi is:
sdox:dev - for product "dev" located in container "sdox"
If poi does not contain a ":" it is interpreted as product name implying that a product within this
container is already active. So if this task is called with ape zap prod (and the corresponding container is
already zapped in), than only the product is switched.
After the context has been switched to sdox:dev additional commands may be available
that are relevant to sdox:dev
:param poi: product of interest, string: <container_name>:<product_name> or <product_name>.
"""
parts = poi.split(':')
if len(parts) == 2:
container_name, product_name = parts
elif len(parts) == 1 and os.environ.get('CONTAINER_NAME'):
# interpret poi as product name if already zapped into a product in order
# to enable simply switching products by doing ape zap prod.
container_name = os.environ.get('CONTAINER_NAME')
product_name = parts[0]
else:
print('unable to find poi: ', poi)
sys.exit(1)
if container_name not in tasks.get_containers():
raise ContainerNotFound('No such container %s' % container_name)
elif product_name not in tasks.get_products(container_name):
raise ProductNotFound('No such product %s' % product_name)
else:
print(SWITCH_TEMPLATE.format(
source_header=tasks.conf.SOURCE_HEADER,
container_name=container_name,
product_name=product_name
)) | [
"def",
"switch",
"(",
"poi",
")",
":",
"parts",
"=",
"poi",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"container_name",
",",
"product_name",
"=",
"parts",
"elif",
"len",
"(",
"parts",
")",
"==",
"1",
"and",
"o... | Zaps into a specific product specified by switch context to the product of interest(poi)
A poi is:
sdox:dev - for product "dev" located in container "sdox"
If poi does not contain a ":" it is interpreted as product name implying that a product within this
container is already active. So if this task is called with ape zap prod (and the corresponding container is
already zapped in), than only the product is switched.
After the context has been switched to sdox:dev additional commands may be available
that are relevant to sdox:dev
:param poi: product of interest, string: <container_name>:<product_name> or <product_name>. | [
"Zaps",
"into",
"a",
"specific",
"product",
"specified",
"by",
"switch",
"context",
"to",
"the",
"product",
"of",
"interest",
"(",
"poi",
")",
"A",
"poi",
"is",
":",
"sdox",
":",
"dev",
"-",
"for",
"product",
"dev",
"located",
"in",
"container",
"sdox"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L127-L163 |
henzk/ape | ape/container_mode/tasks.py | install_container | def install_container(container_name):
"""
Installs the container specified by container_name
:param container_name: string, name of the container
"""
container_dir = os.path.join(os.environ['APE_ROOT_DIR'], container_name)
if os.path.exists(container_dir):
os.environ['CONTAINER_DIR'] = container_dir
else:
raise ContainerNotFound('ERROR: container directory not found: %s' % container_dir)
install_script = os.path.join(container_dir, 'install.py')
if os.path.exists(install_script):
print('... running install.py for %s' % container_name)
subprocess.check_call(['python', install_script])
else:
raise ContainerError('ERROR: this container does not provide an install.py!') | python | def install_container(container_name):
"""
Installs the container specified by container_name
:param container_name: string, name of the container
"""
container_dir = os.path.join(os.environ['APE_ROOT_DIR'], container_name)
if os.path.exists(container_dir):
os.environ['CONTAINER_DIR'] = container_dir
else:
raise ContainerNotFound('ERROR: container directory not found: %s' % container_dir)
install_script = os.path.join(container_dir, 'install.py')
if os.path.exists(install_script):
print('... running install.py for %s' % container_name)
subprocess.check_call(['python', install_script])
else:
raise ContainerError('ERROR: this container does not provide an install.py!') | [
"def",
"install_container",
"(",
"container_name",
")",
":",
"container_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'APE_ROOT_DIR'",
"]",
",",
"container_name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"container_di... | Installs the container specified by container_name
:param container_name: string, name of the container | [
"Installs",
"the",
"container",
"specified",
"by",
"container_name",
":",
"param",
"container_name",
":",
"string",
"name",
"of",
"the",
"container"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L184-L201 |
henzk/ape | ape/container_mode/tasks.py | get_poi_tuple | def get_poi_tuple(poi=None):
"""
Takes the poi or None and returns the container_dir and the product name either of the passed poi
(<container_name>: <product_name>) or from os.environ-
:param poi: optional; <container_name>: <product_name>
:return: tuple of the container directory and the product name
"""
if poi:
parts = poi.split(':')
if len(parts) == 2:
container_name, product_name = parts
if container_name not in tasks.get_containers():
print('No such container')
sys.exit(1)
elif product_name not in tasks.get_products(container_name):
print('No such product')
sys.exit(1)
else:
container_dir = tasks.get_container_dir(container_name)
else:
print('Please check your arguments: --poi <container>:<product>')
sys.exit(1)
else:
container_dir = os.environ.get('CONTAINER_DIR')
product_name = os.environ.get('PRODUCT_NAME')
return container_dir, product_name | python | def get_poi_tuple(poi=None):
"""
Takes the poi or None and returns the container_dir and the product name either of the passed poi
(<container_name>: <product_name>) or from os.environ-
:param poi: optional; <container_name>: <product_name>
:return: tuple of the container directory and the product name
"""
if poi:
parts = poi.split(':')
if len(parts) == 2:
container_name, product_name = parts
if container_name not in tasks.get_containers():
print('No such container')
sys.exit(1)
elif product_name not in tasks.get_products(container_name):
print('No such product')
sys.exit(1)
else:
container_dir = tasks.get_container_dir(container_name)
else:
print('Please check your arguments: --poi <container>:<product>')
sys.exit(1)
else:
container_dir = os.environ.get('CONTAINER_DIR')
product_name = os.environ.get('PRODUCT_NAME')
return container_dir, product_name | [
"def",
"get_poi_tuple",
"(",
"poi",
"=",
"None",
")",
":",
"if",
"poi",
":",
"parts",
"=",
"poi",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"container_name",
",",
"product_name",
"=",
"parts",
"if",
"container_nam... | Takes the poi or None and returns the container_dir and the product name either of the passed poi
(<container_name>: <product_name>) or from os.environ-
:param poi: optional; <container_name>: <product_name>
:return: tuple of the container directory and the product name | [
"Takes",
"the",
"poi",
"or",
"None",
"and",
"returns",
"the",
"container_dir",
"and",
"the",
"product",
"name",
"either",
"of",
"the",
"passed",
"poi",
"(",
"<container_name",
">",
":",
"<product_name",
">",
")",
"or",
"from",
"os",
".",
"environ",
"-",
... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L211-L237 |
henzk/ape | ape/container_mode/tasks.py | validate_product_equation | def validate_product_equation(poi=None):
"""
Validates the product equation.
* Validates the feature order
* Validates the product spec (mandatory functional features)
:param poi: optional product of interest
"""
from . import utils
from . import validators
container_dir, product_name = tasks.get_poi_tuple(poi=poi)
feature_list = utils.get_features_from_equation(container_dir, product_name)
ordering_constraints = utils.get_feature_order_constraints(container_dir)
spec_path = utils.get_feature_ide_paths(container_dir, product_name).product_spec_path
print('*** Starting product.equation validation')
# --------------------------------------------------------
# Validate the feature order
print('\tChecking feature order')
feature_order_validator = validators.FeatureOrderValidator(feature_list, ordering_constraints)
feature_order_validator.check_order()
if feature_order_validator.has_errors():
print('\t\txxx ERROR in your product.equation feature order xxx')
for error in feature_order_validator.get_violations():
print('\t\t\t', error[1])
else:
print('\t\tOK')
# --------------------------------------------------------
# Validate the functional product specification
print('\tChecking functional product spec')
if not os.path.exists(spec_path):
print(
'\t\tSkipped - No product spec exists.\n'
'\t\tYou may create a product spec if you want to ensure that\n'
'\t\trequired functional features are represented in the product equation\n'
'\t\t=> Create spec file featuremodel/productline/<container>/product_spec.json'
)
return
spec_validator = validators.ProductSpecValidator(spec_path, product_name, feature_list)
if not spec_validator.is_valid():
if spec_validator.get_errors_mandatory():
print('\t\tERROR: The following feature are missing', spec_validator.get_errors_mandatory())
if spec_validator.get_errors_never():
print('\t\tERROR: The following feature are not allowed', spec_validator.get_errors_never())
else:
print('\t\tOK')
if feature_order_validator.has_errors() or spec_validator.has_errors():
sys.exit(1) | python | def validate_product_equation(poi=None):
"""
Validates the product equation.
* Validates the feature order
* Validates the product spec (mandatory functional features)
:param poi: optional product of interest
"""
from . import utils
from . import validators
container_dir, product_name = tasks.get_poi_tuple(poi=poi)
feature_list = utils.get_features_from_equation(container_dir, product_name)
ordering_constraints = utils.get_feature_order_constraints(container_dir)
spec_path = utils.get_feature_ide_paths(container_dir, product_name).product_spec_path
print('*** Starting product.equation validation')
# --------------------------------------------------------
# Validate the feature order
print('\tChecking feature order')
feature_order_validator = validators.FeatureOrderValidator(feature_list, ordering_constraints)
feature_order_validator.check_order()
if feature_order_validator.has_errors():
print('\t\txxx ERROR in your product.equation feature order xxx')
for error in feature_order_validator.get_violations():
print('\t\t\t', error[1])
else:
print('\t\tOK')
# --------------------------------------------------------
# Validate the functional product specification
print('\tChecking functional product spec')
if not os.path.exists(spec_path):
print(
'\t\tSkipped - No product spec exists.\n'
'\t\tYou may create a product spec if you want to ensure that\n'
'\t\trequired functional features are represented in the product equation\n'
'\t\t=> Create spec file featuremodel/productline/<container>/product_spec.json'
)
return
spec_validator = validators.ProductSpecValidator(spec_path, product_name, feature_list)
if not spec_validator.is_valid():
if spec_validator.get_errors_mandatory():
print('\t\tERROR: The following feature are missing', spec_validator.get_errors_mandatory())
if spec_validator.get_errors_never():
print('\t\tERROR: The following feature are not allowed', spec_validator.get_errors_never())
else:
print('\t\tOK')
if feature_order_validator.has_errors() or spec_validator.has_errors():
sys.exit(1) | [
"def",
"validate_product_equation",
"(",
"poi",
"=",
"None",
")",
":",
"from",
".",
"import",
"utils",
"from",
".",
"import",
"validators",
"container_dir",
",",
"product_name",
"=",
"tasks",
".",
"get_poi_tuple",
"(",
"poi",
"=",
"poi",
")",
"feature_list",
... | Validates the product equation.
* Validates the feature order
* Validates the product spec (mandatory functional features)
:param poi: optional product of interest | [
"Validates",
"the",
"product",
"equation",
".",
"*",
"Validates",
"the",
"feature",
"order",
"*",
"Validates",
"the",
"product",
"spec",
"(",
"mandatory",
"functional",
"features",
")",
":",
"param",
"poi",
":",
"optional",
"product",
"of",
"interest"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L241-L296 |
henzk/ape | ape/container_mode/tasks.py | get_ordered_feature_list | def get_ordered_feature_list(info_object, feature_list):
"""
Orders the passed feature list by the given, json-formatted feature
dependency file using feaquencer's topsort algorithm.
:param feature_list:
:param info_object:
:return:
"""
feature_dependencies = json.load(open(info_object.feature_order_json))
feature_selection = [feature for feature in [feature.strip().replace('\n', '') for feature in feature_list]
if len(feature) > 0 and not feature.startswith('_') and not feature.startswith('#')]
return [feature + '\n' for feature in feaquencer.get_total_order(feature_selection, feature_dependencies)] | python | def get_ordered_feature_list(info_object, feature_list):
"""
Orders the passed feature list by the given, json-formatted feature
dependency file using feaquencer's topsort algorithm.
:param feature_list:
:param info_object:
:return:
"""
feature_dependencies = json.load(open(info_object.feature_order_json))
feature_selection = [feature for feature in [feature.strip().replace('\n', '') for feature in feature_list]
if len(feature) > 0 and not feature.startswith('_') and not feature.startswith('#')]
return [feature + '\n' for feature in feaquencer.get_total_order(feature_selection, feature_dependencies)] | [
"def",
"get_ordered_feature_list",
"(",
"info_object",
",",
"feature_list",
")",
":",
"feature_dependencies",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"info_object",
".",
"feature_order_json",
")",
")",
"feature_selection",
"=",
"[",
"feature",
"for",
"feature"... | Orders the passed feature list by the given, json-formatted feature
dependency file using feaquencer's topsort algorithm.
:param feature_list:
:param info_object:
:return: | [
"Orders",
"the",
"passed",
"feature",
"list",
"by",
"the",
"given",
"json",
"-",
"formatted",
"feature",
"dependency",
"file",
"using",
"feaquencer",
"s",
"topsort",
"algorithm",
".",
":",
"param",
"feature_list",
":",
":",
"param",
"info_object",
":",
":",
... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L300-L311 |
henzk/ape | ape/container_mode/tasks.py | config_to_equation | def config_to_equation(poi=None):
"""
Generates a product.equation file for the given product name.
It generates it from the <product_name>.config file in the products folder.
For that you need to have your project imported to featureIDE and set the correct settings.
"""
from . import utils
container_dir, product_name = tasks.get_poi_tuple(poi=poi)
info_object = utils.get_feature_ide_paths(container_dir, product_name)
feature_list = list()
try:
print('*** Processing ', info_object.config_file_path)
with open(info_object.config_file_path, 'r') as config_file:
config_file = config_file.readlines()
for line in config_file:
# in FeatureIDE we cant use '.' for the paths to sub-features so we used '__'
# e.g. django_productline__features__development
if len(line.split('__')) <= 2:
line = line
else:
line = line.replace('__', '.')
if line.startswith('abstract_'):
# we skipp abstract features; this is a special case as featureIDE does not work with abstract
# sub trees / leafs.
line = ''
feature_list.append(line)
except IOError:
print('{} does not exist. Make sure your config file exists.'.format(info_object.config_file_path))
feature_list = tasks.get_ordered_feature_list(info_object, feature_list)
try:
with open(info_object.equation_file_path, 'w') as eq_file:
eq_file.writelines(feature_list)
print('*** Successfully generated product.equation')
except IOError:
print('product.equation file not found. Please make sure you have a valid product.equation in your chosen product')
# finally performing the validation of the product equation
tasks.validate_product_equation() | python | def config_to_equation(poi=None):
"""
Generates a product.equation file for the given product name.
It generates it from the <product_name>.config file in the products folder.
For that you need to have your project imported to featureIDE and set the correct settings.
"""
from . import utils
container_dir, product_name = tasks.get_poi_tuple(poi=poi)
info_object = utils.get_feature_ide_paths(container_dir, product_name)
feature_list = list()
try:
print('*** Processing ', info_object.config_file_path)
with open(info_object.config_file_path, 'r') as config_file:
config_file = config_file.readlines()
for line in config_file:
# in FeatureIDE we cant use '.' for the paths to sub-features so we used '__'
# e.g. django_productline__features__development
if len(line.split('__')) <= 2:
line = line
else:
line = line.replace('__', '.')
if line.startswith('abstract_'):
# we skipp abstract features; this is a special case as featureIDE does not work with abstract
# sub trees / leafs.
line = ''
feature_list.append(line)
except IOError:
print('{} does not exist. Make sure your config file exists.'.format(info_object.config_file_path))
feature_list = tasks.get_ordered_feature_list(info_object, feature_list)
try:
with open(info_object.equation_file_path, 'w') as eq_file:
eq_file.writelines(feature_list)
print('*** Successfully generated product.equation')
except IOError:
print('product.equation file not found. Please make sure you have a valid product.equation in your chosen product')
# finally performing the validation of the product equation
tasks.validate_product_equation() | [
"def",
"config_to_equation",
"(",
"poi",
"=",
"None",
")",
":",
"from",
".",
"import",
"utils",
"container_dir",
",",
"product_name",
"=",
"tasks",
".",
"get_poi_tuple",
"(",
"poi",
"=",
"poi",
")",
"info_object",
"=",
"utils",
".",
"get_feature_ide_paths",
... | Generates a product.equation file for the given product name.
It generates it from the <product_name>.config file in the products folder.
For that you need to have your project imported to featureIDE and set the correct settings. | [
"Generates",
"a",
"product",
".",
"equation",
"file",
"for",
"the",
"given",
"product",
"name",
".",
"It",
"generates",
"it",
"from",
"the",
"<product_name",
">",
".",
"config",
"file",
"in",
"the",
"products",
"folder",
".",
"For",
"that",
"you",
"need",
... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L315-L359 |
duniter/duniter-python-api | duniterpy/grammars/output.py | SIG.token | def token(cls: Type[SIGType], pubkey: str) -> SIGType:
"""
Return SIG instance from pubkey
:param pubkey: Public key of the signature issuer
:return:
"""
sig = cls()
sig.pubkey = pubkey
return sig | python | def token(cls: Type[SIGType], pubkey: str) -> SIGType:
"""
Return SIG instance from pubkey
:param pubkey: Public key of the signature issuer
:return:
"""
sig = cls()
sig.pubkey = pubkey
return sig | [
"def",
"token",
"(",
"cls",
":",
"Type",
"[",
"SIGType",
"]",
",",
"pubkey",
":",
"str",
")",
"->",
"SIGType",
":",
"sig",
"=",
"cls",
"(",
")",
"sig",
".",
"pubkey",
"=",
"pubkey",
"return",
"sig"
] | Return SIG instance from pubkey
:param pubkey: Public key of the signature issuer
:return: | [
"Return",
"SIG",
"instance",
"from",
"pubkey"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L52-L61 |
duniter/duniter-python-api | duniterpy/grammars/output.py | CSV.token | def token(cls: Type[CSVType], time: int) -> CSVType:
"""
Return CSV instance from time
:param time: Timestamp
:return:
"""
csv = cls()
csv.time = str(time)
return csv | python | def token(cls: Type[CSVType], time: int) -> CSVType:
"""
Return CSV instance from time
:param time: Timestamp
:return:
"""
csv = cls()
csv.time = str(time)
return csv | [
"def",
"token",
"(",
"cls",
":",
"Type",
"[",
"CSVType",
"]",
",",
"time",
":",
"int",
")",
"->",
"CSVType",
":",
"csv",
"=",
"cls",
"(",
")",
"csv",
".",
"time",
"=",
"str",
"(",
"time",
")",
"return",
"csv"
] | Return CSV instance from time
:param time: Timestamp
:return: | [
"Return",
"CSV",
"instance",
"from",
"time"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L98-L107 |
duniter/duniter-python-api | duniterpy/grammars/output.py | CSV.compose | def compose(self, parser: Any, grammar: Any = None, attr_of: str = None):
"""
Return the CSV(time) expression as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of...
"""
return "CSV({0})".format(self.time) | python | def compose(self, parser: Any, grammar: Any = None, attr_of: str = None):
"""
Return the CSV(time) expression as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of...
"""
return "CSV({0})".format(self.time) | [
"def",
"compose",
"(",
"self",
",",
"parser",
":",
"Any",
",",
"grammar",
":",
"Any",
"=",
"None",
",",
"attr_of",
":",
"str",
"=",
"None",
")",
":",
"return",
"\"CSV({0})\"",
".",
"format",
"(",
"self",
".",
"time",
")"
] | Return the CSV(time) expression as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of... | [
"Return",
"the",
"CSV",
"(",
"time",
")",
"expression",
"as",
"string",
"format"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L109-L117 |
duniter/duniter-python-api | duniterpy/grammars/output.py | CLTV.token | def token(cls: Type[CLTVType], timestamp: int) -> CLTVType:
"""
Return CLTV instance from timestamp
:param timestamp: Timestamp
:return:
"""
cltv = cls()
cltv.timestamp = str(timestamp)
return cltv | python | def token(cls: Type[CLTVType], timestamp: int) -> CLTVType:
"""
Return CLTV instance from timestamp
:param timestamp: Timestamp
:return:
"""
cltv = cls()
cltv.timestamp = str(timestamp)
return cltv | [
"def",
"token",
"(",
"cls",
":",
"Type",
"[",
"CLTVType",
"]",
",",
"timestamp",
":",
"int",
")",
"->",
"CLTVType",
":",
"cltv",
"=",
"cls",
"(",
")",
"cltv",
".",
"timestamp",
"=",
"str",
"(",
"timestamp",
")",
"return",
"cltv"
] | Return CLTV instance from timestamp
:param timestamp: Timestamp
:return: | [
"Return",
"CLTV",
"instance",
"from",
"timestamp"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L143-L152 |
duniter/duniter-python-api | duniterpy/grammars/output.py | XHX.token | def token(cls: Type[XHXType], sha_hash: str) -> XHXType:
"""
Return XHX instance from sha_hash
:param sha_hash: SHA256 hash
:return:
"""
xhx = cls()
xhx.sha_hash = sha_hash
return xhx | python | def token(cls: Type[XHXType], sha_hash: str) -> XHXType:
"""
Return XHX instance from sha_hash
:param sha_hash: SHA256 hash
:return:
"""
xhx = cls()
xhx.sha_hash = sha_hash
return xhx | [
"def",
"token",
"(",
"cls",
":",
"Type",
"[",
"XHXType",
"]",
",",
"sha_hash",
":",
"str",
")",
"->",
"XHXType",
":",
"xhx",
"=",
"cls",
"(",
")",
"xhx",
".",
"sha_hash",
"=",
"sha_hash",
"return",
"xhx"
] | Return XHX instance from sha_hash
:param sha_hash: SHA256 hash
:return: | [
"Return",
"XHX",
"instance",
"from",
"sha_hash"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L188-L197 |
duniter/duniter-python-api | duniterpy/grammars/output.py | Operator.token | def token(cls: Type[OperatorType], keyword: str) -> OperatorType:
"""
Return Operator instance from keyword
:param keyword: Operator keyword in expression
:return:
"""
op = cls(keyword)
return op | python | def token(cls: Type[OperatorType], keyword: str) -> OperatorType:
"""
Return Operator instance from keyword
:param keyword: Operator keyword in expression
:return:
"""
op = cls(keyword)
return op | [
"def",
"token",
"(",
"cls",
":",
"Type",
"[",
"OperatorType",
"]",
",",
"keyword",
":",
"str",
")",
"->",
"OperatorType",
":",
"op",
"=",
"cls",
"(",
"keyword",
")",
"return",
"op"
] | Return Operator instance from keyword
:param keyword: Operator keyword in expression
:return: | [
"Return",
"Operator",
"instance",
"from",
"keyword"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L222-L230 |
duniter/duniter-python-api | duniterpy/grammars/output.py | Condition.token | def token(cls: Type[ConditionType], left: Any, op: Optional[Any] = None,
right: Optional[Any] = None) -> ConditionType:
"""
Return Condition instance from arguments and Operator
:param left: Left argument
:param op: Operator
:param right: Right argument
:return:
"""
condition = cls()
condition.left = left
if op:
condition.op = op
if right:
condition.right = right
return condition | python | def token(cls: Type[ConditionType], left: Any, op: Optional[Any] = None,
right: Optional[Any] = None) -> ConditionType:
"""
Return Condition instance from arguments and Operator
:param left: Left argument
:param op: Operator
:param right: Right argument
:return:
"""
condition = cls()
condition.left = left
if op:
condition.op = op
if right:
condition.right = right
return condition | [
"def",
"token",
"(",
"cls",
":",
"Type",
"[",
"ConditionType",
"]",
",",
"left",
":",
"Any",
",",
"op",
":",
"Optional",
"[",
"Any",
"]",
"=",
"None",
",",
"right",
":",
"Optional",
"[",
"Any",
"]",
"=",
"None",
")",
"->",
"ConditionType",
":",
"... | Return Condition instance from arguments and Operator
:param left: Left argument
:param op: Operator
:param right: Right argument
:return: | [
"Return",
"Condition",
"instance",
"from",
"arguments",
"and",
"Operator"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L269-L285 |
duniter/duniter-python-api | duniterpy/grammars/output.py | Condition.compose | def compose(self, parser: Any, grammar: Any = None, attr_of: str = None) -> str:
"""
Return the Condition as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of...
"""
if type(self.left) is Condition:
left = "({0})".format(parser.compose(self.left, grammar=grammar, attr_of=attr_of))
else:
left = parser.compose(self.left, grammar=grammar, attr_of=attr_of)
if getattr(self, 'op', None):
if type(self.right) is Condition:
right = "({0})".format(parser.compose(self.right, grammar=grammar, attr_of=attr_of))
else:
right = parser.compose(self.right, grammar=grammar, attr_of=attr_of)
op = parser.compose(self.op, grammar=grammar, attr_of=attr_of)
result = "{0} {1} {2}".format(left, op, right)
else:
result = left
return result | python | def compose(self, parser: Any, grammar: Any = None, attr_of: str = None) -> str:
"""
Return the Condition as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of...
"""
if type(self.left) is Condition:
left = "({0})".format(parser.compose(self.left, grammar=grammar, attr_of=attr_of))
else:
left = parser.compose(self.left, grammar=grammar, attr_of=attr_of)
if getattr(self, 'op', None):
if type(self.right) is Condition:
right = "({0})".format(parser.compose(self.right, grammar=grammar, attr_of=attr_of))
else:
right = parser.compose(self.right, grammar=grammar, attr_of=attr_of)
op = parser.compose(self.op, grammar=grammar, attr_of=attr_of)
result = "{0} {1} {2}".format(left, op, right)
else:
result = left
return result | [
"def",
"compose",
"(",
"self",
",",
"parser",
":",
"Any",
",",
"grammar",
":",
"Any",
"=",
"None",
",",
"attr_of",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"type",
"(",
"self",
".",
"left",
")",
"is",
"Condition",
":",
"left",
"=",
... | Return the Condition as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of... | [
"Return",
"the",
"Condition",
"as",
"string",
"format"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L287-L310 |
funkybob/knights-templater | knights/parser.py | Parser.load_library | def load_library(self, path):
'''
Load a template library into the state.
'''
module = import_module(path)
self.tags.update(module.register.tags)
self.helpers.update(module.register.helpers) | python | def load_library(self, path):
'''
Load a template library into the state.
'''
module = import_module(path)
self.tags.update(module.register.tags)
self.helpers.update(module.register.helpers) | [
"def",
"load_library",
"(",
"self",
",",
"path",
")",
":",
"module",
"=",
"import_module",
"(",
"path",
")",
"self",
".",
"tags",
".",
"update",
"(",
"module",
".",
"register",
".",
"tags",
")",
"self",
".",
"helpers",
".",
"update",
"(",
"module",
"... | Load a template library into the state. | [
"Load",
"a",
"template",
"library",
"into",
"the",
"state",
"."
] | train | https://github.com/funkybob/knights-templater/blob/b15cdbaae7d824d02f7f03ca04599ae94bb759dd/knights/parser.py#L38-L44 |
lokhman/pydbal | pydbal/connection.py | Connection.get_default_logger | def get_default_logger():
"""Returns default driver logger.
:return: logger instance
:rtype: logging.Logger
"""
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter(
"[%(levelname)1.1s %(asctime)s %(name)s] %(message)s",
"%y%m%d %H:%M:%S"))
logger_name = "pydbal"
if Connection._instance_count > 1:
logger_name += ":" + str(Connection._instance_count)
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
return logger | python | def get_default_logger():
"""Returns default driver logger.
:return: logger instance
:rtype: logging.Logger
"""
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter(
"[%(levelname)1.1s %(asctime)s %(name)s] %(message)s",
"%y%m%d %H:%M:%S"))
logger_name = "pydbal"
if Connection._instance_count > 1:
logger_name += ":" + str(Connection._instance_count)
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
return logger | [
"def",
"get_default_logger",
"(",
")",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"\"[%(levelname)1.1s %(... | Returns default driver logger.
:return: logger instance
:rtype: logging.Logger | [
"Returns",
"default",
"driver",
"logger",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L118-L136 |
lokhman/pydbal | pydbal/connection.py | Connection.ensure_connected | def ensure_connected(self):
"""Ensures database connection is still open."""
if not self.is_connected():
if not self._auto_connect:
raise DBALConnectionError.connection_closed()
self.connect() | python | def ensure_connected(self):
"""Ensures database connection is still open."""
if not self.is_connected():
if not self._auto_connect:
raise DBALConnectionError.connection_closed()
self.connect() | [
"def",
"ensure_connected",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"if",
"not",
"self",
".",
"_auto_connect",
":",
"raise",
"DBALConnectionError",
".",
"connection_closed",
"(",
")",
"self",
".",
"connect",
"(",
")"
... | Ensures database connection is still open. | [
"Ensures",
"database",
"connection",
"is",
"still",
"open",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L205-L210 |
lokhman/pydbal | pydbal/connection.py | Connection.query | def query(self, sql, *args, **kwargs):
"""Executes an SQL SELECT query, returning a result set as a Statement object.
:param sql: query to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: result set as a Statement object
:rtype: pydbal.statement.Statement
"""
self.ensure_connected()
stmt = Statement(self)
stmt.execute(sql, *args, **kwargs)
return stmt | python | def query(self, sql, *args, **kwargs):
"""Executes an SQL SELECT query, returning a result set as a Statement object.
:param sql: query to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: result set as a Statement object
:rtype: pydbal.statement.Statement
"""
self.ensure_connected()
stmt = Statement(self)
stmt.execute(sql, *args, **kwargs)
return stmt | [
"def",
"query",
"(",
"self",
",",
"sql",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"ensure_connected",
"(",
")",
"stmt",
"=",
"Statement",
"(",
"self",
")",
"stmt",
".",
"execute",
"(",
"sql",
",",
"*",
"args",
",",
"*",
... | Executes an SQL SELECT query, returning a result set as a Statement object.
:param sql: query to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: result set as a Statement object
:rtype: pydbal.statement.Statement | [
"Executes",
"an",
"SQL",
"SELECT",
"query",
"returning",
"a",
"result",
"set",
"as",
"a",
"Statement",
"object",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L251-L263 |
lokhman/pydbal | pydbal/connection.py | Connection.execute | def execute(self, sql, *args, **kwargs):
"""Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.
:param sql: statement to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: number of affected rows
:rtype: int
"""
self.ensure_connected()
return Statement(self).execute(sql, *args, **kwargs) | python | def execute(self, sql, *args, **kwargs):
"""Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.
:param sql: statement to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: number of affected rows
:rtype: int
"""
self.ensure_connected()
return Statement(self).execute(sql, *args, **kwargs) | [
"def",
"execute",
"(",
"self",
",",
"sql",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"ensure_connected",
"(",
")",
"return",
"Statement",
"(",
"self",
")",
".",
"execute",
"(",
"sql",
",",
"*",
"args",
",",
"*",
"*",
"kwar... | Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.
:param sql: statement to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: number of affected rows
:rtype: int | [
"Executes",
"an",
"SQL",
"INSERT",
"/",
"UPDATE",
"/",
"DELETE",
"query",
"with",
"the",
"given",
"parameters",
"and",
"returns",
"the",
"number",
"of",
"affected",
"rows",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L265-L275 |
lokhman/pydbal | pydbal/connection.py | Connection.begin_transaction | def begin_transaction(self):
"""Starts a transaction by suspending auto-commit mode."""
self.ensure_connected()
self._transaction_nesting_level += 1
if self._transaction_nesting_level == 1:
self._driver.begin_transaction()
elif self._nest_transactions_with_savepoints:
self.create_savepoint(self._get_nested_transaction_savepoint_name()) | python | def begin_transaction(self):
"""Starts a transaction by suspending auto-commit mode."""
self.ensure_connected()
self._transaction_nesting_level += 1
if self._transaction_nesting_level == 1:
self._driver.begin_transaction()
elif self._nest_transactions_with_savepoints:
self.create_savepoint(self._get_nested_transaction_savepoint_name()) | [
"def",
"begin_transaction",
"(",
"self",
")",
":",
"self",
".",
"ensure_connected",
"(",
")",
"self",
".",
"_transaction_nesting_level",
"+=",
"1",
"if",
"self",
".",
"_transaction_nesting_level",
"==",
"1",
":",
"self",
".",
"_driver",
".",
"begin_transaction",... | Starts a transaction by suspending auto-commit mode. | [
"Starts",
"a",
"transaction",
"by",
"suspending",
"auto",
"-",
"commit",
"mode",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L320-L327 |
lokhman/pydbal | pydbal/connection.py | Connection.commit | def commit(self):
"""Commits the current transaction."""
if self._transaction_nesting_level == 0:
raise DBALConnectionError.no_active_transaction()
if self._is_rollback_only:
raise DBALConnectionError.commit_failed_rollback_only()
self.ensure_connected()
if self._transaction_nesting_level == 1:
self._driver.commit()
elif self._nest_transactions_with_savepoints:
self.release_savepoint(self._get_nested_transaction_savepoint_name())
self._transaction_nesting_level -= 1
if not self._auto_commit and self._transaction_nesting_level == 0:
self.begin_transaction() | python | def commit(self):
"""Commits the current transaction."""
if self._transaction_nesting_level == 0:
raise DBALConnectionError.no_active_transaction()
if self._is_rollback_only:
raise DBALConnectionError.commit_failed_rollback_only()
self.ensure_connected()
if self._transaction_nesting_level == 1:
self._driver.commit()
elif self._nest_transactions_with_savepoints:
self.release_savepoint(self._get_nested_transaction_savepoint_name())
self._transaction_nesting_level -= 1
if not self._auto_commit and self._transaction_nesting_level == 0:
self.begin_transaction() | [
"def",
"commit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_transaction_nesting_level",
"==",
"0",
":",
"raise",
"DBALConnectionError",
".",
"no_active_transaction",
"(",
")",
"if",
"self",
".",
"_is_rollback_only",
":",
"raise",
"DBALConnectionError",
".",
"co... | Commits the current transaction. | [
"Commits",
"the",
"current",
"transaction",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L329-L345 |
lokhman/pydbal | pydbal/connection.py | Connection.commit_all | def commit_all(self):
"""Commits all current nesting transactions."""
while self._transaction_nesting_level != 0:
if not self._auto_commit and self._transaction_nesting_level == 1:
return self.commit()
self.commit() | python | def commit_all(self):
"""Commits all current nesting transactions."""
while self._transaction_nesting_level != 0:
if not self._auto_commit and self._transaction_nesting_level == 1:
return self.commit()
self.commit() | [
"def",
"commit_all",
"(",
"self",
")",
":",
"while",
"self",
".",
"_transaction_nesting_level",
"!=",
"0",
":",
"if",
"not",
"self",
".",
"_auto_commit",
"and",
"self",
".",
"_transaction_nesting_level",
"==",
"1",
":",
"return",
"self",
".",
"commit",
"(",
... | Commits all current nesting transactions. | [
"Commits",
"all",
"current",
"nesting",
"transactions",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L347-L352 |
lokhman/pydbal | pydbal/connection.py | Connection.rollback | def rollback(self):
"""Cancels any database changes done during the current transaction."""
if self._transaction_nesting_level == 0:
raise DBALConnectionError.no_active_transaction()
self.ensure_connected()
if self._transaction_nesting_level == 1:
self._transaction_nesting_level = 0
self._driver.rollback()
self._is_rollback_only = False
if not self._auto_commit:
self.begin_transaction()
elif self._nest_transactions_with_savepoints:
self.rollback_savepoint(self._get_nested_transaction_savepoint_name())
self._transaction_nesting_level -= 1
else:
self._is_rollback_only = True
self._transaction_nesting_level -= 1 | python | def rollback(self):
"""Cancels any database changes done during the current transaction."""
if self._transaction_nesting_level == 0:
raise DBALConnectionError.no_active_transaction()
self.ensure_connected()
if self._transaction_nesting_level == 1:
self._transaction_nesting_level = 0
self._driver.rollback()
self._is_rollback_only = False
if not self._auto_commit:
self.begin_transaction()
elif self._nest_transactions_with_savepoints:
self.rollback_savepoint(self._get_nested_transaction_savepoint_name())
self._transaction_nesting_level -= 1
else:
self._is_rollback_only = True
self._transaction_nesting_level -= 1 | [
"def",
"rollback",
"(",
"self",
")",
":",
"if",
"self",
".",
"_transaction_nesting_level",
"==",
"0",
":",
"raise",
"DBALConnectionError",
".",
"no_active_transaction",
"(",
")",
"self",
".",
"ensure_connected",
"(",
")",
"if",
"self",
".",
"_transaction_nesting... | Cancels any database changes done during the current transaction. | [
"Cancels",
"any",
"database",
"changes",
"done",
"during",
"the",
"current",
"transaction",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L354-L371 |
lokhman/pydbal | pydbal/connection.py | Connection.transaction | def transaction(self, callback):
"""Executes a function in a transaction.
The function gets passed this Connection instance as an (optional) parameter.
If an exception occurs during execution of the function or transaction commit,
the transaction is rolled back and the exception re-thrown.
:param callback: the function to execute in a transaction
:return: the value returned by the `callback`
:raise: Exception
"""
self.begin_transaction()
try:
result = callback(self)
self.commit()
return result
except:
self.rollback()
raise | python | def transaction(self, callback):
"""Executes a function in a transaction.
The function gets passed this Connection instance as an (optional) parameter.
If an exception occurs during execution of the function or transaction commit,
the transaction is rolled back and the exception re-thrown.
:param callback: the function to execute in a transaction
:return: the value returned by the `callback`
:raise: Exception
"""
self.begin_transaction()
try:
result = callback(self)
self.commit()
return result
except:
self.rollback()
raise | [
"def",
"transaction",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"begin_transaction",
"(",
")",
"try",
":",
"result",
"=",
"callback",
"(",
"self",
")",
"self",
".",
"commit",
"(",
")",
"return",
"result",
"except",
":",
"self",
".",
"rollbac... | Executes a function in a transaction.
The function gets passed this Connection instance as an (optional) parameter.
If an exception occurs during execution of the function or transaction commit,
the transaction is rolled back and the exception re-thrown.
:param callback: the function to execute in a transaction
:return: the value returned by the `callback`
:raise: Exception | [
"Executes",
"a",
"function",
"in",
"a",
"transaction",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L373-L392 |
lokhman/pydbal | pydbal/connection.py | Connection.set_auto_commit | def set_auto_commit(self, auto_commit):
"""Sets auto-commit mode for this connection.
If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to
either the method commit or the method rollback. By default, new connections are in auto-commit mode.
NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
:param auto_commit: `True` to enable auto-commit mode; `False` to disable it
"""
auto_commit = bool(auto_commit)
if auto_commit == self._auto_commit:
return
self._auto_commit = auto_commit
if self.is_connected() and self._transaction_nesting_level != 0:
self.commit_all() | python | def set_auto_commit(self, auto_commit):
"""Sets auto-commit mode for this connection.
If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to
either the method commit or the method rollback. By default, new connections are in auto-commit mode.
NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
:param auto_commit: `True` to enable auto-commit mode; `False` to disable it
"""
auto_commit = bool(auto_commit)
if auto_commit == self._auto_commit:
return
self._auto_commit = auto_commit
if self.is_connected() and self._transaction_nesting_level != 0:
self.commit_all() | [
"def",
"set_auto_commit",
"(",
"self",
",",
"auto_commit",
")",
":",
"auto_commit",
"=",
"bool",
"(",
"auto_commit",
")",
"if",
"auto_commit",
"==",
"self",
".",
"_auto_commit",
":",
"return",
"self",
".",
"_auto_commit",
"=",
"auto_commit",
"if",
"self",
".... | Sets auto-commit mode for this connection.
If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to
either the method commit or the method rollback. By default, new connections are in auto-commit mode.
NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
:param auto_commit: `True` to enable auto-commit mode; `False` to disable it | [
"Sets",
"auto",
"-",
"commit",
"mode",
"for",
"this",
"connection",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L402-L421 |
lokhman/pydbal | pydbal/connection.py | Connection.set_transaction_isolation | def set_transaction_isolation(self, level):
"""Sets the transaction isolation level.
:param level: the level to set
"""
self.ensure_connected()
self._transaction_isolation_level = level
self._platform.set_transaction_isolation(level) | python | def set_transaction_isolation(self, level):
"""Sets the transaction isolation level.
:param level: the level to set
"""
self.ensure_connected()
self._transaction_isolation_level = level
self._platform.set_transaction_isolation(level) | [
"def",
"set_transaction_isolation",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"ensure_connected",
"(",
")",
"self",
".",
"_transaction_isolation_level",
"=",
"level",
"self",
".",
"_platform",
".",
"set_transaction_isolation",
"(",
"level",
")"
] | Sets the transaction isolation level.
:param level: the level to set | [
"Sets",
"the",
"transaction",
"isolation",
"level",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L447-L454 |
lokhman/pydbal | pydbal/connection.py | Connection.get_transaction_isolation | def get_transaction_isolation(self):
"""Returns the currently active transaction isolation level.
:return: the current transaction isolation level
:rtype: int
"""
if self._transaction_isolation_level is None:
self._transaction_isolation_level = self._platform.get_default_transaction_isolation_level()
return self._transaction_isolation_level | python | def get_transaction_isolation(self):
"""Returns the currently active transaction isolation level.
:return: the current transaction isolation level
:rtype: int
"""
if self._transaction_isolation_level is None:
self._transaction_isolation_level = self._platform.get_default_transaction_isolation_level()
return self._transaction_isolation_level | [
"def",
"get_transaction_isolation",
"(",
"self",
")",
":",
"if",
"self",
".",
"_transaction_isolation_level",
"is",
"None",
":",
"self",
".",
"_transaction_isolation_level",
"=",
"self",
".",
"_platform",
".",
"get_default_transaction_isolation_level",
"(",
")",
"retu... | Returns the currently active transaction isolation level.
:return: the current transaction isolation level
:rtype: int | [
"Returns",
"the",
"currently",
"active",
"transaction",
"isolation",
"level",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L456-L464 |
lokhman/pydbal | pydbal/connection.py | Connection.set_nest_transactions_with_savepoints | def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints):
"""Sets if nested transactions should use savepoints.
:param nest_transactions_with_savepoints: `True` or `False`
"""
if self._transaction_nesting_level > 0:
raise DBALConnectionError.may_not_alter_nested_transaction_with_savepoints_in_transaction()
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
self._nest_transactions_with_savepoints = bool(nest_transactions_with_savepoints) | python | def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints):
"""Sets if nested transactions should use savepoints.
:param nest_transactions_with_savepoints: `True` or `False`
"""
if self._transaction_nesting_level > 0:
raise DBALConnectionError.may_not_alter_nested_transaction_with_savepoints_in_transaction()
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
self._nest_transactions_with_savepoints = bool(nest_transactions_with_savepoints) | [
"def",
"set_nest_transactions_with_savepoints",
"(",
"self",
",",
"nest_transactions_with_savepoints",
")",
":",
"if",
"self",
".",
"_transaction_nesting_level",
">",
"0",
":",
"raise",
"DBALConnectionError",
".",
"may_not_alter_nested_transaction_with_savepoints_in_transaction",... | Sets if nested transactions should use savepoints.
:param nest_transactions_with_savepoints: `True` or `False` | [
"Sets",
"if",
"nested",
"transactions",
"should",
"use",
"savepoints",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L466-L475 |
lokhman/pydbal | pydbal/connection.py | Connection.create_savepoint | def create_savepoint(self, savepoint):
"""Creates a new savepoint.
:param savepoint: the name of the savepoint to create
:raise: pydbal.exception.DBALConnectionError
"""
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
self.ensure_connected()
self._platform.create_savepoint(savepoint) | python | def create_savepoint(self, savepoint):
"""Creates a new savepoint.
:param savepoint: the name of the savepoint to create
:raise: pydbal.exception.DBALConnectionError
"""
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
self.ensure_connected()
self._platform.create_savepoint(savepoint) | [
"def",
"create_savepoint",
"(",
"self",
",",
"savepoint",
")",
":",
"if",
"not",
"self",
".",
"_platform",
".",
"is_savepoints_supported",
"(",
")",
":",
"raise",
"DBALConnectionError",
".",
"savepoints_not_supported",
"(",
")",
"self",
".",
"ensure_connected",
... | Creates a new savepoint.
:param savepoint: the name of the savepoint to create
:raise: pydbal.exception.DBALConnectionError | [
"Creates",
"a",
"new",
"savepoint",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L493-L502 |
lokhman/pydbal | pydbal/connection.py | Connection.release_savepoint | def release_savepoint(self, savepoint):
"""Releases the given savepoint.
:param savepoint: the name of the savepoint to release
:raise: pydbal.exception.DBALConnectionError
"""
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
if self._platform.is_release_savepoints_supported():
self.ensure_connected()
self._platform.release_savepoint(savepoint) | python | def release_savepoint(self, savepoint):
"""Releases the given savepoint.
:param savepoint: the name of the savepoint to release
:raise: pydbal.exception.DBALConnectionError
"""
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
if self._platform.is_release_savepoints_supported():
self.ensure_connected()
self._platform.release_savepoint(savepoint) | [
"def",
"release_savepoint",
"(",
"self",
",",
"savepoint",
")",
":",
"if",
"not",
"self",
".",
"_platform",
".",
"is_savepoints_supported",
"(",
")",
":",
"raise",
"DBALConnectionError",
".",
"savepoints_not_supported",
"(",
")",
"if",
"self",
".",
"_platform",
... | Releases the given savepoint.
:param savepoint: the name of the savepoint to release
:raise: pydbal.exception.DBALConnectionError | [
"Releases",
"the",
"given",
"savepoint",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L504-L514 |
lokhman/pydbal | pydbal/connection.py | Connection.rollback_savepoint | def rollback_savepoint(self, savepoint):
"""Rolls back to the given savepoint.
:param savepoint: the name of the savepoint to rollback to
:raise: pydbal.exception.DBALConnectionError
"""
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
self.ensure_connected()
self._platform.rollback_savepoint(savepoint) | python | def rollback_savepoint(self, savepoint):
"""Rolls back to the given savepoint.
:param savepoint: the name of the savepoint to rollback to
:raise: pydbal.exception.DBALConnectionError
"""
if not self._platform.is_savepoints_supported():
raise DBALConnectionError.savepoints_not_supported()
self.ensure_connected()
self._platform.rollback_savepoint(savepoint) | [
"def",
"rollback_savepoint",
"(",
"self",
",",
"savepoint",
")",
":",
"if",
"not",
"self",
".",
"_platform",
".",
"is_savepoints_supported",
"(",
")",
":",
"raise",
"DBALConnectionError",
".",
"savepoints_not_supported",
"(",
")",
"self",
".",
"ensure_connected",
... | Rolls back to the given savepoint.
:param savepoint: the name of the savepoint to rollback to
:raise: pydbal.exception.DBALConnectionError | [
"Rolls",
"back",
"to",
"the",
"given",
"savepoint",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L516-L525 |
lokhman/pydbal | pydbal/connection.py | Connection.insert | def insert(self, table, values):
"""Inserts a table row with specified data.
:param table: the expression of the table to insert data into, quoted or unquoted
:param values: a dictionary containing column-value pairs
:return: last inserted ID
"""
assert isinstance(values, dict)
sb = self.sql_builder().insert(table)
for column, value in values.iteritems():
values[column] = sb.create_positional_parameter(value)
return sb.values(values).execute() | python | def insert(self, table, values):
"""Inserts a table row with specified data.
:param table: the expression of the table to insert data into, quoted or unquoted
:param values: a dictionary containing column-value pairs
:return: last inserted ID
"""
assert isinstance(values, dict)
sb = self.sql_builder().insert(table)
for column, value in values.iteritems():
values[column] = sb.create_positional_parameter(value)
return sb.values(values).execute() | [
"def",
"insert",
"(",
"self",
",",
"table",
",",
"values",
")",
":",
"assert",
"isinstance",
"(",
"values",
",",
"dict",
")",
"sb",
"=",
"self",
".",
"sql_builder",
"(",
")",
".",
"insert",
"(",
"table",
")",
"for",
"column",
",",
"value",
"in",
"v... | Inserts a table row with specified data.
:param table: the expression of the table to insert data into, quoted or unquoted
:param values: a dictionary containing column-value pairs
:return: last inserted ID | [
"Inserts",
"a",
"table",
"row",
"with",
"specified",
"data",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L527-L539 |
lokhman/pydbal | pydbal/connection.py | Connection.update | def update(self, table, values, identifier):
"""Updates a table row with specified data by given identifier.
:param table: the expression of the table to update quoted or unquoted
:param values: a dictionary containing column-value pairs
:param identifier: the update criteria; a dictionary containing column-value pairs
:return: the number of affected rows
:rtype: int
"""
assert isinstance(values, dict)
assert isinstance(identifier, dict)
sb = self.sql_builder().update(table)
for column, value in values.iteritems():
sb.set(column, sb.create_positional_parameter(value))
for column, value in identifier.iteritems():
func = self._expr.in_ if isinstance(value, (list, tuple)) else self._expr.eq
sb.and_where(func(column, sb.create_positional_parameter(value)))
return sb.execute() | python | def update(self, table, values, identifier):
"""Updates a table row with specified data by given identifier.
:param table: the expression of the table to update quoted or unquoted
:param values: a dictionary containing column-value pairs
:param identifier: the update criteria; a dictionary containing column-value pairs
:return: the number of affected rows
:rtype: int
"""
assert isinstance(values, dict)
assert isinstance(identifier, dict)
sb = self.sql_builder().update(table)
for column, value in values.iteritems():
sb.set(column, sb.create_positional_parameter(value))
for column, value in identifier.iteritems():
func = self._expr.in_ if isinstance(value, (list, tuple)) else self._expr.eq
sb.and_where(func(column, sb.create_positional_parameter(value)))
return sb.execute() | [
"def",
"update",
"(",
"self",
",",
"table",
",",
"values",
",",
"identifier",
")",
":",
"assert",
"isinstance",
"(",
"values",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"identifier",
",",
"dict",
")",
"sb",
"=",
"self",
".",
"sql_builder",
"(",
")... | Updates a table row with specified data by given identifier.
:param table: the expression of the table to update quoted or unquoted
:param values: a dictionary containing column-value pairs
:param identifier: the update criteria; a dictionary containing column-value pairs
:return: the number of affected rows
:rtype: int | [
"Updates",
"a",
"table",
"row",
"with",
"specified",
"data",
"by",
"given",
"identifier",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L541-L559 |
lokhman/pydbal | pydbal/connection.py | Connection.delete | def delete(self, table, identifier):
"""Deletes a table row by given identifier.
:param table: the expression of the table to update quoted or unquoted
:param identifier: the delete criteria; a dictionary containing column-value pairs
:return: the number of affected rows
:rtype: int
"""
assert isinstance(identifier, dict)
sb = self.sql_builder().delete(table)
for column, value in identifier.iteritems():
func = self._expr.in_ if isinstance(value, (list, tuple)) else self._expr.eq
sb.and_where(func(column, sb.create_positional_parameter(value)))
return sb.execute() | python | def delete(self, table, identifier):
"""Deletes a table row by given identifier.
:param table: the expression of the table to update quoted or unquoted
:param identifier: the delete criteria; a dictionary containing column-value pairs
:return: the number of affected rows
:rtype: int
"""
assert isinstance(identifier, dict)
sb = self.sql_builder().delete(table)
for column, value in identifier.iteritems():
func = self._expr.in_ if isinstance(value, (list, tuple)) else self._expr.eq
sb.and_where(func(column, sb.create_positional_parameter(value)))
return sb.execute() | [
"def",
"delete",
"(",
"self",
",",
"table",
",",
"identifier",
")",
":",
"assert",
"isinstance",
"(",
"identifier",
",",
"dict",
")",
"sb",
"=",
"self",
".",
"sql_builder",
"(",
")",
".",
"delete",
"(",
"table",
")",
"for",
"column",
",",
"value",
"i... | Deletes a table row by given identifier.
:param table: the expression of the table to update quoted or unquoted
:param identifier: the delete criteria; a dictionary containing column-value pairs
:return: the number of affected rows
:rtype: int | [
"Deletes",
"a",
"table",
"row",
"by",
"given",
"identifier",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/connection.py#L561-L575 |
lokhman/pydbal | pydbal/drivers/mysql.py | MySQLDriver._execute | def _execute(self, sql, params):
"""Execute statement with reconnecting by connection closed error codes.
2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away
2013 (CR_SERVER_LOST): Lost connection to MySQL server during query
2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL server at '%s', system error: %d
"""
try:
return self._execute_unsafe(sql, params)
except MySQLdb.OperationalError as ex:
if ex.args[0] in (2006, 2013, 2055):
self._log("Connection with server is lost. Trying to reconnect.")
self.connect()
return self._execute_unsafe(sql, params)
raise | python | def _execute(self, sql, params):
"""Execute statement with reconnecting by connection closed error codes.
2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away
2013 (CR_SERVER_LOST): Lost connection to MySQL server during query
2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL server at '%s', system error: %d
"""
try:
return self._execute_unsafe(sql, params)
except MySQLdb.OperationalError as ex:
if ex.args[0] in (2006, 2013, 2055):
self._log("Connection with server is lost. Trying to reconnect.")
self.connect()
return self._execute_unsafe(sql, params)
raise | [
"def",
"_execute",
"(",
"self",
",",
"sql",
",",
"params",
")",
":",
"try",
":",
"return",
"self",
".",
"_execute_unsafe",
"(",
"sql",
",",
"params",
")",
"except",
"MySQLdb",
".",
"OperationalError",
"as",
"ex",
":",
"if",
"ex",
".",
"args",
"[",
"0... | Execute statement with reconnecting by connection closed error codes.
2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away
2013 (CR_SERVER_LOST): Lost connection to MySQL server during query
2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL server at '%s', system error: %d | [
"Execute",
"statement",
"with",
"reconnecting",
"by",
"connection",
"closed",
"error",
"codes",
"."
] | train | https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/drivers/mysql.py#L98-L112 |
simodalla/pygmount | pygmount/utils/mount.py | MountSmbSharesOld.requirements | def requirements(self):
"""
Verifica che tutti i pacchetti apt necessari al "funzionamento" della
classe siano installati. Se cosi' non fosse li installa.
"""
cache = apt.cache.Cache()
for pkg in self.pkgs_required:
try:
pkg = cache[pkg]
if not pkg.is_installed:
try:
pkg.mark_install()
cache.commit()
except LockFailedException as lfe:
logging.error(
'Errore "{}" probabilmente l\'utente {} non ha i '
'diritti di amministratore'.format(lfe,
self.username))
raise lfe
except Exception as e:
logging.error('Errore non classificato "{}"'.format(e))
raise e
except KeyError:
logging.error('Il pacchetto "{}" non e\' presente in questa'
' distribuzione'.format(pkg)) | python | def requirements(self):
"""
Verifica che tutti i pacchetti apt necessari al "funzionamento" della
classe siano installati. Se cosi' non fosse li installa.
"""
cache = apt.cache.Cache()
for pkg in self.pkgs_required:
try:
pkg = cache[pkg]
if not pkg.is_installed:
try:
pkg.mark_install()
cache.commit()
except LockFailedException as lfe:
logging.error(
'Errore "{}" probabilmente l\'utente {} non ha i '
'diritti di amministratore'.format(lfe,
self.username))
raise lfe
except Exception as e:
logging.error('Errore non classificato "{}"'.format(e))
raise e
except KeyError:
logging.error('Il pacchetto "{}" non e\' presente in questa'
' distribuzione'.format(pkg)) | [
"def",
"requirements",
"(",
"self",
")",
":",
"cache",
"=",
"apt",
".",
"cache",
".",
"Cache",
"(",
")",
"for",
"pkg",
"in",
"self",
".",
"pkgs_required",
":",
"try",
":",
"pkg",
"=",
"cache",
"[",
"pkg",
"]",
"if",
"not",
"pkg",
".",
"is_installed... | Verifica che tutti i pacchetti apt necessari al "funzionamento" della
classe siano installati. Se cosi' non fosse li installa. | [
"Verifica",
"che",
"tutti",
"i",
"pacchetti",
"apt",
"necessari",
"al",
"funzionamento",
"della",
"classe",
"siano",
"installati",
".",
"Se",
"cosi",
"non",
"fosse",
"li",
"installa",
"."
] | train | https://github.com/simodalla/pygmount/blob/8027cfa2ed5fa8e9207d72b6013ecec7fcf2e5f5/pygmount/utils/mount.py#L57-L81 |
simodalla/pygmount | pygmount/utils/mount.py | MountSmbSharesOld.set_shares | def set_shares(self):
"""
Setta la variabile membro 'self.samba_shares' il quale e' una lista
di dizionari con i dati da passare ai comandi di "umount" e "mount".
I vari dizionari sono popolati o da un file ~/.pygmount.rc e da un
file passato dall'utente.
"""
if self.filename is None:
self.filenamename = os.path.expanduser(
'~%s/%s' % (self.host_username, FILE_RC))
if not os.path.exists(self.filename):
error_msg = (u"Impossibile trovare il file di configurazione "
u"'%s'.\nLe unità di rete non saranno collegate." % (
FILE_RC.lstrip('.')))
if not self.shell_mode:
ErrorMessage(error_msg)
logging.error(error_msg)
sys.exit(5)
if self.verbose:
logging.warning("File RC utilizzato: %s", self.filename)
self.samba_shares = read_config(self.filename) | python | def set_shares(self):
"""
Setta la variabile membro 'self.samba_shares' il quale e' una lista
di dizionari con i dati da passare ai comandi di "umount" e "mount".
I vari dizionari sono popolati o da un file ~/.pygmount.rc e da un
file passato dall'utente.
"""
if self.filename is None:
self.filenamename = os.path.expanduser(
'~%s/%s' % (self.host_username, FILE_RC))
if not os.path.exists(self.filename):
error_msg = (u"Impossibile trovare il file di configurazione "
u"'%s'.\nLe unità di rete non saranno collegate." % (
FILE_RC.lstrip('.')))
if not self.shell_mode:
ErrorMessage(error_msg)
logging.error(error_msg)
sys.exit(5)
if self.verbose:
logging.warning("File RC utilizzato: %s", self.filename)
self.samba_shares = read_config(self.filename) | [
"def",
"set_shares",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
"is",
"None",
":",
"self",
".",
"filenamename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~%s/%s'",
"%",
"(",
"self",
".",
"host_username",
",",
"FILE_RC",
")",
")",
"... | Setta la variabile membro 'self.samba_shares' il quale e' una lista
di dizionari con i dati da passare ai comandi di "umount" e "mount".
I vari dizionari sono popolati o da un file ~/.pygmount.rc e da un
file passato dall'utente. | [
"Setta",
"la",
"variabile",
"membro",
"self",
".",
"samba_shares",
"il",
"quale",
"e",
"una",
"lista",
"di",
"dizionari",
"con",
"i",
"dati",
"da",
"passare",
"ai",
"comandi",
"di",
"umount",
"e",
"mount",
".",
"I",
"vari",
"dizionari",
"sono",
"popolati",... | train | https://github.com/simodalla/pygmount/blob/8027cfa2ed5fa8e9207d72b6013ecec7fcf2e5f5/pygmount/utils/mount.py#L83-L103 |
simodalla/pygmount | pygmount/utils/mount.py | MountSmbSharesOld.run | def run(self):
"""
Esegue il montaggio delle varie condivisioni chiedendo all'utente
username e password di dominio.
"""
logging.info('start run with "{}" at {}'.format(
self.username, datetime.datetime.now()))
progress = Progress(text="Controllo requisiti software...",
pulsate=True, auto_close=True)
progress(1)
try:
self.requirements()
except LockFailedException as lfe:
ErrorMessage('Errore "{}" probabilmente l\'utente {} non ha i'
' diritti di amministratore'.format(lfe,
self.username))
sys.exit(20)
except Exception as e:
ErrorMessage("Si e' verificato un errore generico: {}".format(e))
sys.exit(21)
progress(100)
self.set_shares()
# richiesta username del dominio
insert_msg = "Inserisci l'utente del Dominio/Posta Elettronica"
default_username = (self.host_username if self.host_username
else os.environ['USER'])
self.domain_username = GetText(text=insert_msg,
entry_text=self.username)
if self.domain_username is None or len(self.domain_username) == 0:
error_msg = "Inserimento di un username di dominio vuoto"
ErrorMessage(self.msg_error % error_msg)
sys.exit(2)
# richiesta della password di dominio
insert_msg = u"Inserisci la password del Dominio/Posta Elettronica"
self.domain_password = GetText(text=insert_msg,
entry_text='password',
password=True)
if self.domain_password is None or len(self.domain_password) == 0:
error_msg = u"Inserimento di una password di dominio vuota"
ErrorMessage(self.msg_error % error_msg)
sys.exit(3)
progress_msg = u"Collegamento unità di rete in corso..."
progress = Progress(text=progress_msg,
pulsate=True,
auto_close=True)
progress(1)
# ciclo per montare tutte le condivisioni
result = []
for share in self.samba_shares:
# print("#######")
# print(share)
if 'mountpoint' not in share.keys():
# creazione stringa che rappresente il mount-point locale
mountpoint = os.path.expanduser(
'~%s/%s/%s' % (self.host_username,
share['hostname'],
share['share']))
share.update({'mountpoint': mountpoint})
elif not share['mountpoint'].startswith('/'):
mountpoint = os.path.expanduser(
'~%s/%s' % (self.host_username, share['mountpoint']))
share.update({'mountpoint': mountpoint})
share.update({
'host_username': self.host_username,
'domain_username': share.get(
'username', self.domain_username),
'domain_password': share.get(
'password', self.domain_password)})
# controllo che il mount-point locale esista altrimenti non
# viene creato
if not os.path.exists(share['mountpoint']):
if self.verbose:
logging.warning('Mountpoint "%s" not exist.' %
share['mountpoint'])
if not self.dry_run:
os.makedirs(share['mountpoint'])
# smonto la condivisione prima di rimontarla
umont_cmd = self.cmd_umount % share
if self.verbose:
logging.warning("Umount command: %s" % umont_cmd)
if not self.dry_run:
umount_p = subprocess.Popen(umont_cmd,
shell=True)
returncode = umount_p.wait()
time.sleep(2)
mount_cmd = self.cmd_mount % share
if self.verbose:
placeholder = ",password="
logging.warning("Mount command: %s%s" % (mount_cmd.split(
placeholder)[0], placeholder + "******\""))
# print(mount_cmd)
# print("#######")
if not self.dry_run:
# montaggio della condivisione
p_mnt = subprocess.Popen(mount_cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
returncode = p_mnt.wait()
result.append({'share': share['share'],
'returncode': returncode,
'stdout': p_mnt.stdout.read(),
'stderr': p_mnt.stderr.read()})
progress(100)
if self.verbose:
logging.warning("Risultati: %s" % result) | python | def run(self):
"""
Esegue il montaggio delle varie condivisioni chiedendo all'utente
username e password di dominio.
"""
logging.info('start run with "{}" at {}'.format(
self.username, datetime.datetime.now()))
progress = Progress(text="Controllo requisiti software...",
pulsate=True, auto_close=True)
progress(1)
try:
self.requirements()
except LockFailedException as lfe:
ErrorMessage('Errore "{}" probabilmente l\'utente {} non ha i'
' diritti di amministratore'.format(lfe,
self.username))
sys.exit(20)
except Exception as e:
ErrorMessage("Si e' verificato un errore generico: {}".format(e))
sys.exit(21)
progress(100)
self.set_shares()
# richiesta username del dominio
insert_msg = "Inserisci l'utente del Dominio/Posta Elettronica"
default_username = (self.host_username if self.host_username
else os.environ['USER'])
self.domain_username = GetText(text=insert_msg,
entry_text=self.username)
if self.domain_username is None or len(self.domain_username) == 0:
error_msg = "Inserimento di un username di dominio vuoto"
ErrorMessage(self.msg_error % error_msg)
sys.exit(2)
# richiesta della password di dominio
insert_msg = u"Inserisci la password del Dominio/Posta Elettronica"
self.domain_password = GetText(text=insert_msg,
entry_text='password',
password=True)
if self.domain_password is None or len(self.domain_password) == 0:
error_msg = u"Inserimento di una password di dominio vuota"
ErrorMessage(self.msg_error % error_msg)
sys.exit(3)
progress_msg = u"Collegamento unità di rete in corso..."
progress = Progress(text=progress_msg,
pulsate=True,
auto_close=True)
progress(1)
# ciclo per montare tutte le condivisioni
result = []
for share in self.samba_shares:
# print("#######")
# print(share)
if 'mountpoint' not in share.keys():
# creazione stringa che rappresente il mount-point locale
mountpoint = os.path.expanduser(
'~%s/%s/%s' % (self.host_username,
share['hostname'],
share['share']))
share.update({'mountpoint': mountpoint})
elif not share['mountpoint'].startswith('/'):
mountpoint = os.path.expanduser(
'~%s/%s' % (self.host_username, share['mountpoint']))
share.update({'mountpoint': mountpoint})
share.update({
'host_username': self.host_username,
'domain_username': share.get(
'username', self.domain_username),
'domain_password': share.get(
'password', self.domain_password)})
# controllo che il mount-point locale esista altrimenti non
# viene creato
if not os.path.exists(share['mountpoint']):
if self.verbose:
logging.warning('Mountpoint "%s" not exist.' %
share['mountpoint'])
if not self.dry_run:
os.makedirs(share['mountpoint'])
# smonto la condivisione prima di rimontarla
umont_cmd = self.cmd_umount % share
if self.verbose:
logging.warning("Umount command: %s" % umont_cmd)
if not self.dry_run:
umount_p = subprocess.Popen(umont_cmd,
shell=True)
returncode = umount_p.wait()
time.sleep(2)
mount_cmd = self.cmd_mount % share
if self.verbose:
placeholder = ",password="
logging.warning("Mount command: %s%s" % (mount_cmd.split(
placeholder)[0], placeholder + "******\""))
# print(mount_cmd)
# print("#######")
if not self.dry_run:
# montaggio della condivisione
p_mnt = subprocess.Popen(mount_cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
returncode = p_mnt.wait()
result.append({'share': share['share'],
'returncode': returncode,
'stdout': p_mnt.stdout.read(),
'stderr': p_mnt.stderr.read()})
progress(100)
if self.verbose:
logging.warning("Risultati: %s" % result) | [
"def",
"run",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'start run with \"{}\" at {}'",
".",
"format",
"(",
"self",
".",
"username",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
")",
"progress",
"=",
"Progress",
"(",
"text",
... | Esegue il montaggio delle varie condivisioni chiedendo all'utente
username e password di dominio. | [
"Esegue",
"il",
"montaggio",
"delle",
"varie",
"condivisioni",
"chiedendo",
"all",
"utente",
"username",
"e",
"password",
"di",
"dominio",
"."
] | train | https://github.com/simodalla/pygmount/blob/8027cfa2ed5fa8e9207d72b6013ecec7fcf2e5f5/pygmount/utils/mount.py#L105-L219 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/mongomock_mate.py | _dump | def _dump(db):
"""
Dump :class:`mongomock.database.Database` to dict data.
"""
db_data = {"name": db.name, "_collections": dict()}
for col_name, collection in iteritems(db._collections):
if col_name != "system.indexes":
col_data = {
"_documents": collection._documents,
"_uniques": collection._uniques,
}
db_data["_collections"][col_name] = col_data
return db_data | python | def _dump(db):
"""
Dump :class:`mongomock.database.Database` to dict data.
"""
db_data = {"name": db.name, "_collections": dict()}
for col_name, collection in iteritems(db._collections):
if col_name != "system.indexes":
col_data = {
"_documents": collection._documents,
"_uniques": collection._uniques,
}
db_data["_collections"][col_name] = col_data
return db_data | [
"def",
"_dump",
"(",
"db",
")",
":",
"db_data",
"=",
"{",
"\"name\"",
":",
"db",
".",
"name",
",",
"\"_collections\"",
":",
"dict",
"(",
")",
"}",
"for",
"col_name",
",",
"collection",
"in",
"iteritems",
"(",
"db",
".",
"_collections",
")",
":",
"if"... | Dump :class:`mongomock.database.Database` to dict data. | [
"Dump",
":",
"class",
":",
"mongomock",
".",
"database",
".",
"Database",
"to",
"dict",
"data",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/mongomock_mate.py#L12-L26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.