repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
allonhadaya/dmenu-python
dmenu/dmenu.py
version
def version(command='dmenu'): '''The dmenu command's version message. Raises: DmenuCommandError Example: >>> import dmenu >>> dmenu.version() 'dmenu-4.5, \xc2\xa9 2006-2012 dmenu engineers, see LICENSE for details' ''' args = [command, '-v'] try: # st...
python
def version(command='dmenu'): '''The dmenu command's version message. Raises: DmenuCommandError Example: >>> import dmenu >>> dmenu.version() 'dmenu-4.5, \xc2\xa9 2006-2012 dmenu engineers, see LICENSE for details' ''' args = [command, '-v'] try: # st...
[ "def", "version", "(", "command", "=", "'dmenu'", ")", ":", "args", "=", "[", "command", ",", "'-v'", "]", "try", ":", "# start the dmenu process", "proc", "=", "subprocess", ".", "Popen", "(", "args", ",", "universal_newlines", "=", "True", ",", "stdout",...
The dmenu command's version message. Raises: DmenuCommandError Example: >>> import dmenu >>> dmenu.version() 'dmenu-4.5, \xc2\xa9 2006-2012 dmenu engineers, see LICENSE for details'
[ "The", "dmenu", "command", "s", "version", "message", "." ]
30eca49a9368c61e13e87f530cc3785a369536c4
https://github.com/allonhadaya/dmenu-python/blob/30eca49a9368c61e13e87f530cc3785a369536c4/dmenu/dmenu.py#L28-L59
train
The dmenu command s version message.
allonhadaya/dmenu-python
dmenu/dmenu.py
show
def show( items, command='dmenu', bottom=None, fast=None, case_insensitive=None, lines=None, monitor=None, prompt=None, font=None, background=None, foreground=None, background_selected=None, foreground_selected=None)...
python
def show( items, command='dmenu', bottom=None, fast=None, case_insensitive=None, lines=None, monitor=None, prompt=None, font=None, background=None, foreground=None, background_selected=None, foreground_selected=None)...
[ "def", "show", "(", "items", ",", "command", "=", "'dmenu'", ",", "bottom", "=", "None", ",", "fast", "=", "None", ",", "case_insensitive", "=", "None", ",", "lines", "=", "None", ",", "monitor", "=", "None", ",", "prompt", "=", "None", ",", "font", ...
Present a dmenu to the user. Args: items (Iterable[str]): defines the menu items being presented to the user. items should not contain the newline character. command (Optional[str]): defines the path to the dmenu executable. Defaults to 'dmenu'. bottom (Optional[bool]): dmenu appears at the...
[ "Present", "a", "dmenu", "to", "the", "user", "." ]
30eca49a9368c61e13e87f530cc3785a369536c4
https://github.com/allonhadaya/dmenu-python/blob/30eca49a9368c61e13e87f530cc3785a369536c4/dmenu/dmenu.py#L62-L206
train
Presents a dmenu to the user.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/filtered_network.py
FilteredNetwork.get_upregulated_genes_network
def get_upregulated_genes_network(self) -> Graph: """Get the graph of up-regulated genes. :return Graph: Graph of up-regulated genes. """ logger.info("In get_upregulated_genes_network()") deg_graph = self.graph.copy() # deep copy graph not_diff_expr = self.graph.vs(up_...
python
def get_upregulated_genes_network(self) -> Graph: """Get the graph of up-regulated genes. :return Graph: Graph of up-regulated genes. """ logger.info("In get_upregulated_genes_network()") deg_graph = self.graph.copy() # deep copy graph not_diff_expr = self.graph.vs(up_...
[ "def", "get_upregulated_genes_network", "(", "self", ")", "->", "Graph", ":", "logger", ".", "info", "(", "\"In get_upregulated_genes_network()\"", ")", "deg_graph", "=", "self", ".", "graph", ".", "copy", "(", ")", "# deep copy graph", "not_diff_expr", "=", "self...
Get the graph of up-regulated genes. :return Graph: Graph of up-regulated genes.
[ "Get", "the", "graph", "of", "up", "-", "regulated", "genes", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/filtered_network.py#L27-L41
train
Get the graph of up - regulated genes.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/filtered_network.py
FilteredNetwork.get_downregulated_genes_network
def get_downregulated_genes_network(self) -> Graph: """Get the graph of down-regulated genes. :return Graph: Graph of down-regulated genes. """ logger.info("In get_downregulated_genes_network()") deg_graph = self.graph.copy() # deep copy graph not_diff_expr = self.grap...
python
def get_downregulated_genes_network(self) -> Graph: """Get the graph of down-regulated genes. :return Graph: Graph of down-regulated genes. """ logger.info("In get_downregulated_genes_network()") deg_graph = self.graph.copy() # deep copy graph not_diff_expr = self.grap...
[ "def", "get_downregulated_genes_network", "(", "self", ")", "->", "Graph", ":", "logger", ".", "info", "(", "\"In get_downregulated_genes_network()\"", ")", "deg_graph", "=", "self", ".", "graph", ".", "copy", "(", ")", "# deep copy graph", "not_diff_expr", "=", "...
Get the graph of down-regulated genes. :return Graph: Graph of down-regulated genes.
[ "Get", "the", "graph", "of", "down", "-", "regulated", "genes", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/filtered_network.py#L43-L57
train
Get the graph of down - regulated genes.
BernardFW/bernard
src/bernard/misc/main/_base.py
make_parser
def make_parser(): """ Generate the parser for all sub-commands """ parser = argparse.ArgumentParser(description='BERNARD CLI utility') sp = parser.add_subparsers(help='Sub-command') parser_run = sp.add_parser('run', help='Run the BERNARD server') parser_run.set_defaults(action='run') ...
python
def make_parser(): """ Generate the parser for all sub-commands """ parser = argparse.ArgumentParser(description='BERNARD CLI utility') sp = parser.add_subparsers(help='Sub-command') parser_run = sp.add_parser('run', help='Run the BERNARD server') parser_run.set_defaults(action='run') ...
[ "def", "make_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'BERNARD CLI utility'", ")", "sp", "=", "parser", ".", "add_subparsers", "(", "help", "=", "'Sub-command'", ")", "parser_run", "=", "sp", ".", "a...
Generate the parser for all sub-commands
[ "Generate", "the", "parser", "for", "all", "sub", "-", "commands" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/main/_base.py#L5-L55
train
Generate the parser for all sub - commands
BernardFW/bernard
src/bernard/misc/main/_base.py
main
def main(): """ Run the appropriate main function according to the output of the parser. """ parser = make_parser() args = parser.parse_args() if not hasattr(args, 'action'): parser.print_help() exit(1) if args.action == 'sheet': from bernard.misc.sheet_sync import...
python
def main(): """ Run the appropriate main function according to the output of the parser. """ parser = make_parser() args = parser.parse_args() if not hasattr(args, 'action'): parser.print_help() exit(1) if args.action == 'sheet': from bernard.misc.sheet_sync import...
[ "def", "main", "(", ")", ":", "parser", "=", "make_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "not", "hasattr", "(", "args", ",", "'action'", ")", ":", "parser", ".", "print_help", "(", ")", "exit", "(", "1", ")", ...
Run the appropriate main function according to the output of the parser.
[ "Run", "the", "appropriate", "main", "function", "according", "to", "the", "output", "of", "the", "parser", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/main/_base.py#L58-L78
train
Run the appropriate main function according to the output of the parser.
sthysel/knobs
src/environment.py
load_dotenv
def load_dotenv(dotenv_path, verbose=False): """ Read a .env file and load into os.environ. :param dotenv_path: :type dotenv_path: str :param verbose: verbosity flag, raise warning if path does not exist :return: success flag """ if not os.path.exists(dotenv_path): if verbose: ...
python
def load_dotenv(dotenv_path, verbose=False): """ Read a .env file and load into os.environ. :param dotenv_path: :type dotenv_path: str :param verbose: verbosity flag, raise warning if path does not exist :return: success flag """ if not os.path.exists(dotenv_path): if verbose: ...
[ "def", "load_dotenv", "(", "dotenv_path", ",", "verbose", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dotenv_path", ")", ":", "if", "verbose", ":", "warnings", ".", "warn", "(", "f\"Not loading {dotenv_path}, it doesn't exist.\...
Read a .env file and load into os.environ. :param dotenv_path: :type dotenv_path: str :param verbose: verbosity flag, raise warning if path does not exist :return: success flag
[ "Read", "a", ".", "env", "file", "and", "load", "into", "os", ".", "environ", "." ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L20-L35
train
Read a. env file and load into os. environ.
sthysel/knobs
src/environment.py
get_key
def get_key(dotenv_path, key_to_get, verbose=False): """ Gets the value of a given key from the given .env If the .env path given doesn't exist, fails :param dotenv_path: path :param key_to_get: key :param verbose: verbosity flag, raise warning if path does not exist :return: value of varia...
python
def get_key(dotenv_path, key_to_get, verbose=False): """ Gets the value of a given key from the given .env If the .env path given doesn't exist, fails :param dotenv_path: path :param key_to_get: key :param verbose: verbosity flag, raise warning if path does not exist :return: value of varia...
[ "def", "get_key", "(", "dotenv_path", ",", "key_to_get", ",", "verbose", "=", "False", ")", ":", "key_to_get", "=", "str", "(", "key_to_get", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dotenv_path", ")", ":", "if", "verbose", ":", "warni...
Gets the value of a given key from the given .env If the .env path given doesn't exist, fails :param dotenv_path: path :param key_to_get: key :param verbose: verbosity flag, raise warning if path does not exist :return: value of variable from environment file or None
[ "Gets", "the", "value", "of", "a", "given", "key", "from", "the", "given", ".", "env" ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L38-L59
train
Gets the value of a given key from the given. env file.
sthysel/knobs
src/environment.py
set_key
def set_key(dotenv_path, key_to_set, value_to_set, quote_mode='always', verbose=False): """ Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the file-system :param dotenv_path: env path :param key_...
python
def set_key(dotenv_path, key_to_set, value_to_set, quote_mode='always', verbose=False): """ Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the file-system :param dotenv_path: env path :param key_...
[ "def", "set_key", "(", "dotenv_path", ",", "key_to_set", ",", "value_to_set", ",", "quote_mode", "=", "'always'", ",", "verbose", "=", "False", ")", ":", "key_to_set", "=", "str", "(", "key_to_set", ")", "value_to_set", "=", "str", "(", "value_to_set", ")", ...
Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the file-system :param dotenv_path: env path :param key_to_set: key :param value_to_set: value :param quote_mode: quote value in .env file :para...
[ "Adds", "or", "Updates", "a", "key", "/", "value", "to", "the", "given", ".", "env" ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L62-L87
train
Adds or updates a key to the given. env file.
sthysel/knobs
src/environment.py
unset_key
def unset_key(dotenv_path, key_to_unset, quote_mode='always', verbose=False): """ Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails :param dotenv_path: env path :param key_to_unset: value :param quote_mode:...
python
def unset_key(dotenv_path, key_to_unset, quote_mode='always', verbose=False): """ Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails :param dotenv_path: env path :param key_to_unset: value :param quote_mode:...
[ "def", "unset_key", "(", "dotenv_path", ",", "key_to_unset", ",", "quote_mode", "=", "'always'", ",", "verbose", "=", "False", ")", ":", "key_to_unset", "=", "str", "(", "key_to_unset", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dotenv_path"...
Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in the .env, fails :param dotenv_path: env path :param key_to_unset: value :param quote_mode: quote value in .env file :param verbose: verbosity flag, raise warning if path does n...
[ "Removes", "a", "given", "key", "from", "the", "given", ".", "env" ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L90-L117
train
Removes a given key from the given. env file and returns success and key.
sthysel/knobs
src/environment.py
dotenv_values
def dotenv_values(dotenv_path): """ :param dotenv_path: env file :return: ordered dict """ values = OrderedDict(parse_dotenv(dotenv_path)) values = resolve_nested_variables(values) return values
python
def dotenv_values(dotenv_path): """ :param dotenv_path: env file :return: ordered dict """ values = OrderedDict(parse_dotenv(dotenv_path)) values = resolve_nested_variables(values) return values
[ "def", "dotenv_values", "(", "dotenv_path", ")", ":", "values", "=", "OrderedDict", "(", "parse_dotenv", "(", "dotenv_path", ")", ")", "values", "=", "resolve_nested_variables", "(", "values", ")", "return", "values" ]
:param dotenv_path: env file :return: ordered dict
[ ":", "param", "dotenv_path", ":", "env", "file", ":", "return", ":", "ordered", "dict" ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L120-L127
train
parse a dotenv file and return a dict of values
sthysel/knobs
src/environment.py
parse_dotenv
def parse_dotenv(dotenv_path): """ Parses the dotenv file, comments (#) are ignored. A key must have a '=' to mark it as a key. Strings without a '=' are ignored. :param dotenv_path: :return: generator yielding (key,value) """ with open(dotenv_path) as f: for line in f: ...
python
def parse_dotenv(dotenv_path): """ Parses the dotenv file, comments (#) are ignored. A key must have a '=' to mark it as a key. Strings without a '=' are ignored. :param dotenv_path: :return: generator yielding (key,value) """ with open(dotenv_path) as f: for line in f: ...
[ "def", "parse_dotenv", "(", "dotenv_path", ")", ":", "with", "open", "(", "dotenv_path", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "line", ".", "startswith", "(", "'#...
Parses the dotenv file, comments (#) are ignored. A key must have a '=' to mark it as a key. Strings without a '=' are ignored. :param dotenv_path: :return: generator yielding (key,value)
[ "Parses", "the", "dotenv", "file", "comments", "(", "#", ")", "are", "ignored", ".", "A", "key", "must", "have", "a", "=", "to", "mark", "it", "as", "a", "key", ".", "Strings", "without", "a", "=", "are", "ignored", "." ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L130-L155
train
Parses the dotenv file and returns a generator yielding the key and value pairs.
sthysel/knobs
src/environment.py
_get_format
def _get_format(value, quote_mode='always'): """ Returns the quote format depending on the quote_mode. This determines if the key value will be quoted when written to the env file. :param value: :param quote_mode: :return: str :raises: KeyError if the quote_mode is unknown """ ...
python
def _get_format(value, quote_mode='always'): """ Returns the quote format depending on the quote_mode. This determines if the key value will be quoted when written to the env file. :param value: :param quote_mode: :return: str :raises: KeyError if the quote_mode is unknown """ ...
[ "def", "_get_format", "(", "value", ",", "quote_mode", "=", "'always'", ")", ":", "formats", "=", "{", "'always'", ":", "'{key}=\"{value}\"\\n'", ",", "'auto'", ":", "'{key}={value}\\n'", "}", "if", "quote_mode", "not", "in", "formats", ".", "keys", "(", ")"...
Returns the quote format depending on the quote_mode. This determines if the key value will be quoted when written to the env file. :param value: :param quote_mode: :return: str :raises: KeyError if the quote_mode is unknown
[ "Returns", "the", "quote", "format", "depending", "on", "the", "quote_mode", ".", "This", "determines", "if", "the", "key", "value", "will", "be", "quoted", "when", "written", "to", "the", "env", "file", "." ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L181-L201
train
Returns the quote format depending on the quote_mode.
sthysel/knobs
src/environment.py
flatten_and_write
def flatten_and_write(dotenv_path, dotenv_as_dict, quote_mode='always'): """ Writes dotenv_as_dict to dotenv_path, flattening the values :param dotenv_path: .env path :param dotenv_as_dict: dict :param quote_mode: :return: """ with open(dotenv_path, 'w') as f: for k, v in dotenv_...
python
def flatten_and_write(dotenv_path, dotenv_as_dict, quote_mode='always'): """ Writes dotenv_as_dict to dotenv_path, flattening the values :param dotenv_path: .env path :param dotenv_as_dict: dict :param quote_mode: :return: """ with open(dotenv_path, 'w') as f: for k, v in dotenv_...
[ "def", "flatten_and_write", "(", "dotenv_path", ",", "dotenv_as_dict", ",", "quote_mode", "=", "'always'", ")", ":", "with", "open", "(", "dotenv_path", ",", "'w'", ")", "as", "f", ":", "for", "k", ",", "v", "in", "dotenv_as_dict", ".", "items", "(", ")"...
Writes dotenv_as_dict to dotenv_path, flattening the values :param dotenv_path: .env path :param dotenv_as_dict: dict :param quote_mode: :return:
[ "Writes", "dotenv_as_dict", "to", "dotenv_path", "flattening", "the", "values", ":", "param", "dotenv_path", ":", ".", "env", "path", ":", "param", "dotenv_as_dict", ":", "dict", ":", "param", "quote_mode", ":", ":", "return", ":" ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L204-L216
train
Writes a dict to a. env file
sthysel/knobs
src/environment.py
find_dotenv
def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False): """ Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise """ if usecwd or '__file__' not in globals(): # should work without __file__, e.g. in ...
python
def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False): """ Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise """ if usecwd or '__file__' not in globals(): # should work without __file__, e.g. in ...
[ "def", "find_dotenv", "(", "filename", "=", "'.env'", ",", "raise_error_if_not_found", "=", "False", ",", "usecwd", "=", "False", ")", ":", "if", "usecwd", "or", "'__file__'", "not", "in", "globals", "(", ")", ":", "# should work without __file__, e.g. in REPL or ...
Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise
[ "Search", "in", "increasingly", "higher", "folders", "for", "the", "given", "file" ]
1d01f50f643068076e38118a93fed9375ea3ac81
https://github.com/sthysel/knobs/blob/1d01f50f643068076e38118a93fed9375ea3ac81/src/environment.py#L237-L259
train
Search in increasingly higher folders for the given file and return the path to the file if found.
cloudmesh-cmd3/cmd3
cmd3/plugins/shell_core.py
shell_core.do_version
def do_version(self, args): """ Usage: version Prints out the version number """ Console.ok("cmd3: {:}".format(str(cmd3.__version__))) Console.ok("cloudmesh_base: {:}".format(str(cloudmesh_base.__version__))) python_version, pip_version = get_python()...
python
def do_version(self, args): """ Usage: version Prints out the version number """ Console.ok("cmd3: {:}".format(str(cmd3.__version__))) Console.ok("cloudmesh_base: {:}".format(str(cloudmesh_base.__version__))) python_version, pip_version = get_python()...
[ "def", "do_version", "(", "self", ",", "args", ")", ":", "Console", ".", "ok", "(", "\"cmd3: {:}\"", ".", "format", "(", "str", "(", "cmd3", ".", "__version__", ")", ")", ")", "Console", ".", "ok", "(", "\"cloudmesh_base: {:}\"", ".", "format", "(", "s...
Usage: version Prints out the version number
[ "Usage", ":", "version" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/shell_core.py#L29-L45
train
Print out the version number of the current version of the cloudmesh base and the python version.
cloudmesh-cmd3/cmd3
cmd3/plugins/shell_core.py
shell_core.do_exec
def do_exec(self, filename): """ :: Usage: exec FILENAME executes the commands in the file. See also the script command. Arguments: FILENAME The name of the file """ if not filename: Console.error("...
python
def do_exec(self, filename): """ :: Usage: exec FILENAME executes the commands in the file. See also the script command. Arguments: FILENAME The name of the file """ if not filename: Console.error("...
[ "def", "do_exec", "(", "self", ",", "filename", ")", ":", "if", "not", "filename", ":", "Console", ".", "error", "(", "\"the command requires a filename as parameter\"", ")", "return", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "with"...
:: Usage: exec FILENAME executes the commands in the file. See also the script command. Arguments: FILENAME The name of the file
[ "::", "Usage", ":", "exec", "FILENAME" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/shell_core.py#L124-L147
train
Execute the commands in the file.
garenchan/policy
policy/_parser.py
reducer
def reducer(*tokens): """Decorator for reduction methods. Arguments are a sequence of tokens, which should trigger running this reduction method. """ def wrapper(func): # Make sure that we have a list of reducer sequences if not hasattr(func, 'reducers'): func.reducers ...
python
def reducer(*tokens): """Decorator for reduction methods. Arguments are a sequence of tokens, which should trigger running this reduction method. """ def wrapper(func): # Make sure that we have a list of reducer sequences if not hasattr(func, 'reducers'): func.reducers ...
[ "def", "reducer", "(", "*", "tokens", ")", ":", "def", "wrapper", "(", "func", ")", ":", "# Make sure that we have a list of reducer sequences", "if", "not", "hasattr", "(", "func", ",", "'reducers'", ")", ":", "func", ".", "reducers", "=", "[", "]", "# Add ...
Decorator for reduction methods. Arguments are a sequence of tokens, which should trigger running this reduction method.
[ "Decorator", "for", "reduction", "methods", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_parser.py#L19-L36
train
Decorator for reduction methods.
garenchan/policy
policy/_parser.py
parse_rule
def parse_rule(rule: str, raise_error=False): """Parses policy to a tree of Check objects.""" parser = Parser(raise_error) return parser.parse(rule)
python
def parse_rule(rule: str, raise_error=False): """Parses policy to a tree of Check objects.""" parser = Parser(raise_error) return parser.parse(rule)
[ "def", "parse_rule", "(", "rule", ":", "str", ",", "raise_error", "=", "False", ")", ":", "parser", "=", "Parser", "(", "raise_error", ")", "return", "parser", ".", "parse", "(", "rule", ")" ]
Parses policy to a tree of Check objects.
[ "Parses", "policy", "to", "a", "tree", "of", "Check", "objects", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_parser.py#L269-L273
train
Parses a policy to a tree of Check objects.
garenchan/policy
policy/_parser.py
Parser._reduce
def _reduce(self): """Perform a greedy reduction of token stream. If a reducer method matches, it will be executed, then the :meth:`reduce` method will be called recursively to search for any more possible reductions. """ for reduction, methname in self.reducers: ...
python
def _reduce(self): """Perform a greedy reduction of token stream. If a reducer method matches, it will be executed, then the :meth:`reduce` method will be called recursively to search for any more possible reductions. """ for reduction, methname in self.reducers: ...
[ "def", "_reduce", "(", "self", ")", ":", "for", "reduction", ",", "methname", "in", "self", ".", "reducers", ":", "token_num", "=", "len", "(", "reduction", ")", "if", "(", "len", "(", "self", ".", "tokens", ")", ">=", "token_num", "and", "self", "."...
Perform a greedy reduction of token stream. If a reducer method matches, it will be executed, then the :meth:`reduce` method will be called recursively to search for any more possible reductions.
[ "Perform", "a", "greedy", "reduction", "of", "token", "stream", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_parser.py#L75-L97
train
Perform a greedy reduction of the token stream.
garenchan/policy
policy/_parser.py
Parser._parse_check
def _parse_check(self, rule): """Parse a single base check rule into an appropriate Check object.""" # Handle the special constant-type checks for check_cls in (checks.FalseCheck, checks.TrueCheck): check = check_cls() if rule == str(check): return check ...
python
def _parse_check(self, rule): """Parse a single base check rule into an appropriate Check object.""" # Handle the special constant-type checks for check_cls in (checks.FalseCheck, checks.TrueCheck): check = check_cls() if rule == str(check): return check ...
[ "def", "_parse_check", "(", "self", ",", "rule", ")", ":", "# Handle the special constant-type checks", "for", "check_cls", "in", "(", "checks", ".", "FalseCheck", ",", "checks", ".", "TrueCheck", ")", ":", "check", "=", "check_cls", "(", ")", "if", "rule", ...
Parse a single base check rule into an appropriate Check object.
[ "Parse", "a", "single", "base", "check", "rule", "into", "an", "appropriate", "Check", "object", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_parser.py#L117-L145
train
Parse a single base check rule into an appropriate Check object.
garenchan/policy
policy/_parser.py
Parser._parse_tokenize
def _parse_tokenize(self, rule): """Tokenizer for the policy language.""" for token in self._TOKENIZE_RE.split(rule): # Skip empty tokens if not token or token.isspace(): continue # Handle leading parens on the token clean = token.lstrip(...
python
def _parse_tokenize(self, rule): """Tokenizer for the policy language.""" for token in self._TOKENIZE_RE.split(rule): # Skip empty tokens if not token or token.isspace(): continue # Handle leading parens on the token clean = token.lstrip(...
[ "def", "_parse_tokenize", "(", "self", ",", "rule", ")", ":", "for", "token", "in", "self", ".", "_TOKENIZE_RE", ".", "split", "(", "rule", ")", ":", "# Skip empty tokens", "if", "not", "token", "or", "token", ".", "isspace", "(", ")", ":", "continue", ...
Tokenizer for the policy language.
[ "Tokenizer", "for", "the", "policy", "language", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_parser.py#L147-L186
train
Yields the tokens in the rule.
garenchan/policy
policy/_parser.py
Parser.parse
def parse(self, rule: str): """Parses policy to tree. Translate a policy written in the policy language into a tree of Check objects. """ # Empty rule means always accept if not rule: return checks.TrueCheck() for token, value in self._parse_tokeniz...
python
def parse(self, rule: str): """Parses policy to tree. Translate a policy written in the policy language into a tree of Check objects. """ # Empty rule means always accept if not rule: return checks.TrueCheck() for token, value in self._parse_tokeniz...
[ "def", "parse", "(", "self", ",", "rule", ":", "str", ")", ":", "# Empty rule means always accept", "if", "not", "rule", ":", "return", "checks", ".", "TrueCheck", "(", ")", "for", "token", ",", "value", "in", "self", ".", "_parse_tokenize", "(", "rule", ...
Parses policy to tree. Translate a policy written in the policy language into a tree of Check objects.
[ "Parses", "policy", "to", "tree", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_parser.py#L188-L207
train
Parses a policy to tree. Translate a policy written in the policy language into a tree of Check objects.
jstitch/MambuPy
MambuPy/rest/mamburepayment.py
MambuRepayments.convertDict2Attrs
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Repayment object for each one, initializing them one at a time, and changing the attrs attribute (which ju...
python
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Repayment object for each one, initializing them one at a time, and changing the attrs attribute (which ju...
[ "def", "convertDict2Attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "n", ",", "r", "in", "enumerate", "(", "self", ".", "attrs", ")", ":", "# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!", "try", ":",...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Repayment object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dictionaries) with a Mam...
[ "The", "trick", "for", "iterable", "Mambu", "Objects", "comes", "here", ":" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mamburepayment.py#L69-L96
train
This method converts a dictionary of plain dictionaries into a list of Mambu Repayment objects.
inveniosoftware/invenio-query-parser
invenio_query_parser/utils.py
build_valid_keywords_grammar
def build_valid_keywords_grammar(keywords=None): """Update parser grammar to add a list of allowed keywords.""" from invenio_query_parser.parser import KeywordQuery, KeywordRule, \ NotKeywordValue, SimpleQuery, ValueQuery if keywords: KeywordRule.grammar = attr('value', re.compile( ...
python
def build_valid_keywords_grammar(keywords=None): """Update parser grammar to add a list of allowed keywords.""" from invenio_query_parser.parser import KeywordQuery, KeywordRule, \ NotKeywordValue, SimpleQuery, ValueQuery if keywords: KeywordRule.grammar = attr('value', re.compile( ...
[ "def", "build_valid_keywords_grammar", "(", "keywords", "=", "None", ")", ":", "from", "invenio_query_parser", ".", "parser", "import", "KeywordQuery", ",", "KeywordRule", ",", "NotKeywordValue", ",", "SimpleQuery", ",", "ValueQuery", "if", "keywords", ":", "Keyword...
Update parser grammar to add a list of allowed keywords.
[ "Update", "parser", "grammar", "to", "add", "a", "list", "of", "allowed", "keywords", "." ]
21a2c36318003ff52d2e18e7196bb420db8ecb4b
https://github.com/inveniosoftware/invenio-query-parser/blob/21a2c36318003ff52d2e18e7196bb420db8ecb4b/invenio_query_parser/utils.py#L34-L51
train
Update parser grammar to add a list of allowed keywords.
frostming/marko
marko/renderer.py
Renderer.render
def render(self, element): """Renders the given element to string. :param element: a element to be rendered. :returns: the output string or any values. """ # Store the root node to provide some context to render functions if not self.root_node: self.root_node...
python
def render(self, element): """Renders the given element to string. :param element: a element to be rendered. :returns: the output string or any values. """ # Store the root node to provide some context to render functions if not self.root_node: self.root_node...
[ "def", "render", "(", "self", ",", "element", ")", ":", "# Store the root node to provide some context to render functions", "if", "not", "self", ".", "root_node", ":", "self", ".", "root_node", "=", "element", "render_func", "=", "getattr", "(", "self", ",", "sel...
Renders the given element to string. :param element: a element to be rendered. :returns: the output string or any values.
[ "Renders", "the", "given", "element", "to", "string", "." ]
1cd030b665fa37bad1f8b3a25a89ce1a7c491dde
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/renderer.py#L37-L50
train
Renders the given element to string.
frostming/marko
marko/renderer.py
Renderer.render_children
def render_children(self, element): """ Recursively renders child elements. Joins the rendered strings with no space in between. If newlines / spaces are needed between elements, add them in their respective templates, or override this function in the renderer subclass, ...
python
def render_children(self, element): """ Recursively renders child elements. Joins the rendered strings with no space in between. If newlines / spaces are needed between elements, add them in their respective templates, or override this function in the renderer subclass, ...
[ "def", "render_children", "(", "self", ",", "element", ")", ":", "rendered", "=", "[", "self", ".", "render", "(", "child", ")", "for", "child", "in", "element", ".", "children", "]", "return", "''", ".", "join", "(", "rendered", ")" ]
Recursively renders child elements. Joins the rendered strings with no space in between. If newlines / spaces are needed between elements, add them in their respective templates, or override this function in the renderer subclass, so that whitespace won't seem to appear magicall...
[ "Recursively", "renders", "child", "elements", ".", "Joins", "the", "rendered", "strings", "with", "no", "space", "in", "between", "." ]
1cd030b665fa37bad1f8b3a25a89ce1a7c491dde
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/renderer.py#L52-L65
train
Recursively renders child elements.
jstitch/MambuPy
MambuPy/rest/mambuuser.py
MambuUser.preprocess
def preprocess(self): """Preprocessing. Removes repeated chars from firstName and lastName fields. Adds a 'name' field joining all names in to one string. """ super(MambuUser,self).preprocess() try: self['firstName'] = self['firstName'].strip() exce...
python
def preprocess(self): """Preprocessing. Removes repeated chars from firstName and lastName fields. Adds a 'name' field joining all names in to one string. """ super(MambuUser,self).preprocess() try: self['firstName'] = self['firstName'].strip() exce...
[ "def", "preprocess", "(", "self", ")", ":", "super", "(", "MambuUser", ",", "self", ")", ".", "preprocess", "(", ")", "try", ":", "self", "[", "'firstName'", "]", "=", "self", "[", "'firstName'", "]", ".", "strip", "(", ")", "except", "Exception", "a...
Preprocessing. Removes repeated chars from firstName and lastName fields. Adds a 'name' field joining all names in to one string.
[ "Preprocessing", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuuser.py#L39-L57
train
Preprocessing.
jstitch/MambuPy
MambuPy/rest/mambuuser.py
MambuUser.setGroups
def setGroups(self, *args, **kwargs): """Adds the groups assigned to this user to a 'groups' field. Returns the number of requests done to Mambu. """ try: groups = self.mambugroupsclass(creditOfficerUsername=self['username'], *args, **kwargs) except AttributeError as...
python
def setGroups(self, *args, **kwargs): """Adds the groups assigned to this user to a 'groups' field. Returns the number of requests done to Mambu. """ try: groups = self.mambugroupsclass(creditOfficerUsername=self['username'], *args, **kwargs) except AttributeError as...
[ "def", "setGroups", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "groups", "=", "self", ".", "mambugroupsclass", "(", "creditOfficerUsername", "=", "self", "[", "'username'", "]", ",", "*", "args", ",", "*", "*", "kwa...
Adds the groups assigned to this user to a 'groups' field. Returns the number of requests done to Mambu.
[ "Adds", "the", "groups", "assigned", "to", "this", "user", "to", "a", "groups", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuuser.py#L60-L73
train
Adds the groups assigned to this user to a groups field. Returns the number of requests done to Mambu.
jstitch/MambuPy
MambuPy/rest/mambuuser.py
MambuUser.setRoles
def setRoles(self, *args, **kwargs): """Adds the role assigned to this user to a 'role' field. Depends on the 'role' field that comes with a fullDetails=True build of the MambuUser. Returns the number of requests done to Mambu. """ try: role = self.mamburole...
python
def setRoles(self, *args, **kwargs): """Adds the role assigned to this user to a 'role' field. Depends on the 'role' field that comes with a fullDetails=True build of the MambuUser. Returns the number of requests done to Mambu. """ try: role = self.mamburole...
[ "def", "setRoles", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "role", "=", "self", ".", "mamburoleclass", "(", "entid", "=", "self", "[", "'role'", "]", "[", "'encodedKey'", "]", ",", "*", "args", ",", "*", "*",...
Adds the role assigned to this user to a 'role' field. Depends on the 'role' field that comes with a fullDetails=True build of the MambuUser. Returns the number of requests done to Mambu.
[ "Adds", "the", "role", "assigned", "to", "this", "user", "to", "a", "role", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuuser.py#L76-L97
train
Adds the role assigned to this user to a role field. Returns the number of requests done to Mambu.
jstitch/MambuPy
MambuPy/rest/mambuuser.py
MambuUser.create
def create(self, data, *args, **kwargs): """Creates an user in Mambu Parameters -data dictionary with data to send """ super(MambuUser, self).create(data) self['user'][self.customFieldName] = self['customInformation'] self.init(attrs=self['user'])
python
def create(self, data, *args, **kwargs): """Creates an user in Mambu Parameters -data dictionary with data to send """ super(MambuUser, self).create(data) self['user'][self.customFieldName] = self['customInformation'] self.init(attrs=self['user'])
[ "def", "create", "(", "self", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "MambuUser", ",", "self", ")", ".", "create", "(", "data", ")", "self", "[", "'user'", "]", "[", "self", ".", "customFieldName", "]", "=...
Creates an user in Mambu Parameters -data dictionary with data to send
[ "Creates", "an", "user", "in", "Mambu" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuuser.py#L100-L109
train
Creates an user in MambuUser
jstitch/MambuPy
MambuPy/rest/mambuuser.py
MambuUsers.convertDict2Attrs
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu User (or your own itemclass) object for each one, initializing them one at a time, and changing the attrs ...
python
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu User (or your own itemclass) object for each one, initializing them one at a time, and changing the attrs ...
[ "def", "convertDict2Attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "n", ",", "u", "in", "enumerate", "(", "self", ".", "attrs", ")", ":", "try", ":", "params", "=", "self", ".", "params", "except", "AttributeError", ...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu User (or your own itemclass) object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dicti...
[ "The", "trick", "for", "iterable", "Mambu", "Objects", "comes", "here", ":" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuuser.py#L146-L172
train
This function converts a list of plain dictionaries into a list of Mambu User objects.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/attribute_network.py
AttributeNetwork.write_attribute_adj_list
def write_attribute_adj_list(self, path): """Write the bipartite attribute graph to a file. :param str path: Path to the output file. """ att_mappings = self.get_attribute_mappings() with open(path, mode="w") as file: for k, v in att_mappings.items(): ...
python
def write_attribute_adj_list(self, path): """Write the bipartite attribute graph to a file. :param str path: Path to the output file. """ att_mappings = self.get_attribute_mappings() with open(path, mode="w") as file: for k, v in att_mappings.items(): ...
[ "def", "write_attribute_adj_list", "(", "self", ",", "path", ")", ":", "att_mappings", "=", "self", ".", "get_attribute_mappings", "(", ")", "with", "open", "(", "path", ",", "mode", "=", "\"w\"", ")", "as", "file", ":", "for", "k", ",", "v", "in", "at...
Write the bipartite attribute graph to a file. :param str path: Path to the output file.
[ "Write", "the", "bipartite", "attribute", "graph", "to", "a", "file", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L25-L34
train
Write the bipartite attribute graph to a file.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/attribute_network.py
AttributeNetwork.get_attribute_mappings
def get_attribute_mappings(self): """Get a dictionary of mappings between vertices and enumerated attributes. :return: Dictionary of mappings between vertices and enumerated attributes. """ att_ind_start = len(self.graph.vs) att_mappings = defaultdict(list) att_ind_end =...
python
def get_attribute_mappings(self): """Get a dictionary of mappings between vertices and enumerated attributes. :return: Dictionary of mappings between vertices and enumerated attributes. """ att_ind_start = len(self.graph.vs) att_mappings = defaultdict(list) att_ind_end =...
[ "def", "get_attribute_mappings", "(", "self", ")", ":", "att_ind_start", "=", "len", "(", "self", ".", "graph", ".", "vs", ")", "att_mappings", "=", "defaultdict", "(", "list", ")", "att_ind_end", "=", "self", ".", "_add_differential_expression_attributes", "(",...
Get a dictionary of mappings between vertices and enumerated attributes. :return: Dictionary of mappings between vertices and enumerated attributes.
[ "Get", "a", "dictionary", "of", "mappings", "between", "vertices", "and", "enumerated", "attributes", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L36-L46
train
Get a dictionary of mappings between vertices and enumerated attributes.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/attribute_network.py
AttributeNetwork._add_differential_expression_attributes
def _add_differential_expression_attributes(self, att_ind_start, att_mappings): """Add differential expression information to the attribute mapping dictionary. :param int att_ind_start: Start index for enumerating the attributes. :param dict att_mappings: Dictionary of mappings between vertices...
python
def _add_differential_expression_attributes(self, att_ind_start, att_mappings): """Add differential expression information to the attribute mapping dictionary. :param int att_ind_start: Start index for enumerating the attributes. :param dict att_mappings: Dictionary of mappings between vertices...
[ "def", "_add_differential_expression_attributes", "(", "self", ",", "att_ind_start", ",", "att_mappings", ")", ":", "up_regulated_ind", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "up_regulated_eq", "=", "True", ")", ".", "indices", "down_regulated_i...
Add differential expression information to the attribute mapping dictionary. :param int att_ind_start: Start index for enumerating the attributes. :param dict att_mappings: Dictionary of mappings between vertices and enumerated attributes. :return: End index for attribute enumeration.
[ "Add", "differential", "expression", "information", "to", "the", "attribute", "mapping", "dictionary", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L48-L62
train
Add differential expression information to the attribute mapping dictionary.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/attribute_network.py
AttributeNetwork._add_attribute_values
def _add_attribute_values(self, value, att_mappings, indices): """Add an attribute value to the given vertices. :param int value: Attribute value. :param dict att_mappings: Dictionary of mappings between vertices and enumerated attributes. :param list indices: Indices of the vertices. ...
python
def _add_attribute_values(self, value, att_mappings, indices): """Add an attribute value to the given vertices. :param int value: Attribute value. :param dict att_mappings: Dictionary of mappings between vertices and enumerated attributes. :param list indices: Indices of the vertices. ...
[ "def", "_add_attribute_values", "(", "self", ",", "value", ",", "att_mappings", ",", "indices", ")", ":", "for", "i", "in", "indices", ":", "att_mappings", "[", "i", "]", ".", "append", "(", "value", ")" ]
Add an attribute value to the given vertices. :param int value: Attribute value. :param dict att_mappings: Dictionary of mappings between vertices and enumerated attributes. :param list indices: Indices of the vertices.
[ "Add", "an", "attribute", "value", "to", "the", "given", "vertices", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L64-L72
train
Add an attribute value to the given vertices.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/attribute_network.py
AttributeNetwork._add_disease_association_attributes
def _add_disease_association_attributes(self, att_ind_start, att_mappings): """Add disease association information to the attribute mapping dictionary. :param int att_ind_start: Start index for enumerating the attributes. :param dict att_mappings: Dictionary of mappings between vertices and enu...
python
def _add_disease_association_attributes(self, att_ind_start, att_mappings): """Add disease association information to the attribute mapping dictionary. :param int att_ind_start: Start index for enumerating the attributes. :param dict att_mappings: Dictionary of mappings between vertices and enu...
[ "def", "_add_disease_association_attributes", "(", "self", ",", "att_ind_start", ",", "att_mappings", ")", ":", "disease_mappings", "=", "self", ".", "get_disease_mappings", "(", "att_ind_start", ")", "for", "vertex", "in", "self", ".", "graph", ".", "vs", ":", ...
Add disease association information to the attribute mapping dictionary. :param int att_ind_start: Start index for enumerating the attributes. :param dict att_mappings: Dictionary of mappings between vertices and enumerated attributes.
[ "Add", "disease", "association", "information", "to", "the", "attribute", "mapping", "dictionary", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L74-L85
train
Add disease association information to the attribute mapping dictionary.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/attribute_network.py
AttributeNetwork.get_disease_mappings
def get_disease_mappings(self, att_ind_start): """Get a dictionary of enumerations for diseases. :param int att_ind_start: Starting index for enumeration. :return: Dictionary of disease, number pairs. """ all_disease_ids = self.get_all_unique_diseases() disease_enum = en...
python
def get_disease_mappings(self, att_ind_start): """Get a dictionary of enumerations for diseases. :param int att_ind_start: Starting index for enumeration. :return: Dictionary of disease, number pairs. """ all_disease_ids = self.get_all_unique_diseases() disease_enum = en...
[ "def", "get_disease_mappings", "(", "self", ",", "att_ind_start", ")", ":", "all_disease_ids", "=", "self", ".", "get_all_unique_diseases", "(", ")", "disease_enum", "=", "enumerate", "(", "all_disease_ids", ",", "start", "=", "att_ind_start", ")", "disease_mappings...
Get a dictionary of enumerations for diseases. :param int att_ind_start: Starting index for enumeration. :return: Dictionary of disease, number pairs.
[ "Get", "a", "dictionary", "of", "enumerations", "for", "diseases", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L87-L98
train
Get a dictionary of diseases and their numbers.
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/attribute_network.py
AttributeNetwork.get_all_unique_diseases
def get_all_unique_diseases(self): """Get all unique diseases that are known to the network. :return: All unique disease identifiers. """ all_disease_ids = self.graph.vs["associated_diseases"] # remove None values from list all_disease_ids = [lst for lst in all_disease_i...
python
def get_all_unique_diseases(self): """Get all unique diseases that are known to the network. :return: All unique disease identifiers. """ all_disease_ids = self.graph.vs["associated_diseases"] # remove None values from list all_disease_ids = [lst for lst in all_disease_i...
[ "def", "get_all_unique_diseases", "(", "self", ")", ":", "all_disease_ids", "=", "self", ".", "graph", ".", "vs", "[", "\"associated_diseases\"", "]", "# remove None values from list", "all_disease_ids", "=", "[", "lst", "for", "lst", "in", "all_disease_ids", "if", ...
Get all unique diseases that are known to the network. :return: All unique disease identifiers.
[ "Get", "all", "unique", "diseases", "that", "are", "known", "to", "the", "network", "." ]
4d7b6713485f2d0a0957e6457edc1b1b5a237460
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L100-L110
train
Get all unique diseases that are known to the network.
BernardFW/bernard
src/bernard/analytics/_helpers.py
page_view
def page_view(url): """ Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state """ def decorator(func): @wraps(func) async def wrapper(self: Base...
python
def page_view(url): """ Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state """ def decorator(func): @wraps(func) async def wrapper(self: Base...
[ "def", "page_view", "(", "url", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "async", "def", "wrapper", "(", "self", ":", "BaseState", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "s...
Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state
[ "Page", "view", "decorator", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/analytics/_helpers.py#L14-L42
train
Decorator for state handler functions that logs a page view each time the handler gets called.
pyQode/pyqode.cobol
pyqode/cobol/api/parsers/pic.py
parse_cobol
def parse_cobol(lines): """ Parses the COBOL - converts the COBOL line into a dictionary containing the information - parses the pic information into type, length, precision - ~~handles redefines~~ -> our implementation does not do that anymore because we want to display item that was rede...
python
def parse_cobol(lines): """ Parses the COBOL - converts the COBOL line into a dictionary containing the information - parses the pic information into type, length, precision - ~~handles redefines~~ -> our implementation does not do that anymore because we want to display item that was rede...
[ "def", "parse_cobol", "(", "lines", ")", ":", "output", "=", "[", "]", "intify", "=", "[", "\"level\"", ",", "\"occurs\"", "]", "# All in 1 line now, let's parse", "for", "row", "in", "lines", ":", "match", "=", "CobolPatterns", ".", "row_pattern", ".", "mat...
Parses the COBOL - converts the COBOL line into a dictionary containing the information - parses the pic information into type, length, precision - ~~handles redefines~~ -> our implementation does not do that anymore because we want to display item that was redefined.
[ "Parses", "the", "COBOL", "-", "converts", "the", "COBOL", "line", "into", "a", "dictionary", "containing", "the", "information", "-", "parses", "the", "pic", "information", "into", "type", "length", "precision", "-", "~~handles", "redefines~~", "-", ">", "our...
eedae4e320a4b2d0c44abb2c3061091321648fb7
https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/pic.py#L114-L143
train
Parses the COBOL line into a list of dictionaries containing the information of the item that was redefined.
pyQode/pyqode.cobol
pyqode/cobol/api/parsers/pic.py
clean_names
def clean_names(lines, ensure_unique_names=False, strip_prefix=False, make_database_safe=False): """ Clean the names. Options to: - strip prefixes on names - enforce unique names - make database safe names by converting - to _ """ names = {} for row in lines: ...
python
def clean_names(lines, ensure_unique_names=False, strip_prefix=False, make_database_safe=False): """ Clean the names. Options to: - strip prefixes on names - enforce unique names - make database safe names by converting - to _ """ names = {} for row in lines: ...
[ "def", "clean_names", "(", "lines", ",", "ensure_unique_names", "=", "False", ",", "strip_prefix", "=", "False", ",", "make_database_safe", "=", "False", ")", ":", "names", "=", "{", "}", "for", "row", "in", "lines", ":", "if", "strip_prefix", ":", "row", ...
Clean the names. Options to: - strip prefixes on names - enforce unique names - make database safe names by converting - to _
[ "Clean", "the", "names", "." ]
eedae4e320a4b2d0c44abb2c3061091321648fb7
https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/pic.py#L230-L263
train
Clean the names.
ikalnytskyi/holocron
src/holocron/__main__.py
create_app_from_yml
def create_app_from_yml(path): """Return an application instance created from YAML.""" try: with open(path, "rt", encoding="UTF-8") as f: try: # Substitute ALL occurrences of '%(here)s' with a path to a # directory with '.holocron.yml'. Please note, we also w...
python
def create_app_from_yml(path): """Return an application instance created from YAML.""" try: with open(path, "rt", encoding="UTF-8") as f: try: # Substitute ALL occurrences of '%(here)s' with a path to a # directory with '.holocron.yml'. Please note, we also w...
[ "def", "create_app_from_yml", "(", "path", ")", ":", "try", ":", "with", "open", "(", "path", ",", "\"rt\"", ",", "encoding", "=", "\"UTF-8\"", ")", "as", "f", ":", "try", ":", "# Substitute ALL occurrences of '%(here)s' with a path to a", "# directory with '.holocr...
Return an application instance created from YAML.
[ "Return", "an", "application", "instance", "created", "from", "YAML", "." ]
d202f6bccfeca64162857c6d0ee5bb53e773d2f2
https://github.com/ikalnytskyi/holocron/blob/d202f6bccfeca64162857c6d0ee5bb53e773d2f2/src/holocron/__main__.py#L18-L40
train
Return an application instance created from YAML.
ikalnytskyi/holocron
src/holocron/__main__.py
configure_logger
def configure_logger(level): """ Configure a root logger to print records in pretty format. The format is more readable for end users, since it's not necessary at all to know a record's dateime and a source of the record. Examples:: [INFO] message [WARN] message [ERRO] mes...
python
def configure_logger(level): """ Configure a root logger to print records in pretty format. The format is more readable for end users, since it's not necessary at all to know a record's dateime and a source of the record. Examples:: [INFO] message [WARN] message [ERRO] mes...
[ "def", "configure_logger", "(", "level", ")", ":", "class", "_Formatter", "(", "logging", ".", "Formatter", ")", ":", "def", "format", "(", "self", ",", "record", ")", ":", "record", ".", "levelname", "=", "record", ".", "levelname", "[", ":", "4", "]"...
Configure a root logger to print records in pretty format. The format is more readable for end users, since it's not necessary at all to know a record's dateime and a source of the record. Examples:: [INFO] message [WARN] message [ERRO] message :param level: a minimum logging...
[ "Configure", "a", "root", "logger", "to", "print", "records", "in", "pretty", "format", "." ]
d202f6bccfeca64162857c6d0ee5bb53e773d2f2
https://github.com/ikalnytskyi/holocron/blob/d202f6bccfeca64162857c6d0ee5bb53e773d2f2/src/holocron/__main__.py#L43-L73
train
Configure a root logger to print records in pretty format.
ikalnytskyi/holocron
src/holocron/__main__.py
parse_command_line
def parse_command_line(args): """ Builds a command line interface, and parses its arguments. Returns an object with attributes, that are represent CLI arguments. :param args: a list of command line arguments :returns: a parsed object with cli options """ parser = argparse.ArgumentParser( ...
python
def parse_command_line(args): """ Builds a command line interface, and parses its arguments. Returns an object with attributes, that are represent CLI arguments. :param args: a list of command line arguments :returns: a parsed object with cli options """ parser = argparse.ArgumentParser( ...
[ "def", "parse_command_line", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "\"Holocron is an easy and lightweight static blog generator, \"", "\"based on markup text and Jinja2 templates.\"", ")", ",", "epilog", "=", ...
Builds a command line interface, and parses its arguments. Returns an object with attributes, that are represent CLI arguments. :param args: a list of command line arguments :returns: a parsed object with cli options
[ "Builds", "a", "command", "line", "interface", "and", "parses", "its", "arguments", ".", "Returns", "an", "object", "with", "attributes", "that", "are", "represent", "CLI", "arguments", "." ]
d202f6bccfeca64162857c6d0ee5bb53e773d2f2
https://github.com/ikalnytskyi/holocron/blob/d202f6bccfeca64162857c6d0ee5bb53e773d2f2/src/holocron/__main__.py#L76-L127
train
Builds a command line interface and parses its arguments.
BernardFW/bernard
src/bernard/cli/_live_reload.py
_list_syntax_error
def _list_syntax_error(): """ If we're going through a syntax error, add the directory of the error to the watchlist. """ _, e, _ = sys.exc_info() if isinstance(e, SyntaxError) and hasattr(e, 'filename'): yield path.dirname(e.filename)
python
def _list_syntax_error(): """ If we're going through a syntax error, add the directory of the error to the watchlist. """ _, e, _ = sys.exc_info() if isinstance(e, SyntaxError) and hasattr(e, 'filename'): yield path.dirname(e.filename)
[ "def", "_list_syntax_error", "(", ")", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "isinstance", "(", "e", ",", "SyntaxError", ")", "and", "hasattr", "(", "e", ",", "'filename'", ")", ":", "yield", "path", ".", "dirna...
If we're going through a syntax error, add the directory of the error to the watchlist.
[ "If", "we", "re", "going", "through", "a", "syntax", "error", "add", "the", "directory", "of", "the", "error", "to", "the", "watchlist", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/cli/_live_reload.py#L51-L59
train
Yields the directory of the error file.
BernardFW/bernard
src/bernard/cli/_live_reload.py
list_dirs
def list_dirs(): """ List all directories known to hold project code. """ out = set() out.update(_list_config_dirs()) out.update(_list_module_dirs()) out.update(_list_syntax_error()) return out
python
def list_dirs(): """ List all directories known to hold project code. """ out = set() out.update(_list_config_dirs()) out.update(_list_module_dirs()) out.update(_list_syntax_error()) return out
[ "def", "list_dirs", "(", ")", ":", "out", "=", "set", "(", ")", "out", ".", "update", "(", "_list_config_dirs", "(", ")", ")", "out", ".", "update", "(", "_list_module_dirs", "(", ")", ")", "out", ".", "update", "(", "_list_syntax_error", "(", ")", "...
List all directories known to hold project code.
[ "List", "all", "directories", "known", "to", "hold", "project", "code", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/cli/_live_reload.py#L62-L71
train
List all directories known to hold project code.
BernardFW/bernard
src/bernard/cli/_live_reload.py
start_child
async def start_child(): """ Start the child process that will look for changes in modules. """ logger.info('Started to watch for code changes') loop = asyncio.get_event_loop() watcher = aionotify.Watcher() flags = ( aionotify.Flags.MODIFY | aionotify.Flags.DELETE | ...
python
async def start_child(): """ Start the child process that will look for changes in modules. """ logger.info('Started to watch for code changes') loop = asyncio.get_event_loop() watcher = aionotify.Watcher() flags = ( aionotify.Flags.MODIFY | aionotify.Flags.DELETE | ...
[ "async", "def", "start_child", "(", ")", ":", "logger", ".", "info", "(", "'Started to watch for code changes'", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "watcher", "=", "aionotify", ".", "Watcher", "(", ")", "flags", "=", "(", "aionotif...
Start the child process that will look for changes in modules.
[ "Start", "the", "child", "process", "that", "will", "look", "for", "changes", "in", "modules", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/cli/_live_reload.py#L83-L120
train
Start the child process that will watch for changes in modules.
BernardFW/bernard
src/bernard/cli/_live_reload.py
start_parent
def start_parent(): """ Start the parent that will simply run the child forever until stopped. """ while True: args = [sys.executable] + sys.argv new_environ = environ.copy() new_environ["_IN_CHILD"] = 'yes' ret = subprocess.call(args, env=new_environ) if ret !=...
python
def start_parent(): """ Start the parent that will simply run the child forever until stopped. """ while True: args = [sys.executable] + sys.argv new_environ = environ.copy() new_environ["_IN_CHILD"] = 'yes' ret = subprocess.call(args, env=new_environ) if ret !=...
[ "def", "start_parent", "(", ")", ":", "while", "True", ":", "args", "=", "[", "sys", ".", "executable", "]", "+", "sys", ".", "argv", "new_environ", "=", "environ", ".", "copy", "(", ")", "new_environ", "[", "\"_IN_CHILD\"", "]", "=", "'yes'", "ret", ...
Start the parent that will simply run the child forever until stopped.
[ "Start", "the", "parent", "that", "will", "simply", "run", "the", "child", "forever", "until", "stopped", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/cli/_live_reload.py#L123-L135
train
Start the parent that will simply run the child forever until stopped.
jpscaletti/authcode
authcode/wsgi/werkzeug.py
get_full_path
def get_full_path(request): """Return the current relative path including the query string. Eg: “/foo/bar/?page=1” """ path = request.path if request.query_string: path += '?' + to_native(request.query_string) return path
python
def get_full_path(request): """Return the current relative path including the query string. Eg: “/foo/bar/?page=1” """ path = request.path if request.query_string: path += '?' + to_native(request.query_string) return path
[ "def", "get_full_path", "(", "request", ")", ":", "path", "=", "request", ".", "path", "if", "request", ".", "query_string", ":", "path", "+=", "'?'", "+", "to_native", "(", "request", ".", "query_string", ")", "return", "path" ]
Return the current relative path including the query string. Eg: “/foo/bar/?page=1”
[ "Return", "the", "current", "relative", "path", "including", "the", "query", "string", ".", "Eg", ":", "“", "/", "foo", "/", "bar", "/", "?page", "=", "1”" ]
91529b6d0caec07d1452758d937e1e0745826139
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L10-L17
train
Return the current relative path including the query string.
jpscaletti/authcode
authcode/wsgi/werkzeug.py
get_from_params
def get_from_params(request, key): """Try to read a value named ``key`` from the GET parameters. """ data = getattr(request, 'json', None) or request.values value = data.get(key) return to_native(value)
python
def get_from_params(request, key): """Try to read a value named ``key`` from the GET parameters. """ data = getattr(request, 'json', None) or request.values value = data.get(key) return to_native(value)
[ "def", "get_from_params", "(", "request", ",", "key", ")", ":", "data", "=", "getattr", "(", "request", ",", "'json'", ",", "None", ")", "or", "request", ".", "values", "value", "=", "data", ".", "get", "(", "key", ")", "return", "to_native", "(", "v...
Try to read a value named ``key`` from the GET parameters.
[ "Try", "to", "read", "a", "value", "named", "key", "from", "the", "GET", "parameters", "." ]
91529b6d0caec07d1452758d937e1e0745826139
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L55-L60
train
Try to read a value named key from the GET parameters.
jpscaletti/authcode
authcode/wsgi/werkzeug.py
get_from_headers
def get_from_headers(request, key): """Try to read a value named ``key`` from the headers. """ value = request.headers.get(key) return to_native(value)
python
def get_from_headers(request, key): """Try to read a value named ``key`` from the headers. """ value = request.headers.get(key) return to_native(value)
[ "def", "get_from_headers", "(", "request", ",", "key", ")", ":", "value", "=", "request", ".", "headers", ".", "get", "(", "key", ")", "return", "to_native", "(", "value", ")" ]
Try to read a value named ``key`` from the headers.
[ "Try", "to", "read", "a", "value", "named", "key", "from", "the", "headers", "." ]
91529b6d0caec07d1452758d937e1e0745826139
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L63-L67
train
Try to read a value named key from the request headers.
jpscaletti/authcode
authcode/wsgi/werkzeug.py
make_response
def make_response(body, mimetype='text/html'): """Build a framework specific HTPP response, containing ``body`` and marked as the type ``mimetype``. """ from werkzeug.wrappers import Response if isinstance(body, Response): body.mimetype = mimetype return body return Response(body...
python
def make_response(body, mimetype='text/html'): """Build a framework specific HTPP response, containing ``body`` and marked as the type ``mimetype``. """ from werkzeug.wrappers import Response if isinstance(body, Response): body.mimetype = mimetype return body return Response(body...
[ "def", "make_response", "(", "body", ",", "mimetype", "=", "'text/html'", ")", ":", "from", "werkzeug", ".", "wrappers", "import", "Response", "if", "isinstance", "(", "body", ",", "Response", ")", ":", "body", ".", "mimetype", "=", "mimetype", "return", "...
Build a framework specific HTPP response, containing ``body`` and marked as the type ``mimetype``.
[ "Build", "a", "framework", "specific", "HTPP", "response", "containing", "body", "and", "marked", "as", "the", "type", "mimetype", "." ]
91529b6d0caec07d1452758d937e1e0745826139
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L76-L84
train
Build an HTPP response with the given body and mimetype.
BernardFW/bernard
src/bernard/storage/redis.py
BaseRedisStore.async_init
async def async_init(self): """ Handle here the asynchronous part of the init. """ self.pool = await aioredis.create_pool( (self.host, self.port), db=self.db_id, minsize=self.min_pool_size, maxsize=self.max_pool_size, loop=asyn...
python
async def async_init(self): """ Handle here the asynchronous part of the init. """ self.pool = await aioredis.create_pool( (self.host, self.port), db=self.db_id, minsize=self.min_pool_size, maxsize=self.max_pool_size, loop=asyn...
[ "async", "def", "async_init", "(", "self", ")", ":", "self", ".", "pool", "=", "await", "aioredis", ".", "create_pool", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ",", "db", "=", "self", ".", "db_id", ",", "minsize", "=", "self",...
Handle here the asynchronous part of the init.
[ "Handle", "here", "the", "asynchronous", "part", "of", "the", "init", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/redis.py#L41-L52
train
Handle here the asynchronous part of the init.
rsgalloway/grit
grit/util/util.py
serialize
def serialize(d): """ Attempts to serialize values from a dictionary, skipping private attrs. :param d: A dictionary of params to serialize, typically cls.__dict__ """ ret = {} for k,v in d.items(): if not k.startswith('_'): ret[k] = str(d[k]) #ret['__c...
python
def serialize(d): """ Attempts to serialize values from a dictionary, skipping private attrs. :param d: A dictionary of params to serialize, typically cls.__dict__ """ ret = {} for k,v in d.items(): if not k.startswith('_'): ret[k] = str(d[k]) #ret['__c...
[ "def", "serialize", "(", "d", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "not", "k", ".", "startswith", "(", "'_'", ")", ":", "ret", "[", "k", "]", "=", "str", "(", "d", "[", "k", ...
Attempts to serialize values from a dictionary, skipping private attrs. :param d: A dictionary of params to serialize, typically cls.__dict__
[ "Attempts", "to", "serialize", "values", "from", "a", "dictionary", "skipping", "private", "attrs", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/util/util.py#L31-L44
train
Serializes a dictionary of params to a dictionary of params skipping private attrs.
rsgalloway/grit
grit/util/util.py
user_config
def user_config(**kwargs): """ Initialize Git user config file. :param kwargs: key/value pairs are stored in the git user config file. """ for kw in kwargs: git('config --global user.%s "%s"' %(kw, kwargs.get(kw))).wait()
python
def user_config(**kwargs): """ Initialize Git user config file. :param kwargs: key/value pairs are stored in the git user config file. """ for kw in kwargs: git('config --global user.%s "%s"' %(kw, kwargs.get(kw))).wait()
[ "def", "user_config", "(", "*", "*", "kwargs", ")", ":", "for", "kw", "in", "kwargs", ":", "git", "(", "'config --global user.%s \"%s\"'", "%", "(", "kw", ",", "kwargs", ".", "get", "(", "kw", ")", ")", ")", ".", "wait", "(", ")" ]
Initialize Git user config file. :param kwargs: key/value pairs are stored in the git user config file.
[ "Initialize", "Git", "user", "config", "file", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/util/util.py#L51-L58
train
Initialize Git user config file.
blockstack-packages/jsontokens-py
jsontokens/token_signer.py
TokenSigner._make_header
def _make_header(self, token_type=None, signing_algorithm=None): """ Make a JWT header """ if not token_type: token_type = self.token_type if not signing_algorithm: signing_algorithm = self.signing_algorithm header = {'typ': token_type, 'alg': si...
python
def _make_header(self, token_type=None, signing_algorithm=None): """ Make a JWT header """ if not token_type: token_type = self.token_type if not signing_algorithm: signing_algorithm = self.signing_algorithm header = {'typ': token_type, 'alg': si...
[ "def", "_make_header", "(", "self", ",", "token_type", "=", "None", ",", "signing_algorithm", "=", "None", ")", ":", "if", "not", "token_type", ":", "token_type", "=", "self", ".", "token_type", "if", "not", "signing_algorithm", ":", "signing_algorithm", "=", ...
Make a JWT header
[ "Make", "a", "JWT", "header" ]
1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3
https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_signer.py#L38-L49
train
Make a JWT header
blockstack-packages/jsontokens-py
jsontokens/token_signer.py
TokenSigner._make_signature
def _make_signature(self, header_b64, payload_b64, signing_key): """ Sign a serialized header and payload. Return the urlsafe-base64-encoded signature. """ token_segments = [header_b64, payload_b64] signing_input = b'.'.join(token_segments) signer = self._get_sig...
python
def _make_signature(self, header_b64, payload_b64, signing_key): """ Sign a serialized header and payload. Return the urlsafe-base64-encoded signature. """ token_segments = [header_b64, payload_b64] signing_input = b'.'.join(token_segments) signer = self._get_sig...
[ "def", "_make_signature", "(", "self", ",", "header_b64", ",", "payload_b64", ",", "signing_key", ")", ":", "token_segments", "=", "[", "header_b64", ",", "payload_b64", "]", "signing_input", "=", "b'.'", ".", "join", "(", "token_segments", ")", "signer", "=",...
Sign a serialized header and payload. Return the urlsafe-base64-encoded signature.
[ "Sign", "a", "serialized", "header", "and", "payload", ".", "Return", "the", "urlsafe", "-", "base64", "-", "encoded", "signature", "." ]
1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3
https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_signer.py#L52-L65
train
Sign a serialized header and payload and return the urlsafe - base64 - encoded signature.
blockstack-packages/jsontokens-py
jsontokens/token_signer.py
TokenSigner._sign_single
def _sign_single(self, payload, signing_key): """ Make a single-signature JWT. Returns the serialized token (compact form), as a string """ if not isinstance(payload, Mapping): raise TypeError('Expecting a mapping object, as only ' 'JSON ob...
python
def _sign_single(self, payload, signing_key): """ Make a single-signature JWT. Returns the serialized token (compact form), as a string """ if not isinstance(payload, Mapping): raise TypeError('Expecting a mapping object, as only ' 'JSON ob...
[ "def", "_sign_single", "(", "self", ",", "payload", ",", "signing_key", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "Mapping", ")", ":", "raise", "TypeError", "(", "'Expecting a mapping object, as only '", "'JSON objects can be used as payloads.'", ")", ...
Make a single-signature JWT. Returns the serialized token (compact form), as a string
[ "Make", "a", "single", "-", "signature", "JWT", ".", "Returns", "the", "serialized", "token", "(", "compact", "form", ")", "as", "a", "string" ]
1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3
https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_signer.py#L68-L90
train
Make a single - signature JWT.
blockstack-packages/jsontokens-py
jsontokens/token_signer.py
TokenSigner._sign_multi
def _sign_multi(self, payload, signing_keys): """ Make a multi-signature JWT. Returns a JSON-structured JWT. TODO: support multiple types of signatures """ if not isinstance(payload, Mapping): raise TypeError('Expecting a mapping object, as only ' ...
python
def _sign_multi(self, payload, signing_keys): """ Make a multi-signature JWT. Returns a JSON-structured JWT. TODO: support multiple types of signatures """ if not isinstance(payload, Mapping): raise TypeError('Expecting a mapping object, as only ' ...
[ "def", "_sign_multi", "(", "self", ",", "payload", ",", "signing_keys", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "Mapping", ")", ":", "raise", "TypeError", "(", "'Expecting a mapping object, as only '", "'JSON objects can be used as payloads.'", ")", ...
Make a multi-signature JWT. Returns a JSON-structured JWT. TODO: support multiple types of signatures
[ "Make", "a", "multi", "-", "signature", "JWT", ".", "Returns", "a", "JSON", "-", "structured", "JWT", "." ]
1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3
https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_signer.py#L93-L127
train
Make a JSON - structured JWT with multiple signatures.
blockstack-packages/jsontokens-py
jsontokens/token_signer.py
TokenSigner.sign
def sign(self, payload, signing_key_or_keys): """ Create a JWT with one or more keys. Returns a compact-form serialized JWT if there is only one key to sign with Returns a JSON-structured serialized JWT if there are multiple keys to sign with """ if isinstance(signing_key...
python
def sign(self, payload, signing_key_or_keys): """ Create a JWT with one or more keys. Returns a compact-form serialized JWT if there is only one key to sign with Returns a JSON-structured serialized JWT if there are multiple keys to sign with """ if isinstance(signing_key...
[ "def", "sign", "(", "self", ",", "payload", ",", "signing_key_or_keys", ")", ":", "if", "isinstance", "(", "signing_key_or_keys", ",", "list", ")", ":", "return", "self", ".", "_sign_multi", "(", "payload", ",", "signing_key_or_keys", ")", "else", ":", "retu...
Create a JWT with one or more keys. Returns a compact-form serialized JWT if there is only one key to sign with Returns a JSON-structured serialized JWT if there are multiple keys to sign with
[ "Create", "a", "JWT", "with", "one", "or", "more", "keys", ".", "Returns", "a", "compact", "-", "form", "serialized", "JWT", "if", "there", "is", "only", "one", "key", "to", "sign", "with", "Returns", "a", "JSON", "-", "structured", "serialized", "JWT", ...
1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3
https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_signer.py#L130-L140
train
Create a compact - form serialized JWT with one or more keys.
pyslackers/sir-bot-a-lot
setup.py
parse_reqs
def parse_reqs(req_path='./requirements/requirements.txt'): """Recursively parse requirements from nested pip files.""" install_requires = [] with codecs.open(req_path, 'r') as handle: # remove comments and empty lines lines = (line.strip() for line in handle if line.strip()...
python
def parse_reqs(req_path='./requirements/requirements.txt'): """Recursively parse requirements from nested pip files.""" install_requires = [] with codecs.open(req_path, 'r') as handle: # remove comments and empty lines lines = (line.strip() for line in handle if line.strip()...
[ "def", "parse_reqs", "(", "req_path", "=", "'./requirements/requirements.txt'", ")", ":", "install_requires", "=", "[", "]", "with", "codecs", ".", "open", "(", "req_path", ",", "'r'", ")", "as", "handle", ":", "# remove comments and empty lines", "lines", "=", ...
Recursively parse requirements from nested pip files.
[ "Recursively", "parse", "requirements", "from", "nested", "pip", "files", "." ]
22dfdd6a14d61dbe29423fd131b7a23e618b68d7
https://github.com/pyslackers/sir-bot-a-lot/blob/22dfdd6a14d61dbe29423fd131b7a23e618b68d7/setup.py#L25-L42
train
Recursively parse requirements from nested pip files.
pyslackers/sir-bot-a-lot
setup.py
parse_readme
def parse_readme(): """Parse contents of the README.""" # Get the long description from the relevant file readme_file = str(Path(__file__).parent / 'README.rst') with codecs.open(readme_file, encoding='utf-8') as handle: long_description = handle.read() return long_description
python
def parse_readme(): """Parse contents of the README.""" # Get the long description from the relevant file readme_file = str(Path(__file__).parent / 'README.rst') with codecs.open(readme_file, encoding='utf-8') as handle: long_description = handle.read() return long_description
[ "def", "parse_readme", "(", ")", ":", "# Get the long description from the relevant file", "readme_file", "=", "str", "(", "Path", "(", "__file__", ")", ".", "parent", "/", "'README.rst'", ")", "with", "codecs", ".", "open", "(", "readme_file", ",", "encoding", ...
Parse contents of the README.
[ "Parse", "contents", "of", "the", "README", "." ]
22dfdd6a14d61dbe29423fd131b7a23e618b68d7
https://github.com/pyslackers/sir-bot-a-lot/blob/22dfdd6a14d61dbe29423fd131b7a23e618b68d7/setup.py#L45-L52
train
Parse the contents of the README file.
BernardFW/bernard
src/bernard/reporter/_raven.py
RavenReporter._make_context
def _make_context(self, request: 'Request'=None, state: Text=None): """ Build the context for a specific request/state """ if request: self.client.user_context({ 'id': request.user.id, }) self.client.extra_context({ 'me...
python
def _make_context(self, request: 'Request'=None, state: Text=None): """ Build the context for a specific request/state """ if request: self.client.user_context({ 'id': request.user.id, }) self.client.extra_context({ 'me...
[ "def", "_make_context", "(", "self", ",", "request", ":", "'Request'", "=", "None", ",", "state", ":", "Text", "=", "None", ")", ":", "if", "request", ":", "self", ".", "client", ".", "user_context", "(", "{", "'id'", ":", "request", ".", "user", "."...
Build the context for a specific request/state
[ "Build", "the", "context", "for", "a", "specific", "request", "/", "state" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/reporter/_raven.py#L40-L58
train
Build the context for a specific request and state
BernardFW/bernard
src/bernard/reporter/_raven.py
RavenReporter.report
def report(self, request: 'Request'=None, state: Text=None): """ Report current exception to Sentry. """ self._make_context(request, state) self.client.captureException() self._clear_context()
python
def report(self, request: 'Request'=None, state: Text=None): """ Report current exception to Sentry. """ self._make_context(request, state) self.client.captureException() self._clear_context()
[ "def", "report", "(", "self", ",", "request", ":", "'Request'", "=", "None", ",", "state", ":", "Text", "=", "None", ")", ":", "self", ".", "_make_context", "(", "request", ",", "state", ")", "self", ".", "client", ".", "captureException", "(", ")", ...
Report current exception to Sentry.
[ "Report", "current", "exception", "to", "Sentry", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/reporter/_raven.py#L68-L74
train
Report current exception to Sentry.
BernardFW/bernard
src/bernard/misc/start_project/_base.py
vary_name
def vary_name(name: Text): """ Validates the name and creates variations """ snake = re.match(r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$', name) if not snake: fail('The project name is not a valid snake-case Python variable name') camel = [x[0].upper() + x[1:] for x in name.split('_')] re...
python
def vary_name(name: Text): """ Validates the name and creates variations """ snake = re.match(r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$', name) if not snake: fail('The project name is not a valid snake-case Python variable name') camel = [x[0].upper() + x[1:] for x in name.split('_')] re...
[ "def", "vary_name", "(", "name", ":", "Text", ")", ":", "snake", "=", "re", ".", "match", "(", "r'^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$'", ",", "name", ")", "if", "not", "snake", ":", "fail", "(", "'The project name is not a valid snake-case Python variable name'", ")", ...
Validates the name and creates variations
[ "Validates", "the", "name", "and", "creates", "variations" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L30-L46
train
Validates the name and creates variations
BernardFW/bernard
src/bernard/misc/start_project/_base.py
make_random_key
def make_random_key() -> Text: """ Generates a secure random string """ r = SystemRandom() allowed = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+/[]' return ''.join([r.choice(allowed) for _ in range(0, 50)])
python
def make_random_key() -> Text: """ Generates a secure random string """ r = SystemRandom() allowed = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+/[]' return ''.join([r.choice(allowed) for _ in range(0, 50)])
[ "def", "make_random_key", "(", ")", "->", "Text", ":", "r", "=", "SystemRandom", "(", ")", "allowed", "=", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+/[]'", "return", "''", ".", "join", "(", "[", "r", ".", "choice", "(", "allowed", ")", "f...
Generates a secure random string
[ "Generates", "a", "secure", "random", "string" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L49-L58
train
Generates a secure random string
BernardFW/bernard
src/bernard/misc/start_project/_base.py
make_dir_path
def make_dir_path(project_dir, root, project_name): """ Generates the target path for a directory """ root = root.replace('__project_name_snake__', project_name) real_dir = path.realpath(project_dir) return path.join(real_dir, root)
python
def make_dir_path(project_dir, root, project_name): """ Generates the target path for a directory """ root = root.replace('__project_name_snake__', project_name) real_dir = path.realpath(project_dir) return path.join(real_dir, root)
[ "def", "make_dir_path", "(", "project_dir", ",", "root", ",", "project_name", ")", ":", "root", "=", "root", ".", "replace", "(", "'__project_name_snake__'", ",", "project_name", ")", "real_dir", "=", "path", ".", "realpath", "(", "project_dir", ")", "return",...
Generates the target path for a directory
[ "Generates", "the", "target", "path", "for", "a", "directory" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L61-L68
train
Generates the target path for a directory.
BernardFW/bernard
src/bernard/misc/start_project/_base.py
make_file_path
def make_file_path(project_dir, project_name, root, name): """ Generates the target path for a file """ return path.join(make_dir_path(project_dir, root, project_name), name)
python
def make_file_path(project_dir, project_name, root, name): """ Generates the target path for a file """ return path.join(make_dir_path(project_dir, root, project_name), name)
[ "def", "make_file_path", "(", "project_dir", ",", "project_name", ",", "root", ",", "name", ")", ":", "return", "path", ".", "join", "(", "make_dir_path", "(", "project_dir", ",", "root", ",", "project_name", ")", ",", "name", ")" ]
Generates the target path for a file
[ "Generates", "the", "target", "path", "for", "a", "file" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L71-L76
train
Generates the target path for a file in a node.
BernardFW/bernard
src/bernard/misc/start_project/_base.py
generate_vars
def generate_vars(project_name, project_dir): """ Generates the variables to replace in files """ out = vary_name(project_name) out['random_key'] = make_random_key() out['settings_file'] = make_file_path( project_dir, project_name, path.join('src', project_name), ...
python
def generate_vars(project_name, project_dir): """ Generates the variables to replace in files """ out = vary_name(project_name) out['random_key'] = make_random_key() out['settings_file'] = make_file_path( project_dir, project_name, path.join('src', project_name), ...
[ "def", "generate_vars", "(", "project_name", ",", "project_dir", ")", ":", "out", "=", "vary_name", "(", "project_name", ")", "out", "[", "'random_key'", "]", "=", "make_random_key", "(", ")", "out", "[", "'settings_file'", "]", "=", "make_file_path", "(", "...
Generates the variables to replace in files
[ "Generates", "the", "variables", "to", "replace", "in", "files" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L79-L93
train
Generates the variables to replace in files
BernardFW/bernard
src/bernard/misc/start_project/_base.py
get_files
def get_files(): """ Read all the template's files """ files_root = path.join(path.dirname(__file__), 'files') for root, dirs, files in walk(files_root): rel_root = path.relpath(root, files_root) for file_name in files: try: f = open(path.join(root, fil...
python
def get_files(): """ Read all the template's files """ files_root = path.join(path.dirname(__file__), 'files') for root, dirs, files in walk(files_root): rel_root = path.relpath(root, files_root) for file_name in files: try: f = open(path.join(root, fil...
[ "def", "get_files", "(", ")", ":", "files_root", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "'files'", ")", "for", "root", ",", "dirs", ",", "files", "in", "walk", "(", "files_root", ")", ":", "rel_root", "=", ...
Read all the template's files
[ "Read", "all", "the", "template", "s", "files" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L96-L114
train
Read all the template s files
BernardFW/bernard
src/bernard/misc/start_project/_base.py
check_target
def check_target(target_path): """ Checks that the target path is not empty """ if not path.exists(target_path): return with scandir(target_path) as d: for entry in d: if not entry.name.startswith('.'): fail(f'Target directory "{target_path}" is not empt...
python
def check_target(target_path): """ Checks that the target path is not empty """ if not path.exists(target_path): return with scandir(target_path) as d: for entry in d: if not entry.name.startswith('.'): fail(f'Target directory "{target_path}" is not empt...
[ "def", "check_target", "(", "target_path", ")", ":", "if", "not", "path", ".", "exists", "(", "target_path", ")", ":", "return", "with", "scandir", "(", "target_path", ")", "as", "d", ":", "for", "entry", "in", "d", ":", "if", "not", "entry", ".", "n...
Checks that the target path is not empty
[ "Checks", "that", "the", "target", "path", "is", "not", "empty" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L117-L128
train
Checks that the target path is not empty.
BernardFW/bernard
src/bernard/misc/start_project/_base.py
replace_content
def replace_content(content, project_vars): """ Replaces variables inside the content. """ for k, v in project_vars.items(): content = content.replace(f'__{k}__', v) return content
python
def replace_content(content, project_vars): """ Replaces variables inside the content. """ for k, v in project_vars.items(): content = content.replace(f'__{k}__', v) return content
[ "def", "replace_content", "(", "content", ",", "project_vars", ")", ":", "for", "k", ",", "v", "in", "project_vars", ".", "items", "(", ")", ":", "content", "=", "content", ".", "replace", "(", "f'__{k}__'", ",", "v", ")", "return", "content" ]
Replaces variables inside the content.
[ "Replaces", "variables", "inside", "the", "content", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L131-L139
train
Replaces variables inside the content.
BernardFW/bernard
src/bernard/misc/start_project/_base.py
copy_files
def copy_files(project_vars, project_dir, files): """ Copies files from the template into their target location. Unicode files get their variables replaced here and files with a shebang are set to be executable. """ for root, name, content, is_unicode in files: project_name = project_va...
python
def copy_files(project_vars, project_dir, files): """ Copies files from the template into their target location. Unicode files get their variables replaced here and files with a shebang are set to be executable. """ for root, name, content, is_unicode in files: project_name = project_va...
[ "def", "copy_files", "(", "project_vars", ",", "project_dir", ",", "files", ")", ":", "for", "root", ",", "name", ",", "content", ",", "is_unicode", "in", "files", ":", "project_name", "=", "project_vars", "[", "'project_name_snake'", "]", "if", "is_unicode", ...
Copies files from the template into their target location. Unicode files get their variables replaced here and files with a shebang are set to be executable.
[ "Copies", "files", "from", "the", "template", "into", "their", "target", "location", ".", "Unicode", "files", "get", "their", "variables", "replaced", "here", "and", "files", "with", "a", "shebang", "are", "set", "to", "be", "executable", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/start_project/_base.py#L142-L166
train
Copy files from the template into the target location.
mattlong/hermes
hermes/chatroom.py
Chatroom.connect
def connect(self): """Connect to the chatroom's server, sets up handlers, invites members as needed.""" for m in self.params['MEMBERS']: m['ONLINE'] = 0 m.setdefault('STATUS', 'INVITED') self.client = xmpp.Client(self.jid.getDomain(), debug=[]) conn = self.client...
python
def connect(self): """Connect to the chatroom's server, sets up handlers, invites members as needed.""" for m in self.params['MEMBERS']: m['ONLINE'] = 0 m.setdefault('STATUS', 'INVITED') self.client = xmpp.Client(self.jid.getDomain(), debug=[]) conn = self.client...
[ "def", "connect", "(", "self", ")", ":", "for", "m", "in", "self", ".", "params", "[", "'MEMBERS'", "]", ":", "m", "[", "'ONLINE'", "]", "=", "0", "m", ".", "setdefault", "(", "'STATUS'", ",", "'INVITED'", ")", "self", ".", "client", "=", "xmpp", ...
Connect to the chatroom's server, sets up handlers, invites members as needed.
[ "Connect", "to", "the", "chatroom", "s", "server", "sets", "up", "handlers", "invites", "members", "as", "needed", "." ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L31-L53
train
Connect to the chatroom s server sets up handlers invites members as needed.
mattlong/hermes
hermes/chatroom.py
Chatroom.get_member
def get_member(self, jid, default=None): """Get a chatroom member by JID""" member = filter(lambda m: m['JID'] == jid, self.params['MEMBERS']) if len(member) == 1: return member[0] elif len(member) == 0: return default else: raise Exception('Mu...
python
def get_member(self, jid, default=None): """Get a chatroom member by JID""" member = filter(lambda m: m['JID'] == jid, self.params['MEMBERS']) if len(member) == 1: return member[0] elif len(member) == 0: return default else: raise Exception('Mu...
[ "def", "get_member", "(", "self", ",", "jid", ",", "default", "=", "None", ")", ":", "member", "=", "filter", "(", "lambda", "m", ":", "m", "[", "'JID'", "]", "==", "jid", ",", "self", ".", "params", "[", "'MEMBERS'", "]", ")", "if", "len", "(", ...
Get a chatroom member by JID
[ "Get", "a", "chatroom", "member", "by", "JID" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L55-L63
train
Get a chatroom member by JID
mattlong/hermes
hermes/chatroom.py
Chatroom.is_member
def is_member(self, m): """Check if a user is a member of the chatroom""" if not m: return False elif isinstance(m, basestring): jid = m else: jid = m['JID'] is_member = len(filter(lambda m: m['JID'] == jid and m.get('STATUS') in ('ACTIVE', 'I...
python
def is_member(self, m): """Check if a user is a member of the chatroom""" if not m: return False elif isinstance(m, basestring): jid = m else: jid = m['JID'] is_member = len(filter(lambda m: m['JID'] == jid and m.get('STATUS') in ('ACTIVE', 'I...
[ "def", "is_member", "(", "self", ",", "m", ")", ":", "if", "not", "m", ":", "return", "False", "elif", "isinstance", "(", "m", ",", "basestring", ")", ":", "jid", "=", "m", "else", ":", "jid", "=", "m", "[", "'JID'", "]", "is_member", "=", "len",...
Check if a user is a member of the chatroom
[ "Check", "if", "a", "user", "is", "a", "member", "of", "the", "chatroom" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L65-L76
train
Check if a user is a member of the chatroom
mattlong/hermes
hermes/chatroom.py
Chatroom.invite_user
def invite_user(self, new_member, inviter=None, roster=None): """Invites a new member to the chatroom""" roster = roster or self.client.getRoster() jid = new_member['JID'] logger.info('roster %s %s' % (jid, roster.getSubscription(jid))) if jid in roster.keys() and roster.getSubs...
python
def invite_user(self, new_member, inviter=None, roster=None): """Invites a new member to the chatroom""" roster = roster or self.client.getRoster() jid = new_member['JID'] logger.info('roster %s %s' % (jid, roster.getSubscription(jid))) if jid in roster.keys() and roster.getSubs...
[ "def", "invite_user", "(", "self", ",", "new_member", ",", "inviter", "=", "None", ",", "roster", "=", "None", ")", ":", "roster", "=", "roster", "or", "self", ".", "client", ".", "getRoster", "(", ")", "jid", "=", "new_member", "[", "'JID'", "]", "l...
Invites a new member to the chatroom
[ "Invites", "a", "new", "member", "to", "the", "chatroom" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L78-L100
train
Invites a new member to the chatroom
mattlong/hermes
hermes/chatroom.py
Chatroom.kick_user
def kick_user(self, jid): """Kicks a member from the chatroom. Kicked user will receive no more messages.""" for member in filter(lambda m: m['JID'] == jid, self.params['MEMBERS']): member['STATUS'] = 'KICKED' self.send_message('You have been kicked from %s' % (self.name,), membe...
python
def kick_user(self, jid): """Kicks a member from the chatroom. Kicked user will receive no more messages.""" for member in filter(lambda m: m['JID'] == jid, self.params['MEMBERS']): member['STATUS'] = 'KICKED' self.send_message('You have been kicked from %s' % (self.name,), membe...
[ "def", "kick_user", "(", "self", ",", "jid", ")", ":", "for", "member", "in", "filter", "(", "lambda", "m", ":", "m", "[", "'JID'", "]", "==", "jid", ",", "self", ".", "params", "[", "'MEMBERS'", "]", ")", ":", "member", "[", "'STATUS'", "]", "="...
Kicks a member from the chatroom. Kicked user will receive no more messages.
[ "Kicks", "a", "member", "from", "the", "chatroom", ".", "Kicked", "user", "will", "receive", "no", "more", "messages", "." ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L102-L110
train
Kicks a member from the chatroom.
mattlong/hermes
hermes/chatroom.py
Chatroom.send_message
def send_message(self, body, to, quiet=False, html_body=None): """Send a message to a single member""" if to.get('MUTED'): to['QUEUED_MESSAGES'].append(body) else: if not quiet: logger.info('message on %s to %s: %s' % (self.name, to['JID'], body)) ...
python
def send_message(self, body, to, quiet=False, html_body=None): """Send a message to a single member""" if to.get('MUTED'): to['QUEUED_MESSAGES'].append(body) else: if not quiet: logger.info('message on %s to %s: %s' % (self.name, to['JID'], body)) ...
[ "def", "send_message", "(", "self", ",", "body", ",", "to", ",", "quiet", "=", "False", ",", "html_body", "=", "None", ")", ":", "if", "to", ".", "get", "(", "'MUTED'", ")", ":", "to", "[", "'QUEUED_MESSAGES'", "]", ".", "append", "(", "body", ")",...
Send a message to a single member
[ "Send", "a", "message", "to", "a", "single", "member" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L112-L126
train
Send a message to a single member.
mattlong/hermes
hermes/chatroom.py
Chatroom.broadcast
def broadcast(self, body, html_body=None, exclude=()): """Broadcast a message to users in the chatroom""" logger.info('broadcast on %s: %s' % (self.name, body,)) for member in filter(lambda m: m.get('STATUS') == 'ACTIVE' and m not in exclude, self.params['MEMBERS']): logger.debug(mem...
python
def broadcast(self, body, html_body=None, exclude=()): """Broadcast a message to users in the chatroom""" logger.info('broadcast on %s: %s' % (self.name, body,)) for member in filter(lambda m: m.get('STATUS') == 'ACTIVE' and m not in exclude, self.params['MEMBERS']): logger.debug(mem...
[ "def", "broadcast", "(", "self", ",", "body", ",", "html_body", "=", "None", ",", "exclude", "=", "(", ")", ")", ":", "logger", ".", "info", "(", "'broadcast on %s: %s'", "%", "(", "self", ".", "name", ",", "body", ",", ")", ")", "for", "member", "...
Broadcast a message to users in the chatroom
[ "Broadcast", "a", "message", "to", "users", "in", "the", "chatroom" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L128-L133
train
Broadcast a message to users in the chatroom
mattlong/hermes
hermes/chatroom.py
Chatroom.do_invite
def do_invite(self, sender, body, args): """Invite members to the chatroom on a user's behalf""" for invitee in args: new_member = { 'JID': invitee } self.invite_user(new_member, inviter=sender)
python
def do_invite(self, sender, body, args): """Invite members to the chatroom on a user's behalf""" for invitee in args: new_member = { 'JID': invitee } self.invite_user(new_member, inviter=sender)
[ "def", "do_invite", "(", "self", ",", "sender", ",", "body", ",", "args", ")", ":", "for", "invitee", "in", "args", ":", "new_member", "=", "{", "'JID'", ":", "invitee", "}", "self", ".", "invite_user", "(", "new_member", ",", "inviter", "=", "sender",...
Invite members to the chatroom on a user's behalf
[ "Invite", "members", "to", "the", "chatroom", "on", "a", "user", "s", "behalf" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L141-L145
train
Invite members to the chatroom on a user s behalf
mattlong/hermes
hermes/chatroom.py
Chatroom.do_kick
def do_kick(self, sender, body, args): """Kick a member from the chatroom. Must be Admin to kick users""" if sender.get('ADMIN') != True: return for user in args: self.kick_user(user)
python
def do_kick(self, sender, body, args): """Kick a member from the chatroom. Must be Admin to kick users""" if sender.get('ADMIN') != True: return for user in args: self.kick_user(user)
[ "def", "do_kick", "(", "self", ",", "sender", ",", "body", ",", "args", ")", ":", "if", "sender", ".", "get", "(", "'ADMIN'", ")", "!=", "True", ":", "return", "for", "user", "in", "args", ":", "self", ".", "kick_user", "(", "user", ")" ]
Kick a member from the chatroom. Must be Admin to kick users
[ "Kick", "a", "member", "from", "the", "chatroom", ".", "Must", "be", "Admin", "to", "kick", "users" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L147-L151
train
Kick a member from the chatroom. Must be Admin to kick users
mattlong/hermes
hermes/chatroom.py
Chatroom.do_mute
def do_mute(self, sender, body, args): """Temporarily mutes chatroom for a user""" if sender.get('MUTED'): self.send_message('you are already muted', sender) else: self.broadcast('%s has muted this chatroom' % (sender['NICK'],)) sender['QUEUED_MESSAGES'] = [] ...
python
def do_mute(self, sender, body, args): """Temporarily mutes chatroom for a user""" if sender.get('MUTED'): self.send_message('you are already muted', sender) else: self.broadcast('%s has muted this chatroom' % (sender['NICK'],)) sender['QUEUED_MESSAGES'] = [] ...
[ "def", "do_mute", "(", "self", ",", "sender", ",", "body", ",", "args", ")", ":", "if", "sender", ".", "get", "(", "'MUTED'", ")", ":", "self", ".", "send_message", "(", "'you are already muted'", ",", "sender", ")", "else", ":", "self", ".", "broadcas...
Temporarily mutes chatroom for a user
[ "Temporarily", "mutes", "chatroom", "for", "a", "user" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L153-L160
train
Temporarily mutes a chatroom for a user
mattlong/hermes
hermes/chatroom.py
Chatroom.do_unmute
def do_unmute(self, sender, body, args): """Unmutes the chatroom for a user""" if sender.get('MUTED'): sender['MUTED'] = False self.broadcast('%s has unmuted this chatroom' % (sender['NICK'],)) for msg in sender.get('QUEUED_MESSAGES', []): self.send_me...
python
def do_unmute(self, sender, body, args): """Unmutes the chatroom for a user""" if sender.get('MUTED'): sender['MUTED'] = False self.broadcast('%s has unmuted this chatroom' % (sender['NICK'],)) for msg in sender.get('QUEUED_MESSAGES', []): self.send_me...
[ "def", "do_unmute", "(", "self", ",", "sender", ",", "body", ",", "args", ")", ":", "if", "sender", ".", "get", "(", "'MUTED'", ")", ":", "sender", "[", "'MUTED'", "]", "=", "False", "self", ".", "broadcast", "(", "'%s has unmuted this chatroom'", "%", ...
Unmutes the chatroom for a user
[ "Unmutes", "the", "chatroom", "for", "a", "user" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L162-L171
train
Unmutes the chatroom for a user
mattlong/hermes
hermes/chatroom.py
Chatroom.on_presence
def on_presence(self, session, presence): """Handles presence stanzas""" from_jid = presence.getFrom() is_member = self.is_member(from_jid.getStripped()) if is_member: member = self.get_member(from_jid.getStripped()) else: member = None logger.inf...
python
def on_presence(self, session, presence): """Handles presence stanzas""" from_jid = presence.getFrom() is_member = self.is_member(from_jid.getStripped()) if is_member: member = self.get_member(from_jid.getStripped()) else: member = None logger.inf...
[ "def", "on_presence", "(", "self", ",", "session", ",", "presence", ")", ":", "from_jid", "=", "presence", ".", "getFrom", "(", ")", "is_member", "=", "self", ".", "is_member", "(", "from_jid", ".", "getStripped", "(", ")", ")", "if", "is_member", ":", ...
Handles presence stanzas
[ "Handles", "presence", "stanzas" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L179-L213
train
Handles presence stanzas
mattlong/hermes
hermes/chatroom.py
Chatroom.on_message
def on_message(self, con, event): """Handles messge stanzas""" msg_type = event.getType() nick = event.getFrom().getResource() from_jid = event.getFrom().getStripped() body = event.getBody() if msg_type == 'chat' and body is None: return logger.debug...
python
def on_message(self, con, event): """Handles messge stanzas""" msg_type = event.getType() nick = event.getFrom().getResource() from_jid = event.getFrom().getStripped() body = event.getBody() if msg_type == 'chat' and body is None: return logger.debug...
[ "def", "on_message", "(", "self", ",", "con", ",", "event", ")", ":", "msg_type", "=", "event", ".", "getType", "(", ")", "nick", "=", "event", ".", "getFrom", "(", ")", ".", "getResource", "(", ")", "from_jid", "=", "event", ".", "getFrom", "(", "...
Handles messge stanzas
[ "Handles", "messge", "stanzas" ]
63a5afcafe90ca99aeb44edeee9ed6f90baae431
https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L215-L254
train
Handles a message from the bot
cloudmesh-cmd3/cmd3
cmd3/plugins/shell_generate.py
shell_generate.do_generate
def do_generate(self, args, arguments): """ :: Usage: generate command COMMAND [--path=PATH] [--topic=TOPIC] the command will generate the package and code for a sample cmd3 module. Arguments: COMMAND the name of the command. ...
python
def do_generate(self, args, arguments): """ :: Usage: generate command COMMAND [--path=PATH] [--topic=TOPIC] the command will generate the package and code for a sample cmd3 module. Arguments: COMMAND the name of the command. ...
[ "def", "do_generate", "(", "self", ",", "args", ",", "arguments", ")", ":", "if", "arguments", "[", "\"command\"", "]", ":", "generate_command", "(", "command", "=", "arguments", "[", "\"COMMAND\"", "]", ",", "path", "=", "arguments", "[", "\"--path\"", "]...
:: Usage: generate command COMMAND [--path=PATH] [--topic=TOPIC] the command will generate the package and code for a sample cmd3 module. Arguments: COMMAND the name of the command. PATH path where to place the directory [de...
[ "::" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/shell_generate.py#L13-L79
train
This function is called by the command line tool to generate the package and code for a sample cmd3 module.
audreyr/jinja2_pluralize
jinja2_pluralize/__init__.py
pluralize_dj
def pluralize_dj(value, arg='s'): """ Adapted from django.template.defaultfilters: https://github.com/django/django/blob/master/django/template/defaultfilters.py Returns a plural suffix if the value is not 1. By default, 's' is used as the suffix: * If value is 0, vote{{ value|pluralize }} dis...
python
def pluralize_dj(value, arg='s'): """ Adapted from django.template.defaultfilters: https://github.com/django/django/blob/master/django/template/defaultfilters.py Returns a plural suffix if the value is not 1. By default, 's' is used as the suffix: * If value is 0, vote{{ value|pluralize }} dis...
[ "def", "pluralize_dj", "(", "value", ",", "arg", "=", "'s'", ")", ":", "if", "','", "not", "in", "arg", ":", "arg", "=", "','", "+", "arg", "bits", "=", "arg", ".", "split", "(", "','", ")", "if", "len", "(", "bits", ")", ">", "2", ":", "retu...
Adapted from django.template.defaultfilters: https://github.com/django/django/blob/master/django/template/defaultfilters.py Returns a plural suffix if the value is not 1. By default, 's' is used as the suffix: * If value is 0, vote{{ value|pluralize }} displays "0 votes". * If value is 1, vote{{ v...
[ "Adapted", "from", "django", ".", "template", ".", "defaultfilters", ":", "https", ":", "//", "github", ".", "com", "/", "django", "/", "django", "/", "blob", "/", "master", "/", "django", "/", "template", "/", "defaultfilters", ".", "py" ]
e94770417ff65c71461980ec26c5a1b4e4212ca5
https://github.com/audreyr/jinja2_pluralize/blob/e94770417ff65c71461980ec26c5a1b4e4212ca5/jinja2_pluralize/__init__.py#L18-L62
train
Returns a plural version of the given value.
cloudmesh-cmd3/cmd3
cmd3/plugins/activate.py
activate.activate
def activate(self): """method to activate all activation methods in the shell and its plugins. """ d = dir(self) self.plugins = [] for key in d: if key.startswith("shell_activate_"): if self.echo: Console.ok("Shell Activate:...
python
def activate(self): """method to activate all activation methods in the shell and its plugins. """ d = dir(self) self.plugins = [] for key in d: if key.startswith("shell_activate_"): if self.echo: Console.ok("Shell Activate:...
[ "def", "activate", "(", "self", ")", ":", "d", "=", "dir", "(", "self", ")", "self", ".", "plugins", "=", "[", "]", "for", "key", "in", "d", ":", "if", "key", ".", "startswith", "(", "\"shell_activate_\"", ")", ":", "if", "self", ".", "echo", ":"...
method to activate all activation methods in the shell and its plugins.
[ "method", "to", "activate", "all", "activation", "methods", "in", "the", "shell", "and", "its", "plugins", "." ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/activate.py#L20-L40
train
method to activate all activation methods in the shell and its plugins.
cloudmesh-cmd3/cmd3
cmd3/plugins/activate.py
activate.do_help
def do_help(self, arg): """List available commands with "help" or detailed help with "help cmd".""" if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc = getattr(s...
python
def do_help(self, arg): """List available commands with "help" or detailed help with "help cmd".""" if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc = getattr(s...
[ "def", "do_help", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "# XXX check arg syntax", "try", ":", "func", "=", "getattr", "(", "self", ",", "'help_'", "+", "arg", ")", "except", "AttributeError", ":", "try", ":", "doc", "=", "getattr", "(", ...
List available commands with "help" or detailed help with "help cmd".
[ "List", "available", "commands", "with", "help", "or", "detailed", "help", "with", "help", "cmd", "." ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/activate.py#L42-L92
train
List available commands with help or detailed help with help cmd
inveniosoftware-contrib/invenio-workflows
invenio_workflows/alembic/a26f133d42a9_create_invenio_workflows_tables.py
upgrade
def upgrade(): """Upgrade database.""" op.create_table( 'workflows_workflow', sa.Column( 'uuid', UUIDType, primary_key=True, nullable=False, default=uuid.uuid4() ), sa.Column( 'name', sa.String(25...
python
def upgrade(): """Upgrade database.""" op.create_table( 'workflows_workflow', sa.Column( 'uuid', UUIDType, primary_key=True, nullable=False, default=uuid.uuid4() ), sa.Column( 'name', sa.String(25...
[ "def", "upgrade", "(", ")", ":", "op", ".", "create_table", "(", "'workflows_workflow'", ",", "sa", ".", "Column", "(", "'uuid'", ",", "UUIDType", ",", "primary_key", "=", "True", ",", "nullable", "=", "False", ",", "default", "=", "uuid", ".", "uuid4", ...
Upgrade database.
[ "Upgrade", "database", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/alembic/a26f133d42a9_create_invenio_workflows_tables.py#L46-L167
train
Upgrade database.
b10m/ziggo_mediabox_xl
ziggo_mediabox_xl.py
ZiggoMediaboxXL._fetch_channels
def _fetch_channels(self): """Retrieve Ziggo channel information.""" json = requests.get(self._channels_url).json() self._channels = {c['channel']['code']: c['channel']['name'] for c in json['channels']}
python
def _fetch_channels(self): """Retrieve Ziggo channel information.""" json = requests.get(self._channels_url).json() self._channels = {c['channel']['code']: c['channel']['name'] for c in json['channels']}
[ "def", "_fetch_channels", "(", "self", ")", ":", "json", "=", "requests", ".", "get", "(", "self", ".", "_channels_url", ")", ".", "json", "(", ")", "self", ".", "_channels", "=", "{", "c", "[", "'channel'", "]", "[", "'code'", "]", ":", "c", "[", ...
Retrieve Ziggo channel information.
[ "Retrieve", "Ziggo", "channel", "information", "." ]
49520ec3e2e3d09339cea667723914b10399249d
https://github.com/b10m/ziggo_mediabox_xl/blob/49520ec3e2e3d09339cea667723914b10399249d/ziggo_mediabox_xl.py#L33-L37
train
Retrieve Ziggo channel information.
b10m/ziggo_mediabox_xl
ziggo_mediabox_xl.py
ZiggoMediaboxXL.update_state
def update_state(self): """Find out whether the media box is turned on/off.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) try: if sock.connect_ex((self._ip, self._port['state'])) == 0: self.state = True ...
python
def update_state(self): """Find out whether the media box is turned on/off.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) try: if sock.connect_ex((self._ip, self._port['state'])) == 0: self.state = True ...
[ "def", "update_state", "(", "self", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "settimeout", "(", "self", ".", "_timeout", ")", "try", ":", "if", "sock", ".", "c...
Find out whether the media box is turned on/off.
[ "Find", "out", "whether", "the", "media", "box", "is", "turned", "on", "/", "off", "." ]
49520ec3e2e3d09339cea667723914b10399249d
https://github.com/b10m/ziggo_mediabox_xl/blob/49520ec3e2e3d09339cea667723914b10399249d/ziggo_mediabox_xl.py#L59-L70
train
Find out whether the media box is turned on or off.
b10m/ziggo_mediabox_xl
ziggo_mediabox_xl.py
ZiggoMediaboxXL.send_keys
def send_keys(self, keys): """Send keys to the device.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) sock.connect((self._ip, self._port['cmd'])) # mandatory dance version_info = sock.recv(15) ...
python
def send_keys(self, keys): """Send keys to the device.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) sock.connect((self._ip, self._port['cmd'])) # mandatory dance version_info = sock.recv(15) ...
[ "def", "send_keys", "(", "self", ",", "keys", ")", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "settimeout", "(", "self", ".", "_timeout", ")", "sock", "."...
Send keys to the device.
[ "Send", "keys", "to", "the", "device", "." ]
49520ec3e2e3d09339cea667723914b10399249d
https://github.com/b10m/ziggo_mediabox_xl/blob/49520ec3e2e3d09339cea667723914b10399249d/ziggo_mediabox_xl.py#L72-L94
train
Send keys to the device.
mbourqui/django-echoices
echoices/fields/fields.py
make_echoicefield
def make_echoicefield(echoices, *args, klass_name=None, **kwargs): """ Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values. Parameters ---------- echoices : subclass of EChoice args Passed to the derived `models.Field` klass_name : str ...
python
def make_echoicefield(echoices, *args, klass_name=None, **kwargs): """ Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values. Parameters ---------- echoices : subclass of EChoice args Passed to the derived `models.Field` klass_name : str ...
[ "def", "make_echoicefield", "(", "echoices", ",", "*", "args", ",", "klass_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "issubclass", "(", "echoices", ",", "EChoice", ")", "value_type", "=", "echoices", ".", "__getvaluetype__", "(", ")"...
Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values. Parameters ---------- echoices : subclass of EChoice args Passed to the derived `models.Field` klass_name : str Give a specific name to the returned class. By default for Django < ...
[ "Construct", "a", "subclass", "of", "a", "derived", "models", ".", "Field", "specific", "to", "the", "type", "of", "the", "EChoice", "values", "." ]
c57405005ec368ac602bb38a71091a1e03c723bb
https://github.com/mbourqui/django-echoices/blob/c57405005ec368ac602bb38a71091a1e03c723bb/echoices/fields/fields.py#L120-L163
train
Returns a new derived field that is a subclass of the specified EChoice class.
mbourqui/django-echoices
echoices/fields/fields.py
EChoiceField.validate
def validate(self, value, model_instance): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ return super(self.__class__, self).validate(value.value, model_instance)
python
def validate(self, value, model_instance): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ return super(self.__class__, self).validate(value.value, model_instance)
[ "def", "validate", "(", "self", ",", "value", ",", "model_instance", ")", ":", "return", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "validate", "(", "value", ".", "value", ",", "model_instance", ")" ]
Validates value and throws ValidationError. Subclasses should override this to provide validation logic.
[ "Validates", "value", "and", "throws", "ValidationError", ".", "Subclasses", "should", "override", "this", "to", "provide", "validation", "logic", "." ]
c57405005ec368ac602bb38a71091a1e03c723bb
https://github.com/mbourqui/django-echoices/blob/c57405005ec368ac602bb38a71091a1e03c723bb/echoices/fields/fields.py#L100-L105
train
Validates value and throws ValidationError.
blockstack-packages/jsontokens-py
jsontokens/key_loading.py
load_signing_key
def load_signing_key(signing_key, crypto_backend=default_backend()): """ Optional: crypto backend object from the "cryptography" python library """ if isinstance(signing_key, EllipticCurvePrivateKey): return signing_key elif isinstance(signing_key, (str, unicode)): invalid_strings = [b'...
python
def load_signing_key(signing_key, crypto_backend=default_backend()): """ Optional: crypto backend object from the "cryptography" python library """ if isinstance(signing_key, EllipticCurvePrivateKey): return signing_key elif isinstance(signing_key, (str, unicode)): invalid_strings = [b'...
[ "def", "load_signing_key", "(", "signing_key", ",", "crypto_backend", "=", "default_backend", "(", ")", ")", ":", "if", "isinstance", "(", "signing_key", ",", "EllipticCurvePrivateKey", ")", ":", "return", "signing_key", "elif", "isinstance", "(", "signing_key", "...
Optional: crypto backend object from the "cryptography" python library
[ "Optional", ":", "crypto", "backend", "object", "from", "the", "cryptography", "python", "library" ]
1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3
https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/key_loading.py#L41-L82
train
Load a private key from the cryptography library.
blockstack-packages/jsontokens-py
jsontokens/key_loading.py
load_verifying_key
def load_verifying_key(verifying_key, crypto_backend=default_backend()): """ Optional: crypto backend object from the "cryptography" python library """ if isinstance(verifying_key, EllipticCurvePublicKey): return verifying_key elif isinstance(verifying_key, (str, unicode)): if is_hex(ve...
python
def load_verifying_key(verifying_key, crypto_backend=default_backend()): """ Optional: crypto backend object from the "cryptography" python library """ if isinstance(verifying_key, EllipticCurvePublicKey): return verifying_key elif isinstance(verifying_key, (str, unicode)): if is_hex(ve...
[ "def", "load_verifying_key", "(", "verifying_key", ",", "crypto_backend", "=", "default_backend", "(", ")", ")", ":", "if", "isinstance", "(", "verifying_key", ",", "EllipticCurvePublicKey", ")", ":", "return", "verifying_key", "elif", "isinstance", "(", "verifying_...
Optional: crypto backend object from the "cryptography" python library
[ "Optional", ":", "crypto", "backend", "object", "from", "the", "cryptography", "python", "library" ]
1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3
https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/key_loading.py#L85-L117
train
Load a verifying key from the cryptography library.
jstitch/MambuPy
MambuPy/orm/schema_dummies.py
make_dummy
def make_dummy(instance, relations = {}, datetime_default = dt.strptime('1901-01-01','%Y-%m-%d'), varchar_default = "", integer_default = 0, numeric_default = 0.0, *args, **kwargs ): """Make an instance...
python
def make_dummy(instance, relations = {}, datetime_default = dt.strptime('1901-01-01','%Y-%m-%d'), varchar_default = "", integer_default = 0, numeric_default = 0.0, *args, **kwargs ): """Make an instance...
[ "def", "make_dummy", "(", "instance", ",", "relations", "=", "{", "}", ",", "datetime_default", "=", "dt", ".", "strptime", "(", "'1901-01-01'", ",", "'%Y-%m-%d'", ")", ",", "varchar_default", "=", "\"\"", ",", "integer_default", "=", "0", ",", "numeric_defa...
Make an instance to look like an empty dummy. Every field of the table is set with zeroes/empty strings. Date fields are set to 01/01/1901. * relations is a dictionary to set properties for relationships on the instance. The keys of the relations dictionary are the name of the fields to be ...
[ "Make", "an", "instance", "to", "look", "like", "an", "empty", "dummy", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/orm/schema_dummies.py#L14-L99
train
Make an empty dummy object for the given instance.