repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
SetBased/py-stratum | pystratum/wrapper/Wrapper.py | Wrapper._write_separator | def _write_separator(self):
"""
Inserts a horizontal (commented) line tot the generated code.
"""
tmp = self._page_width - ((4 * self.__indent_level) + 2)
self._write_line('# ' + ('-' * tmp)) | python | def _write_separator(self):
"""
Inserts a horizontal (commented) line tot the generated code.
"""
tmp = self._page_width - ((4 * self.__indent_level) + 2)
self._write_line('# ' + ('-' * tmp)) | [
"def",
"_write_separator",
"(",
"self",
")",
":",
"tmp",
"=",
"self",
".",
"_page_width",
"-",
"(",
"(",
"4",
"*",
"self",
".",
"__indent_level",
")",
"+",
"2",
")",
"self",
".",
"_write_line",
"(",
"'# '",
"+",
"(",
"'-'",
"*",
"tmp",
")",
")"
] | Inserts a horizontal (commented) line tot the generated code. | [
"Inserts",
"a",
"horizontal",
"(",
"commented",
")",
"line",
"tot",
"the",
"generated",
"code",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/wrapper/Wrapper.py#L94-L99 |
SetBased/py-stratum | pystratum/wrapper/Wrapper.py | Wrapper.write_routine_method | def write_routine_method(self, routine):
"""
Returns a complete wrapper method.
:param dict[str,*] routine: The routine metadata.
:rtype: str
"""
if self._lob_as_string_flag:
return self._write_routine_method_without_lob(routine)
else:
if... | python | def write_routine_method(self, routine):
"""
Returns a complete wrapper method.
:param dict[str,*] routine: The routine metadata.
:rtype: str
"""
if self._lob_as_string_flag:
return self._write_routine_method_without_lob(routine)
else:
if... | [
"def",
"write_routine_method",
"(",
"self",
",",
"routine",
")",
":",
"if",
"self",
".",
"_lob_as_string_flag",
":",
"return",
"self",
".",
"_write_routine_method_without_lob",
"(",
"routine",
")",
"else",
":",
"if",
"self",
".",
"is_lob_parameter",
"(",
"routin... | Returns a complete wrapper method.
:param dict[str,*] routine: The routine metadata.
:rtype: str | [
"Returns",
"a",
"complete",
"wrapper",
"method",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/wrapper/Wrapper.py#L113-L127 |
SetBased/py-stratum | pystratum/wrapper/Wrapper.py | Wrapper._write_docstring_parameters | def _write_docstring_parameters(self, routine):
"""
Writes the parameters part of the docstring for the wrapper method of a stored routine.
:param dict routine: The metadata of the stored routine.
"""
if routine['pydoc']['parameters']:
self._write_line('')
... | python | def _write_docstring_parameters(self, routine):
"""
Writes the parameters part of the docstring for the wrapper method of a stored routine.
:param dict routine: The metadata of the stored routine.
"""
if routine['pydoc']['parameters']:
self._write_line('')
... | [
"def",
"_write_docstring_parameters",
"(",
"self",
",",
"routine",
")",
":",
"if",
"routine",
"[",
"'pydoc'",
"]",
"[",
"'parameters'",
"]",
":",
"self",
".",
"_write_line",
"(",
"''",
")",
"for",
"param",
"in",
"routine",
"[",
"'pydoc'",
"]",
"[",
"'par... | Writes the parameters part of the docstring for the wrapper method of a stored routine.
:param dict routine: The metadata of the stored routine. | [
"Writes",
"the",
"parameters",
"part",
"of",
"the",
"docstring",
"for",
"the",
"wrapper",
"method",
"of",
"a",
"stored",
"routine",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/wrapper/Wrapper.py#L140-L161 |
SetBased/py-stratum | pystratum/wrapper/Wrapper.py | Wrapper.__write_docstring_return_type | def __write_docstring_return_type(self):
"""
Writes the return type part of the docstring for the wrapper method of a stored routine.
"""
rtype = self._get_docstring_return_type()
if rtype:
self._write_line('')
self._write_line(':rtype: {0}'.format(rtype)) | python | def __write_docstring_return_type(self):
"""
Writes the return type part of the docstring for the wrapper method of a stored routine.
"""
rtype = self._get_docstring_return_type()
if rtype:
self._write_line('')
self._write_line(':rtype: {0}'.format(rtype)) | [
"def",
"__write_docstring_return_type",
"(",
"self",
")",
":",
"rtype",
"=",
"self",
".",
"_get_docstring_return_type",
"(",
")",
"if",
"rtype",
":",
"self",
".",
"_write_line",
"(",
"''",
")",
"self",
".",
"_write_line",
"(",
"':rtype: {0}'",
".",
"format",
... | Writes the return type part of the docstring for the wrapper method of a stored routine. | [
"Writes",
"the",
"return",
"type",
"part",
"of",
"the",
"docstring",
"for",
"the",
"wrapper",
"method",
"of",
"a",
"stored",
"routine",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/wrapper/Wrapper.py#L164-L171 |
SetBased/py-stratum | pystratum/wrapper/Wrapper.py | Wrapper.__write_docstring | def __write_docstring(self, routine):
"""
Writes the docstring for the wrapper method of a stored routine.
:param dict routine: The metadata of the stored routine.
"""
self._write_line('"""')
self.__write_docstring_description(routine)
self._write_docstring_para... | python | def __write_docstring(self, routine):
"""
Writes the docstring for the wrapper method of a stored routine.
:param dict routine: The metadata of the stored routine.
"""
self._write_line('"""')
self.__write_docstring_description(routine)
self._write_docstring_para... | [
"def",
"__write_docstring",
"(",
"self",
",",
"routine",
")",
":",
"self",
".",
"_write_line",
"(",
"'\"\"\"'",
")",
"self",
".",
"__write_docstring_description",
"(",
"routine",
")",
"self",
".",
"_write_docstring_parameters",
"(",
"routine",
")",
"self",
".",
... | Writes the docstring for the wrapper method of a stored routine.
:param dict routine: The metadata of the stored routine. | [
"Writes",
"the",
"docstring",
"for",
"the",
"wrapper",
"method",
"of",
"a",
"stored",
"routine",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/wrapper/Wrapper.py#L174-L186 |
SetBased/py-stratum | pystratum/wrapper/Wrapper.py | Wrapper._get_wrapper_args | def _get_wrapper_args(routine):
"""
Returns code for the parameters of the wrapper method for the stored routine.
:param dict[str,*] routine: The routine metadata.
:rtype: str
"""
ret = ''
for parameter_info in routine['parameters']:
if ret:
... | python | def _get_wrapper_args(routine):
"""
Returns code for the parameters of the wrapper method for the stored routine.
:param dict[str,*] routine: The routine metadata.
:rtype: str
"""
ret = ''
for parameter_info in routine['parameters']:
if ret:
... | [
"def",
"_get_wrapper_args",
"(",
"routine",
")",
":",
"ret",
"=",
"''",
"for",
"parameter_info",
"in",
"routine",
"[",
"'parameters'",
"]",
":",
"if",
"ret",
":",
"ret",
"+=",
"', '",
"ret",
"+=",
"parameter_info",
"[",
"'name'",
"]",
"return",
"ret"
] | Returns code for the parameters of the wrapper method for the stored routine.
:param dict[str,*] routine: The routine metadata.
:rtype: str | [
"Returns",
"code",
"for",
"the",
"parameters",
"of",
"the",
"wrapper",
"method",
"for",
"the",
"stored",
"routine",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/wrapper/Wrapper.py#L224-L240 |
launchdarkly/relayCommander | relay_commander/generators.py | ConfigGenerator.generate_relay_config | def generate_relay_config(self, environments: list) -> None:
"""Generate ld-relay.conf file.
Given a list of environments of a project, this will generate a
``ld-relay.conf`` file in the current working directory. The conf file
follows the specification that is documented in the main `l... | python | def generate_relay_config(self, environments: list) -> None:
"""Generate ld-relay.conf file.
Given a list of environments of a project, this will generate a
``ld-relay.conf`` file in the current working directory. The conf file
follows the specification that is documented in the main `l... | [
"def",
"generate_relay_config",
"(",
"self",
",",
"environments",
":",
"list",
")",
"->",
"None",
":",
"template",
"=",
"self",
".",
"env",
".",
"get_template",
"(",
"'ld-relay.conf.jinja'",
")",
"with",
"open",
"(",
"'ld-relay.conf'",
",",
"'w'",
")",
"as",... | Generate ld-relay.conf file.
Given a list of environments of a project, this will generate a
``ld-relay.conf`` file in the current working directory. The conf file
follows the specification that is documented in the main `ld-relay`_
documentation.
.. _ld-relay: https://github.c... | [
"Generate",
"ld",
"-",
"relay",
".",
"conf",
"file",
"."
] | train | https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/generators.py#L20-L38 |
SetBased/py-stratum | pystratum/ConstantClass.py | ConstantClass.__load | def __load(self):
"""
Loads dynamically the class that acts like a namespace for constants.
"""
parts = self.__class_name.split('.')
module_name = ".".join(parts[:-1])
module = __import__(module_name)
modules = []
for comp in parts[1:]:
module ... | python | def __load(self):
"""
Loads dynamically the class that acts like a namespace for constants.
"""
parts = self.__class_name.split('.')
module_name = ".".join(parts[:-1])
module = __import__(module_name)
modules = []
for comp in parts[1:]:
module ... | [
"def",
"__load",
"(",
"self",
")",
":",
"parts",
"=",
"self",
".",
"__class_name",
".",
"split",
"(",
"'.'",
")",
"module_name",
"=",
"\".\"",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"module",
"=",
"__import__",
"(",
"module_name",
... | Loads dynamically the class that acts like a namespace for constants. | [
"Loads",
"dynamically",
"the",
"class",
"that",
"acts",
"like",
"a",
"namespace",
"for",
"constants",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/ConstantClass.py#L53-L65 |
SetBased/py-stratum | pystratum/ConstantClass.py | ConstantClass.constants | def constants(self):
"""
Gets the constants from the class that acts like a namespace for constants.
:rtype: dict<str,*>
"""
ret = {}
name = self.__class_name.split('.')[-1]
constant_class = getattr(self.__module, name)
for name, value in constant_class.... | python | def constants(self):
"""
Gets the constants from the class that acts like a namespace for constants.
:rtype: dict<str,*>
"""
ret = {}
name = self.__class_name.split('.')[-1]
constant_class = getattr(self.__module, name)
for name, value in constant_class.... | [
"def",
"constants",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"name",
"=",
"self",
".",
"__class_name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"constant_class",
"=",
"getattr",
"(",
"self",
".",
"__module",
",",
"name",
")",
"for",
... | Gets the constants from the class that acts like a namespace for constants.
:rtype: dict<str,*> | [
"Gets",
"the",
"constants",
"from",
"the",
"class",
"that",
"acts",
"like",
"a",
"namespace",
"for",
"constants",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/ConstantClass.py#L93-L107 |
SetBased/py-stratum | pystratum/ConstantClass.py | ConstantClass.__extract_info | def __extract_info(self, lines):
"""
Extracts the following info from the source of the module with the class that acts like a namespace for
constants:
* Start line with constants
* Last line with constants
* Indent for constants
:param list[str] lines: The sourc... | python | def __extract_info(self, lines):
"""
Extracts the following info from the source of the module with the class that acts like a namespace for
constants:
* Start line with constants
* Last line with constants
* Indent for constants
:param list[str] lines: The sourc... | [
"def",
"__extract_info",
"(",
"self",
",",
"lines",
")",
":",
"ret",
"=",
"{",
"'start_line'",
":",
"0",
",",
"'last_line'",
":",
"0",
",",
"'indent'",
":",
"''",
"}",
"mode",
"=",
"1",
"count",
"=",
"0",
"for",
"line",
"in",
"lines",
":",
"if",
... | Extracts the following info from the source of the module with the class that acts like a namespace for
constants:
* Start line with constants
* Last line with constants
* Indent for constants
:param list[str] lines: The source of the module with the class that acts like a names... | [
"Extracts",
"the",
"following",
"info",
"from",
"the",
"source",
"of",
"the",
"module",
"with",
"the",
"class",
"that",
"acts",
"like",
"a",
"namespace",
"for",
"constants",
":",
"*",
"Start",
"line",
"with",
"constants",
"*",
"Last",
"line",
"with",
"cons... | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/ConstantClass.py#L110-L151 |
SetBased/py-stratum | pystratum/ConstantClass.py | ConstantClass.source_with_constants | def source_with_constants(self, constants):
"""
Returns the source of the module with the class that acts like a namespace for constants with new constants.
:param dict[str,int] constants: The new constants.
:rtype: str
"""
old_lines = self.source().split("\n")
... | python | def source_with_constants(self, constants):
"""
Returns the source of the module with the class that acts like a namespace for constants with new constants.
:param dict[str,int] constants: The new constants.
:rtype: str
"""
old_lines = self.source().split("\n")
... | [
"def",
"source_with_constants",
"(",
"self",
",",
"constants",
")",
":",
"old_lines",
"=",
"self",
".",
"source",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"info",
"=",
"self",
".",
"__extract_info",
"(",
"old_lines",
")",
"new_lines",
"=",
"old_lines",... | Returns the source of the module with the class that acts like a namespace for constants with new constants.
:param dict[str,int] constants: The new constants.
:rtype: str | [
"Returns",
"the",
"source",
"of",
"the",
"module",
"with",
"the",
"class",
"that",
"acts",
"like",
"a",
"namespace",
"for",
"constants",
"with",
"new",
"constants",
"."
] | train | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/ConstantClass.py#L154-L172 |
vsoch/helpme | helpme/main/base/settings.py | get_configfile_user | def get_configfile_user():
'''return the full path for the user configuration file. If doesn't
exist, create it for the user.
'''
from helpme.defaults import HELPME_CLIENT_SECRETS
# The inital file has a funny username
if not os.path.exists(HELPME_CLIENT_SECRETS):
bot.debug('Generat... | python | def get_configfile_user():
'''return the full path for the user configuration file. If doesn't
exist, create it for the user.
'''
from helpme.defaults import HELPME_CLIENT_SECRETS
# The inital file has a funny username
if not os.path.exists(HELPME_CLIENT_SECRETS):
bot.debug('Generat... | [
"def",
"get_configfile_user",
"(",
")",
":",
"from",
"helpme",
".",
"defaults",
"import",
"HELPME_CLIENT_SECRETS",
"# The inital file has a funny username",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"HELPME_CLIENT_SECRETS",
")",
":",
"bot",
".",
"debug",
... | return the full path for the user configuration file. If doesn't
exist, create it for the user. | [
"return",
"the",
"full",
"path",
"for",
"the",
"user",
"configuration",
"file",
".",
"If",
"doesn",
"t",
"exist",
"create",
"it",
"for",
"the",
"user",
"."
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L42-L66 |
vsoch/helpme | helpme/main/base/settings.py | _remove_setting | def _remove_setting(section, name, configfile, save=False):
'''remove a setting from the global config
'''
removed = False
config = _load_config(configfile)
if section in config:
if name.lower() in config[section]:
removed = config.remove_option(section, name)
# Does the use... | python | def _remove_setting(section, name, configfile, save=False):
'''remove a setting from the global config
'''
removed = False
config = _load_config(configfile)
if section in config:
if name.lower() in config[section]:
removed = config.remove_option(section, name)
# Does the use... | [
"def",
"_remove_setting",
"(",
"section",
",",
"name",
",",
"configfile",
",",
"save",
"=",
"False",
")",
":",
"removed",
"=",
"False",
"config",
"=",
"_load_config",
"(",
"configfile",
")",
"if",
"section",
"in",
"config",
":",
"if",
"name",
".",
"lower... | remove a setting from the global config | [
"remove",
"a",
"setting",
"from",
"the",
"global",
"config"
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L85-L98 |
vsoch/helpme | helpme/main/base/settings.py | remove_setting | def remove_setting(self, section, name, save=False):
'''remove a setting from the global config
'''
configfile = get_configfile()
return _remove_setting(section, name, configfile, save) | python | def remove_setting(self, section, name, save=False):
'''remove a setting from the global config
'''
configfile = get_configfile()
return _remove_setting(section, name, configfile, save) | [
"def",
"remove_setting",
"(",
"self",
",",
"section",
",",
"name",
",",
"save",
"=",
"False",
")",
":",
"configfile",
"=",
"get_configfile",
"(",
")",
"return",
"_remove_setting",
"(",
"section",
",",
"name",
",",
"configfile",
",",
"save",
")"
] | remove a setting from the global config | [
"remove",
"a",
"setting",
"from",
"the",
"global",
"config"
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L100-L104 |
vsoch/helpme | helpme/main/base/settings.py | remove_user_setting | def remove_user_setting(self, section, name, save=False):
'''remove a setting from the user config
'''
configfile = get_configfile_user()
return _remove_setting(section, name, configfile, save) | python | def remove_user_setting(self, section, name, save=False):
'''remove a setting from the user config
'''
configfile = get_configfile_user()
return _remove_setting(section, name, configfile, save) | [
"def",
"remove_user_setting",
"(",
"self",
",",
"section",
",",
"name",
",",
"save",
"=",
"False",
")",
":",
"configfile",
"=",
"get_configfile_user",
"(",
")",
"return",
"_remove_setting",
"(",
"section",
",",
"name",
",",
"configfile",
",",
"save",
")"
] | remove a setting from the user config | [
"remove",
"a",
"setting",
"from",
"the",
"user",
"config"
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L107-L111 |
vsoch/helpme | helpme/main/base/settings.py | _load_config | def _load_config(configfile, section=None):
'''general function to load and return a configuration given a helper
name. This function is used for both the user config and global help me
config files.
'''
if os.path.exists(configfile):
config = read_config(configfile)
if section... | python | def _load_config(configfile, section=None):
'''general function to load and return a configuration given a helper
name. This function is used for both the user config and global help me
config files.
'''
if os.path.exists(configfile):
config = read_config(configfile)
if section... | [
"def",
"_load_config",
"(",
"configfile",
",",
"section",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"configfile",
")",
":",
"config",
"=",
"read_config",
"(",
"configfile",
")",
"if",
"section",
"is",
"not",
"None",
":",
"if",... | general function to load and return a configuration given a helper
name. This function is used for both the user config and global help me
config files. | [
"general",
"function",
"to",
"load",
"and",
"return",
"a",
"configuration",
"given",
"a",
"helper",
"name",
".",
"This",
"function",
"is",
"used",
"for",
"both",
"the",
"user",
"config",
"and",
"global",
"help",
"me",
"config",
"files",
"."
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L114-L126 |
vsoch/helpme | helpme/main/base/settings.py | load_envars | def load_envars(self, items):
'''load a tuple of environment variables, to add to the user settings
Example:
items = [('HELPME_DISCOURSE_BOARD', 'user_prompt_board'),
('HELPME_DISCOURSE_CATEGORY', 'user_prompt_category')]
# Note that it's added to the client with an ... | python | def load_envars(self, items):
'''load a tuple of environment variables, to add to the user settings
Example:
items = [('HELPME_DISCOURSE_BOARD', 'user_prompt_board'),
('HELPME_DISCOURSE_CATEGORY', 'user_prompt_category')]
# Note that it's added to the client with an ... | [
"def",
"load_envars",
"(",
"self",
",",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"envar",
"=",
"item",
"[",
"0",
"]",
"key",
"=",
"item",
"[",
"1",
"]",
"value",
"=",
"self",
".",
"_get_and_update_setting",
"(",
"envar",
")",
"if",
"va... | load a tuple of environment variables, to add to the user settings
Example:
items = [('HELPME_DISCOURSE_BOARD', 'user_prompt_board'),
('HELPME_DISCOURSE_CATEGORY', 'user_prompt_category')]
# Note that it's added to the client with an underscore:
self._load_envars... | [
"load",
"a",
"tuple",
"of",
"environment",
"variables",
"to",
"add",
"to",
"the",
"user",
"settings",
"Example",
":",
"items",
"=",
"[",
"(",
"HELPME_DISCOURSE_BOARD",
"user_prompt_board",
")",
"(",
"HELPME_DISCOURSE_CATEGORY",
"user_prompt_category",
")",
"]"
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L132-L150 |
vsoch/helpme | helpme/main/base/settings.py | get_setting | def get_setting(self, name, section=None, default=None, user=True):
'''return a setting from the environment (first priority) and then
secrets (second priority) if one can be found. If not, return None.
Parameters
==========
section: the section in the config, defaults to self.name
... | python | def get_setting(self, name, section=None, default=None, user=True):
'''return a setting from the environment (first priority) and then
secrets (second priority) if one can be found. If not, return None.
Parameters
==========
section: the section in the config, defaults to self.name
... | [
"def",
"get_setting",
"(",
"self",
",",
"name",
",",
"section",
"=",
"None",
",",
"default",
"=",
"None",
",",
"user",
"=",
"True",
")",
":",
"loader",
"=",
"self",
".",
"_load_config_user",
"if",
"not",
"user",
":",
"loader",
"=",
"self",
".",
"_loa... | return a setting from the environment (first priority) and then
secrets (second priority) if one can be found. If not, return None.
Parameters
==========
section: the section in the config, defaults to self.name
name: they key (index) of the setting to look up
default: (option... | [
"return",
"a",
"setting",
"from",
"the",
"environment",
"(",
"first",
"priority",
")",
"and",
"then",
"secrets",
"(",
"second",
"priority",
")",
"if",
"one",
"can",
"be",
"found",
".",
"If",
"not",
"return",
"None",
"."
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L155-L193 |
vsoch/helpme | helpme/main/base/settings.py | get_settings | def get_settings(self):
'''get all settings for a client, if defined in config.
'''
config = self._load_config_user()
if self.name in config:
return config[self.name] | python | def get_settings(self):
'''get all settings for a client, if defined in config.
'''
config = self._load_config_user()
if self.name in config:
return config[self.name] | [
"def",
"get_settings",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_load_config_user",
"(",
")",
"if",
"self",
".",
"name",
"in",
"config",
":",
"return",
"config",
"[",
"self",
".",
"name",
"]"
] | get all settings for a client, if defined in config. | [
"get",
"all",
"settings",
"for",
"a",
"client",
"if",
"defined",
"in",
"config",
"."
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L197-L202 |
vsoch/helpme | helpme/main/base/settings.py | update_settings | def update_settings(self, updates, config=None):
'''update client secrets will update the data structure for a particular
authentication. This should only be used for a (quasi permanent) token
or similar. The secrets file, if found, is updated and saved by default.
Parameters
==========... | python | def update_settings(self, updates, config=None):
'''update client secrets will update the data structure for a particular
authentication. This should only be used for a (quasi permanent) token
or similar. The secrets file, if found, is updated and saved by default.
Parameters
==========... | [
"def",
"update_settings",
"(",
"self",
",",
"updates",
",",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"self",
".",
"_load_config_user",
"(",
")",
"if",
"self",
".",
"name",
"not",
"in",
"config",
":",
"config",
... | update client secrets will update the data structure for a particular
authentication. This should only be used for a (quasi permanent) token
or similar. The secrets file, if found, is updated and saved by default.
Parameters
==========
helper: the name of the helper to look up in the... | [
"update",
"client",
"secrets",
"will",
"update",
"the",
"data",
"structure",
"for",
"a",
"particular",
"authentication",
".",
"This",
"should",
"only",
"be",
"used",
"for",
"a",
"(",
"quasi",
"permanent",
")",
"token",
"or",
"similar",
".",
"The",
"secrets",... | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L205-L229 |
vsoch/helpme | helpme/main/base/settings.py | get_and_update_setting | def get_and_update_setting(self, name, default=None, user=True):
'''Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a ca... | python | def get_and_update_setting(self, name, default=None, user=True):
'''Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a ca... | [
"def",
"get_and_update_setting",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"user",
"=",
"True",
")",
":",
"setting",
"=",
"self",
".",
"_get_setting",
"(",
"name",
",",
"user",
"=",
"user",
")",
"if",
"setting",
"is",
"None",
"and",
... | Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a cache for the variable
2. the environment variable always takes pri... | [
"Look",
"for",
"a",
"setting",
"in",
"the",
"environment",
"(",
"first",
"priority",
")",
"and",
"then",
"the",
"settings",
"file",
"(",
"second",
")",
".",
"If",
"something",
"is",
"found",
"the",
"settings",
"file",
"is",
"updated",
".",
"The",
"order"... | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L232-L258 |
nephila/djangocms-helper | djangocms_helper/runner.py | run | def run(app, argv=sys.argv, extra_args=None):
"""
Run commands in a plain django environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments
"""
if app not in argv[:2]:
# app is automatically added if not present
... | python | def run(app, argv=sys.argv, extra_args=None):
"""
Run commands in a plain django environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments
"""
if app not in argv[:2]:
# app is automatically added if not present
... | [
"def",
"run",
"(",
"app",
",",
"argv",
"=",
"sys",
".",
"argv",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"app",
"not",
"in",
"argv",
"[",
":",
"2",
"]",
":",
"# app is automatically added if not present",
"argv",
".",
"insert",
"(",
"1",
",",
... | Run commands in a plain django environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments | [
"Run",
"commands",
"in",
"a",
"plain",
"django",
"environment"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/runner.py#L9-L25 |
nephila/djangocms-helper | djangocms_helper/runner.py | cms | def cms(app, argv=sys.argv, extra_args=None):
"""
Run commands in a django cMS environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments
"""
try:
import cms # NOQA # nopyflakes
except ImportError:
print(... | python | def cms(app, argv=sys.argv, extra_args=None):
"""
Run commands in a django cMS environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments
"""
try:
import cms # NOQA # nopyflakes
except ImportError:
print(... | [
"def",
"cms",
"(",
"app",
",",
"argv",
"=",
"sys",
".",
"argv",
",",
"extra_args",
"=",
"None",
")",
":",
"try",
":",
"import",
"cms",
"# NOQA # nopyflakes",
"except",
"ImportError",
":",
"print",
"(",
"'runner.cms is available only if django CMS is installed'",
... | Run commands in a django cMS environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments | [
"Run",
"commands",
"in",
"a",
"django",
"cMS",
"environment"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/runner.py#L28-L52 |
nephila/djangocms-helper | djangocms_helper/runner.py | setup | def setup(app, helper_module, extra_args=None, use_cms=False):
"""
Setup the Django / django CMS environment and return the environment settings.
:param app: application
:param helper_module: helper module
:param extra_args: list of extra arguments
:param use_cms: setup a django CMS environemtn... | python | def setup(app, helper_module, extra_args=None, use_cms=False):
"""
Setup the Django / django CMS environment and return the environment settings.
:param app: application
:param helper_module: helper module
:param extra_args: list of extra arguments
:param use_cms: setup a django CMS environemtn... | [
"def",
"setup",
"(",
"app",
",",
"helper_module",
",",
"extra_args",
"=",
"None",
",",
"use_cms",
"=",
"False",
")",
":",
"helper",
"=",
"helper_module",
".",
"__file__",
"argv",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"helper",
")",
",",
... | Setup the Django / django CMS environment and return the environment settings.
:param app: application
:param helper_module: helper module
:param extra_args: list of extra arguments
:param use_cms: setup a django CMS environemtn
:return: Django settings module | [
"Setup",
"the",
"Django",
"/",
"django",
"CMS",
"environment",
"and",
"return",
"the",
"environment",
"settings",
"."
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/runner.py#L55-L71 |
jurismarches/chopper | chopper/html/extractor.py | HTMLExtractor.parse | def parse(self):
"""
Returns a cleaned lxml ElementTree
:returns: Whether the cleaned HTML has matches or not
:rtype: bool
"""
# Create the element tree
self.tree = self._build_tree(self.html_contents)
# Get explicits elements to keep and discard
... | python | def parse(self):
"""
Returns a cleaned lxml ElementTree
:returns: Whether the cleaned HTML has matches or not
:rtype: bool
"""
# Create the element tree
self.tree = self._build_tree(self.html_contents)
# Get explicits elements to keep and discard
... | [
"def",
"parse",
"(",
"self",
")",
":",
"# Create the element tree",
"self",
".",
"tree",
"=",
"self",
".",
"_build_tree",
"(",
"self",
".",
"html_contents",
")",
"# Get explicits elements to keep and discard",
"self",
".",
"elts_to_keep",
"=",
"self",
".",
"_get_e... | Returns a cleaned lxml ElementTree
:returns: Whether the cleaned HTML has matches or not
:rtype: bool | [
"Returns",
"a",
"cleaned",
"lxml",
"ElementTree"
] | train | https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L40-L68 |
jurismarches/chopper | chopper/html/extractor.py | HTMLExtractor.rel_to_abs | def rel_to_abs(self, base_url):
"""
Converts relative links from html contents to absolute links
"""
# Delete target attributes
strip_attributes(self.tree, 'target')
# Absolute links
self.tree.rewrite_links(
lambda link: urljoin(base_url, link)
... | python | def rel_to_abs(self, base_url):
"""
Converts relative links from html contents to absolute links
"""
# Delete target attributes
strip_attributes(self.tree, 'target')
# Absolute links
self.tree.rewrite_links(
lambda link: urljoin(base_url, link)
... | [
"def",
"rel_to_abs",
"(",
"self",
",",
"base_url",
")",
":",
"# Delete target attributes",
"strip_attributes",
"(",
"self",
".",
"tree",
",",
"'target'",
")",
"# Absolute links",
"self",
".",
"tree",
".",
"rewrite_links",
"(",
"lambda",
"link",
":",
"urljoin",
... | Converts relative links from html contents to absolute links | [
"Converts",
"relative",
"links",
"from",
"html",
"contents",
"to",
"absolute",
"links"
] | train | https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L70-L91 |
jurismarches/chopper | chopper/html/extractor.py | HTMLExtractor._get_elements | def _get_elements(self, source):
"""
Returns the list of HtmlElements for the source
:param source: The source list to parse
:type source: list
:returns: A list of HtmlElements
:rtype: list
"""
return list(chain(*[self.tree.xpath(xpath) for xpath in sourc... | python | def _get_elements(self, source):
"""
Returns the list of HtmlElements for the source
:param source: The source list to parse
:type source: list
:returns: A list of HtmlElements
:rtype: list
"""
return list(chain(*[self.tree.xpath(xpath) for xpath in sourc... | [
"def",
"_get_elements",
"(",
"self",
",",
"source",
")",
":",
"return",
"list",
"(",
"chain",
"(",
"*",
"[",
"self",
".",
"tree",
".",
"xpath",
"(",
"xpath",
")",
"for",
"xpath",
"in",
"source",
"]",
")",
")"
] | Returns the list of HtmlElements for the source
:param source: The source list to parse
:type source: list
:returns: A list of HtmlElements
:rtype: list | [
"Returns",
"the",
"list",
"of",
"HtmlElements",
"for",
"the",
"source"
] | train | https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L106-L115 |
jurismarches/chopper | chopper/html/extractor.py | HTMLExtractor._parse_element | def _parse_element(self, elt, parent_is_keep=False):
"""
Parses an Element recursively
:param elt: HtmlElement to parse
:type elt: lxml.html.HtmlElement
:param parent_is_keep: Whether the element is inside a keep element or not
:type parent_is_keep: bool
"""
... | python | def _parse_element(self, elt, parent_is_keep=False):
"""
Parses an Element recursively
:param elt: HtmlElement to parse
:type elt: lxml.html.HtmlElement
:param parent_is_keep: Whether the element is inside a keep element or not
:type parent_is_keep: bool
"""
... | [
"def",
"_parse_element",
"(",
"self",
",",
"elt",
",",
"parent_is_keep",
"=",
"False",
")",
":",
"for",
"e",
"in",
"elt",
".",
"iterchildren",
"(",
")",
":",
"is_discard_element",
"=",
"self",
".",
"_is_discard",
"(",
"e",
")",
"is_keep_element",
"=",
"s... | Parses an Element recursively
:param elt: HtmlElement to parse
:type elt: lxml.html.HtmlElement
:param parent_is_keep: Whether the element is inside a keep element or not
:type parent_is_keep: bool | [
"Parses",
"an",
"Element",
"recursively"
] | train | https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L135-L171 |
jurismarches/chopper | chopper/html/extractor.py | HTMLExtractor._has_keep_elt_in_descendants | def _has_keep_elt_in_descendants(self, elt):
"""
Returns whether the element has a descendant to keep or not
:param elt: The HtmlElement to check
:type elt: lxml.html.HtmlElement
:returns: True if the element has a keep element in its descendants
:rtype: bool
"""... | python | def _has_keep_elt_in_descendants(self, elt):
"""
Returns whether the element has a descendant to keep or not
:param elt: The HtmlElement to check
:type elt: lxml.html.HtmlElement
:returns: True if the element has a keep element in its descendants
:rtype: bool
"""... | [
"def",
"_has_keep_elt_in_descendants",
"(",
"self",
",",
"elt",
")",
":",
"# iterdescendants is a generator, don't cast it as a list to avoid",
"# parsing the whole descendants tree if not necessary",
"for",
"d",
"in",
"elt",
".",
"iterdescendants",
"(",
")",
":",
"if",
"d",
... | Returns whether the element has a descendant to keep or not
:param elt: The HtmlElement to check
:type elt: lxml.html.HtmlElement
:returns: True if the element has a keep element in its descendants
:rtype: bool | [
"Returns",
"whether",
"the",
"element",
"has",
"a",
"descendant",
"to",
"keep",
"or",
"not"
] | train | https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L195-L210 |
jurismarches/chopper | chopper/html/extractor.py | HTMLExtractor._remove_elements | def _remove_elements(self, elts_to_remove):
"""
Removes flagged elements from the ElementTree
"""
for e in elts_to_remove:
# Get the element parent
parent = e.getparent()
# lxml also remove the element tail, preserve it
if e.tail and e.ta... | python | def _remove_elements(self, elts_to_remove):
"""
Removes flagged elements from the ElementTree
"""
for e in elts_to_remove:
# Get the element parent
parent = e.getparent()
# lxml also remove the element tail, preserve it
if e.tail and e.ta... | [
"def",
"_remove_elements",
"(",
"self",
",",
"elts_to_remove",
")",
":",
"for",
"e",
"in",
"elts_to_remove",
":",
"# Get the element parent",
"parent",
"=",
"e",
".",
"getparent",
"(",
")",
"# lxml also remove the element tail, preserve it",
"if",
"e",
".",
"tail",
... | Removes flagged elements from the ElementTree | [
"Removes",
"flagged",
"elements",
"from",
"the",
"ElementTree"
] | train | https://github.com/jurismarches/chopper/blob/53c5489a53e3a5d205a5cb207df751c09633e7ce/chopper/html/extractor.py#L212-L227 |
bpannier/simpletr64 | simpletr64/actions/system.py | System.getSystemInfo | def getSystemInfo(self, timeout=1):
"""Execute GetInfo action to get information's about the System on the device.
:return: information's about the System on the device.
:rtype: SystemInfo
"""
namespace = System.getServiceType("getSystemInfo")
uri = self.getControlURL(na... | python | def getSystemInfo(self, timeout=1):
"""Execute GetInfo action to get information's about the System on the device.
:return: information's about the System on the device.
:rtype: SystemInfo
"""
namespace = System.getServiceType("getSystemInfo")
uri = self.getControlURL(na... | [
"def",
"getSystemInfo",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"getSystemInfo\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execut... | Execute GetInfo action to get information's about the System on the device.
:return: information's about the System on the device.
:rtype: SystemInfo | [
"Execute",
"GetInfo",
"action",
"to",
"get",
"information",
"s",
"about",
"the",
"System",
"on",
"the",
"device",
"."
] | train | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L86-L97 |
bpannier/simpletr64 | simpletr64/actions/system.py | System.reboot | def reboot(self, timeout=1):
"""Reboot the device"""
namespace = System.getServiceType("reboot")
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "Reboot", timeout=timeout) | python | def reboot(self, timeout=1):
"""Reboot the device"""
namespace = System.getServiceType("reboot")
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "Reboot", timeout=timeout) | [
"def",
"reboot",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"reboot\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"self",
".",
"execute",
"(",
"uri",
",",
"name... | Reboot the device | [
"Reboot",
"the",
"device"
] | train | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L99-L104 |
bpannier/simpletr64 | simpletr64/actions/system.py | System.getTimeInfo | def getTimeInfo(self, timeout=1):
"""Execute GetInfo action to get information's about the time on the device.
:return: information's about the time on the device.
:rtype: TimeInfo
"""
namespace = System.getServiceType("getTimeInfo")
uri = self.getControlURL(namespace)
... | python | def getTimeInfo(self, timeout=1):
"""Execute GetInfo action to get information's about the time on the device.
:return: information's about the time on the device.
:rtype: TimeInfo
"""
namespace = System.getServiceType("getTimeInfo")
uri = self.getControlURL(namespace)
... | [
"def",
"getTimeInfo",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"getTimeInfo\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
... | Execute GetInfo action to get information's about the time on the device.
:return: information's about the time on the device.
:rtype: TimeInfo | [
"Execute",
"GetInfo",
"action",
"to",
"get",
"information",
"s",
"about",
"the",
"time",
"on",
"the",
"device",
"."
] | train | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L106-L117 |
bpannier/simpletr64 | simpletr64/actions/system.py | System.softwareUpdateAvailable | def softwareUpdateAvailable(self, timeout=1):
"""Returns if a software update is available
:return: if a software update is available
:rtype: bool
"""
namespace = System.getServiceType("softwareUpdateAvailable")
uri = self.getControlURL(namespace)
results = self... | python | def softwareUpdateAvailable(self, timeout=1):
"""Returns if a software update is available
:return: if a software update is available
:rtype: bool
"""
namespace = System.getServiceType("softwareUpdateAvailable")
uri = self.getControlURL(namespace)
results = self... | [
"def",
"softwareUpdateAvailable",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"softwareUpdateAvailable\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"sel... | Returns if a software update is available
:return: if a software update is available
:rtype: bool | [
"Returns",
"if",
"a",
"software",
"update",
"is",
"available"
] | train | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/system.py#L119-L130 |
PlaidWeb/Pushl | pushl/caching.py | make_headers | def make_headers(headers):
""" Make the cache control headers based on a previous request's
response headers
"""
out = {}
if 'etag' in headers:
out['if-none-match'] = headers['etag']
if 'last-modified' in headers:
out['if-modified-since'] = headers['last-modified']
return out | python | def make_headers(headers):
""" Make the cache control headers based on a previous request's
response headers
"""
out = {}
if 'etag' in headers:
out['if-none-match'] = headers['etag']
if 'last-modified' in headers:
out['if-modified-since'] = headers['last-modified']
return out | [
"def",
"make_headers",
"(",
"headers",
")",
":",
"out",
"=",
"{",
"}",
"if",
"'etag'",
"in",
"headers",
":",
"out",
"[",
"'if-none-match'",
"]",
"=",
"headers",
"[",
"'etag'",
"]",
"if",
"'last-modified'",
"in",
"headers",
":",
"out",
"[",
"'if-modified-... | Make the cache control headers based on a previous request's
response headers | [
"Make",
"the",
"cache",
"control",
"headers",
"based",
"on",
"a",
"previous",
"request",
"s",
"response",
"headers"
] | train | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/caching.py#L69-L78 |
PlaidWeb/Pushl | pushl/caching.py | Cache.get | def get(self, prefix, url, schema_version=None):
""" Get the cached object """
if not self.cache_dir:
return None
filename = self._get_cache_file(prefix, url)
try:
with open(filename, 'rb') as file:
item = pickle.load(file)
if schema_... | python | def get(self, prefix, url, schema_version=None):
""" Get the cached object """
if not self.cache_dir:
return None
filename = self._get_cache_file(prefix, url)
try:
with open(filename, 'rb') as file:
item = pickle.load(file)
if schema_... | [
"def",
"get",
"(",
"self",
",",
"prefix",
",",
"url",
",",
"schema_version",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"cache_dir",
":",
"return",
"None",
"filename",
"=",
"self",
".",
"_get_cache_file",
"(",
"prefix",
",",
"url",
")",
"try",
... | Get the cached object | [
"Get",
"the",
"cached",
"object"
] | train | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/caching.py#L29-L51 |
PlaidWeb/Pushl | pushl/caching.py | Cache.set | def set(self, prefix, url, obj):
""" Add an object into the cache """
if not self.cache_dir:
return
filename = self._get_cache_file(prefix, url)
try:
os.makedirs(os.path.join(self.cache_dir, prefix))
except OSError:
pass
with open(fi... | python | def set(self, prefix, url, obj):
""" Add an object into the cache """
if not self.cache_dir:
return
filename = self._get_cache_file(prefix, url)
try:
os.makedirs(os.path.join(self.cache_dir, prefix))
except OSError:
pass
with open(fi... | [
"def",
"set",
"(",
"self",
",",
"prefix",
",",
"url",
",",
"obj",
")",
":",
"if",
"not",
"self",
".",
"cache_dir",
":",
"return",
"filename",
"=",
"self",
".",
"_get_cache_file",
"(",
"prefix",
",",
"url",
")",
"try",
":",
"os",
".",
"makedirs",
"(... | Add an object into the cache | [
"Add",
"an",
"object",
"into",
"the",
"cache"
] | train | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/caching.py#L53-L66 |
mjirik/io3d | io3d/datasets.py | join_path | def join_path(*path_to_join, **kwargs):
"""Join input path to sample data path (usually in ~/lisa_data)
:param path_to_join: one or more paths
:param get_root: return dataset root path. If false, the path would be into "medical/orig"
:return: joined path
"""
if "get_root" in kwargs:
get... | python | def join_path(*path_to_join, **kwargs):
"""Join input path to sample data path (usually in ~/lisa_data)
:param path_to_join: one or more paths
:param get_root: return dataset root path. If false, the path would be into "medical/orig"
:return: joined path
"""
if "get_root" in kwargs:
get... | [
"def",
"join_path",
"(",
"*",
"path_to_join",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"get_root\"",
"in",
"kwargs",
":",
"get_root",
"=",
"kwargs",
"[",
"\"get_root\"",
"]",
"else",
":",
"# default value",
"get_root",
"=",
"False",
"sdp",
"=",
"dataset_... | Join input path to sample data path (usually in ~/lisa_data)
:param path_to_join: one or more paths
:param get_root: return dataset root path. If false, the path would be into "medical/orig"
:return: joined path | [
"Join",
"input",
"path",
"to",
"sample",
"data",
"path",
"(",
"usually",
"in",
"~",
"/",
"lisa_data",
")"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L180-L196 |
mjirik/io3d | io3d/datasets.py | set_dataset_path | def set_dataset_path(path, cache=None, cachefile="~/.io3d_cache.yaml"):
"""Sets path to dataset. Warning: function with side effects!
:param path: path you want to store dataset
:param cache: CacheFile object
:param cachefile: default '~/.io3d_cache.yaml'
"""
if cachefile is not None:
c... | python | def set_dataset_path(path, cache=None, cachefile="~/.io3d_cache.yaml"):
"""Sets path to dataset. Warning: function with side effects!
:param path: path you want to store dataset
:param cache: CacheFile object
:param cachefile: default '~/.io3d_cache.yaml'
"""
if cachefile is not None:
c... | [
"def",
"set_dataset_path",
"(",
"path",
",",
"cache",
"=",
"None",
",",
"cachefile",
"=",
"\"~/.io3d_cache.yaml\"",
")",
":",
"if",
"cachefile",
"is",
"not",
"None",
":",
"cache",
"=",
"cachef",
".",
"CacheFile",
"(",
"cachefile",
")",
"cache",
".",
"updat... | Sets path to dataset. Warning: function with side effects!
:param path: path you want to store dataset
:param cache: CacheFile object
:param cachefile: default '~/.io3d_cache.yaml' | [
"Sets",
"path",
"to",
"dataset",
".",
"Warning",
":",
"function",
"with",
"side",
"effects!"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L199-L208 |
mjirik/io3d | io3d/datasets.py | dataset_path | def dataset_path(cache=None, cachefile="~/.io3d_cache.yaml", get_root=False):
"""Get dataset path.
:param cache: CacheFile object
:param cachefile: cachefile path, default '~/.io3d_cache.yaml'
:return: path to dataset
"""
local_data_dir = local_dir
if cachefile is not None:
cache =... | python | def dataset_path(cache=None, cachefile="~/.io3d_cache.yaml", get_root=False):
"""Get dataset path.
:param cache: CacheFile object
:param cachefile: cachefile path, default '~/.io3d_cache.yaml'
:return: path to dataset
"""
local_data_dir = local_dir
if cachefile is not None:
cache =... | [
"def",
"dataset_path",
"(",
"cache",
"=",
"None",
",",
"cachefile",
"=",
"\"~/.io3d_cache.yaml\"",
",",
"get_root",
"=",
"False",
")",
":",
"local_data_dir",
"=",
"local_dir",
"if",
"cachefile",
"is",
"not",
"None",
":",
"cache",
"=",
"cachef",
".",
"CacheFi... | Get dataset path.
:param cache: CacheFile object
:param cachefile: cachefile path, default '~/.io3d_cache.yaml'
:return: path to dataset | [
"Get",
"dataset",
"path",
"."
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L211-L232 |
mjirik/io3d | io3d/datasets.py | get_dataset_meta | def get_dataset_meta(label):
"""Gives you metadata for dataset chosen via 'label' param
:param label: label = key in data_url dict (that big dict containing all possible datasets)
:return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir)
relative_download_dir says where will be do... | python | def get_dataset_meta(label):
"""Gives you metadata for dataset chosen via 'label' param
:param label: label = key in data_url dict (that big dict containing all possible datasets)
:return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir)
relative_download_dir says where will be do... | [
"def",
"get_dataset_meta",
"(",
"label",
")",
":",
"data_url",
"=",
"data_urls",
"[",
"label",
"]",
"if",
"type",
"(",
"data_url",
")",
"==",
"str",
":",
"# back compatibility",
"data_url",
"=",
"[",
"data_url",
"]",
"if",
"type",
"(",
"data_url",
")",
"... | Gives you metadata for dataset chosen via 'label' param
:param label: label = key in data_url dict (that big dict containing all possible datasets)
:return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir)
relative_download_dir says where will be downloaded the file from url and event... | [
"Gives",
"you",
"metadata",
"for",
"dataset",
"chosen",
"via",
"label",
"param"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L241-L260 |
mjirik/io3d | io3d/datasets.py | _expand_dataset_packages | def _expand_dataset_packages(dataset_label_dict):
"""Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'.
In case the param is not pointing to multidataset returns only that label in a list.
:param str dataset_label_dict: label of multi dataset
:ret... | python | def _expand_dataset_packages(dataset_label_dict):
"""Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'.
In case the param is not pointing to multidataset returns only that label in a list.
:param str dataset_label_dict: label of multi dataset
:ret... | [
"def",
"_expand_dataset_packages",
"(",
"dataset_label_dict",
")",
":",
"new_dataset_label_dict",
"=",
"[",
"]",
"for",
"label",
"in",
"dataset_label_dict",
":",
"dataset_metadata",
"=",
"data_urls",
"[",
"label",
"]",
"if",
"type",
"(",
"dataset_metadata",
")",
"... | Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'.
In case the param is not pointing to multidataset returns only that label in a list.
:param str dataset_label_dict: label of multi dataset
:return: list of labels | [
"Returns",
"list",
"of",
"possible",
"packages",
"contained",
"in",
"dataset",
"in",
"case",
"the",
"dataset",
"is",
"multi",
"dataset",
"eg",
".",
"lisa",
"."
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L264-L279 |
mjirik/io3d | io3d/datasets.py | download | def download(dataset_label=None, destination_dir=None, dry_run=False):
"""Download sample data by data label. Warning: function with side effect!
Labels can be listed by sample_data.data_urls.keys(). Returns downloaded files.
:param dataset_label: label of data. If it is set to None, all data are download... | python | def download(dataset_label=None, destination_dir=None, dry_run=False):
"""Download sample data by data label. Warning: function with side effect!
Labels can be listed by sample_data.data_urls.keys(). Returns downloaded files.
:param dataset_label: label of data. If it is set to None, all data are download... | [
"def",
"download",
"(",
"dataset_label",
"=",
"None",
",",
"destination_dir",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"destination_dir",
"is",
"None",
":",
"destination_dir",
"=",
"op",
".",
"join",
"(",
"dataset_path",
"(",
"get_root",
... | Download sample data by data label. Warning: function with side effect!
Labels can be listed by sample_data.data_urls.keys(). Returns downloaded files.
:param dataset_label: label of data. If it is set to None, all data are downloaded
:param destination_dir: output dir for data
:param dry_run: runs fu... | [
"Download",
"sample",
"data",
"by",
"data",
"label",
".",
"Warning",
":",
"function",
"with",
"side",
"effect!"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L282-L356 |
mjirik/io3d | io3d/datasets.py | get_old | def get_old(dataset_label, data_id, destination_dir=None):
"""Get the 3D data from specified dataset with specified id.
Download data if necessary.
:param dataset_label:
:param data_id: integer or wildcards file pattern
:param destination_dir:
:return:
"""
# TODO implement
if desti... | python | def get_old(dataset_label, data_id, destination_dir=None):
"""Get the 3D data from specified dataset with specified id.
Download data if necessary.
:param dataset_label:
:param data_id: integer or wildcards file pattern
:param destination_dir:
:return:
"""
# TODO implement
if desti... | [
"def",
"get_old",
"(",
"dataset_label",
",",
"data_id",
",",
"destination_dir",
"=",
"None",
")",
":",
"# TODO implement",
"if",
"destination_dir",
"is",
"None",
":",
"destination_dir",
"=",
"op",
".",
"join",
"(",
"dataset_path",
"(",
"get_root",
"=",
"True",... | Get the 3D data from specified dataset with specified id.
Download data if necessary.
:param dataset_label:
:param data_id: integer or wildcards file pattern
:param destination_dir:
:return: | [
"Get",
"the",
"3D",
"data",
"from",
"specified",
"dataset",
"with",
"specified",
"id",
"."
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L360-L387 |
mjirik/io3d | io3d/datasets.py | checksum | def checksum(path, hashfunc="md5"):
"""Return checksum of files given by path.
Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'.
:param path: path of files to get hash from
:param hashfunc: function used to get hash, default 'md5'
:return:... | python | def checksum(path, hashfunc="md5"):
"""Return checksum of files given by path.
Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'.
:param path: path of files to get hash from
:param hashfunc: function used to get hash, default 'md5'
:return:... | [
"def",
"checksum",
"(",
"path",
",",
"hashfunc",
"=",
"\"md5\"",
")",
":",
"import",
"checksumdir",
"hash_func",
"=",
"checksumdir",
".",
"HASH_FUNCS",
".",
"get",
"(",
"hashfunc",
")",
"if",
"not",
"hash_func",
":",
"raise",
"NotImplementedError",
"(",
"\"{... | Return checksum of files given by path.
Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'.
:param path: path of files to get hash from
:param hashfunc: function used to get hash, default 'md5'
:return: (str) hash of the file/files given by path | [
"Return",
"checksum",
"of",
"files",
"given",
"by",
"path",
"."
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L415-L447 |
mjirik/io3d | io3d/datasets.py | generate_donut | def generate_donut():
"""Generate donut like shape with stick inside
:return: dict {'data3d': '', 'segmentation': '', 'voxelsize_mm': ''}
"""
segmentation = np.zeros([20, 30, 40])
# generate test data
segmentation[6:10, 7:24, 10:37] = 1
segmentation[6:10, 7, 10] = 0
segmentation[6:10, 2... | python | def generate_donut():
"""Generate donut like shape with stick inside
:return: dict {'data3d': '', 'segmentation': '', 'voxelsize_mm': ''}
"""
segmentation = np.zeros([20, 30, 40])
# generate test data
segmentation[6:10, 7:24, 10:37] = 1
segmentation[6:10, 7, 10] = 0
segmentation[6:10, 2... | [
"def",
"generate_donut",
"(",
")",
":",
"segmentation",
"=",
"np",
".",
"zeros",
"(",
"[",
"20",
",",
"30",
",",
"40",
"]",
")",
"# generate test data",
"segmentation",
"[",
"6",
":",
"10",
",",
"7",
":",
"24",
",",
"10",
":",
"37",
"]",
"=",
"1"... | Generate donut like shape with stick inside
:return: dict {'data3d': '', 'segmentation': '', 'voxelsize_mm': ''} | [
"Generate",
"donut",
"like",
"shape",
"with",
"stick",
"inside"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L450-L473 |
mjirik/io3d | io3d/datasets.py | generate_round_data | def generate_round_data(
sz=32, offset=0, radius=7, seedsz=3, add_object_without_seeds=False
):
"""
Generate data with two sphere objects.
:param sz: output data shape is [sz, sz+1, sz+2]
:param offset:
:param radius:
:param seedsz:
:param add_object_without_seeds: Add also one cube-like... | python | def generate_round_data(
sz=32, offset=0, radius=7, seedsz=3, add_object_without_seeds=False
):
"""
Generate data with two sphere objects.
:param sz: output data shape is [sz, sz+1, sz+2]
:param offset:
:param radius:
:param seedsz:
:param add_object_without_seeds: Add also one cube-like... | [
"def",
"generate_round_data",
"(",
"sz",
"=",
"32",
",",
"offset",
"=",
"0",
",",
"radius",
"=",
"7",
",",
"seedsz",
"=",
"3",
",",
"add_object_without_seeds",
"=",
"False",
")",
":",
"import",
"scipy",
".",
"ndimage",
"# seedsz= int(sz/10)",
"space",
"=",... | Generate data with two sphere objects.
:param sz: output data shape is [sz, sz+1, sz+2]
:param offset:
:param radius:
:param seedsz:
:param add_object_without_seeds: Add also one cube-like object in the corner.
:return: | [
"Generate",
"data",
"with",
"two",
"sphere",
"objects",
".",
":",
"param",
"sz",
":",
"output",
"data",
"shape",
"is",
"[",
"sz",
"sz",
"+",
"1",
"sz",
"+",
"2",
"]",
":",
"param",
"offset",
":",
":",
"param",
"radius",
":",
":",
"param",
"seedsz",... | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L532-L570 |
mjirik/io3d | io3d/datasets.py | generate_synthetic_liver | def generate_synthetic_liver(return_dataplus=False):
"""
Create synthetic data. There is some liver and porta -like object.
:return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta:
"""
# data
slab = {"none": 0, "liver": 1, "porta": 2}
voxelsize_mm = np.array([1.0, 1.0, 1.2... | python | def generate_synthetic_liver(return_dataplus=False):
"""
Create synthetic data. There is some liver and porta -like object.
:return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta:
"""
# data
slab = {"none": 0, "liver": 1, "porta": 2}
voxelsize_mm = np.array([1.0, 1.0, 1.2... | [
"def",
"generate_synthetic_liver",
"(",
"return_dataplus",
"=",
"False",
")",
":",
"# data",
"slab",
"=",
"{",
"\"none\"",
":",
"0",
",",
"\"liver\"",
":",
"1",
",",
"\"porta\"",
":",
"2",
"}",
"voxelsize_mm",
"=",
"np",
".",
"array",
"(",
"[",
"1.0",
... | Create synthetic data. There is some liver and porta -like object.
:return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta: | [
"Create",
"synthetic",
"data",
".",
"There",
"is",
"some",
"liver",
"and",
"porta",
"-",
"like",
"object",
".",
":",
"return",
"data3d",
"segmentation",
"voxelsize_mm",
"slab",
"seeds_liver",
"seeds_porta",
":"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L573-L625 |
mjirik/io3d | io3d/datasets.py | _get_face2 | def _get_face2(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2):
"""
Create 2D binar face
:param shape:
:param face_r:
:param smile_r1:
:param smile_r2:
:param eye_r:
:return:
"""
# data3d = np.zeros([1,7,7], dtype=np.int16)
if shape is None:
shape = [3... | python | def _get_face2(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2):
"""
Create 2D binar face
:param shape:
:param face_r:
:param smile_r1:
:param smile_r2:
:param eye_r:
:return:
"""
# data3d = np.zeros([1,7,7], dtype=np.int16)
if shape is None:
shape = [3... | [
"def",
"_get_face2",
"(",
"shape",
"=",
"None",
",",
"face_r",
"=",
"1.0",
",",
"smile_r1",
"=",
"0.5",
",",
"smile_r2",
"=",
"0.7",
",",
"eye_r",
"=",
"0.2",
")",
":",
"# data3d = np.zeros([1,7,7], dtype=np.int16)",
"if",
"shape",
"is",
"None",
":",
"shap... | Create 2D binar face
:param shape:
:param face_r:
:param smile_r1:
:param smile_r2:
:param eye_r:
:return: | [
"Create",
"2D",
"binar",
"face",
":",
"param",
"shape",
":",
":",
"param",
"face_r",
":",
":",
"param",
"smile_r1",
":",
":",
"param",
"smile_r2",
":",
":",
"param",
"eye_r",
":",
":",
"return",
":"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L628-L666 |
mjirik/io3d | io3d/datasets.py | generate_face | def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2):
"""
Create 2D or 3D binar data with smile face.
:param shape: 2D or 3D shape of data
:param face_r:
:param smile_r1:
:param smile_r2:
:param eye_r:
:return: binar ndarray
"""
# TODO add axis (ax=0)... | python | def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2):
"""
Create 2D or 3D binar data with smile face.
:param shape: 2D or 3D shape of data
:param face_r:
:param smile_r1:
:param smile_r2:
:param eye_r:
:return: binar ndarray
"""
# TODO add axis (ax=0)... | [
"def",
"generate_face",
"(",
"shape",
"=",
"None",
",",
"face_r",
"=",
"1.0",
",",
"smile_r1",
"=",
"0.5",
",",
"smile_r2",
"=",
"0.7",
",",
"eye_r",
"=",
"0.2",
")",
":",
"# TODO add axis (ax=0)",
"if",
"shape",
"is",
"None",
":",
"shape",
"=",
"[",
... | Create 2D or 3D binar data with smile face.
:param shape: 2D or 3D shape of data
:param face_r:
:param smile_r1:
:param smile_r2:
:param eye_r:
:return: binar ndarray | [
"Create",
"2D",
"or",
"3D",
"binar",
"data",
"with",
"smile",
"face",
"."
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L669-L698 |
mjirik/io3d | io3d/datasets.py | remove | def remove(local_file_name):
"""Function attempts to remove file, if failure occures -> print exception
:param local_file_name: name of file to remove
"""
try:
os.remove(local_file_name)
except Exception as e:
print(
"Cannot remove file '" + local_file_name + "'. Please ... | python | def remove(local_file_name):
"""Function attempts to remove file, if failure occures -> print exception
:param local_file_name: name of file to remove
"""
try:
os.remove(local_file_name)
except Exception as e:
print(
"Cannot remove file '" + local_file_name + "'. Please ... | [
"def",
"remove",
"(",
"local_file_name",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"local_file_name",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Cannot remove file '\"",
"+",
"local_file_name",
"+",
"\"'. Please remove it manually.\"",
")",... | Function attempts to remove file, if failure occures -> print exception
:param local_file_name: name of file to remove | [
"Function",
"attempts",
"to",
"remove",
"file",
"if",
"failure",
"occures",
"-",
">",
"print",
"exception"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L741-L752 |
mjirik/io3d | io3d/datasets.py | downzip | def downzip(url, destination="./sample_data/"):
"""Download, unzip and delete. Warning: function with strong side effects!
Returns downloaded data.
:param str url: url from which data should be donloaded
:param destination: destination to which data should be downloaded
"""
# url = "http://14... | python | def downzip(url, destination="./sample_data/"):
"""Download, unzip and delete. Warning: function with strong side effects!
Returns downloaded data.
:param str url: url from which data should be donloaded
:param destination: destination to which data should be downloaded
"""
# url = "http://14... | [
"def",
"downzip",
"(",
"url",
",",
"destination",
"=",
"\"./sample_data/\"",
")",
":",
"# url = \"http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip\"",
"logmsg",
"=",
"\"downloading from '\"",
"+",
"url",
"+",
"\"' to '\"",
"+",
"destination",
"+",
"\"'\"",... | Download, unzip and delete. Warning: function with strong side effects!
Returns downloaded data.
:param str url: url from which data should be donloaded
:param destination: destination to which data should be downloaded | [
"Download",
"unzip",
"and",
"delete",
".",
"Warning",
":",
"function",
"with",
"strong",
"side",
"effects!"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L758-L782 |
mjirik/io3d | io3d/datasets.py | unzip_one | def unzip_one(local_file_name):
"""Unzips one file and deletes it. Warning: function with side effects!
:param str local_file_name: file name of zip file
:return: list of archive members by name.
"""
local_file_name = op.expanduser(local_file_name)
destination = op.dirname(local_file_name)
... | python | def unzip_one(local_file_name):
"""Unzips one file and deletes it. Warning: function with side effects!
:param str local_file_name: file name of zip file
:return: list of archive members by name.
"""
local_file_name = op.expanduser(local_file_name)
destination = op.dirname(local_file_name)
... | [
"def",
"unzip_one",
"(",
"local_file_name",
")",
":",
"local_file_name",
"=",
"op",
".",
"expanduser",
"(",
"local_file_name",
")",
"destination",
"=",
"op",
".",
"dirname",
"(",
"local_file_name",
")",
"datafile",
"=",
"zipfile",
".",
"ZipFile",
"(",
"local_f... | Unzips one file and deletes it. Warning: function with side effects!
:param str local_file_name: file name of zip file
:return: list of archive members by name. | [
"Unzips",
"one",
"file",
"and",
"deletes",
"it",
".",
"Warning",
":",
"function",
"with",
"side",
"effects!"
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L801-L818 |
mjirik/io3d | io3d/datasets.py | unzip_recursive | def unzip_recursive(zip_file_name):
"""Unzip file with all recursive zip files inside and delete zip files after that.
:param zip_file_name: file name of zip file
:return: list of archive members by name.
"""
logger.debug("unzipping " + zip_file_name)
fnlist = unzip_one(zip_file_name)
for f... | python | def unzip_recursive(zip_file_name):
"""Unzip file with all recursive zip files inside and delete zip files after that.
:param zip_file_name: file name of zip file
:return: list of archive members by name.
"""
logger.debug("unzipping " + zip_file_name)
fnlist = unzip_one(zip_file_name)
for f... | [
"def",
"unzip_recursive",
"(",
"zip_file_name",
")",
":",
"logger",
".",
"debug",
"(",
"\"unzipping \"",
"+",
"zip_file_name",
")",
"fnlist",
"=",
"unzip_one",
"(",
"zip_file_name",
")",
"for",
"fn",
"in",
"fnlist",
":",
"if",
"zipfile",
".",
"is_zipfile",
"... | Unzip file with all recursive zip files inside and delete zip files after that.
:param zip_file_name: file name of zip file
:return: list of archive members by name. | [
"Unzip",
"file",
"with",
"all",
"recursive",
"zip",
"files",
"inside",
"and",
"delete",
"zip",
"files",
"after",
"that",
"."
] | train | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datasets.py#L821-L833 |
vsoch/helpme | helpme/action/submit.py | upload_asciinema | def upload_asciinema(filename):
'''a wrapper around generation of an asciinema.api.Api to call the
upload command given an already existing asciinema file.
Parameters
==========
filename: the asciinema file to upload, can be generated with
function record_asciinema i... | python | def upload_asciinema(filename):
'''a wrapper around generation of an asciinema.api.Api to call the
upload command given an already existing asciinema file.
Parameters
==========
filename: the asciinema file to upload, can be generated with
function record_asciinema i... | [
"def",
"upload_asciinema",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"import",
"asciinema",
".",
"config",
"as",
"aconfig",
"from",
"asciinema",
".",
"api",
"import",
"Api",
"# Load the API class",
"cfg",
... | a wrapper around generation of an asciinema.api.Api to call the
upload command given an already existing asciinema file.
Parameters
==========
filename: the asciinema file to upload, can be generated with
function record_asciinema in record.py | [
"a",
"wrapper",
"around",
"generation",
"of",
"an",
"asciinema",
".",
"api",
".",
"Api",
"to",
"call",
"the",
"upload",
"command",
"given",
"an",
"already",
"existing",
"asciinema",
"file",
"."
] | train | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/action/submit.py#L24-L64 |
tonyseek/flask-docker | flask_docker.py | make_tls_config | def make_tls_config(app_config):
"""Creates TLS configuration object."""
if not app_config['DOCKER_TLS']:
return False
cert_path = app_config['DOCKER_TLS_CERT_PATH']
if cert_path:
client_cert = '{0}:{1}'.format(
os.path.join(cert_path, 'cert.pem'),
os.path.join(... | python | def make_tls_config(app_config):
"""Creates TLS configuration object."""
if not app_config['DOCKER_TLS']:
return False
cert_path = app_config['DOCKER_TLS_CERT_PATH']
if cert_path:
client_cert = '{0}:{1}'.format(
os.path.join(cert_path, 'cert.pem'),
os.path.join(... | [
"def",
"make_tls_config",
"(",
"app_config",
")",
":",
"if",
"not",
"app_config",
"[",
"'DOCKER_TLS'",
"]",
":",
"return",
"False",
"cert_path",
"=",
"app_config",
"[",
"'DOCKER_TLS_CERT_PATH'",
"]",
"if",
"cert_path",
":",
"client_cert",
"=",
"'{0}:{1}'",
".",
... | Creates TLS configuration object. | [
"Creates",
"TLS",
"configuration",
"object",
"."
] | train | https://github.com/tonyseek/flask-docker/blob/bbc7faa72d0bb08fcd17f336abc210bb71f1e34e/flask_docker.py#L71-L93 |
tonyseek/flask-docker | flask_docker.py | parse_client_cert_pair | def parse_client_cert_pair(config_value):
"""Parses the client cert pair from config item.
:param config_value: the string value of config item.
:returns: tuple or none.
"""
if not config_value:
return
client_cert = config_value.split(':')
if len(client_cert) != 2:
tips = ('... | python | def parse_client_cert_pair(config_value):
"""Parses the client cert pair from config item.
:param config_value: the string value of config item.
:returns: tuple or none.
"""
if not config_value:
return
client_cert = config_value.split(':')
if len(client_cert) != 2:
tips = ('... | [
"def",
"parse_client_cert_pair",
"(",
"config_value",
")",
":",
"if",
"not",
"config_value",
":",
"return",
"client_cert",
"=",
"config_value",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"client_cert",
")",
"!=",
"2",
":",
"tips",
"=",
"(",
"'client_... | Parses the client cert pair from config item.
:param config_value: the string value of config item.
:returns: tuple or none. | [
"Parses",
"the",
"client",
"cert",
"pair",
"from",
"config",
"item",
"."
] | train | https://github.com/tonyseek/flask-docker/blob/bbc7faa72d0bb08fcd17f336abc210bb71f1e34e/flask_docker.py#L96-L109 |
tonyseek/flask-docker | flask_docker.py | Docker.init_app | def init_app(self, app):
"""Initializes an application for using :class:`docker.Client`.
:param app: an instance of :class:`~flask.Flask`.
"""
app.extensions = getattr(app, 'extensions', {})
app.extensions['docker.client'] = None
app.config.setdefault('DOCKER_URL', None... | python | def init_app(self, app):
"""Initializes an application for using :class:`docker.Client`.
:param app: an instance of :class:`~flask.Flask`.
"""
app.extensions = getattr(app, 'extensions', {})
app.extensions['docker.client'] = None
app.config.setdefault('DOCKER_URL', None... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"extensions",
"=",
"getattr",
"(",
"app",
",",
"'extensions'",
",",
"{",
"}",
")",
"app",
".",
"extensions",
"[",
"'docker.client'",
"]",
"=",
"None",
"app",
".",
"config",
".",
"setde... | Initializes an application for using :class:`docker.Client`.
:param app: an instance of :class:`~flask.Flask`. | [
"Initializes",
"an",
"application",
"for",
"using",
":",
"class",
":",
"docker",
".",
"Client",
"."
] | train | https://github.com/tonyseek/flask-docker/blob/bbc7faa72d0bb08fcd17f336abc210bb71f1e34e/flask_docker.py#L26-L44 |
tonyseek/flask-docker | flask_docker.py | Docker.client | def client(self):
"""The original :class:`docker.Client` object. All docker operation
calling will be forwarded here. ::
docker.create_container('ubuntu')
docker.client.create_container('ubuntu') # equivalent
"""
if not self.app.config['DOCKER_URL']:
... | python | def client(self):
"""The original :class:`docker.Client` object. All docker operation
calling will be forwarded here. ::
docker.create_container('ubuntu')
docker.client.create_container('ubuntu') # equivalent
"""
if not self.app.config['DOCKER_URL']:
... | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"app",
".",
"config",
"[",
"'DOCKER_URL'",
"]",
":",
"raise",
"RuntimeError",
"(",
"'\"DOCKER_URL\" must be specified'",
")",
"if",
"not",
"self",
".",
"app",
".",
"extensions",
"[",
"'docke... | The original :class:`docker.Client` object. All docker operation
calling will be forwarded here. ::
docker.create_container('ubuntu')
docker.client.create_container('ubuntu') # equivalent | [
"The",
"original",
":",
"class",
":",
"docker",
".",
"Client",
"object",
".",
"All",
"docker",
"operation",
"calling",
"will",
"be",
"forwarded",
"here",
".",
"::"
] | train | https://github.com/tonyseek/flask-docker/blob/bbc7faa72d0bb08fcd17f336abc210bb71f1e34e/flask_docker.py#L47-L63 |
PlaidWeb/Pushl | pushl/__init__.py | Pushl.process_feed | async def process_feed(self, url, send_mentions=True):
""" process a feed """
self._feed_domains.add(utils.get_domain(url))
if url in self._processed_feeds:
LOGGER.debug("Skipping already processed feed %s", url)
return
self._processed_feeds.add(url)
LO... | python | async def process_feed(self, url, send_mentions=True):
""" process a feed """
self._feed_domains.add(utils.get_domain(url))
if url in self._processed_feeds:
LOGGER.debug("Skipping already processed feed %s", url)
return
self._processed_feeds.add(url)
LO... | [
"async",
"def",
"process_feed",
"(",
"self",
",",
"url",
",",
"send_mentions",
"=",
"True",
")",
":",
"self",
".",
"_feed_domains",
".",
"add",
"(",
"utils",
".",
"get_domain",
"(",
"url",
")",
")",
"if",
"url",
"in",
"self",
".",
"_processed_feeds",
"... | process a feed | [
"process",
"a",
"feed"
] | train | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/__init__.py#L31-L94 |
PlaidWeb/Pushl | pushl/__init__.py | Pushl.process_entry | async def process_entry(self, url, add_domain=False, send_mentions=True):
""" process an entry """
if add_domain:
self._feed_domains.add(utils.get_domain(url))
if url in self._processed_entries:
LOGGER.debug("Skipping already processed entry %s", url)
return... | python | async def process_entry(self, url, add_domain=False, send_mentions=True):
""" process an entry """
if add_domain:
self._feed_domains.add(utils.get_domain(url))
if url in self._processed_entries:
LOGGER.debug("Skipping already processed entry %s", url)
return... | [
"async",
"def",
"process_entry",
"(",
"self",
",",
"url",
",",
"add_domain",
"=",
"False",
",",
"send_mentions",
"=",
"True",
")",
":",
"if",
"add_domain",
":",
"self",
".",
"_feed_domains",
".",
"add",
"(",
"utils",
".",
"get_domain",
"(",
"url",
")",
... | process an entry | [
"process",
"an",
"entry"
] | train | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/__init__.py#L96-L144 |
PlaidWeb/Pushl | pushl/__init__.py | Pushl.send_webmention | async def send_webmention(self, entry, url):
""" send a webmention from an entry to a URL """
if (entry.url, url) in self._processed_mentions:
LOGGER.debug(
"Skipping already processed mention %s -> %s", entry.url, url)
self._processed_mentions.add((entry.url, url))
... | python | async def send_webmention(self, entry, url):
""" send a webmention from an entry to a URL """
if (entry.url, url) in self._processed_mentions:
LOGGER.debug(
"Skipping already processed mention %s -> %s", entry.url, url)
self._processed_mentions.add((entry.url, url))
... | [
"async",
"def",
"send_webmention",
"(",
"self",
",",
"entry",
",",
"url",
")",
":",
"if",
"(",
"entry",
".",
"url",
",",
"url",
")",
"in",
"self",
".",
"_processed_mentions",
":",
"LOGGER",
".",
"debug",
"(",
"\"Skipping already processed mention %s -> %s\"",
... | send a webmention from an entry to a URL | [
"send",
"a",
"webmention",
"from",
"an",
"entry",
"to",
"a",
"URL"
] | train | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/__init__.py#L146-L161 |
nephila/djangocms-helper | djangocms_helper/main.py | compilemessages | def compilemessages(application):
"""
Compiles locale messages
"""
from django.core.management import call_command
with work_in(application):
if DJANGO_1_11:
call_command('compilemessages', all=True)
else:
call_command('compilemessages') | python | def compilemessages(application):
"""
Compiles locale messages
"""
from django.core.management import call_command
with work_in(application):
if DJANGO_1_11:
call_command('compilemessages', all=True)
else:
call_command('compilemessages') | [
"def",
"compilemessages",
"(",
"application",
")",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"call_command",
"with",
"work_in",
"(",
"application",
")",
":",
"if",
"DJANGO_1_11",
":",
"call_command",
"(",
"'compilemessages'",
",",
"all",
... | Compiles locale messages | [
"Compiles",
"locale",
"messages"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L99-L109 |
nephila/djangocms-helper | djangocms_helper/main.py | makemessages | def makemessages(application, locale):
"""
Updates the locale message files
"""
from django.core.management import call_command
if not locale:
locale = 'en'
with work_in(application):
call_command('makemessages', locale=(locale,)) | python | def makemessages(application, locale):
"""
Updates the locale message files
"""
from django.core.management import call_command
if not locale:
locale = 'en'
with work_in(application):
call_command('makemessages', locale=(locale,)) | [
"def",
"makemessages",
"(",
"application",
",",
"locale",
")",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"call_command",
"if",
"not",
"locale",
":",
"locale",
"=",
"'en'",
"with",
"work_in",
"(",
"application",
")",
":",
"call_command"... | Updates the locale message files | [
"Updates",
"the",
"locale",
"message",
"files"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L112-L121 |
nephila/djangocms-helper | djangocms_helper/main.py | cms_check | def cms_check(migrate_cmd=False):
"""
Runs the django CMS ``cms check`` command
"""
from django.core.management import call_command
try:
import cms # NOQA # nopyflakes
_create_db(migrate_cmd)
call_command('cms', 'check')
except ImportError:
print('cms_check avail... | python | def cms_check(migrate_cmd=False):
"""
Runs the django CMS ``cms check`` command
"""
from django.core.management import call_command
try:
import cms # NOQA # nopyflakes
_create_db(migrate_cmd)
call_command('cms', 'check')
except ImportError:
print('cms_check avail... | [
"def",
"cms_check",
"(",
"migrate_cmd",
"=",
"False",
")",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"call_command",
"try",
":",
"import",
"cms",
"# NOQA # nopyflakes",
"_create_db",
"(",
"migrate_cmd",
")",
"call_command",
"(",
"'cms'",
... | Runs the django CMS ``cms check`` command | [
"Runs",
"the",
"django",
"CMS",
"cms",
"check",
"command"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L124-L134 |
nephila/djangocms-helper | djangocms_helper/main.py | makemigrations | def makemigrations(application, merge=False, dry_run=False, empty=False, extra_applications=None):
"""
Generate migrations
"""
from django.core.management import call_command
apps = [application]
if extra_applications:
if isinstance(extra_applications, text_type):
apps += [e... | python | def makemigrations(application, merge=False, dry_run=False, empty=False, extra_applications=None):
"""
Generate migrations
"""
from django.core.management import call_command
apps = [application]
if extra_applications:
if isinstance(extra_applications, text_type):
apps += [e... | [
"def",
"makemigrations",
"(",
"application",
",",
"merge",
"=",
"False",
",",
"dry_run",
"=",
"False",
",",
"empty",
"=",
"False",
",",
"extra_applications",
"=",
"None",
")",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"call_command",
... | Generate migrations | [
"Generate",
"migrations"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L137-L151 |
nephila/djangocms-helper | djangocms_helper/main.py | generate_authors | def generate_authors():
"""
Updates the authors list
"""
print('Generating AUTHORS')
# Get our list of authors
print('Collecting author names')
r = subprocess.Popen(['git', 'log', '--use-mailmap', '--format=%aN'],
stdout=subprocess.PIPE)
seen_authors = []
au... | python | def generate_authors():
"""
Updates the authors list
"""
print('Generating AUTHORS')
# Get our list of authors
print('Collecting author names')
r = subprocess.Popen(['git', 'log', '--use-mailmap', '--format=%aN'],
stdout=subprocess.PIPE)
seen_authors = []
au... | [
"def",
"generate_authors",
"(",
")",
":",
"print",
"(",
"'Generating AUTHORS'",
")",
"# Get our list of authors",
"print",
"(",
"'Collecting author names'",
")",
"r",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'git'",
",",
"'log'",
",",
"'--use-mailmap'",
",",
... | Updates the authors list | [
"Updates",
"the",
"authors",
"list"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L154-L186 |
nephila/djangocms-helper | djangocms_helper/main.py | static_analisys | def static_analisys(application):
"""
Performs a pyflakes static analysis with the same configuration as
django CMS testsuite
"""
try:
from cms.test_utils.util.static_analysis import pyflakes
application_module = __import__(application)
report = pyflakes((application_module,)... | python | def static_analisys(application):
"""
Performs a pyflakes static analysis with the same configuration as
django CMS testsuite
"""
try:
from cms.test_utils.util.static_analysis import pyflakes
application_module = __import__(application)
report = pyflakes((application_module,)... | [
"def",
"static_analisys",
"(",
"application",
")",
":",
"try",
":",
"from",
"cms",
".",
"test_utils",
".",
"util",
".",
"static_analysis",
"import",
"pyflakes",
"application_module",
"=",
"__import__",
"(",
"application",
")",
"report",
"=",
"pyflakes",
"(",
"... | Performs a pyflakes static analysis with the same configuration as
django CMS testsuite | [
"Performs",
"a",
"pyflakes",
"static",
"analysis",
"with",
"the",
"same",
"configuration",
"as",
"django",
"CMS",
"testsuite"
] | train | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/main.py#L189-L203 |
julot/sphinxcontrib-dd | sphinxcontrib/dd/data_dictionary.py | Parser.setup_parse | def setup_parse(self, inputstring, document):
"""Initial parse setup. Call at start of `self.parse()`."""
self.inputstring = inputstring
self.document = document | python | def setup_parse(self, inputstring, document):
"""Initial parse setup. Call at start of `self.parse()`."""
self.inputstring = inputstring
self.document = document | [
"def",
"setup_parse",
"(",
"self",
",",
"inputstring",
",",
"document",
")",
":",
"self",
".",
"inputstring",
"=",
"inputstring",
"self",
".",
"document",
"=",
"document"
] | Initial parse setup. Call at start of `self.parse()`. | [
"Initial",
"parse",
"setup",
".",
"Call",
"at",
"start",
"of",
"self",
".",
"parse",
"()",
"."
] | train | https://github.com/julot/sphinxcontrib-dd/blob/18619b356508b9a99cc329eeae53cbf299a5d1de/sphinxcontrib/dd/data_dictionary.py#L19-L22 |
iotile/baBLE | tools/release.py | check_version | def check_version(expected_version):
""" Make sure the package version in setuptools matches what we expect it to be """
with open(os.path.join(root_folder, 'VERSION'), 'r') as version_file:
version = version_file.read().strip()
if version != expected_version:
raise EnvironmentError("Versi... | python | def check_version(expected_version):
""" Make sure the package version in setuptools matches what we expect it to be """
with open(os.path.join(root_folder, 'VERSION'), 'r') as version_file:
version = version_file.read().strip()
if version != expected_version:
raise EnvironmentError("Versi... | [
"def",
"check_version",
"(",
"expected_version",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root_folder",
",",
"'VERSION'",
")",
",",
"'r'",
")",
"as",
"version_file",
":",
"version",
"=",
"version_file",
".",
"read",
"(",
")",
... | Make sure the package version in setuptools matches what we expect it to be | [
"Make",
"sure",
"the",
"package",
"version",
"in",
"setuptools",
"matches",
"what",
"we",
"expect",
"it",
"to",
"be"
] | train | https://github.com/iotile/baBLE/blob/faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db/tools/release.py#L12-L20 |
iotile/baBLE | tools/release.py | build_wheel | def build_wheel(platform):
"""Create a wheel"""
if platform in ['x86_64', 'i686']:
system = 'manylinux1'
else:
system = 'linux'
setuptools.sandbox.run_setup(
'setup.py',
['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)]
) | python | def build_wheel(platform):
"""Create a wheel"""
if platform in ['x86_64', 'i686']:
system = 'manylinux1'
else:
system = 'linux'
setuptools.sandbox.run_setup(
'setup.py',
['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)]
) | [
"def",
"build_wheel",
"(",
"platform",
")",
":",
"if",
"platform",
"in",
"[",
"'x86_64'",
",",
"'i686'",
"]",
":",
"system",
"=",
"'manylinux1'",
"else",
":",
"system",
"=",
"'linux'",
"setuptools",
".",
"sandbox",
".",
"run_setup",
"(",
"'setup.py'",
",",... | Create a wheel | [
"Create",
"a",
"wheel"
] | train | https://github.com/iotile/baBLE/blob/faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db/tools/release.py#L23-L34 |
iotile/baBLE | tools/release.py | upload | def upload(dist_dir):
"""Upload a given component to pypi
The pypi username and password must either be specified in a ~/.pypirc file
or in environment variables PYPI_USER and PYPI_PASS
"""
if 'PYPI_USER' in os.environ and 'PYPI_PASS' in os.environ:
pypi_user = os.environ['PYPI_USER']
... | python | def upload(dist_dir):
"""Upload a given component to pypi
The pypi username and password must either be specified in a ~/.pypirc file
or in environment variables PYPI_USER and PYPI_PASS
"""
if 'PYPI_USER' in os.environ and 'PYPI_PASS' in os.environ:
pypi_user = os.environ['PYPI_USER']
... | [
"def",
"upload",
"(",
"dist_dir",
")",
":",
"if",
"'PYPI_USER'",
"in",
"os",
".",
"environ",
"and",
"'PYPI_PASS'",
"in",
"os",
".",
"environ",
":",
"pypi_user",
"=",
"os",
".",
"environ",
"[",
"'PYPI_USER'",
"]",
"pypi_pass",
"=",
"os",
".",
"environ",
... | Upload a given component to pypi
The pypi username and password must either be specified in a ~/.pypirc file
or in environment variables PYPI_USER and PYPI_PASS | [
"Upload",
"a",
"given",
"component",
"to",
"pypi",
"The",
"pypi",
"username",
"and",
"password",
"must",
"either",
"be",
"specified",
"in",
"a",
"~",
"/",
".",
"pypirc",
"file",
"or",
"in",
"environment",
"variables",
"PYPI_USER",
"and",
"PYPI_PASS"
] | train | https://github.com/iotile/baBLE/blob/faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db/tools/release.py#L43-L60 |
ClericPy/torequests | torequests/utils.py | simple_cmd | def simple_cmd():
"""
``Deprecated``: Not better than ``fire`` -> pip install fire
"""
parser = argparse.ArgumentParser(
prog="Simple command-line function toolkit.",
description="""Input function name and args and kwargs.
python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""",
)
... | python | def simple_cmd():
"""
``Deprecated``: Not better than ``fire`` -> pip install fire
"""
parser = argparse.ArgumentParser(
prog="Simple command-line function toolkit.",
description="""Input function name and args and kwargs.
python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""",
)
... | [
"def",
"simple_cmd",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"\"Simple command-line function toolkit.\"",
",",
"description",
"=",
"\"\"\"Input function name and args and kwargs.\n python xxx.py main -a 1 2 3 -k a=1,b=2,c=3\"\"\"",
... | ``Deprecated``: Not better than ``fire`` -> pip install fire | [
"Deprecated",
":",
"Not",
"better",
"than",
"fire",
"-",
">",
"pip",
"install",
"fire"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L68-L107 |
ClericPy/torequests | torequests/utils.py | print_mem | def print_mem(unit="MB"):
"""Show the proc-mem-cost with psutil, use this only for lazinesssss.
:param unit: B, KB, MB, GB.
"""
try:
import psutil
B = float(psutil.Process(os.getpid()).memory_info().vms)
KB = B / 1024
MB = KB / 1024
GB = MB / 1024
result... | python | def print_mem(unit="MB"):
"""Show the proc-mem-cost with psutil, use this only for lazinesssss.
:param unit: B, KB, MB, GB.
"""
try:
import psutil
B = float(psutil.Process(os.getpid()).memory_info().vms)
KB = B / 1024
MB = KB / 1024
GB = MB / 1024
result... | [
"def",
"print_mem",
"(",
"unit",
"=",
"\"MB\"",
")",
":",
"try",
":",
"import",
"psutil",
"B",
"=",
"float",
"(",
"psutil",
".",
"Process",
"(",
"os",
".",
"getpid",
"(",
")",
")",
".",
"memory_info",
"(",
")",
".",
"vms",
")",
"KB",
"=",
"B",
... | Show the proc-mem-cost with psutil, use this only for lazinesssss.
:param unit: B, KB, MB, GB. | [
"Show",
"the",
"proc",
"-",
"mem",
"-",
"cost",
"with",
"psutil",
"use",
"this",
"only",
"for",
"lazinesssss",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L110-L126 |
ClericPy/torequests | torequests/utils.py | curlparse | def curlparse(string, encoding="utf-8"):
"""Translate curl-string into dict of request.
:param string: standard curl-string, like `r'''curl ...'''`.
:param encoding: encoding for post-data encoding.
Basic Usage::
>>> from torequests.utils import curlparse
>>> curl_string = '''curl ... | python | def curlparse(string, encoding="utf-8"):
"""Translate curl-string into dict of request.
:param string: standard curl-string, like `r'''curl ...'''`.
:param encoding: encoding for post-data encoding.
Basic Usage::
>>> from torequests.utils import curlparse
>>> curl_string = '''curl ... | [
"def",
"curlparse",
"(",
"string",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"assert",
"\"\\n\"",
"not",
"in",
"string",
",",
"'curl-string should not contain \\\\n, try r\"...\".'",
"if",
"string",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"return",
"{",
... | Translate curl-string into dict of request.
:param string: standard curl-string, like `r'''curl ...'''`.
:param encoding: encoding for post-data encoding.
Basic Usage::
>>> from torequests.utils import curlparse
>>> curl_string = '''curl 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0' -H ... | [
"Translate",
"curl",
"-",
"string",
"into",
"dict",
"of",
"request",
".",
":",
"param",
"string",
":",
"standard",
"curl",
"-",
"string",
"like",
"r",
"curl",
"...",
".",
":",
"param",
"encoding",
":",
"encoding",
"for",
"post",
"-",
"data",
"encoding",
... | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L150-L203 |
ClericPy/torequests | torequests/utils.py | slice_into_pieces | def slice_into_pieces(seq, n):
"""Slice a sequence into `n` pieces, return a generation of n pieces"""
length = len(seq)
if length % n == 0:
size = length // n
else:
size = length // n + 1
for it in slice_by_size(seq, size):
yield it | python | def slice_into_pieces(seq, n):
"""Slice a sequence into `n` pieces, return a generation of n pieces"""
length = len(seq)
if length % n == 0:
size = length // n
else:
size = length // n + 1
for it in slice_by_size(seq, size):
yield it | [
"def",
"slice_into_pieces",
"(",
"seq",
",",
"n",
")",
":",
"length",
"=",
"len",
"(",
"seq",
")",
"if",
"length",
"%",
"n",
"==",
"0",
":",
"size",
"=",
"length",
"//",
"n",
"else",
":",
"size",
"=",
"length",
"//",
"n",
"+",
"1",
"for",
"it",... | Slice a sequence into `n` pieces, return a generation of n pieces | [
"Slice",
"a",
"sequence",
"into",
"n",
"pieces",
"return",
"a",
"generation",
"of",
"n",
"pieces"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L250-L258 |
ClericPy/torequests | torequests/utils.py | slice_by_size | def slice_by_size(seq, size):
"""Slice a sequence into chunks, return as a generation of chunks with `size`."""
filling = null
for it in zip(*(itertools_chain(seq, [filling] * size),) * size):
if filling in it:
it = tuple(i for i in it if i is not filling)
if it:
yiel... | python | def slice_by_size(seq, size):
"""Slice a sequence into chunks, return as a generation of chunks with `size`."""
filling = null
for it in zip(*(itertools_chain(seq, [filling] * size),) * size):
if filling in it:
it = tuple(i for i in it if i is not filling)
if it:
yiel... | [
"def",
"slice_by_size",
"(",
"seq",
",",
"size",
")",
":",
"filling",
"=",
"null",
"for",
"it",
"in",
"zip",
"(",
"*",
"(",
"itertools_chain",
"(",
"seq",
",",
"[",
"filling",
"]",
"*",
"size",
")",
",",
")",
"*",
"size",
")",
":",
"if",
"filling... | Slice a sequence into chunks, return as a generation of chunks with `size`. | [
"Slice",
"a",
"sequence",
"into",
"chunks",
"return",
"as",
"a",
"generation",
"of",
"chunks",
"with",
"size",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L261-L268 |
ClericPy/torequests | torequests/utils.py | ttime | def ttime(timestamp=None, tzone=None, fail="", fmt="%Y-%m-%d %H:%M:%S"):
"""Translate timestamp into human-readable: %Y-%m-%d %H:%M:%S.
:param timestamp: the timestamp float, or `time.time()` by default.
:param tzone: time compensation, int(-time.timezone / 3600) by default,
(can be set wit... | python | def ttime(timestamp=None, tzone=None, fail="", fmt="%Y-%m-%d %H:%M:%S"):
"""Translate timestamp into human-readable: %Y-%m-%d %H:%M:%S.
:param timestamp: the timestamp float, or `time.time()` by default.
:param tzone: time compensation, int(-time.timezone / 3600) by default,
(can be set wit... | [
"def",
"ttime",
"(",
"timestamp",
"=",
"None",
",",
"tzone",
"=",
"None",
",",
"fail",
"=",
"\"\"",
",",
"fmt",
"=",
"\"%Y-%m-%d %H:%M:%S\"",
")",
":",
"tzone",
"=",
"Config",
".",
"TIMEZONE",
"if",
"tzone",
"is",
"None",
"else",
"tzone",
"fix_tz",
"="... | Translate timestamp into human-readable: %Y-%m-%d %H:%M:%S.
:param timestamp: the timestamp float, or `time.time()` by default.
:param tzone: time compensation, int(-time.timezone / 3600) by default,
(can be set with Config.TIMEZONE).
:param fail: while raising an exception, return it.
... | [
"Translate",
"timestamp",
"into",
"human",
"-",
"readable",
":",
"%Y",
"-",
"%m",
"-",
"%d",
"%H",
":",
"%M",
":",
"%S",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L271-L302 |
ClericPy/torequests | torequests/utils.py | ptime | def ptime(timestr=None, tzone=None, fail=0, fmt="%Y-%m-%d %H:%M:%S"):
"""Translate %Y-%m-%d %H:%M:%S into timestamp.
:param timestr: string like 2018-03-15 01:27:56, or time.time() if not set.
:param tzone: time compensation, int(-time.timezone / 3600) by default,
(can be set with Config.TI... | python | def ptime(timestr=None, tzone=None, fail=0, fmt="%Y-%m-%d %H:%M:%S"):
"""Translate %Y-%m-%d %H:%M:%S into timestamp.
:param timestr: string like 2018-03-15 01:27:56, or time.time() if not set.
:param tzone: time compensation, int(-time.timezone / 3600) by default,
(can be set with Config.TI... | [
"def",
"ptime",
"(",
"timestr",
"=",
"None",
",",
"tzone",
"=",
"None",
",",
"fail",
"=",
"0",
",",
"fmt",
"=",
"\"%Y-%m-%d %H:%M:%S\"",
")",
":",
"tzone",
"=",
"Config",
".",
"TIMEZONE",
"if",
"tzone",
"is",
"None",
"else",
"tzone",
"fix_tz",
"=",
"... | Translate %Y-%m-%d %H:%M:%S into timestamp.
:param timestr: string like 2018-03-15 01:27:56, or time.time() if not set.
:param tzone: time compensation, int(-time.timezone / 3600) by default,
(can be set with Config.TIMEZONE).
:param fail: while raising an exception, return it.
:param f... | [
"Translate",
"%Y",
"-",
"%m",
"-",
"%d",
"%H",
":",
"%M",
":",
"%S",
"into",
"timestamp",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L305-L325 |
ClericPy/torequests | torequests/utils.py | split_seconds | def split_seconds(seconds):
"""Split seconds into [day, hour, minute, second, ms]
`divisor: 1, 24, 60, 60, 1000`
`units: day, hour, minute, second, ms`
>>> split_seconds(6666666)
[77, 3, 51, 6, 0]
"""
ms = seconds * 1000
divisors = (1, 24, 60, 60, 1000)
quotient, result = ... | python | def split_seconds(seconds):
"""Split seconds into [day, hour, minute, second, ms]
`divisor: 1, 24, 60, 60, 1000`
`units: day, hour, minute, second, ms`
>>> split_seconds(6666666)
[77, 3, 51, 6, 0]
"""
ms = seconds * 1000
divisors = (1, 24, 60, 60, 1000)
quotient, result = ... | [
"def",
"split_seconds",
"(",
"seconds",
")",
":",
"ms",
"=",
"seconds",
"*",
"1000",
"divisors",
"=",
"(",
"1",
",",
"24",
",",
"60",
",",
"60",
",",
"1000",
")",
"quotient",
",",
"result",
"=",
"ms",
",",
"[",
"]",
"for",
"divisor",
"in",
"divis... | Split seconds into [day, hour, minute, second, ms]
`divisor: 1, 24, 60, 60, 1000`
`units: day, hour, minute, second, ms`
>>> split_seconds(6666666)
[77, 3, 51, 6, 0] | [
"Split",
"seconds",
"into",
"[",
"day",
"hour",
"minute",
"second",
"ms",
"]"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L328-L344 |
ClericPy/torequests | torequests/utils.py | timeago | def timeago(seconds=0, accuracy=4, format=0, lang="en"):
"""Translate seconds into human-readable.
:param seconds: seconds (float/int).
:param accuracy: 4 by default (units[:accuracy]), determine the length of elements.
:param format: index of [led, literal, dict].
:param lang: en o... | python | def timeago(seconds=0, accuracy=4, format=0, lang="en"):
"""Translate seconds into human-readable.
:param seconds: seconds (float/int).
:param accuracy: 4 by default (units[:accuracy]), determine the length of elements.
:param format: index of [led, literal, dict].
:param lang: en o... | [
"def",
"timeago",
"(",
"seconds",
"=",
"0",
",",
"accuracy",
"=",
"4",
",",
"format",
"=",
"0",
",",
"lang",
"=",
"\"en\"",
")",
":",
"assert",
"format",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
",",
"ValueError",
"(",
"\"format arg should be one of ... | Translate seconds into human-readable.
:param seconds: seconds (float/int).
:param accuracy: 4 by default (units[:accuracy]), determine the length of elements.
:param format: index of [led, literal, dict].
:param lang: en or cn.
:param units: day, hour, minute, second, ms.
... | [
"Translate",
"seconds",
"into",
"human",
"-",
"readable",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L347-L401 |
ClericPy/torequests | torequests/utils.py | md5 | def md5(string, n=32, encoding="utf-8", skip_encode=False):
"""str(obj) -> md5_string
:param string: string to operate.
:param n: md5_str length.
>>> from torequests.utils import md5
>>> md5(1, 10)
'923820dcc5'
>>> md5('test')
'098f6bcd4621d373cade4e832627b4f6'
"""
todo = strin... | python | def md5(string, n=32, encoding="utf-8", skip_encode=False):
"""str(obj) -> md5_string
:param string: string to operate.
:param n: md5_str length.
>>> from torequests.utils import md5
>>> md5(1, 10)
'923820dcc5'
>>> md5('test')
'098f6bcd4621d373cade4e832627b4f6'
"""
todo = strin... | [
"def",
"md5",
"(",
"string",
",",
"n",
"=",
"32",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"skip_encode",
"=",
"False",
")",
":",
"todo",
"=",
"string",
"if",
"skip_encode",
"else",
"unicode",
"(",
"string",
")",
".",
"encode",
"(",
"encoding",
")",
"... | str(obj) -> md5_string
:param string: string to operate.
:param n: md5_str length.
>>> from torequests.utils import md5
>>> md5(1, 10)
'923820dcc5'
>>> md5('test')
'098f6bcd4621d373cade4e832627b4f6' | [
"str",
"(",
"obj",
")",
"-",
">",
"md5_string"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L408-L426 |
ClericPy/torequests | torequests/utils.py | unique | def unique(seq, key=None, return_as=None):
"""Unique the seq and keep the order.
Instead of the slow way:
`lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)`
:param seq: raw sequence.
:param return_as: generator for default, or list / set / str...
>>> from torequests.u... | python | def unique(seq, key=None, return_as=None):
"""Unique the seq and keep the order.
Instead of the slow way:
`lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)`
:param seq: raw sequence.
:param return_as: generator for default, or list / set / str...
>>> from torequests.u... | [
"def",
"unique",
"(",
"seq",
",",
"key",
"=",
"None",
",",
"return_as",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"add",
"=",
"seen",
".",
"add",
"if",
"key",
":",
"generator",
"=",
"(",
"x",
"for",
"x",
"in",
"seq",
"if",
"key",
"... | Unique the seq and keep the order.
Instead of the slow way:
`lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)`
:param seq: raw sequence.
:param return_as: generator for default, or list / set / str...
>>> from torequests.utils import unique
>>> a = [1,2,3,4,2,3,4]
... | [
"Unique",
"the",
"seq",
"and",
"keep",
"the",
"order",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L482-L513 |
ClericPy/torequests | torequests/utils.py | unparse_qs | def unparse_qs(qs, sort=False, reverse=False):
"""Reverse conversion for parse_qs"""
result = []
items = qs.items()
if sort:
items = sorted(items, key=lambda x: x[0], reverse=reverse)
for keys, values in items:
query_name = quote(keys)
for value in values:
result.... | python | def unparse_qs(qs, sort=False, reverse=False):
"""Reverse conversion for parse_qs"""
result = []
items = qs.items()
if sort:
items = sorted(items, key=lambda x: x[0], reverse=reverse)
for keys, values in items:
query_name = quote(keys)
for value in values:
result.... | [
"def",
"unparse_qs",
"(",
"qs",
",",
"sort",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"items",
"=",
"qs",
".",
"items",
"(",
")",
"if",
"sort",
":",
"items",
"=",
"sorted",
"(",
"items",
",",
"key",
"=",
"l... | Reverse conversion for parse_qs | [
"Reverse",
"conversion",
"for",
"parse_qs"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L516-L526 |
ClericPy/torequests | torequests/utils.py | unparse_qsl | def unparse_qsl(qsl, sort=False, reverse=False):
"""Reverse conversion for parse_qsl"""
result = []
items = qsl
if sort:
items = sorted(items, key=lambda x: x[0], reverse=reverse)
for keys, values in items:
query_name = quote(keys)
result.append(query_name + "=" + quote(value... | python | def unparse_qsl(qsl, sort=False, reverse=False):
"""Reverse conversion for parse_qsl"""
result = []
items = qsl
if sort:
items = sorted(items, key=lambda x: x[0], reverse=reverse)
for keys, values in items:
query_name = quote(keys)
result.append(query_name + "=" + quote(value... | [
"def",
"unparse_qsl",
"(",
"qsl",
",",
"sort",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"items",
"=",
"qsl",
"if",
"sort",
":",
"items",
"=",
"sorted",
"(",
"items",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
... | Reverse conversion for parse_qsl | [
"Reverse",
"conversion",
"for",
"parse_qsl"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L529-L538 |
ClericPy/torequests | torequests/utils.py | kill_after | def kill_after(seconds, timeout=2):
"""Kill self after seconds"""
pid = os.getpid()
kill = os.kill
run_after_async(seconds, kill, pid, signal.SIGTERM)
run_after_async(seconds + timeout, kill, pid, 9) | python | def kill_after(seconds, timeout=2):
"""Kill self after seconds"""
pid = os.getpid()
kill = os.kill
run_after_async(seconds, kill, pid, signal.SIGTERM)
run_after_async(seconds + timeout, kill, pid, 9) | [
"def",
"kill_after",
"(",
"seconds",
",",
"timeout",
"=",
"2",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"kill",
"=",
"os",
".",
"kill",
"run_after_async",
"(",
"seconds",
",",
"kill",
",",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"run... | Kill self after seconds | [
"Kill",
"self",
"after",
"seconds"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L682-L687 |
ClericPy/torequests | torequests/utils.py | try_import | def try_import(module_name, names=None, default=ImportErrorModule, warn=True):
"""Try import module_name, except ImportError and return default,
sometimes to be used for catch ImportError and lazy-import.
"""
try:
module = importlib.import_module(module_name)
except ImportError:
... | python | def try_import(module_name, names=None, default=ImportErrorModule, warn=True):
"""Try import module_name, except ImportError and return default,
sometimes to be used for catch ImportError and lazy-import.
"""
try:
module = importlib.import_module(module_name)
except ImportError:
... | [
"def",
"try_import",
"(",
"module_name",
",",
"names",
"=",
"None",
",",
"default",
"=",
"ImportErrorModule",
",",
"warn",
"=",
"True",
")",
":",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"except",
"ImportError",
... | Try import module_name, except ImportError and return default,
sometimes to be used for catch ImportError and lazy-import. | [
"Try",
"import",
"module_name",
"except",
"ImportError",
"and",
"return",
"default",
"sometimes",
"to",
"be",
"used",
"for",
"catch",
"ImportError",
"and",
"lazy",
"-",
"import",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L709-L741 |
ClericPy/torequests | torequests/utils.py | ensure_request | def ensure_request(request):
"""Used for requests.request / Requests.request with **ensure_request(request)
:param request: dict or curl-string or url
>>> from torequests.utils import ensure_request
>>> ensure_request('''curl http://test.com''')
{'url': 'http://test.com', 'method': 'get'}
>>> e... | python | def ensure_request(request):
"""Used for requests.request / Requests.request with **ensure_request(request)
:param request: dict or curl-string or url
>>> from torequests.utils import ensure_request
>>> ensure_request('''curl http://test.com''')
{'url': 'http://test.com', 'method': 'get'}
>>> e... | [
"def",
"ensure_request",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"request",
",",
"dict",
")",
":",
"result",
"=",
"request",
"elif",
"isinstance",
"(",
"request",
",",
"(",
"unicode",
",",
"str",
")",
")",
":",
"request",
"=",
"request",
"."... | Used for requests.request / Requests.request with **ensure_request(request)
:param request: dict or curl-string or url
>>> from torequests.utils import ensure_request
>>> ensure_request('''curl http://test.com''')
{'url': 'http://test.com', 'method': 'get'}
>>> ensure_request('http://test.com')
... | [
"Used",
"for",
"requests",
".",
"request",
"/",
"Requests",
".",
"request",
"with",
"**",
"ensure_request",
"(",
"request",
")",
":",
"param",
"request",
":",
"dict",
"or",
"curl",
"-",
"string",
"or",
"url"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L744-L770 |
ClericPy/torequests | torequests/utils.py | ensure_dict_key_title | def ensure_dict_key_title(dict_obj):
"""Set the dict key as key.title(); keys should be str.
Always be used to headers.
>>> from torequests.utils import ensure_dict_key_title
>>> ensure_dict_key_title({'hello-world':1, 'HELLOWORLD':2})
{'Hello-World': 1, 'Helloworld': 2}
"""
if ... | python | def ensure_dict_key_title(dict_obj):
"""Set the dict key as key.title(); keys should be str.
Always be used to headers.
>>> from torequests.utils import ensure_dict_key_title
>>> ensure_dict_key_title({'hello-world':1, 'HELLOWORLD':2})
{'Hello-World': 1, 'Helloworld': 2}
"""
if ... | [
"def",
"ensure_dict_key_title",
"(",
"dict_obj",
")",
":",
"if",
"not",
"all",
"(",
"(",
"isinstance",
"(",
"i",
",",
"unicode",
")",
"for",
"i",
"in",
"dict_obj",
".",
"keys",
"(",
")",
")",
")",
":",
"return",
"dict_obj",
"return",
"{",
"key",
".",... | Set the dict key as key.title(); keys should be str.
Always be used to headers.
>>> from torequests.utils import ensure_dict_key_title
>>> ensure_dict_key_title({'hello-world':1, 'HELLOWORLD':2})
{'Hello-World': 1, 'Helloworld': 2} | [
"Set",
"the",
"dict",
"key",
"as",
"key",
".",
"title",
"()",
";",
"keys",
"should",
"be",
"str",
".",
"Always",
"be",
"used",
"to",
"headers",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L929-L939 |
ClericPy/torequests | torequests/utils.py | guess_interval | def guess_interval(nums, accuracy=0):
"""Given a seq of number, return the median, only calculate interval >= accuracy.
::
from torequests.utils import guess_interval
import random
seq = [random.randint(1, 100) for i in range(20)]
print(guess_interval(seq, 5))
# sorted... | python | def guess_interval(nums, accuracy=0):
"""Given a seq of number, return the median, only calculate interval >= accuracy.
::
from torequests.utils import guess_interval
import random
seq = [random.randint(1, 100) for i in range(20)]
print(guess_interval(seq, 5))
# sorted... | [
"def",
"guess_interval",
"(",
"nums",
",",
"accuracy",
"=",
"0",
")",
":",
"if",
"not",
"nums",
":",
"return",
"0",
"nums",
"=",
"sorted",
"(",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"nums",
"]",
")",
"if",
"len",
"(",
"nums",
")",
"==",
... | Given a seq of number, return the median, only calculate interval >= accuracy.
::
from torequests.utils import guess_interval
import random
seq = [random.randint(1, 100) for i in range(20)]
print(guess_interval(seq, 5))
# sorted_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40,... | [
"Given",
"a",
"seq",
"of",
"number",
"return",
"the",
"median",
"only",
"calculate",
"interval",
">",
"=",
"accuracy",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1211-L1234 |
ClericPy/torequests | torequests/utils.py | split_n | def split_n(string, seps, reg=False):
r"""Split strings into n-dimensional list.
::
from torequests.utils import split_n
ss = '''a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6'''
print(split_n(ss, ('\n', ' ', ' ')))
# [[['a',... | python | def split_n(string, seps, reg=False):
r"""Split strings into n-dimensional list.
::
from torequests.utils import split_n
ss = '''a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6'''
print(split_n(ss, ('\n', ' ', ' ')))
# [[['a',... | [
"def",
"split_n",
"(",
"string",
",",
"seps",
",",
"reg",
"=",
"False",
")",
":",
"deep",
"=",
"len",
"(",
"seps",
")",
"if",
"not",
"deep",
":",
"return",
"string",
"return",
"[",
"split_n",
"(",
"i",
",",
"seps",
"[",
"1",
":",
"]",
")",
"for... | r"""Split strings into n-dimensional list.
::
from torequests.utils import split_n
ss = '''a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6'''
print(split_n(ss, ('\n', ' ', ' ')))
# [[['a', 'b', 'c'], ['d', 'e', 'f'], ['1', '2', '3... | [
"r",
"Split",
"strings",
"into",
"n",
"-",
"dimensional",
"list",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1244-L1263 |
ClericPy/torequests | torequests/utils.py | bg | def bg(func):
"""Run a function in background, will not block main thread's exit.(thread.daemon=True)
::
from torequests.utils import bg, print_info
import time
def test1(n):
time.sleep(n)
print_info(n, 'done')
@bg
def test2(n):
time... | python | def bg(func):
"""Run a function in background, will not block main thread's exit.(thread.daemon=True)
::
from torequests.utils import bg, print_info
import time
def test1(n):
time.sleep(n)
print_info(n, 'done')
@bg
def test2(n):
time... | [
"def",
"bg",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
... | Run a function in background, will not block main thread's exit.(thread.daemon=True)
::
from torequests.utils import bg, print_info
import time
def test1(n):
time.sleep(n)
print_info(n, 'done')
@bg
def test2(n):
time.sleep(n)
... | [
"Run",
"a",
"function",
"in",
"background",
"will",
"not",
"block",
"main",
"thread",
"s",
"exit",
".",
"(",
"thread",
".",
"daemon",
"=",
"True",
")",
"::"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1266-L1301 |
ClericPy/torequests | torequests/utils.py | countdown | def countdown(
seconds=None,
block=True,
interval=1,
daemon=True,
tick_callback=None,
finish_callback=None,
):
"""Run a countdown function to wait something, similar to threading.Timer,
but will show the detail tick by tick_callback.
::
from torequests.utils import countdo... | python | def countdown(
seconds=None,
block=True,
interval=1,
daemon=True,
tick_callback=None,
finish_callback=None,
):
"""Run a countdown function to wait something, similar to threading.Timer,
but will show the detail tick by tick_callback.
::
from torequests.utils import countdo... | [
"def",
"countdown",
"(",
"seconds",
"=",
"None",
",",
"block",
"=",
"True",
",",
"interval",
"=",
"1",
",",
"daemon",
"=",
"True",
",",
"tick_callback",
"=",
"None",
",",
"finish_callback",
"=",
"None",
",",
")",
":",
"def",
"default_tick_callback",
"(",... | Run a countdown function to wait something, similar to threading.Timer,
but will show the detail tick by tick_callback.
::
from torequests.utils import countdown
countdown(3)
# 3 2 1
# countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58.
countd... | [
"Run",
"a",
"countdown",
"function",
"to",
"wait",
"something",
"similar",
"to",
"threading",
".",
"Timer",
"but",
"will",
"show",
"the",
"detail",
"tick",
"by",
"tick_callback",
".",
"::"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1304-L1353 |
ClericPy/torequests | torequests/utils.py | flush_print | def flush_print(*args, **kwargs):
"""
Like print_function at python3, support flush, but not support file.
:param sep: space by default
:param end: '\\n' by default
:param flush: True by default
::
import time
from torequests.utils import flush_print
flush_print("=" *... | python | def flush_print(*args, **kwargs):
"""
Like print_function at python3, support flush, but not support file.
:param sep: space by default
:param end: '\\n' by default
:param flush: True by default
::
import time
from torequests.utils import flush_print
flush_print("=" *... | [
"def",
"flush_print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# PY2 raise SyntaxError for : def flush_print(*args, sep='', end=''):",
"sep",
",",
"end",
",",
"flush",
"=",
"(",
"kwargs",
".",
"pop",
"(",
"\"sep\"",
",",
"\" \"",
")",
",",
"kwargs... | Like print_function at python3, support flush, but not support file.
:param sep: space by default
:param end: '\\n' by default
:param flush: True by default
::
import time
from torequests.utils import flush_print
flush_print("=" * 10)
for _ in range(10):
t... | [
"Like",
"print_function",
"at",
"python3",
"support",
"flush",
"but",
"not",
"support",
"file",
".",
":",
"param",
"sep",
":",
"space",
"by",
"default",
":",
"param",
"end",
":",
"\\\\",
"n",
"by",
"default",
":",
"param",
"flush",
":",
"True",
"by",
"... | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1356-L1382 |
ClericPy/torequests | torequests/utils.py | curlrequests | def curlrequests(curl_string, **kwargs):
"""Use tPool to request for curl string.
If kwargs contains the req which hasattr request method, like req=requests.
:param curl_string: standard curl string.
:type curl_string: str
:param kwargs: valid kwargs for tPool.
:type curl_string: dict
Basi... | python | def curlrequests(curl_string, **kwargs):
"""Use tPool to request for curl string.
If kwargs contains the req which hasattr request method, like req=requests.
:param curl_string: standard curl string.
:type curl_string: str
:param kwargs: valid kwargs for tPool.
:type curl_string: dict
Basi... | [
"def",
"curlrequests",
"(",
"curl_string",
",",
"*",
"*",
"kwargs",
")",
":",
"req",
"=",
"kwargs",
".",
"pop",
"(",
"'req'",
",",
"tPool",
"(",
")",
")",
"kwargs",
".",
"update",
"(",
"curlparse",
"(",
"curl_string",
")",
")",
"return",
"req",
".",
... | Use tPool to request for curl string.
If kwargs contains the req which hasattr request method, like req=requests.
:param curl_string: standard curl string.
:type curl_string: str
:param kwargs: valid kwargs for tPool.
:type curl_string: dict
Basic Usage::
from torequests.utils import ... | [
"Use",
"tPool",
"to",
"request",
"for",
"curl",
"string",
".",
"If",
"kwargs",
"contains",
"the",
"req",
"which",
"hasattr",
"request",
"method",
"like",
"req",
"=",
"requests",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1621-L1640 |
ClericPy/torequests | torequests/utils.py | Regex.register | def register(self, patterns, obj=None, instances=None, **reg_kwargs):
"""Register one object which can be matched/searched by regex.
:param patterns: a list/tuple/set of regex-pattern.
:param obj: return it while search/match success.
:param instances: instance list will search/match th... | python | def register(self, patterns, obj=None, instances=None, **reg_kwargs):
"""Register one object which can be matched/searched by regex.
:param patterns: a list/tuple/set of regex-pattern.
:param obj: return it while search/match success.
:param instances: instance list will search/match th... | [
"def",
"register",
"(",
"self",
",",
"patterns",
",",
"obj",
"=",
"None",
",",
"instances",
"=",
"None",
",",
"*",
"*",
"reg_kwargs",
")",
":",
"assert",
"obj",
",",
"\"bool(obj) should be True.\"",
"patterns",
"=",
"patterns",
"if",
"isinstance",
"(",
"pa... | Register one object which can be matched/searched by regex.
:param patterns: a list/tuple/set of regex-pattern.
:param obj: return it while search/match success.
:param instances: instance list will search/match the patterns.
:param reg_kwargs: kwargs for re.compile. | [
"Register",
"one",
"object",
"which",
"can",
"be",
"matched",
"/",
"searched",
"by",
"regex",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L577-L605 |
ClericPy/torequests | torequests/utils.py | Regex.register_function | def register_function(self, patterns, instances=None, **reg_kwargs):
"""Decorator for register."""
def wrapper(function):
self.register(patterns, function, instances=instances, **reg_kwargs)
return function
return wrapper | python | def register_function(self, patterns, instances=None, **reg_kwargs):
"""Decorator for register."""
def wrapper(function):
self.register(patterns, function, instances=instances, **reg_kwargs)
return function
return wrapper | [
"def",
"register_function",
"(",
"self",
",",
"patterns",
",",
"instances",
"=",
"None",
",",
"*",
"*",
"reg_kwargs",
")",
":",
"def",
"wrapper",
"(",
"function",
")",
":",
"self",
".",
"register",
"(",
"patterns",
",",
"function",
",",
"instances",
"=",... | Decorator for register. | [
"Decorator",
"for",
"register",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L607-L614 |
ClericPy/torequests | torequests/utils.py | Regex.find | def find(self, string, default=None):
"""Return match or search result.
:rtype: list"""
return self.match(string) or self.search(string) or default | python | def find(self, string, default=None):
"""Return match or search result.
:rtype: list"""
return self.match(string) or self.search(string) or default | [
"def",
"find",
"(",
"self",
",",
"string",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"match",
"(",
"string",
")",
"or",
"self",
".",
"search",
"(",
"string",
")",
"or",
"default"
] | Return match or search result.
:rtype: list | [
"Return",
"match",
"or",
"search",
"result",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L616-L620 |
ClericPy/torequests | torequests/utils.py | Regex.search | def search(self, string, default=None):
"""Use re.search to find the result
:rtype: list"""
default = default if default else []
result = [item[1] for item in self.container if item[0].search(string)]
if self.ensure_mapping:
assert len(result) < 2, "%s matches more t... | python | def search(self, string, default=None):
"""Use re.search to find the result
:rtype: list"""
default = default if default else []
result = [item[1] for item in self.container if item[0].search(string)]
if self.ensure_mapping:
assert len(result) < 2, "%s matches more t... | [
"def",
"search",
"(",
"self",
",",
"string",
",",
"default",
"=",
"None",
")",
":",
"default",
"=",
"default",
"if",
"default",
"else",
"[",
"]",
"result",
"=",
"[",
"item",
"[",
"1",
"]",
"for",
"item",
"in",
"self",
".",
"container",
"if",
"item"... | Use re.search to find the result
:rtype: list | [
"Use",
"re",
".",
"search",
"to",
"find",
"the",
"result"
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L622-L633 |
ClericPy/torequests | torequests/utils.py | Regex.fuzzy | def fuzzy(self, key, limit=5):
"""Give suggestion from all instances."""
instances = [i[2] for i in self.container if i[2]]
if not instances:
return
instances = sum(instances, [])
from fuzzywuzzy import process
maybe = process.extract(key, instances, limit=li... | python | def fuzzy(self, key, limit=5):
"""Give suggestion from all instances."""
instances = [i[2] for i in self.container if i[2]]
if not instances:
return
instances = sum(instances, [])
from fuzzywuzzy import process
maybe = process.extract(key, instances, limit=li... | [
"def",
"fuzzy",
"(",
"self",
",",
"key",
",",
"limit",
"=",
"5",
")",
":",
"instances",
"=",
"[",
"i",
"[",
"2",
"]",
"for",
"i",
"in",
"self",
".",
"container",
"if",
"i",
"[",
"2",
"]",
"]",
"if",
"not",
"instances",
":",
"return",
"instances... | Give suggestion from all instances. | [
"Give",
"suggestion",
"from",
"all",
"instances",
"."
] | train | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L648-L657 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.