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
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 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 self.is_lob_parameter(routine['parameters']):
return self._write_routine_method_with_lob(routine)
else:
return self._write_routine_method_without_lob(routine) | 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 self.is_lob_parameter(routine['parameters']):
return self._write_routine_method_with_lob(routine)
else:
return self._write_routine_method_without_lob(routine) | [
"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",
"(",
"routine",
"[",
"'parameters'",
"]",
")",
":",
"return",
"self",
".",
"_write_routine_method_with_lob",
"(",
"routine",
")",
"else",
":",
"return",
"self",
".",
"_write_routine_method_without_lob",
"(",
"routine",
")"
] | 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('')
for param in routine['pydoc']['parameters']:
lines = param['description'].split(os.linesep)
self._write_line(':param {0} {1}: {2}'.format(param['python_type'],
param['parameter_name'],
lines[0]))
del lines[0]
tmp = ':param {0} {1}:'.format(param['python_type'], param['parameter_name'])
indent = ' ' * len(tmp)
for line in lines:
self._write_line('{0} {1}'.format(indent, line))
self._write_line('{0} {1}'.format(indent, param['data_type_descriptor'])) | 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('')
for param in routine['pydoc']['parameters']:
lines = param['description'].split(os.linesep)
self._write_line(':param {0} {1}: {2}'.format(param['python_type'],
param['parameter_name'],
lines[0]))
del lines[0]
tmp = ':param {0} {1}:'.format(param['python_type'], param['parameter_name'])
indent = ' ' * len(tmp)
for line in lines:
self._write_line('{0} {1}'.format(indent, line))
self._write_line('{0} {1}'.format(indent, param['data_type_descriptor'])) | [
"def",
"_write_docstring_parameters",
"(",
"self",
",",
"routine",
")",
":",
"if",
"routine",
"[",
"'pydoc'",
"]",
"[",
"'parameters'",
"]",
":",
"self",
".",
"_write_line",
"(",
"''",
")",
"for",
"param",
"in",
"routine",
"[",
"'pydoc'",
"]",
"[",
"'parameters'",
"]",
":",
"lines",
"=",
"param",
"[",
"'description'",
"]",
".",
"split",
"(",
"os",
".",
"linesep",
")",
"self",
".",
"_write_line",
"(",
"':param {0} {1}: {2}'",
".",
"format",
"(",
"param",
"[",
"'python_type'",
"]",
",",
"param",
"[",
"'parameter_name'",
"]",
",",
"lines",
"[",
"0",
"]",
")",
")",
"del",
"lines",
"[",
"0",
"]",
"tmp",
"=",
"':param {0} {1}:'",
".",
"format",
"(",
"param",
"[",
"'python_type'",
"]",
",",
"param",
"[",
"'parameter_name'",
"]",
")",
"indent",
"=",
"' '",
"*",
"len",
"(",
"tmp",
")",
"for",
"line",
"in",
"lines",
":",
"self",
".",
"_write_line",
"(",
"'{0} {1}'",
".",
"format",
"(",
"indent",
",",
"line",
")",
")",
"self",
".",
"_write_line",
"(",
"'{0} {1}'",
".",
"format",
"(",
"indent",
",",
"param",
"[",
"'data_type_descriptor'",
"]",
")",
")"
] | 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",
"(",
"rtype",
")",
")"
] | 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_parameters(routine)
self.__write_docstring_return_type()
self._write_line('"""') | 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_parameters(routine)
self.__write_docstring_return_type()
self._write_line('"""') | [
"def",
"__write_docstring",
"(",
"self",
",",
"routine",
")",
":",
"self",
".",
"_write_line",
"(",
"'\"\"\"'",
")",
"self",
".",
"__write_docstring_description",
"(",
"routine",
")",
"self",
".",
"_write_docstring_parameters",
"(",
"routine",
")",
"self",
".",
"__write_docstring_return_type",
"(",
")",
"self",
".",
"_write_line",
"(",
"'\"\"\"'",
")"
] | 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:
ret += ', '
ret += parameter_info['name']
return 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:
ret += ', '
ret += parameter_info['name']
return 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 `ld-relay`_
documentation.
.. _ld-relay: https://github.com/launchdarkly/ld-relay#configuration-file-format
:param environments: list of LaunchDarkly environments.
"""
template = self.env.get_template('ld-relay.conf.jinja')
with open('ld-relay.conf', 'w') as ld_relay_config:
template = template.render(
envs=environments
)
ld_relay_config.write(template) | 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 `ld-relay`_
documentation.
.. _ld-relay: https://github.com/launchdarkly/ld-relay#configuration-file-format
:param environments: list of LaunchDarkly environments.
"""
template = self.env.get_template('ld-relay.conf.jinja')
with open('ld-relay.conf', 'w') as ld_relay_config:
template = template.render(
envs=environments
)
ld_relay_config.write(template) | [
"def",
"generate_relay_config",
"(",
"self",
",",
"environments",
":",
"list",
")",
"->",
"None",
":",
"template",
"=",
"self",
".",
"env",
".",
"get_template",
"(",
"'ld-relay.conf.jinja'",
")",
"with",
"open",
"(",
"'ld-relay.conf'",
",",
"'w'",
")",
"as",
"ld_relay_config",
":",
"template",
"=",
"template",
".",
"render",
"(",
"envs",
"=",
"environments",
")",
"ld_relay_config",
".",
"write",
"(",
"template",
")"
] | 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.com/launchdarkly/ld-relay#configuration-file-format
:param environments: list of LaunchDarkly environments. | [
"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 = getattr(module, comp)
modules.append(module)
self.__module = modules[-2] | 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 = getattr(module, comp)
modules.append(module)
self.__module = modules[-2] | [
"def",
"__load",
"(",
"self",
")",
":",
"parts",
"=",
"self",
".",
"__class_name",
".",
"split",
"(",
"'.'",
")",
"module_name",
"=",
"\".\"",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"module",
"=",
"__import__",
"(",
"module_name",
")",
"modules",
"=",
"[",
"]",
"for",
"comp",
"in",
"parts",
"[",
"1",
":",
"]",
":",
"module",
"=",
"getattr",
"(",
"module",
",",
"comp",
")",
"modules",
".",
"append",
"(",
"module",
")",
"self",
".",
"__module",
"=",
"modules",
"[",
"-",
"2",
"]"
] | 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.__dict__.items():
if re.match(r'^[A-Z][A-Z0-9_]*$', name):
ret[name] = value
return ret | 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.__dict__.items():
if re.match(r'^[A-Z][A-Z0-9_]*$', name):
ret[name] = value
return ret | [
"def",
"constants",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"name",
"=",
"self",
".",
"__class_name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"constant_class",
"=",
"getattr",
"(",
"self",
".",
"__module",
",",
"name",
")",
"for",
"name",
",",
"value",
"in",
"constant_class",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'^[A-Z][A-Z0-9_]*$'",
",",
"name",
")",
":",
"ret",
"[",
"name",
"]",
"=",
"value",
"return",
"ret"
] | 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 source of the module with the class that acts like a namespace for constants.
:rtype: dict<str,int|str>
"""
ret = {'start_line': 0,
'last_line': 0,
'indent': ''}
mode = 1
count = 0
for line in lines:
if mode == 1:
if line.strip() == self.__annotation:
ret['start_line'] = count + 1
ret['last_line'] = count + 1
parts = re.match(r'^(\s+)', line)
ret['indent'] = parts.group(1)
mode = 2
elif mode == 2:
if line.strip() == '' or line.strip()[0:1] == '#':
mode = 3
else:
ret['last_line'] = count + 1
else:
break
count += 1
if mode != 3:
raise RuntimeError("Unable to find '{}' in file {}".format(self.__annotation, self.source()))
return ret | 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 source of the module with the class that acts like a namespace for constants.
:rtype: dict<str,int|str>
"""
ret = {'start_line': 0,
'last_line': 0,
'indent': ''}
mode = 1
count = 0
for line in lines:
if mode == 1:
if line.strip() == self.__annotation:
ret['start_line'] = count + 1
ret['last_line'] = count + 1
parts = re.match(r'^(\s+)', line)
ret['indent'] = parts.group(1)
mode = 2
elif mode == 2:
if line.strip() == '' or line.strip()[0:1] == '#':
mode = 3
else:
ret['last_line'] = count + 1
else:
break
count += 1
if mode != 3:
raise RuntimeError("Unable to find '{}' in file {}".format(self.__annotation, self.source()))
return ret | [
"def",
"__extract_info",
"(",
"self",
",",
"lines",
")",
":",
"ret",
"=",
"{",
"'start_line'",
":",
"0",
",",
"'last_line'",
":",
"0",
",",
"'indent'",
":",
"''",
"}",
"mode",
"=",
"1",
"count",
"=",
"0",
"for",
"line",
"in",
"lines",
":",
"if",
"mode",
"==",
"1",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"self",
".",
"__annotation",
":",
"ret",
"[",
"'start_line'",
"]",
"=",
"count",
"+",
"1",
"ret",
"[",
"'last_line'",
"]",
"=",
"count",
"+",
"1",
"parts",
"=",
"re",
".",
"match",
"(",
"r'^(\\s+)'",
",",
"line",
")",
"ret",
"[",
"'indent'",
"]",
"=",
"parts",
".",
"group",
"(",
"1",
")",
"mode",
"=",
"2",
"elif",
"mode",
"==",
"2",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"''",
"or",
"line",
".",
"strip",
"(",
")",
"[",
"0",
":",
"1",
"]",
"==",
"'#'",
":",
"mode",
"=",
"3",
"else",
":",
"ret",
"[",
"'last_line'",
"]",
"=",
"count",
"+",
"1",
"else",
":",
"break",
"count",
"+=",
"1",
"if",
"mode",
"!=",
"3",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to find '{}' in file {}\"",
".",
"format",
"(",
"self",
".",
"__annotation",
",",
"self",
".",
"source",
"(",
")",
")",
")",
"return",
"ret"
] | 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 namespace for constants.
:rtype: dict<str,int|str> | [
"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"
] | 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")
info = self.__extract_info(old_lines)
new_lines = old_lines[0:info['start_line']]
for constant, value in sorted(constants.items()):
new_lines.append("{0}{1} = {2}".format(info['indent'], str(constant), str(value)))
new_lines.extend(old_lines[info['last_line']:])
return "\n".join(new_lines) | 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")
info = self.__extract_info(old_lines)
new_lines = old_lines[0:info['start_line']]
for constant, value in sorted(constants.items()):
new_lines.append("{0}{1} = {2}".format(info['indent'], str(constant), str(value)))
new_lines.extend(old_lines[info['last_line']:])
return "\n".join(new_lines) | [
"def",
"source_with_constants",
"(",
"self",
",",
"constants",
")",
":",
"old_lines",
"=",
"self",
".",
"source",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"info",
"=",
"self",
".",
"__extract_info",
"(",
"old_lines",
")",
"new_lines",
"=",
"old_lines",
"[",
"0",
":",
"info",
"[",
"'start_line'",
"]",
"]",
"for",
"constant",
",",
"value",
"in",
"sorted",
"(",
"constants",
".",
"items",
"(",
")",
")",
":",
"new_lines",
".",
"append",
"(",
"\"{0}{1} = {2}\"",
".",
"format",
"(",
"info",
"[",
"'indent'",
"]",
",",
"str",
"(",
"constant",
")",
",",
"str",
"(",
"value",
")",
")",
")",
"new_lines",
".",
"extend",
"(",
"old_lines",
"[",
"info",
"[",
"'last_line'",
"]",
":",
"]",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"new_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('Generating settings file at %s' % HELPME_CLIENT_SECRETS)
config_dir = os.path.dirname(HELPME_CLIENT_SECRETS)
# The configuration directory might be needed for different clients
if not os.path.exists(config_dir):
mkdir_p(config_dir)
name = RobotNamer().generate()
# Generate the user config
config = configparser.ConfigParser()
config['DEFAULT'] = {'Alias': name }
write_config(HELPME_CLIENT_SECRETS, config)
return HELPME_CLIENT_SECRETS | 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('Generating settings file at %s' % HELPME_CLIENT_SECRETS)
config_dir = os.path.dirname(HELPME_CLIENT_SECRETS)
# The configuration directory might be needed for different clients
if not os.path.exists(config_dir):
mkdir_p(config_dir)
name = RobotNamer().generate()
# Generate the user config
config = configparser.ConfigParser()
config['DEFAULT'] = {'Alias': name }
write_config(HELPME_CLIENT_SECRETS, config)
return HELPME_CLIENT_SECRETS | [
"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",
"(",
"'Generating settings file at %s'",
"%",
"HELPME_CLIENT_SECRETS",
")",
"config_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"HELPME_CLIENT_SECRETS",
")",
"# The configuration directory might be needed for different clients",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_dir",
")",
":",
"mkdir_p",
"(",
"config_dir",
")",
"name",
"=",
"RobotNamer",
"(",
")",
".",
"generate",
"(",
")",
"# Generate the user config",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
"[",
"'DEFAULT'",
"]",
"=",
"{",
"'Alias'",
":",
"name",
"}",
"write_config",
"(",
"HELPME_CLIENT_SECRETS",
",",
"config",
")",
"return",
"HELPME_CLIENT_SECRETS"
] | 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 user want to save the file?
if removed and save:
write_config(configfile, config)
return removed | 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 user want to save the file?
if removed and save:
write_config(configfile, config)
return removed | [
"def",
"_remove_setting",
"(",
"section",
",",
"name",
",",
"configfile",
",",
"save",
"=",
"False",
")",
":",
"removed",
"=",
"False",
"config",
"=",
"_load_config",
"(",
"configfile",
")",
"if",
"section",
"in",
"config",
":",
"if",
"name",
".",
"lower",
"(",
")",
"in",
"config",
"[",
"section",
"]",
":",
"removed",
"=",
"config",
".",
"remove_option",
"(",
"section",
",",
"name",
")",
"# Does the user want to save the file?",
"if",
"removed",
"and",
"save",
":",
"write_config",
"(",
"configfile",
",",
"config",
")",
"return",
"removed"
] | 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 is not None:
if section in config:
return config._sections[section]
else:
bot.warning('%s not found in %s' %(section, configfile))
return config | 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 is not None:
if section in config:
return config._sections[section]
else:
bot.warning('%s not found in %s' %(section, configfile))
return config | [
"def",
"_load_config",
"(",
"configfile",
",",
"section",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"configfile",
")",
":",
"config",
"=",
"read_config",
"(",
"configfile",
")",
"if",
"section",
"is",
"not",
"None",
":",
"if",
"section",
"in",
"config",
":",
"return",
"config",
".",
"_sections",
"[",
"section",
"]",
"else",
":",
"bot",
".",
"warning",
"(",
"'%s not found in %s'",
"%",
"(",
"section",
",",
"configfile",
")",
")",
"return",
"config"
] | 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 underscore:
self._load_envars()
'''
for item in items:
envar = item[0]
key = item[1]
value = self._get_and_update_setting(envar)
if value != None:
self.data[key] = value
self.config.remove_option(self.name, key) | 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 underscore:
self._load_envars()
'''
for item in items:
envar = item[0]
key = item[1]
value = self._get_and_update_setting(envar)
if value != None:
self.data[key] = value
self.config.remove_option(self.name, key) | [
"def",
"load_envars",
"(",
"self",
",",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"envar",
"=",
"item",
"[",
"0",
"]",
"key",
"=",
"item",
"[",
"1",
"]",
"value",
"=",
"self",
".",
"_get_and_update_setting",
"(",
"envar",
")",
"if",
"value",
"!=",
"None",
":",
"self",
".",
"data",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"config",
".",
"remove_option",
"(",
"self",
".",
"name",
",",
"key",
")"
] | 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
name: they key (index) of the setting to look up
default: (optional) if not found, return default instead.
user: if True, load from user config. Otherwise, main config
'''
loader = self._load_config_user
if not user:
loader = self._load_config
if section is None:
section = self.name
# First priority is the environment
setting = os.environ.get(name)
# Second priority is the secrets file
if setting is None:
# Loads user config on level of helper (already indexed)
config = loader()
if section in config:
if name.lower() in config[section]:
setting = config[section][name.lower()]
# Third priority, return a default
if setting is None and default is not None:
setting = default
return setting | 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
name: they key (index) of the setting to look up
default: (optional) if not found, return default instead.
user: if True, load from user config. Otherwise, main config
'''
loader = self._load_config_user
if not user:
loader = self._load_config
if section is None:
section = self.name
# First priority is the environment
setting = os.environ.get(name)
# Second priority is the secrets file
if setting is None:
# Loads user config on level of helper (already indexed)
config = loader()
if section in config:
if name.lower() in config[section]:
setting = config[section][name.lower()]
# Third priority, return a default
if setting is None and default is not None:
setting = default
return setting | [
"def",
"get_setting",
"(",
"self",
",",
"name",
",",
"section",
"=",
"None",
",",
"default",
"=",
"None",
",",
"user",
"=",
"True",
")",
":",
"loader",
"=",
"self",
".",
"_load_config_user",
"if",
"not",
"user",
":",
"loader",
"=",
"self",
".",
"_load_config",
"if",
"section",
"is",
"None",
":",
"section",
"=",
"self",
".",
"name",
"# First priority is the environment",
"setting",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
")",
"# Second priority is the secrets file",
"if",
"setting",
"is",
"None",
":",
"# Loads user config on level of helper (already indexed)",
"config",
"=",
"loader",
"(",
")",
"if",
"section",
"in",
"config",
":",
"if",
"name",
".",
"lower",
"(",
")",
"in",
"config",
"[",
"section",
"]",
":",
"setting",
"=",
"config",
"[",
"section",
"]",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"# Third priority, return a default",
"if",
"setting",
"is",
"None",
"and",
"default",
"is",
"not",
"None",
":",
"setting",
"=",
"default",
"return",
"setting"
] | 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: (optional) if not found, return default instead.
user: if True, load from user config. Otherwise, main config | [
"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
==========
helper: the name of the helper to look up in the config
updates: a dictionary of key:value pairs to add to the config
config: a configparser.ConfigParser(), if already loaded
'''
if config is None:
config = self._load_config_user()
if self.name not in config:
config[self.name] = {}
config[self.name].update(updates)
# Update the saved file
configfile = get_configfile_user()
write_config(configfile, config)
return config | 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
==========
helper: the name of the helper to look up in the config
updates: a dictionary of key:value pairs to add to the config
config: a configparser.ConfigParser(), if already loaded
'''
if config is None:
config = self._load_config_user()
if self.name not in config:
config[self.name] = {}
config[self.name].update(updates)
# Update the saved file
configfile = get_configfile_user()
write_config(configfile, config)
return config | [
"def",
"update_settings",
"(",
"self",
",",
"updates",
",",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"self",
".",
"_load_config_user",
"(",
")",
"if",
"self",
".",
"name",
"not",
"in",
"config",
":",
"config",
"[",
"self",
".",
"name",
"]",
"=",
"{",
"}",
"config",
"[",
"self",
".",
"name",
"]",
".",
"update",
"(",
"updates",
")",
"# Update the saved file",
"configfile",
"=",
"get_configfile_user",
"(",
")",
"write_config",
"(",
"configfile",
",",
"config",
")",
"return",
"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 config
updates: a dictionary of key:value pairs to add to the config
config: a configparser.ConfigParser(), if already loaded | [
"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",
"."
] | 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 cache for the variable
2. the environment variable always takes priority to cache, and if
found, will update the cache.
3. If the variable is not found and the cache is set, we are good
5. If the variable is not found and the cache isn't set, return
default (default is None)
So the user of the function can assume a return of None equates to
not set anywhere, and take the appropriate action.
'''
setting = self._get_setting(name, user=user)
if setting is None and default is not None:
setting = default
# If the setting is found, update the client secrets
if setting is not None:
updates = {name : setting}
self._update_settings(updates)
return setting | 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 cache for the variable
2. the environment variable always takes priority to cache, and if
found, will update the cache.
3. If the variable is not found and the cache is set, we are good
5. If the variable is not found and the cache isn't set, return
default (default is None)
So the user of the function can assume a return of None equates to
not set anywhere, and take the appropriate action.
'''
setting = self._get_setting(name, user=user)
if setting is None and default is not None:
setting = default
# If the setting is found, update the client secrets
if setting is not None:
updates = {name : setting}
self._update_settings(updates)
return setting | [
"def",
"get_and_update_setting",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"user",
"=",
"True",
")",
":",
"setting",
"=",
"self",
".",
"_get_setting",
"(",
"name",
",",
"user",
"=",
"user",
")",
"if",
"setting",
"is",
"None",
"and",
"default",
"is",
"not",
"None",
":",
"setting",
"=",
"default",
"# If the setting is found, update the client secrets",
"if",
"setting",
"is",
"not",
"None",
":",
"updates",
"=",
"{",
"name",
":",
"setting",
"}",
"self",
".",
"_update_settings",
"(",
"updates",
")",
"return",
"setting"
] | 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 priority to cache, and if
found, will update the cache.
3. If the variable is not found and the cache is set, we are good
5. If the variable is not found and the cache isn't set, return
default (default is None)
So the user of the function can assume a return of None equates to
not set anywhere, and take the appropriate action. | [
"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",
":"
] | 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
argv.insert(1, app)
if len(argv) < 3 and 'test' not in argv[:2]:
# test argument is given if not argument is passed
argv.insert(2, 'test')
if extra_args:
argv.extend(extra_args)
return runner(argv) | 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
argv.insert(1, app)
if len(argv) < 3 and 'test' not in argv[:2]:
# test argument is given if not argument is passed
argv.insert(2, 'test')
if extra_args:
argv.extend(extra_args)
return runner(argv) | [
"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",
",",
"app",
")",
"if",
"len",
"(",
"argv",
")",
"<",
"3",
"and",
"'test'",
"not",
"in",
"argv",
"[",
":",
"2",
"]",
":",
"# test argument is given if not argument is passed",
"argv",
".",
"insert",
"(",
"2",
",",
"'test'",
")",
"if",
"extra_args",
":",
"argv",
".",
"extend",
"(",
"extra_args",
")",
"return",
"runner",
"(",
"argv",
")"
] | 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('runner.cms is available only if django CMS is installed')
raise
if app not in argv[:2]:
# app is automatically added if not present
argv.insert(1, app)
if len(argv) < 3 and 'test' not in argv[:2]:
# test argument is given if not argument is passed
argv.insert(2, 'test')
if '--cms' not in argv:
# this is the cms runner, just add the cms argument
argv.append('--cms')
if extra_args:
argv.extend(extra_args)
return runner(argv) | 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('runner.cms is available only if django CMS is installed')
raise
if app not in argv[:2]:
# app is automatically added if not present
argv.insert(1, app)
if len(argv) < 3 and 'test' not in argv[:2]:
# test argument is given if not argument is passed
argv.insert(2, 'test')
if '--cms' not in argv:
# this is the cms runner, just add the cms argument
argv.append('--cms')
if extra_args:
argv.extend(extra_args)
return runner(argv) | [
"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'",
")",
"raise",
"if",
"app",
"not",
"in",
"argv",
"[",
":",
"2",
"]",
":",
"# app is automatically added if not present",
"argv",
".",
"insert",
"(",
"1",
",",
"app",
")",
"if",
"len",
"(",
"argv",
")",
"<",
"3",
"and",
"'test'",
"not",
"in",
"argv",
"[",
":",
"2",
"]",
":",
"# test argument is given if not argument is passed",
"argv",
".",
"insert",
"(",
"2",
",",
"'test'",
")",
"if",
"'--cms'",
"not",
"in",
"argv",
":",
"# this is the cms runner, just add the cms argument",
"argv",
".",
"append",
"(",
"'--cms'",
")",
"if",
"extra_args",
":",
"argv",
".",
"extend",
"(",
"extra_args",
")",
"return",
"runner",
"(",
"argv",
")"
] | 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
:return: Django settings module
"""
helper = helper_module.__file__
argv = [os.path.basename(helper), app, 'setup', '--extra-settings={0}'.format(helper)]
if use_cms:
argv.append('--cms')
if extra_args:
argv.extend(extra_args)
return runner(argv) | 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
:return: Django settings module
"""
helper = helper_module.__file__
argv = [os.path.basename(helper), app, 'setup', '--extra-settings={0}'.format(helper)]
if use_cms:
argv.append('--cms')
if extra_args:
argv.extend(extra_args)
return runner(argv) | [
"def",
"setup",
"(",
"app",
",",
"helper_module",
",",
"extra_args",
"=",
"None",
",",
"use_cms",
"=",
"False",
")",
":",
"helper",
"=",
"helper_module",
".",
"__file__",
"argv",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"helper",
")",
",",
"app",
",",
"'setup'",
",",
"'--extra-settings={0}'",
".",
"format",
"(",
"helper",
")",
"]",
"if",
"use_cms",
":",
"argv",
".",
"append",
"(",
"'--cms'",
")",
"if",
"extra_args",
":",
"argv",
".",
"extend",
"(",
"extra_args",
")",
"return",
"runner",
"(",
"argv",
")"
] | 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
self.elts_to_keep = self._get_elements_to_keep()
self.elts_to_discard = self._get_elements_to_discard()
# Init an empty list of Elements to remove
self.elts_to_remove = []
# Check if the root is a match or if there is any matches
is_root = self._is_keep(self.tree)
has_descendant = self._has_keep_elt_in_descendants(self.tree)
if not(is_root or has_descendant):
return False
# Parse and clean the ElementTree
self._parse_element(self.tree, parent_is_keep=is_root)
self._remove_elements(self.elts_to_remove)
return True | 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
self.elts_to_keep = self._get_elements_to_keep()
self.elts_to_discard = self._get_elements_to_discard()
# Init an empty list of Elements to remove
self.elts_to_remove = []
# Check if the root is a match or if there is any matches
is_root = self._is_keep(self.tree)
has_descendant = self._has_keep_elt_in_descendants(self.tree)
if not(is_root or has_descendant):
return False
# Parse and clean the ElementTree
self._parse_element(self.tree, parent_is_keep=is_root)
self._remove_elements(self.elts_to_remove)
return True | [
"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_elements_to_keep",
"(",
")",
"self",
".",
"elts_to_discard",
"=",
"self",
".",
"_get_elements_to_discard",
"(",
")",
"# Init an empty list of Elements to remove",
"self",
".",
"elts_to_remove",
"=",
"[",
"]",
"# Check if the root is a match or if there is any matches",
"is_root",
"=",
"self",
".",
"_is_keep",
"(",
"self",
".",
"tree",
")",
"has_descendant",
"=",
"self",
".",
"_has_keep_elt_in_descendants",
"(",
"self",
".",
"tree",
")",
"if",
"not",
"(",
"is_root",
"or",
"has_descendant",
")",
":",
"return",
"False",
"# Parse and clean the ElementTree",
"self",
".",
"_parse_element",
"(",
"self",
".",
"tree",
",",
"parent_is_keep",
"=",
"is_root",
")",
"self",
".",
"_remove_elements",
"(",
"self",
".",
"elts_to_remove",
")",
"return",
"True"
] | 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)
if not link.startswith(self.rel_to_abs_excluded_prefixes) else link)
# Extra attributes
onclick_elements = self.tree.xpath('//*[@onclick]')
for element in onclick_elements:
# Replace attribute with absolute URL
element.set('onclick', self.javascript_open_re.sub(
lambda match: '%s%s%s' % (match.group('opening'),
urljoin(base_url, match.group('url')),
match.group('ending')),
element.get('onclick'))) | 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)
if not link.startswith(self.rel_to_abs_excluded_prefixes) else link)
# Extra attributes
onclick_elements = self.tree.xpath('//*[@onclick]')
for element in onclick_elements:
# Replace attribute with absolute URL
element.set('onclick', self.javascript_open_re.sub(
lambda match: '%s%s%s' % (match.group('opening'),
urljoin(base_url, match.group('url')),
match.group('ending')),
element.get('onclick'))) | [
"def",
"rel_to_abs",
"(",
"self",
",",
"base_url",
")",
":",
"# Delete target attributes",
"strip_attributes",
"(",
"self",
".",
"tree",
",",
"'target'",
")",
"# Absolute links",
"self",
".",
"tree",
".",
"rewrite_links",
"(",
"lambda",
"link",
":",
"urljoin",
"(",
"base_url",
",",
"link",
")",
"if",
"not",
"link",
".",
"startswith",
"(",
"self",
".",
"rel_to_abs_excluded_prefixes",
")",
"else",
"link",
")",
"# Extra attributes",
"onclick_elements",
"=",
"self",
".",
"tree",
".",
"xpath",
"(",
"'//*[@onclick]'",
")",
"for",
"element",
"in",
"onclick_elements",
":",
"# Replace attribute with absolute URL",
"element",
".",
"set",
"(",
"'onclick'",
",",
"self",
".",
"javascript_open_re",
".",
"sub",
"(",
"lambda",
"match",
":",
"'%s%s%s'",
"%",
"(",
"match",
".",
"group",
"(",
"'opening'",
")",
",",
"urljoin",
"(",
"base_url",
",",
"match",
".",
"group",
"(",
"'url'",
")",
")",
",",
"match",
".",
"group",
"(",
"'ending'",
")",
")",
",",
"element",
".",
"get",
"(",
"'onclick'",
")",
")",
")"
] | 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 source])) | 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 source])) | [
"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
"""
for e in elt.iterchildren():
is_discard_element = self._is_discard(e)
is_keep_element = self._is_keep(e)
# Element is an explicit one to discard, flag it and continue
if is_discard_element and not is_keep_element:
self.elts_to_remove.append(e)
continue
if not parent_is_keep:
# Parent element is not an explicit keep, normal process
# Element is an explicit one to keep, inspect it
if is_keep_element:
self._parse_element(e, parent_is_keep=True)
continue
# Has a descendant to keep, inspect it
if self._has_keep_elt_in_descendants(e):
self._parse_element(e)
continue
# Element did not match anything, remove it
self.elts_to_remove.append(e)
else:
# Element is a child of a keep element, only check explicit discards
self._parse_element(e, parent_is_keep=True) | 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
"""
for e in elt.iterchildren():
is_discard_element = self._is_discard(e)
is_keep_element = self._is_keep(e)
# Element is an explicit one to discard, flag it and continue
if is_discard_element and not is_keep_element:
self.elts_to_remove.append(e)
continue
if not parent_is_keep:
# Parent element is not an explicit keep, normal process
# Element is an explicit one to keep, inspect it
if is_keep_element:
self._parse_element(e, parent_is_keep=True)
continue
# Has a descendant to keep, inspect it
if self._has_keep_elt_in_descendants(e):
self._parse_element(e)
continue
# Element did not match anything, remove it
self.elts_to_remove.append(e)
else:
# Element is a child of a keep element, only check explicit discards
self._parse_element(e, parent_is_keep=True) | [
"def",
"_parse_element",
"(",
"self",
",",
"elt",
",",
"parent_is_keep",
"=",
"False",
")",
":",
"for",
"e",
"in",
"elt",
".",
"iterchildren",
"(",
")",
":",
"is_discard_element",
"=",
"self",
".",
"_is_discard",
"(",
"e",
")",
"is_keep_element",
"=",
"self",
".",
"_is_keep",
"(",
"e",
")",
"# Element is an explicit one to discard, flag it and continue",
"if",
"is_discard_element",
"and",
"not",
"is_keep_element",
":",
"self",
".",
"elts_to_remove",
".",
"append",
"(",
"e",
")",
"continue",
"if",
"not",
"parent_is_keep",
":",
"# Parent element is not an explicit keep, normal process",
"# Element is an explicit one to keep, inspect it",
"if",
"is_keep_element",
":",
"self",
".",
"_parse_element",
"(",
"e",
",",
"parent_is_keep",
"=",
"True",
")",
"continue",
"# Has a descendant to keep, inspect it",
"if",
"self",
".",
"_has_keep_elt_in_descendants",
"(",
"e",
")",
":",
"self",
".",
"_parse_element",
"(",
"e",
")",
"continue",
"# Element did not match anything, remove it",
"self",
".",
"elts_to_remove",
".",
"append",
"(",
"e",
")",
"else",
":",
"# Element is a child of a keep element, only check explicit discards",
"self",
".",
"_parse_element",
"(",
"e",
",",
"parent_is_keep",
"=",
"True",
")"
] | 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
"""
# 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 in self.elts_to_keep:
return True
return False | 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
"""
# 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 in self.elts_to_keep:
return True
return False | [
"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",
"in",
"self",
".",
"elts_to_keep",
":",
"return",
"True",
"return",
"False"
] | 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.tail.strip():
parent_text = parent.text or ''
parent.text = parent_text + e.tail
# Remove the element
e.getparent().remove(e) | 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.tail.strip():
parent_text = parent.text or ''
parent.text = parent_text + e.tail
# Remove the element
e.getparent().remove(e) | [
"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",
"and",
"e",
".",
"tail",
".",
"strip",
"(",
")",
":",
"parent_text",
"=",
"parent",
".",
"text",
"or",
"''",
"parent",
".",
"text",
"=",
"parent_text",
"+",
"e",
".",
"tail",
"# Remove the element",
"e",
".",
"getparent",
"(",
")",
".",
"remove",
"(",
"e",
")"
] | 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(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return SystemInfo(results) | 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(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return SystemInfo(results) | [
"def",
"getSystemInfo",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"getSystemInfo\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetInfo\"",
",",
"timeout",
"=",
"timeout",
")",
"return",
"SystemInfo",
"(",
"results",
")"
] | 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",
",",
"namespace",
",",
"\"Reboot\"",
",",
"timeout",
"=",
"timeout",
")"
] | 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)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return TimeInfo(results) | 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)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return TimeInfo(results) | [
"def",
"getTimeInfo",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"getTimeInfo\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetInfo\"",
",",
"timeout",
"=",
"timeout",
")",
"return",
"TimeInfo",
"(",
"results",
")"
] | 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.execute(uri, namespace, "GetInfo", timeout=timeout)
return bool(int(results["NewUpgradeAvailable"])) | 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.execute(uri, namespace, "GetInfo", timeout=timeout)
return bool(int(results["NewUpgradeAvailable"])) | [
"def",
"softwareUpdateAvailable",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"System",
".",
"getServiceType",
"(",
"\"softwareUpdateAvailable\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetInfo\"",
",",
"timeout",
"=",
"timeout",
")",
"return",
"bool",
"(",
"int",
"(",
"results",
"[",
"\"NewUpgradeAvailable\"",
"]",
")",
")"
] | 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-since'",
"]",
"=",
"headers",
"[",
"'last-modified'",
"]",
"return",
"out"
] | 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_version and schema_version != item.schema:
LOGGER.debug("Cache get %s %s: Wanted schema %d, got %d",
prefix, url,
schema_version, item.schema)
return None
return item
except FileNotFoundError:
pass
except Exception: # pylint:disable=broad-except
_, msg, _ = sys.exc_info()
LOGGER.warning("Cache get %s %s failed: %s", prefix, url, msg)
return None | 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_version and schema_version != item.schema:
LOGGER.debug("Cache get %s %s: Wanted schema %d, got %d",
prefix, url,
schema_version, item.schema)
return None
return item
except FileNotFoundError:
pass
except Exception: # pylint:disable=broad-except
_, msg, _ = sys.exc_info()
LOGGER.warning("Cache get %s %s failed: %s", prefix, url, msg)
return None | [
"def",
"get",
"(",
"self",
",",
"prefix",
",",
"url",
",",
"schema_version",
"=",
"None",
")",
":",
"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_version",
"and",
"schema_version",
"!=",
"item",
".",
"schema",
":",
"LOGGER",
".",
"debug",
"(",
"\"Cache get %s %s: Wanted schema %d, got %d\"",
",",
"prefix",
",",
"url",
",",
"schema_version",
",",
"item",
".",
"schema",
")",
"return",
"None",
"return",
"item",
"except",
"FileNotFoundError",
":",
"pass",
"except",
"Exception",
":",
"# pylint:disable=broad-except",
"_",
",",
"msg",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"LOGGER",
".",
"warning",
"(",
"\"Cache get %s %s failed: %s\"",
",",
"prefix",
",",
"url",
",",
"msg",
")",
"return",
"None"
] | 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(filename, 'wb') as file:
pickle.dump(obj, file) | 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(filename, 'wb') as file:
pickle.dump(obj, file) | [
"def",
"set",
"(",
"self",
",",
"prefix",
",",
"url",
",",
"obj",
")",
":",
"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",
"(",
"filename",
",",
"'wb'",
")",
"as",
"file",
":",
"pickle",
".",
"dump",
"(",
"obj",
",",
"file",
")"
] | 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_root = kwargs["get_root"]
else:
# default value
get_root = False
sdp = dataset_path(get_root=get_root)
pth = os.path.join(sdp, *path_to_join)
logger.debug("sample_data_path" + str(sdp))
logger.debug("path " + str(pth))
return pth | 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_root = kwargs["get_root"]
else:
# default value
get_root = False
sdp = dataset_path(get_root=get_root)
pth = os.path.join(sdp, *path_to_join)
logger.debug("sample_data_path" + str(sdp))
logger.debug("path " + str(pth))
return pth | [
"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_path",
"(",
"get_root",
"=",
"get_root",
")",
"pth",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sdp",
",",
"*",
"path_to_join",
")",
"logger",
".",
"debug",
"(",
"\"sample_data_path\"",
"+",
"str",
"(",
"sdp",
")",
")",
"logger",
".",
"debug",
"(",
"\"path \"",
"+",
"str",
"(",
"pth",
")",
")",
"return",
"pth"
] | 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:
cache = cachef.CacheFile(cachefile)
cache.update("local_dataset_dir", path) | 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:
cache = cachef.CacheFile(cachefile)
cache.update("local_dataset_dir", path) | [
"def",
"set_dataset_path",
"(",
"path",
",",
"cache",
"=",
"None",
",",
"cachefile",
"=",
"\"~/.io3d_cache.yaml\"",
")",
":",
"if",
"cachefile",
"is",
"not",
"None",
":",
"cache",
"=",
"cachef",
".",
"CacheFile",
"(",
"cachefile",
")",
"cache",
".",
"update",
"(",
"\"local_dataset_dir\"",
",",
"path",
")"
] | 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 = cachef.CacheFile(cachefile)
# cache.update('local_dataset_dir', head)
if cache is not None:
local_data_dir = cache.get_or_save_default("local_dataset_dir", local_dir)
if get_root:
local_data_dir
else:
logger.warning("Parameter")
local_data_dir = op.join(local_data_dir, "medical", "orig")
return op.expanduser(local_data_dir) | 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 = cachef.CacheFile(cachefile)
# cache.update('local_dataset_dir', head)
if cache is not None:
local_data_dir = cache.get_or_save_default("local_dataset_dir", local_dir)
if get_root:
local_data_dir
else:
logger.warning("Parameter")
local_data_dir = op.join(local_data_dir, "medical", "orig")
return op.expanduser(local_data_dir) | [
"def",
"dataset_path",
"(",
"cache",
"=",
"None",
",",
"cachefile",
"=",
"\"~/.io3d_cache.yaml\"",
",",
"get_root",
"=",
"False",
")",
":",
"local_data_dir",
"=",
"local_dir",
"if",
"cachefile",
"is",
"not",
"None",
":",
"cache",
"=",
"cachef",
".",
"CacheFile",
"(",
"cachefile",
")",
"# cache.update('local_dataset_dir', head)",
"if",
"cache",
"is",
"not",
"None",
":",
"local_data_dir",
"=",
"cache",
".",
"get_or_save_default",
"(",
"\"local_dataset_dir\"",
",",
"local_dir",
")",
"if",
"get_root",
":",
"local_data_dir",
"else",
":",
"logger",
".",
"warning",
"(",
"\"Parameter\"",
")",
"local_data_dir",
"=",
"op",
".",
"join",
"(",
"local_data_dir",
",",
"\"medical\"",
",",
"\"orig\"",
")",
"return",
"op",
".",
"expanduser",
"(",
"local_data_dir",
")"
] | 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 downloaded the file from url and eventually unzipped
"""
data_url = data_urls[label]
if type(data_url) == str:
# back compatibility
data_url = [data_url]
if type(data_url) == list:
data_url.extend([None, None, None, None])
data_url = data_url[:4]
url, expected_hash, hash_path, relative_donwload_dir = data_url
if hash_path is None:
hash_path = label
# elif type(data_url) == dict:
return data_url, url, expected_hash, hash_path, relative_donwload_dir | 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 downloaded the file from url and eventually unzipped
"""
data_url = data_urls[label]
if type(data_url) == str:
# back compatibility
data_url = [data_url]
if type(data_url) == list:
data_url.extend([None, None, None, None])
data_url = data_url[:4]
url, expected_hash, hash_path, relative_donwload_dir = data_url
if hash_path is None:
hash_path = label
# elif type(data_url) == dict:
return data_url, url, expected_hash, hash_path, relative_donwload_dir | [
"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",
")",
"==",
"list",
":",
"data_url",
".",
"extend",
"(",
"[",
"None",
",",
"None",
",",
"None",
",",
"None",
"]",
")",
"data_url",
"=",
"data_url",
"[",
":",
"4",
"]",
"url",
",",
"expected_hash",
",",
"hash_path",
",",
"relative_donwload_dir",
"=",
"data_url",
"if",
"hash_path",
"is",
"None",
":",
"hash_path",
"=",
"label",
"# elif type(data_url) == dict:",
"return",
"data_url",
",",
"url",
",",
"expected_hash",
",",
"hash_path",
",",
"relative_donwload_dir"
] | 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 eventually unzipped | [
"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
:return: list of labels
"""
new_dataset_label_dict = []
for label in dataset_label_dict:
dataset_metadata = data_urls[label]
if type(dataset_metadata) == dict and "package" in dataset_metadata:
new_dataset_label_dict.extend(dataset_metadata["package"])
else:
new_dataset_label_dict.append(label)
return new_dataset_label_dict | 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
:return: list of labels
"""
new_dataset_label_dict = []
for label in dataset_label_dict:
dataset_metadata = data_urls[label]
if type(dataset_metadata) == dict and "package" in dataset_metadata:
new_dataset_label_dict.extend(dataset_metadata["package"])
else:
new_dataset_label_dict.append(label)
return new_dataset_label_dict | [
"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",
")",
"==",
"dict",
"and",
"\"package\"",
"in",
"dataset_metadata",
":",
"new_dataset_label_dict",
".",
"extend",
"(",
"dataset_metadata",
"[",
"\"package\"",
"]",
")",
"else",
":",
"new_dataset_label_dict",
".",
"append",
"(",
"label",
")",
"return",
"new_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
: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 downloaded
:param destination_dir: output dir for data
:param dry_run: runs function without downloading anything
"""
if destination_dir is None:
destination_dir = op.join(dataset_path(get_root=True), "medical", "orig")
destination_dir = op.expanduser(destination_dir)
logger.info("destination dir: {}".format(destination_dir))
if dataset_label is None:
dataset_label = data_urls.keys()
if type(dataset_label) == str:
dataset_label = [dataset_label]
dataset_label = _expand_dataset_packages(dataset_label)
for label in dataset_label:
# make all data:url have length 3
data_url, url, expected_hash, hash_path, relative_download_dir = get_dataset_meta(
label
)
if relative_download_dir is None:
label_destination_dir = destination_dir
else:
label_destination_dir = op.join(destination_dir, relative_download_dir)
if not op.exists(label_destination_dir):
logger.debug("creating directory {}".format(label_destination_dir))
os.makedirs(label_destination_dir)
if hash_path is None:
hash_path = label
path_to_hash = os.path.join(label_destination_dir, hash_path)
try:
computed_hash = checksum(path_to_hash)
except Exception as e:
# there is probably no checksumdir module
logger.warning(e)
logger.warning("problem with sample_data.checksum()")
computed_hash = None
logger.info("dataset: '" + label + "'")
logger.info("path to hash: {}".format(path_to_hash))
logger.info("expected hash: '" + str(expected_hash) + "'")
logger.info("computed hash: '" + str(computed_hash) + "'")
if (computed_hash is not None) and (expected_hash == computed_hash):
logger.info("match ok - no download needed")
else:
logger.info("downloading")
if not dry_run:
downzip(url, destination=label_destination_dir)
logger.info("finished")
downloaded_hash = checksum(
os.path.join(label_destination_dir, hash_path)
)
logger.info("downloaded hash: '" + str(downloaded_hash) + "'")
if downloaded_hash != expected_hash:
logger.warning(
"downloaded hash is different from expected hash\n"
+ "expected hash: '"
+ str(expected_hash)
+ "'\n"
+ "downloaded hash: '"
+ str(downloaded_hash)
+ "'\n"
)
else:
logger.debug("dry run") | 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 downloaded
:param destination_dir: output dir for data
:param dry_run: runs function without downloading anything
"""
if destination_dir is None:
destination_dir = op.join(dataset_path(get_root=True), "medical", "orig")
destination_dir = op.expanduser(destination_dir)
logger.info("destination dir: {}".format(destination_dir))
if dataset_label is None:
dataset_label = data_urls.keys()
if type(dataset_label) == str:
dataset_label = [dataset_label]
dataset_label = _expand_dataset_packages(dataset_label)
for label in dataset_label:
# make all data:url have length 3
data_url, url, expected_hash, hash_path, relative_download_dir = get_dataset_meta(
label
)
if relative_download_dir is None:
label_destination_dir = destination_dir
else:
label_destination_dir = op.join(destination_dir, relative_download_dir)
if not op.exists(label_destination_dir):
logger.debug("creating directory {}".format(label_destination_dir))
os.makedirs(label_destination_dir)
if hash_path is None:
hash_path = label
path_to_hash = os.path.join(label_destination_dir, hash_path)
try:
computed_hash = checksum(path_to_hash)
except Exception as e:
# there is probably no checksumdir module
logger.warning(e)
logger.warning("problem with sample_data.checksum()")
computed_hash = None
logger.info("dataset: '" + label + "'")
logger.info("path to hash: {}".format(path_to_hash))
logger.info("expected hash: '" + str(expected_hash) + "'")
logger.info("computed hash: '" + str(computed_hash) + "'")
if (computed_hash is not None) and (expected_hash == computed_hash):
logger.info("match ok - no download needed")
else:
logger.info("downloading")
if not dry_run:
downzip(url, destination=label_destination_dir)
logger.info("finished")
downloaded_hash = checksum(
os.path.join(label_destination_dir, hash_path)
)
logger.info("downloaded hash: '" + str(downloaded_hash) + "'")
if downloaded_hash != expected_hash:
logger.warning(
"downloaded hash is different from expected hash\n"
+ "expected hash: '"
+ str(expected_hash)
+ "'\n"
+ "downloaded hash: '"
+ str(downloaded_hash)
+ "'\n"
)
else:
logger.debug("dry run") | [
"def",
"download",
"(",
"dataset_label",
"=",
"None",
",",
"destination_dir",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"destination_dir",
"is",
"None",
":",
"destination_dir",
"=",
"op",
".",
"join",
"(",
"dataset_path",
"(",
"get_root",
"=",
"True",
")",
",",
"\"medical\"",
",",
"\"orig\"",
")",
"destination_dir",
"=",
"op",
".",
"expanduser",
"(",
"destination_dir",
")",
"logger",
".",
"info",
"(",
"\"destination dir: {}\"",
".",
"format",
"(",
"destination_dir",
")",
")",
"if",
"dataset_label",
"is",
"None",
":",
"dataset_label",
"=",
"data_urls",
".",
"keys",
"(",
")",
"if",
"type",
"(",
"dataset_label",
")",
"==",
"str",
":",
"dataset_label",
"=",
"[",
"dataset_label",
"]",
"dataset_label",
"=",
"_expand_dataset_packages",
"(",
"dataset_label",
")",
"for",
"label",
"in",
"dataset_label",
":",
"# make all data:url have length 3",
"data_url",
",",
"url",
",",
"expected_hash",
",",
"hash_path",
",",
"relative_download_dir",
"=",
"get_dataset_meta",
"(",
"label",
")",
"if",
"relative_download_dir",
"is",
"None",
":",
"label_destination_dir",
"=",
"destination_dir",
"else",
":",
"label_destination_dir",
"=",
"op",
".",
"join",
"(",
"destination_dir",
",",
"relative_download_dir",
")",
"if",
"not",
"op",
".",
"exists",
"(",
"label_destination_dir",
")",
":",
"logger",
".",
"debug",
"(",
"\"creating directory {}\"",
".",
"format",
"(",
"label_destination_dir",
")",
")",
"os",
".",
"makedirs",
"(",
"label_destination_dir",
")",
"if",
"hash_path",
"is",
"None",
":",
"hash_path",
"=",
"label",
"path_to_hash",
"=",
"os",
".",
"path",
".",
"join",
"(",
"label_destination_dir",
",",
"hash_path",
")",
"try",
":",
"computed_hash",
"=",
"checksum",
"(",
"path_to_hash",
")",
"except",
"Exception",
"as",
"e",
":",
"# there is probably no checksumdir module",
"logger",
".",
"warning",
"(",
"e",
")",
"logger",
".",
"warning",
"(",
"\"problem with sample_data.checksum()\"",
")",
"computed_hash",
"=",
"None",
"logger",
".",
"info",
"(",
"\"dataset: '\"",
"+",
"label",
"+",
"\"'\"",
")",
"logger",
".",
"info",
"(",
"\"path to hash: {}\"",
".",
"format",
"(",
"path_to_hash",
")",
")",
"logger",
".",
"info",
"(",
"\"expected hash: '\"",
"+",
"str",
"(",
"expected_hash",
")",
"+",
"\"'\"",
")",
"logger",
".",
"info",
"(",
"\"computed hash: '\"",
"+",
"str",
"(",
"computed_hash",
")",
"+",
"\"'\"",
")",
"if",
"(",
"computed_hash",
"is",
"not",
"None",
")",
"and",
"(",
"expected_hash",
"==",
"computed_hash",
")",
":",
"logger",
".",
"info",
"(",
"\"match ok - no download needed\"",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"downloading\"",
")",
"if",
"not",
"dry_run",
":",
"downzip",
"(",
"url",
",",
"destination",
"=",
"label_destination_dir",
")",
"logger",
".",
"info",
"(",
"\"finished\"",
")",
"downloaded_hash",
"=",
"checksum",
"(",
"os",
".",
"path",
".",
"join",
"(",
"label_destination_dir",
",",
"hash_path",
")",
")",
"logger",
".",
"info",
"(",
"\"downloaded hash: '\"",
"+",
"str",
"(",
"downloaded_hash",
")",
"+",
"\"'\"",
")",
"if",
"downloaded_hash",
"!=",
"expected_hash",
":",
"logger",
".",
"warning",
"(",
"\"downloaded hash is different from expected hash\\n\"",
"+",
"\"expected hash: '\"",
"+",
"str",
"(",
"expected_hash",
")",
"+",
"\"'\\n\"",
"+",
"\"downloaded hash: '\"",
"+",
"str",
"(",
"downloaded_hash",
")",
"+",
"\"'\\n\"",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"dry run\"",
")"
] | 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 function without downloading anything | [
"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 destination_dir is None:
destination_dir = op.join(dataset_path(get_root=True), "medical", "orig")
destination_dir = op.expanduser(destination_dir)
data_url, url, expected_hash, hash_path, relative_output_path = get_dataset_meta(
dataset_label
)
paths = glob.glob(os.path.join(destination_dir, hash_path))
paths.sort()
import fnmatch
print(paths)
print(data_id)
pathsf = fnmatch.filter(paths, data_id)
print(pathsf)
datap = io3d.read(pathsf[0], dataplus_format=True)
return datap | 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 destination_dir is None:
destination_dir = op.join(dataset_path(get_root=True), "medical", "orig")
destination_dir = op.expanduser(destination_dir)
data_url, url, expected_hash, hash_path, relative_output_path = get_dataset_meta(
dataset_label
)
paths = glob.glob(os.path.join(destination_dir, hash_path))
paths.sort()
import fnmatch
print(paths)
print(data_id)
pathsf = fnmatch.filter(paths, data_id)
print(pathsf)
datap = io3d.read(pathsf[0], dataplus_format=True)
return datap | [
"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",
")",
",",
"\"medical\"",
",",
"\"orig\"",
")",
"destination_dir",
"=",
"op",
".",
"expanduser",
"(",
"destination_dir",
")",
"data_url",
",",
"url",
",",
"expected_hash",
",",
"hash_path",
",",
"relative_output_path",
"=",
"get_dataset_meta",
"(",
"dataset_label",
")",
"paths",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"destination_dir",
",",
"hash_path",
")",
")",
"paths",
".",
"sort",
"(",
")",
"import",
"fnmatch",
"print",
"(",
"paths",
")",
"print",
"(",
"data_id",
")",
"pathsf",
"=",
"fnmatch",
".",
"filter",
"(",
"paths",
",",
"data_id",
")",
"print",
"(",
"pathsf",
")",
"datap",
"=",
"io3d",
".",
"read",
"(",
"pathsf",
"[",
"0",
"]",
",",
"dataplus_format",
"=",
"True",
")",
"return",
"datap"
] | 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: (str) hash of the file/files given by path
"""
import checksumdir
hash_func = checksumdir.HASH_FUNCS.get(hashfunc)
if not hash_func:
raise NotImplementedError("{} not implemented.".format(hashfunc))
if os.path.isdir(path):
return checksumdir.dirhash(path, hashfunc=hashfunc)
hashvalues = []
path_list = list(sorted(glob.glob(path)))
logger.debug("path_list: len: %i", len(path_list))
if len(path_list) > 0:
logger.debug("first ... last: %s ... %s", str(path_list[0]), str(path_list[-1]))
for path in path_list:
if os.path.isfile(path):
hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func))
logger.debug("one hash per file: len: %i", len(hashvalues))
if len(path_list) > 0:
logger.debug("first ... last: %s ... %s", str(hashvalues[0]), str(hashvalues[-1]))
checksum_hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func)
logger.debug("total hash: {}".format(str(checksum_hash)))
return checksum_hash | 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: (str) hash of the file/files given by path
"""
import checksumdir
hash_func = checksumdir.HASH_FUNCS.get(hashfunc)
if not hash_func:
raise NotImplementedError("{} not implemented.".format(hashfunc))
if os.path.isdir(path):
return checksumdir.dirhash(path, hashfunc=hashfunc)
hashvalues = []
path_list = list(sorted(glob.glob(path)))
logger.debug("path_list: len: %i", len(path_list))
if len(path_list) > 0:
logger.debug("first ... last: %s ... %s", str(path_list[0]), str(path_list[-1]))
for path in path_list:
if os.path.isfile(path):
hashvalues.append(checksumdir._filehash(path, hashfunc=hash_func))
logger.debug("one hash per file: len: %i", len(hashvalues))
if len(path_list) > 0:
logger.debug("first ... last: %s ... %s", str(hashvalues[0]), str(hashvalues[-1]))
checksum_hash = checksumdir._reduce_hash(hashvalues, hashfunc=hash_func)
logger.debug("total hash: {}".format(str(checksum_hash)))
return checksum_hash | [
"def",
"checksum",
"(",
"path",
",",
"hashfunc",
"=",
"\"md5\"",
")",
":",
"import",
"checksumdir",
"hash_func",
"=",
"checksumdir",
".",
"HASH_FUNCS",
".",
"get",
"(",
"hashfunc",
")",
"if",
"not",
"hash_func",
":",
"raise",
"NotImplementedError",
"(",
"\"{} not implemented.\"",
".",
"format",
"(",
"hashfunc",
")",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"checksumdir",
".",
"dirhash",
"(",
"path",
",",
"hashfunc",
"=",
"hashfunc",
")",
"hashvalues",
"=",
"[",
"]",
"path_list",
"=",
"list",
"(",
"sorted",
"(",
"glob",
".",
"glob",
"(",
"path",
")",
")",
")",
"logger",
".",
"debug",
"(",
"\"path_list: len: %i\"",
",",
"len",
"(",
"path_list",
")",
")",
"if",
"len",
"(",
"path_list",
")",
">",
"0",
":",
"logger",
".",
"debug",
"(",
"\"first ... last: %s ... %s\"",
",",
"str",
"(",
"path_list",
"[",
"0",
"]",
")",
",",
"str",
"(",
"path_list",
"[",
"-",
"1",
"]",
")",
")",
"for",
"path",
"in",
"path_list",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"hashvalues",
".",
"append",
"(",
"checksumdir",
".",
"_filehash",
"(",
"path",
",",
"hashfunc",
"=",
"hash_func",
")",
")",
"logger",
".",
"debug",
"(",
"\"one hash per file: len: %i\"",
",",
"len",
"(",
"hashvalues",
")",
")",
"if",
"len",
"(",
"path_list",
")",
">",
"0",
":",
"logger",
".",
"debug",
"(",
"\"first ... last: %s ... %s\"",
",",
"str",
"(",
"hashvalues",
"[",
"0",
"]",
")",
",",
"str",
"(",
"hashvalues",
"[",
"-",
"1",
"]",
")",
")",
"checksum_hash",
"=",
"checksumdir",
".",
"_reduce_hash",
"(",
"hashvalues",
",",
"hashfunc",
"=",
"hash_func",
")",
"logger",
".",
"debug",
"(",
"\"total hash: {}\"",
".",
"format",
"(",
"str",
"(",
"checksum_hash",
")",
")",
")",
"return",
"checksum_hash"
] | 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, 23, 10] = 0
segmentation[6:10, 7, 36] = 0
segmentation[6:10, 23, 36] = 0
segmentation[2:18, 12:19, 18:28] = 2
data3d = segmentation * 100 + np.random.random(segmentation.shape) * 30
voxelsize_mm = [3, 2, 1]
datap = {
"data3d": data3d,
"segmentation": segmentation,
"voxelsize_mm": voxelsize_mm,
}
# io3d.write(datap, "donut.pklz")
return datap | 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, 23, 10] = 0
segmentation[6:10, 7, 36] = 0
segmentation[6:10, 23, 36] = 0
segmentation[2:18, 12:19, 18:28] = 2
data3d = segmentation * 100 + np.random.random(segmentation.shape) * 30
voxelsize_mm = [3, 2, 1]
datap = {
"data3d": data3d,
"segmentation": segmentation,
"voxelsize_mm": voxelsize_mm,
}
# io3d.write(datap, "donut.pklz")
return datap | [
"def",
"generate_donut",
"(",
")",
":",
"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",
",",
"23",
",",
"10",
"]",
"=",
"0",
"segmentation",
"[",
"6",
":",
"10",
",",
"7",
",",
"36",
"]",
"=",
"0",
"segmentation",
"[",
"6",
":",
"10",
",",
"23",
",",
"36",
"]",
"=",
"0",
"segmentation",
"[",
"2",
":",
"18",
",",
"12",
":",
"19",
",",
"18",
":",
"28",
"]",
"=",
"2",
"data3d",
"=",
"segmentation",
"*",
"100",
"+",
"np",
".",
"random",
".",
"random",
"(",
"segmentation",
".",
"shape",
")",
"*",
"30",
"voxelsize_mm",
"=",
"[",
"3",
",",
"2",
",",
"1",
"]",
"datap",
"=",
"{",
"\"data3d\"",
":",
"data3d",
",",
"\"segmentation\"",
":",
"segmentation",
",",
"\"voxelsize_mm\"",
":",
"voxelsize_mm",
",",
"}",
"# io3d.write(datap, \"donut.pklz\")",
"return",
"datap"
] | 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 object in the corner.
:return:
"""
import scipy.ndimage
# seedsz= int(sz/10)
space = 2
seeds = np.zeros([sz, sz + 1, sz + 2], dtype=np.int8)
xmin = radius + seedsz + offset + 2
ymin = radius + seedsz + offset + 6
seeds[offset + 12, xmin + 3 : xmin + 7 + seedsz, ymin : ymin + 2] = 1
seeds[offset + 20, xmin + 7 : xmin + 12 + seedsz, ymin + 5 : ymin + 7] = 1
# add temp seed
if add_object_without_seeds:
seeds[-3, -3, -3] = 1
img = np.ones([sz, sz + 1, sz + 2])
img = img - seeds
seeds[2 : 10 + seedsz, 2 : 9 + seedsz, 2 : 3 + seedsz] = 2
# remove temo seed
if add_object_without_seeds:
seeds[-3, -3, -3] = 0
img = scipy.ndimage.morphology.distance_transform_edt(img)
segm = img < radius
img = (100 * segm + 80 * np.random.random(img.shape)).astype(np.uint8)
return img, segm, seeds | 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 object in the corner.
:return:
"""
import scipy.ndimage
# seedsz= int(sz/10)
space = 2
seeds = np.zeros([sz, sz + 1, sz + 2], dtype=np.int8)
xmin = radius + seedsz + offset + 2
ymin = radius + seedsz + offset + 6
seeds[offset + 12, xmin + 3 : xmin + 7 + seedsz, ymin : ymin + 2] = 1
seeds[offset + 20, xmin + 7 : xmin + 12 + seedsz, ymin + 5 : ymin + 7] = 1
# add temp seed
if add_object_without_seeds:
seeds[-3, -3, -3] = 1
img = np.ones([sz, sz + 1, sz + 2])
img = img - seeds
seeds[2 : 10 + seedsz, 2 : 9 + seedsz, 2 : 3 + seedsz] = 2
# remove temo seed
if add_object_without_seeds:
seeds[-3, -3, -3] = 0
img = scipy.ndimage.morphology.distance_transform_edt(img)
segm = img < radius
img = (100 * segm + 80 * np.random.random(img.shape)).astype(np.uint8)
return img, segm, seeds | [
"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",
"=",
"2",
"seeds",
"=",
"np",
".",
"zeros",
"(",
"[",
"sz",
",",
"sz",
"+",
"1",
",",
"sz",
"+",
"2",
"]",
",",
"dtype",
"=",
"np",
".",
"int8",
")",
"xmin",
"=",
"radius",
"+",
"seedsz",
"+",
"offset",
"+",
"2",
"ymin",
"=",
"radius",
"+",
"seedsz",
"+",
"offset",
"+",
"6",
"seeds",
"[",
"offset",
"+",
"12",
",",
"xmin",
"+",
"3",
":",
"xmin",
"+",
"7",
"+",
"seedsz",
",",
"ymin",
":",
"ymin",
"+",
"2",
"]",
"=",
"1",
"seeds",
"[",
"offset",
"+",
"20",
",",
"xmin",
"+",
"7",
":",
"xmin",
"+",
"12",
"+",
"seedsz",
",",
"ymin",
"+",
"5",
":",
"ymin",
"+",
"7",
"]",
"=",
"1",
"# add temp seed",
"if",
"add_object_without_seeds",
":",
"seeds",
"[",
"-",
"3",
",",
"-",
"3",
",",
"-",
"3",
"]",
"=",
"1",
"img",
"=",
"np",
".",
"ones",
"(",
"[",
"sz",
",",
"sz",
"+",
"1",
",",
"sz",
"+",
"2",
"]",
")",
"img",
"=",
"img",
"-",
"seeds",
"seeds",
"[",
"2",
":",
"10",
"+",
"seedsz",
",",
"2",
":",
"9",
"+",
"seedsz",
",",
"2",
":",
"3",
"+",
"seedsz",
"]",
"=",
"2",
"# remove temo seed",
"if",
"add_object_without_seeds",
":",
"seeds",
"[",
"-",
"3",
",",
"-",
"3",
",",
"-",
"3",
"]",
"=",
"0",
"img",
"=",
"scipy",
".",
"ndimage",
".",
"morphology",
".",
"distance_transform_edt",
"(",
"img",
")",
"segm",
"=",
"img",
"<",
"radius",
"img",
"=",
"(",
"100",
"*",
"segm",
"+",
"80",
"*",
"np",
".",
"random",
".",
"random",
"(",
"img",
".",
"shape",
")",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"return",
"img",
",",
"segm",
",",
"seeds"
] | 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",
":",
":",
"param",
"add_object_without_seeds",
":",
"Add",
"also",
"one",
"cube",
"-",
"like",
"object",
"in",
"the",
"corner",
".",
":",
"return",
":"
] | 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])
segm = np.zeros([80, 256, 250], dtype=np.int16)
# liver
segm[30:60, 70:180, 40:190] = slab["liver"]
# porta
segm[40:45, 120:130, 70:190] = slab["porta"]
segm[41:44, 122:127, 68:70] = slab[
"porta"
] # hack to fix stability of skeleton algorithm
#
segm[40:45, 80:130, 100:110] = slab["porta"]
segm[42:44, 77:80, 103:106] = slab[
"porta"
] # hack to fix stability of skeleton algorithm
# segm[41:44, 78:80, 101:109] = slab['porta']
# vertical branch under main branch
segm[40:44, 120:170, 130:135] = slab["porta"]
data3d = np.zeros(segm.shape)
data3d[segm == slab["liver"]] = 146
data3d[segm == slab["porta"]] = 206
noise = np.random.normal(0, 10, segm.shape) # .astype(np.int16)
data3d = (data3d + noise).astype(np.int16)
seeds_liver = np.zeros(data3d.shape, np.int8)
seeds_liver[40:55, 90:120, 70:110] = 1
seeds_liver[30:45, 190:200, 40:90] = 2
seeds_porta = np.zeros(data3d.shape, np.int8)
seeds_porta[40:45, 121:139, 80:95] = 1
if return_dataplus:
datap = {
"data3d": data3d,
"voxelsize_mm": voxelsize_mm,
"slab": slab,
"seeds_liver": seeds_liver,
"seeds_porta": seeds_porta,
"segmentation": segm,
}
return datap
else:
return data3d, segm, voxelsize_mm, slab, seeds_liver, seeds_porta | 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])
segm = np.zeros([80, 256, 250], dtype=np.int16)
# liver
segm[30:60, 70:180, 40:190] = slab["liver"]
# porta
segm[40:45, 120:130, 70:190] = slab["porta"]
segm[41:44, 122:127, 68:70] = slab[
"porta"
] # hack to fix stability of skeleton algorithm
#
segm[40:45, 80:130, 100:110] = slab["porta"]
segm[42:44, 77:80, 103:106] = slab[
"porta"
] # hack to fix stability of skeleton algorithm
# segm[41:44, 78:80, 101:109] = slab['porta']
# vertical branch under main branch
segm[40:44, 120:170, 130:135] = slab["porta"]
data3d = np.zeros(segm.shape)
data3d[segm == slab["liver"]] = 146
data3d[segm == slab["porta"]] = 206
noise = np.random.normal(0, 10, segm.shape) # .astype(np.int16)
data3d = (data3d + noise).astype(np.int16)
seeds_liver = np.zeros(data3d.shape, np.int8)
seeds_liver[40:55, 90:120, 70:110] = 1
seeds_liver[30:45, 190:200, 40:90] = 2
seeds_porta = np.zeros(data3d.shape, np.int8)
seeds_porta[40:45, 121:139, 80:95] = 1
if return_dataplus:
datap = {
"data3d": data3d,
"voxelsize_mm": voxelsize_mm,
"slab": slab,
"seeds_liver": seeds_liver,
"seeds_porta": seeds_porta,
"segmentation": segm,
}
return datap
else:
return data3d, segm, voxelsize_mm, slab, seeds_liver, seeds_porta | [
"def",
"generate_synthetic_liver",
"(",
"return_dataplus",
"=",
"False",
")",
":",
"# data",
"slab",
"=",
"{",
"\"none\"",
":",
"0",
",",
"\"liver\"",
":",
"1",
",",
"\"porta\"",
":",
"2",
"}",
"voxelsize_mm",
"=",
"np",
".",
"array",
"(",
"[",
"1.0",
",",
"1.0",
",",
"1.2",
"]",
")",
"segm",
"=",
"np",
".",
"zeros",
"(",
"[",
"80",
",",
"256",
",",
"250",
"]",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"# liver",
"segm",
"[",
"30",
":",
"60",
",",
"70",
":",
"180",
",",
"40",
":",
"190",
"]",
"=",
"slab",
"[",
"\"liver\"",
"]",
"# porta",
"segm",
"[",
"40",
":",
"45",
",",
"120",
":",
"130",
",",
"70",
":",
"190",
"]",
"=",
"slab",
"[",
"\"porta\"",
"]",
"segm",
"[",
"41",
":",
"44",
",",
"122",
":",
"127",
",",
"68",
":",
"70",
"]",
"=",
"slab",
"[",
"\"porta\"",
"]",
"# hack to fix stability of skeleton algorithm",
"#",
"segm",
"[",
"40",
":",
"45",
",",
"80",
":",
"130",
",",
"100",
":",
"110",
"]",
"=",
"slab",
"[",
"\"porta\"",
"]",
"segm",
"[",
"42",
":",
"44",
",",
"77",
":",
"80",
",",
"103",
":",
"106",
"]",
"=",
"slab",
"[",
"\"porta\"",
"]",
"# hack to fix stability of skeleton algorithm",
"# segm[41:44, 78:80, 101:109] = slab['porta']",
"# vertical branch under main branch",
"segm",
"[",
"40",
":",
"44",
",",
"120",
":",
"170",
",",
"130",
":",
"135",
"]",
"=",
"slab",
"[",
"\"porta\"",
"]",
"data3d",
"=",
"np",
".",
"zeros",
"(",
"segm",
".",
"shape",
")",
"data3d",
"[",
"segm",
"==",
"slab",
"[",
"\"liver\"",
"]",
"]",
"=",
"146",
"data3d",
"[",
"segm",
"==",
"slab",
"[",
"\"porta\"",
"]",
"]",
"=",
"206",
"noise",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"10",
",",
"segm",
".",
"shape",
")",
"# .astype(np.int16)",
"data3d",
"=",
"(",
"data3d",
"+",
"noise",
")",
".",
"astype",
"(",
"np",
".",
"int16",
")",
"seeds_liver",
"=",
"np",
".",
"zeros",
"(",
"data3d",
".",
"shape",
",",
"np",
".",
"int8",
")",
"seeds_liver",
"[",
"40",
":",
"55",
",",
"90",
":",
"120",
",",
"70",
":",
"110",
"]",
"=",
"1",
"seeds_liver",
"[",
"30",
":",
"45",
",",
"190",
":",
"200",
",",
"40",
":",
"90",
"]",
"=",
"2",
"seeds_porta",
"=",
"np",
".",
"zeros",
"(",
"data3d",
".",
"shape",
",",
"np",
".",
"int8",
")",
"seeds_porta",
"[",
"40",
":",
"45",
",",
"121",
":",
"139",
",",
"80",
":",
"95",
"]",
"=",
"1",
"if",
"return_dataplus",
":",
"datap",
"=",
"{",
"\"data3d\"",
":",
"data3d",
",",
"\"voxelsize_mm\"",
":",
"voxelsize_mm",
",",
"\"slab\"",
":",
"slab",
",",
"\"seeds_liver\"",
":",
"seeds_liver",
",",
"\"seeds_porta\"",
":",
"seeds_porta",
",",
"\"segmentation\"",
":",
"segm",
",",
"}",
"return",
"datap",
"else",
":",
"return",
"data3d",
",",
"segm",
",",
"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: | [
"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 = [32, 32]
center = (np.asarray(shape) - 1) / 2.0
r = np.min(center) * face_r
# np.min(np.asarray(shape) / 2.0)
# shape = data3d.shape[1:]
# data3d[center[0], center[1], center[2]] = 1
x, y = np.meshgrid(range(shape[1]), range(shape[0]))
head = (x - center[0]) ** 2 + (y - center[1]) ** 2 < r ** 2
smile = (
((x - center[0]) ** 2 + (y - center[1]) ** 2 < (r * smile_r2) ** 2)
& (y > (center[1] + 0.3 * r))
& ((x - center[0]) ** 2 + (y - center[1]) ** 2 >= (r * smile_r1) ** 2)
)
smile
e1c = center + r * np.array([-0.35, -0.2])
e2c = center + r * np.array([0.35, -0.2])
eyes = (x - e1c[0]) ** 2 + (y - e1c[1]) ** 2 <= (r * eye_r) ** 2
eyes += (x - e2c[0]) ** 2 + (y - e1c[1]) ** 2 <= (r * eye_r) ** 2
face = head & ~smile & ~eyes
return face | 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 = [32, 32]
center = (np.asarray(shape) - 1) / 2.0
r = np.min(center) * face_r
# np.min(np.asarray(shape) / 2.0)
# shape = data3d.shape[1:]
# data3d[center[0], center[1], center[2]] = 1
x, y = np.meshgrid(range(shape[1]), range(shape[0]))
head = (x - center[0]) ** 2 + (y - center[1]) ** 2 < r ** 2
smile = (
((x - center[0]) ** 2 + (y - center[1]) ** 2 < (r * smile_r2) ** 2)
& (y > (center[1] + 0.3 * r))
& ((x - center[0]) ** 2 + (y - center[1]) ** 2 >= (r * smile_r1) ** 2)
)
smile
e1c = center + r * np.array([-0.35, -0.2])
e2c = center + r * np.array([0.35, -0.2])
eyes = (x - e1c[0]) ** 2 + (y - e1c[1]) ** 2 <= (r * eye_r) ** 2
eyes += (x - e2c[0]) ** 2 + (y - e1c[1]) ** 2 <= (r * eye_r) ** 2
face = head & ~smile & ~eyes
return face | [
"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",
":",
"shape",
"=",
"[",
"32",
",",
"32",
"]",
"center",
"=",
"(",
"np",
".",
"asarray",
"(",
"shape",
")",
"-",
"1",
")",
"/",
"2.0",
"r",
"=",
"np",
".",
"min",
"(",
"center",
")",
"*",
"face_r",
"# np.min(np.asarray(shape) / 2.0)",
"# shape = data3d.shape[1:]",
"# data3d[center[0], center[1], center[2]] = 1",
"x",
",",
"y",
"=",
"np",
".",
"meshgrid",
"(",
"range",
"(",
"shape",
"[",
"1",
"]",
")",
",",
"range",
"(",
"shape",
"[",
"0",
"]",
")",
")",
"head",
"=",
"(",
"x",
"-",
"center",
"[",
"0",
"]",
")",
"**",
"2",
"+",
"(",
"y",
"-",
"center",
"[",
"1",
"]",
")",
"**",
"2",
"<",
"r",
"**",
"2",
"smile",
"=",
"(",
"(",
"(",
"x",
"-",
"center",
"[",
"0",
"]",
")",
"**",
"2",
"+",
"(",
"y",
"-",
"center",
"[",
"1",
"]",
")",
"**",
"2",
"<",
"(",
"r",
"*",
"smile_r2",
")",
"**",
"2",
")",
"&",
"(",
"y",
">",
"(",
"center",
"[",
"1",
"]",
"+",
"0.3",
"*",
"r",
")",
")",
"&",
"(",
"(",
"x",
"-",
"center",
"[",
"0",
"]",
")",
"**",
"2",
"+",
"(",
"y",
"-",
"center",
"[",
"1",
"]",
")",
"**",
"2",
">=",
"(",
"r",
"*",
"smile_r1",
")",
"**",
"2",
")",
")",
"smile",
"e1c",
"=",
"center",
"+",
"r",
"*",
"np",
".",
"array",
"(",
"[",
"-",
"0.35",
",",
"-",
"0.2",
"]",
")",
"e2c",
"=",
"center",
"+",
"r",
"*",
"np",
".",
"array",
"(",
"[",
"0.35",
",",
"-",
"0.2",
"]",
")",
"eyes",
"=",
"(",
"x",
"-",
"e1c",
"[",
"0",
"]",
")",
"**",
"2",
"+",
"(",
"y",
"-",
"e1c",
"[",
"1",
"]",
")",
"**",
"2",
"<=",
"(",
"r",
"*",
"eye_r",
")",
"**",
"2",
"eyes",
"+=",
"(",
"x",
"-",
"e2c",
"[",
"0",
"]",
")",
"**",
"2",
"+",
"(",
"y",
"-",
"e1c",
"[",
"1",
"]",
")",
"**",
"2",
"<=",
"(",
"r",
"*",
"eye_r",
")",
"**",
"2",
"face",
"=",
"head",
"&",
"~",
"smile",
"&",
"~",
"eyes",
"return",
"face"
] | 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)
if shape is None:
shape = [32, 32]
nd = len(shape)
if nd == 2:
sh2 = shape
else:
sh2 = shape[1:]
fc2 = _get_face2(
sh2, face_r=face_r, smile_r1=smile_r1, smile_r2=smile_r2, eye_r=eye_r
)
if nd == 2:
return fc2
else:
fc3 = np.zeros(shape)
for i in range(fc3.shape[0]):
fc3[i, :, :] = fc2
return fc3 | 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)
if shape is None:
shape = [32, 32]
nd = len(shape)
if nd == 2:
sh2 = shape
else:
sh2 = shape[1:]
fc2 = _get_face2(
sh2, face_r=face_r, smile_r1=smile_r1, smile_r2=smile_r2, eye_r=eye_r
)
if nd == 2:
return fc2
else:
fc3 = np.zeros(shape)
for i in range(fc3.shape[0]):
fc3[i, :, :] = fc2
return fc3 | [
"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",
"=",
"[",
"32",
",",
"32",
"]",
"nd",
"=",
"len",
"(",
"shape",
")",
"if",
"nd",
"==",
"2",
":",
"sh2",
"=",
"shape",
"else",
":",
"sh2",
"=",
"shape",
"[",
"1",
":",
"]",
"fc2",
"=",
"_get_face2",
"(",
"sh2",
",",
"face_r",
"=",
"face_r",
",",
"smile_r1",
"=",
"smile_r1",
",",
"smile_r2",
"=",
"smile_r2",
",",
"eye_r",
"=",
"eye_r",
")",
"if",
"nd",
"==",
"2",
":",
"return",
"fc2",
"else",
":",
"fc3",
"=",
"np",
".",
"zeros",
"(",
"shape",
")",
"for",
"i",
"in",
"range",
"(",
"fc3",
".",
"shape",
"[",
"0",
"]",
")",
":",
"fc3",
"[",
"i",
",",
":",
",",
":",
"]",
"=",
"fc2",
"return",
"fc3"
] | 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 remove it manually."
)
print(e) | 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 remove it manually."
)
print(e) | [
"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.\"",
")",
"print",
"(",
"e",
")"
] | 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://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip"
logmsg = "downloading from '" + url + "' to '" + destination + "'"
print(logmsg)
logger.info(logmsg)
tmp_filename = url[url.rfind("/") + 1 :]
# tmp_filename = "tmp.zip"
# urllibr.urlretrieve(url, zip_file_name)
from . import network
network.download_file(url, destination, filename=tmp_filename)
zip_file_name = os.path.join(destination, tmp_filename)
base, ext = op.splitext(tmp_filename)
# print(ext)
# print(tmp_filename)
if ext in (".zip"):
unzip_recursive(zip_file_name) | 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://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip"
logmsg = "downloading from '" + url + "' to '" + destination + "'"
print(logmsg)
logger.info(logmsg)
tmp_filename = url[url.rfind("/") + 1 :]
# tmp_filename = "tmp.zip"
# urllibr.urlretrieve(url, zip_file_name)
from . import network
network.download_file(url, destination, filename=tmp_filename)
zip_file_name = os.path.join(destination, tmp_filename)
base, ext = op.splitext(tmp_filename)
# print(ext)
# print(tmp_filename)
if ext in (".zip"):
unzip_recursive(zip_file_name) | [
"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",
"+",
"\"'\"",
"print",
"(",
"logmsg",
")",
"logger",
".",
"info",
"(",
"logmsg",
")",
"tmp_filename",
"=",
"url",
"[",
"url",
".",
"rfind",
"(",
"\"/\"",
")",
"+",
"1",
":",
"]",
"# tmp_filename = \"tmp.zip\"",
"# urllibr.urlretrieve(url, zip_file_name)",
"from",
".",
"import",
"network",
"network",
".",
"download_file",
"(",
"url",
",",
"destination",
",",
"filename",
"=",
"tmp_filename",
")",
"zip_file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"tmp_filename",
")",
"base",
",",
"ext",
"=",
"op",
".",
"splitext",
"(",
"tmp_filename",
")",
"# print(ext)",
"# print(tmp_filename)",
"if",
"ext",
"in",
"(",
"\".zip\"",
")",
":",
"unzip_recursive",
"(",
"zip_file_name",
")"
] | 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)
datafile = zipfile.ZipFile(local_file_name)
namelist = datafile.namelist()
datafile.extractall(destination)
datafile.close()
remove(local_file_name)
fullnamelist = []
for fn in namelist:
fullnamelist.append(op.join(destination, fn))
return fullnamelist | 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)
datafile = zipfile.ZipFile(local_file_name)
namelist = datafile.namelist()
datafile.extractall(destination)
datafile.close()
remove(local_file_name)
fullnamelist = []
for fn in namelist:
fullnamelist.append(op.join(destination, fn))
return fullnamelist | [
"def",
"unzip_one",
"(",
"local_file_name",
")",
":",
"local_file_name",
"=",
"op",
".",
"expanduser",
"(",
"local_file_name",
")",
"destination",
"=",
"op",
".",
"dirname",
"(",
"local_file_name",
")",
"datafile",
"=",
"zipfile",
".",
"ZipFile",
"(",
"local_file_name",
")",
"namelist",
"=",
"datafile",
".",
"namelist",
"(",
")",
"datafile",
".",
"extractall",
"(",
"destination",
")",
"datafile",
".",
"close",
"(",
")",
"remove",
"(",
"local_file_name",
")",
"fullnamelist",
"=",
"[",
"]",
"for",
"fn",
"in",
"namelist",
":",
"fullnamelist",
".",
"append",
"(",
"op",
".",
"join",
"(",
"destination",
",",
"fn",
")",
")",
"return",
"fullnamelist"
] | 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 fn in fnlist:
if zipfile.is_zipfile(fn):
local_fnlist = unzip_recursive(fn)
fnlist.extend(local_fnlist)
return fnlist | 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 fn in fnlist:
if zipfile.is_zipfile(fn):
local_fnlist = unzip_recursive(fn)
fnlist.extend(local_fnlist)
return fnlist | [
"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",
"(",
"fn",
")",
":",
"local_fnlist",
"=",
"unzip_recursive",
"(",
"fn",
")",
"fnlist",
".",
"extend",
"(",
"local_fnlist",
")",
"return",
"fnlist"
] | 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 in record.py
'''
if os.path.exists(filename):
import asciinema.config as aconfig
from asciinema.api import Api
# Load the API class
cfg = aconfig.load()
api = Api(cfg.api_url, os.environ.get("USER"), cfg.install_id)
# Perform the upload, return the url
uploader = UploadCommand(api, filename)
try:
url, warn = uploader.api.upload_asciicast(filename)
if warn:
uploader.print_warning(warn)
# Extract just the url, if provided (always is https)
if url:
match = re.search('https://.+', url)
if match:
url = match.group()
return url
except:
bot.error('Problem with upload, skipping')
else:
bot.warning('Cannot find %s, skipping submission.' %filename) | 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 in record.py
'''
if os.path.exists(filename):
import asciinema.config as aconfig
from asciinema.api import Api
# Load the API class
cfg = aconfig.load()
api = Api(cfg.api_url, os.environ.get("USER"), cfg.install_id)
# Perform the upload, return the url
uploader = UploadCommand(api, filename)
try:
url, warn = uploader.api.upload_asciicast(filename)
if warn:
uploader.print_warning(warn)
# Extract just the url, if provided (always is https)
if url:
match = re.search('https://.+', url)
if match:
url = match.group()
return url
except:
bot.error('Problem with upload, skipping')
else:
bot.warning('Cannot find %s, skipping submission.' %filename) | [
"def",
"upload_asciinema",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"import",
"asciinema",
".",
"config",
"as",
"aconfig",
"from",
"asciinema",
".",
"api",
"import",
"Api",
"# Load the API class",
"cfg",
"=",
"aconfig",
".",
"load",
"(",
")",
"api",
"=",
"Api",
"(",
"cfg",
".",
"api_url",
",",
"os",
".",
"environ",
".",
"get",
"(",
"\"USER\"",
")",
",",
"cfg",
".",
"install_id",
")",
"# Perform the upload, return the url",
"uploader",
"=",
"UploadCommand",
"(",
"api",
",",
"filename",
")",
"try",
":",
"url",
",",
"warn",
"=",
"uploader",
".",
"api",
".",
"upload_asciicast",
"(",
"filename",
")",
"if",
"warn",
":",
"uploader",
".",
"print_warning",
"(",
"warn",
")",
"# Extract just the url, if provided (always is https)",
"if",
"url",
":",
"match",
"=",
"re",
".",
"search",
"(",
"'https://.+'",
",",
"url",
")",
"if",
"match",
":",
"url",
"=",
"match",
".",
"group",
"(",
")",
"return",
"url",
"except",
":",
"bot",
".",
"error",
"(",
"'Problem with upload, skipping'",
")",
"else",
":",
"bot",
".",
"warning",
"(",
"'Cannot find %s, skipping submission.'",
"%",
"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 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(cert_path, 'key.pem'))
ca_cert = os.path.join(cert_path, 'ca.pem')
else:
client_cert = app_config['DOCKER_TLS_CLIENT_CERT']
ca_cert = app_config['DOCKER_TLS_CA_CERT']
client_cert = parse_client_cert_pair(client_cert)
return TLSConfig(
client_cert=client_cert,
ca_cert=ca_cert,
verify=app_config['DOCKER_TLS_VERIFY'],
ssl_version=app_config['DOCKER_TLS_SSL_VERSION'],
assert_hostname=app_config['DOCKER_TLS_ASSERT_HOSTNAME']) | 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(cert_path, 'key.pem'))
ca_cert = os.path.join(cert_path, 'ca.pem')
else:
client_cert = app_config['DOCKER_TLS_CLIENT_CERT']
ca_cert = app_config['DOCKER_TLS_CA_CERT']
client_cert = parse_client_cert_pair(client_cert)
return TLSConfig(
client_cert=client_cert,
ca_cert=ca_cert,
verify=app_config['DOCKER_TLS_VERIFY'],
ssl_version=app_config['DOCKER_TLS_SSL_VERSION'],
assert_hostname=app_config['DOCKER_TLS_ASSERT_HOSTNAME']) | [
"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}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cert_path",
",",
"'cert.pem'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"cert_path",
",",
"'key.pem'",
")",
")",
"ca_cert",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cert_path",
",",
"'ca.pem'",
")",
"else",
":",
"client_cert",
"=",
"app_config",
"[",
"'DOCKER_TLS_CLIENT_CERT'",
"]",
"ca_cert",
"=",
"app_config",
"[",
"'DOCKER_TLS_CA_CERT'",
"]",
"client_cert",
"=",
"parse_client_cert_pair",
"(",
"client_cert",
")",
"return",
"TLSConfig",
"(",
"client_cert",
"=",
"client_cert",
",",
"ca_cert",
"=",
"ca_cert",
",",
"verify",
"=",
"app_config",
"[",
"'DOCKER_TLS_VERIFY'",
"]",
",",
"ssl_version",
"=",
"app_config",
"[",
"'DOCKER_TLS_SSL_VERSION'",
"]",
",",
"assert_hostname",
"=",
"app_config",
"[",
"'DOCKER_TLS_ASSERT_HOSTNAME'",
"]",
")"
] | 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 = ('client_cert should be formatted like '
'"/path/to/cert.pem:/path/to/key.pem"')
raise ValueError('{0!r} is invalid.\n{1}'.format(config_value, tips))
return tuple(client_cert) | 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 = ('client_cert should be formatted like '
'"/path/to/cert.pem:/path/to/key.pem"')
raise ValueError('{0!r} is invalid.\n{1}'.format(config_value, tips))
return tuple(client_cert) | [
"def",
"parse_client_cert_pair",
"(",
"config_value",
")",
":",
"if",
"not",
"config_value",
":",
"return",
"client_cert",
"=",
"config_value",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"client_cert",
")",
"!=",
"2",
":",
"tips",
"=",
"(",
"'client_cert should be formatted like '",
"'\"/path/to/cert.pem:/path/to/key.pem\"'",
")",
"raise",
"ValueError",
"(",
"'{0!r} is invalid.\\n{1}'",
".",
"format",
"(",
"config_value",
",",
"tips",
")",
")",
"return",
"tuple",
"(",
"client_cert",
")"
] | 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)
app.config.setdefault('DOCKER_VERSION', '1.16')
app.config.setdefault('DOCKER_TIMEOUT', 30)
app.config.setdefault('DOCKER_TLS', False)
app.config.setdefault('DOCKER_TLS_VERIFY', True)
app.config.setdefault('DOCKER_TLS_SSL_VERSION', None)
app.config.setdefault('DOCKER_TLS_ASSERT_HOSTNAME', None)
app.config.setdefault('DOCKER_TLS_CERT_PATH', None)
app.config.setdefault('DOCKER_TLS_CLIENT_CERT', None)
app.config.setdefault('DOCKER_TLS_CA_CERT', 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)
app.config.setdefault('DOCKER_VERSION', '1.16')
app.config.setdefault('DOCKER_TIMEOUT', 30)
app.config.setdefault('DOCKER_TLS', False)
app.config.setdefault('DOCKER_TLS_VERIFY', True)
app.config.setdefault('DOCKER_TLS_SSL_VERSION', None)
app.config.setdefault('DOCKER_TLS_ASSERT_HOSTNAME', None)
app.config.setdefault('DOCKER_TLS_CERT_PATH', None)
app.config.setdefault('DOCKER_TLS_CLIENT_CERT', None)
app.config.setdefault('DOCKER_TLS_CA_CERT', None) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"extensions",
"=",
"getattr",
"(",
"app",
",",
"'extensions'",
",",
"{",
"}",
")",
"app",
".",
"extensions",
"[",
"'docker.client'",
"]",
"=",
"None",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_URL'",
",",
"None",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_VERSION'",
",",
"'1.16'",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TIMEOUT'",
",",
"30",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TLS'",
",",
"False",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TLS_VERIFY'",
",",
"True",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TLS_SSL_VERSION'",
",",
"None",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TLS_ASSERT_HOSTNAME'",
",",
"None",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TLS_CERT_PATH'",
",",
"None",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TLS_CLIENT_CERT'",
",",
"None",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'DOCKER_TLS_CA_CERT'",
",",
"None",
")"
] | 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']:
raise RuntimeError('"DOCKER_URL" must be specified')
if not self.app.extensions['docker.client']:
self.app.extensions['docker.client'] = Client(
base_url=self.app.config['DOCKER_URL'],
version=self.app.config['DOCKER_VERSION'],
timeout=self.app.config['DOCKER_TIMEOUT'],
tls=make_tls_config(self.app.config))
return self.app.extensions['docker.client'] | 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']:
raise RuntimeError('"DOCKER_URL" must be specified')
if not self.app.extensions['docker.client']:
self.app.extensions['docker.client'] = Client(
base_url=self.app.config['DOCKER_URL'],
version=self.app.config['DOCKER_VERSION'],
timeout=self.app.config['DOCKER_TIMEOUT'],
tls=make_tls_config(self.app.config))
return self.app.extensions['docker.client'] | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"app",
".",
"config",
"[",
"'DOCKER_URL'",
"]",
":",
"raise",
"RuntimeError",
"(",
"'\"DOCKER_URL\" must be specified'",
")",
"if",
"not",
"self",
".",
"app",
".",
"extensions",
"[",
"'docker.client'",
"]",
":",
"self",
".",
"app",
".",
"extensions",
"[",
"'docker.client'",
"]",
"=",
"Client",
"(",
"base_url",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'DOCKER_URL'",
"]",
",",
"version",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'DOCKER_VERSION'",
"]",
",",
"timeout",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'DOCKER_TIMEOUT'",
"]",
",",
"tls",
"=",
"make_tls_config",
"(",
"self",
".",
"app",
".",
"config",
")",
")",
"return",
"self",
".",
"app",
".",
"extensions",
"[",
"'docker.client'",
"]"
] | 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)
LOGGER.debug("++WAIT: %s: get feed", url)
feed, previous, updated = await feeds.get_feed(self, url)
LOGGER.debug("++DONE: %s: get feed", url)
if updated:
LOGGER.info("Feed %s has been updated", url)
if not feed:
return
LOGGER.debug("--- starting process_feed %s %s", url, send_mentions)
pending = []
try:
for link in feed.links:
href = link['href']
if not href:
continue
# RFC5005 archive links
if self.args.archive and link.get('rel') in ('prev-archive',
'next-archive',
'prev-page',
'next-page'):
LOGGER.debug("Found archive link %s", link)
pending.append(
("process feed " + href, self.process_feed(href, send_mentions)))
# WebSub notification
if updated and link.get('rel') == 'hub' and not feed.is_archive:
LOGGER.debug("Found WebSub hub %s", link)
pending.append(
("update websub " + href, feed.update_websub(self, href)))
except (AttributeError, KeyError):
LOGGER.debug("Feed %s has no links", url)
# Schedule the entries
items = set(feed.entry_links)
if previous:
items |= set(previous.entry_links)
for entry in items:
pending.append(("process entry " + entry,
self.process_entry(entry, send_mentions=send_mentions)))
LOGGER.debug("--- finish process_feed %s %s", url, send_mentions)
if pending:
LOGGER.debug("+++WAIT: process_feed(%s): %d subtasks",
url, len(pending))
LOGGER.debug("%s", [name for (name, _) in pending])
await asyncio.wait([task for (_, task) in pending])
LOGGER.debug("+++DONE: process_feed(%s): %d subtasks",
url, len(pending)) | 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)
LOGGER.debug("++WAIT: %s: get feed", url)
feed, previous, updated = await feeds.get_feed(self, url)
LOGGER.debug("++DONE: %s: get feed", url)
if updated:
LOGGER.info("Feed %s has been updated", url)
if not feed:
return
LOGGER.debug("--- starting process_feed %s %s", url, send_mentions)
pending = []
try:
for link in feed.links:
href = link['href']
if not href:
continue
# RFC5005 archive links
if self.args.archive and link.get('rel') in ('prev-archive',
'next-archive',
'prev-page',
'next-page'):
LOGGER.debug("Found archive link %s", link)
pending.append(
("process feed " + href, self.process_feed(href, send_mentions)))
# WebSub notification
if updated and link.get('rel') == 'hub' and not feed.is_archive:
LOGGER.debug("Found WebSub hub %s", link)
pending.append(
("update websub " + href, feed.update_websub(self, href)))
except (AttributeError, KeyError):
LOGGER.debug("Feed %s has no links", url)
# Schedule the entries
items = set(feed.entry_links)
if previous:
items |= set(previous.entry_links)
for entry in items:
pending.append(("process entry " + entry,
self.process_entry(entry, send_mentions=send_mentions)))
LOGGER.debug("--- finish process_feed %s %s", url, send_mentions)
if pending:
LOGGER.debug("+++WAIT: process_feed(%s): %d subtasks",
url, len(pending))
LOGGER.debug("%s", [name for (name, _) in pending])
await asyncio.wait([task for (_, task) in pending])
LOGGER.debug("+++DONE: process_feed(%s): %d subtasks",
url, len(pending)) | [
"async",
"def",
"process_feed",
"(",
"self",
",",
"url",
",",
"send_mentions",
"=",
"True",
")",
":",
"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",
")",
"LOGGER",
".",
"debug",
"(",
"\"++WAIT: %s: get feed\"",
",",
"url",
")",
"feed",
",",
"previous",
",",
"updated",
"=",
"await",
"feeds",
".",
"get_feed",
"(",
"self",
",",
"url",
")",
"LOGGER",
".",
"debug",
"(",
"\"++DONE: %s: get feed\"",
",",
"url",
")",
"if",
"updated",
":",
"LOGGER",
".",
"info",
"(",
"\"Feed %s has been updated\"",
",",
"url",
")",
"if",
"not",
"feed",
":",
"return",
"LOGGER",
".",
"debug",
"(",
"\"--- starting process_feed %s %s\"",
",",
"url",
",",
"send_mentions",
")",
"pending",
"=",
"[",
"]",
"try",
":",
"for",
"link",
"in",
"feed",
".",
"links",
":",
"href",
"=",
"link",
"[",
"'href'",
"]",
"if",
"not",
"href",
":",
"continue",
"# RFC5005 archive links",
"if",
"self",
".",
"args",
".",
"archive",
"and",
"link",
".",
"get",
"(",
"'rel'",
")",
"in",
"(",
"'prev-archive'",
",",
"'next-archive'",
",",
"'prev-page'",
",",
"'next-page'",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Found archive link %s\"",
",",
"link",
")",
"pending",
".",
"append",
"(",
"(",
"\"process feed \"",
"+",
"href",
",",
"self",
".",
"process_feed",
"(",
"href",
",",
"send_mentions",
")",
")",
")",
"# WebSub notification",
"if",
"updated",
"and",
"link",
".",
"get",
"(",
"'rel'",
")",
"==",
"'hub'",
"and",
"not",
"feed",
".",
"is_archive",
":",
"LOGGER",
".",
"debug",
"(",
"\"Found WebSub hub %s\"",
",",
"link",
")",
"pending",
".",
"append",
"(",
"(",
"\"update websub \"",
"+",
"href",
",",
"feed",
".",
"update_websub",
"(",
"self",
",",
"href",
")",
")",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Feed %s has no links\"",
",",
"url",
")",
"# Schedule the entries",
"items",
"=",
"set",
"(",
"feed",
".",
"entry_links",
")",
"if",
"previous",
":",
"items",
"|=",
"set",
"(",
"previous",
".",
"entry_links",
")",
"for",
"entry",
"in",
"items",
":",
"pending",
".",
"append",
"(",
"(",
"\"process entry \"",
"+",
"entry",
",",
"self",
".",
"process_entry",
"(",
"entry",
",",
"send_mentions",
"=",
"send_mentions",
")",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"--- finish process_feed %s %s\"",
",",
"url",
",",
"send_mentions",
")",
"if",
"pending",
":",
"LOGGER",
".",
"debug",
"(",
"\"+++WAIT: process_feed(%s): %d subtasks\"",
",",
"url",
",",
"len",
"(",
"pending",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"%s\"",
",",
"[",
"name",
"for",
"(",
"name",
",",
"_",
")",
"in",
"pending",
"]",
")",
"await",
"asyncio",
".",
"wait",
"(",
"[",
"task",
"for",
"(",
"_",
",",
"task",
")",
"in",
"pending",
"]",
")",
"LOGGER",
".",
"debug",
"(",
"\"+++DONE: process_feed(%s): %d subtasks\"",
",",
"url",
",",
"len",
"(",
"pending",
")",
")"
] | 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
self._processed_entries.add(url)
LOGGER.debug("++WAIT: get entry %s", url)
entry, previous, updated = await entries.get_entry(self, url)
LOGGER.debug("++DONE: get entry %s", url)
LOGGER.debug("--- starting process_entry %s", url)
pending = []
if updated:
LOGGER.info("Processing entry: %s", url)
if send_mentions:
# get the webmention targets
links = entry.get_targets(self)
if previous:
# Only bother with links that changed from the last time
links = links ^ previous.get_targets(self)
for link in links:
pending.append(("send webmention {} -> {}".format(url, link),
self.send_webmention(entry, link)))
if self.args.recurse:
for feed in entry.feeds:
if utils.get_domain(feed) in self._feed_domains:
pending.append(("process feed " + feed,
self.process_feed(feed, send_mentions=send_mentions)))
else:
LOGGER.info("Ignoring non-local feed %s", feed)
LOGGER.debug("--- finish process_entry %s", url)
if pending:
LOGGER.debug("+++WAIT: process_entry(%s): %d subtasks",
url, len(pending))
LOGGER.debug("%s", [name for (name, _) in pending])
await asyncio.wait([task for (_, task) in pending])
LOGGER.debug("+++DONE: process_entry(%s): %d subtasks",
url, len(pending)) | 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
self._processed_entries.add(url)
LOGGER.debug("++WAIT: get entry %s", url)
entry, previous, updated = await entries.get_entry(self, url)
LOGGER.debug("++DONE: get entry %s", url)
LOGGER.debug("--- starting process_entry %s", url)
pending = []
if updated:
LOGGER.info("Processing entry: %s", url)
if send_mentions:
# get the webmention targets
links = entry.get_targets(self)
if previous:
# Only bother with links that changed from the last time
links = links ^ previous.get_targets(self)
for link in links:
pending.append(("send webmention {} -> {}".format(url, link),
self.send_webmention(entry, link)))
if self.args.recurse:
for feed in entry.feeds:
if utils.get_domain(feed) in self._feed_domains:
pending.append(("process feed " + feed,
self.process_feed(feed, send_mentions=send_mentions)))
else:
LOGGER.info("Ignoring non-local feed %s", feed)
LOGGER.debug("--- finish process_entry %s", url)
if pending:
LOGGER.debug("+++WAIT: process_entry(%s): %d subtasks",
url, len(pending))
LOGGER.debug("%s", [name for (name, _) in pending])
await asyncio.wait([task for (_, task) in pending])
LOGGER.debug("+++DONE: process_entry(%s): %d subtasks",
url, len(pending)) | [
"async",
"def",
"process_entry",
"(",
"self",
",",
"url",
",",
"add_domain",
"=",
"False",
",",
"send_mentions",
"=",
"True",
")",
":",
"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",
"self",
".",
"_processed_entries",
".",
"add",
"(",
"url",
")",
"LOGGER",
".",
"debug",
"(",
"\"++WAIT: get entry %s\"",
",",
"url",
")",
"entry",
",",
"previous",
",",
"updated",
"=",
"await",
"entries",
".",
"get_entry",
"(",
"self",
",",
"url",
")",
"LOGGER",
".",
"debug",
"(",
"\"++DONE: get entry %s\"",
",",
"url",
")",
"LOGGER",
".",
"debug",
"(",
"\"--- starting process_entry %s\"",
",",
"url",
")",
"pending",
"=",
"[",
"]",
"if",
"updated",
":",
"LOGGER",
".",
"info",
"(",
"\"Processing entry: %s\"",
",",
"url",
")",
"if",
"send_mentions",
":",
"# get the webmention targets",
"links",
"=",
"entry",
".",
"get_targets",
"(",
"self",
")",
"if",
"previous",
":",
"# Only bother with links that changed from the last time",
"links",
"=",
"links",
"^",
"previous",
".",
"get_targets",
"(",
"self",
")",
"for",
"link",
"in",
"links",
":",
"pending",
".",
"append",
"(",
"(",
"\"send webmention {} -> {}\"",
".",
"format",
"(",
"url",
",",
"link",
")",
",",
"self",
".",
"send_webmention",
"(",
"entry",
",",
"link",
")",
")",
")",
"if",
"self",
".",
"args",
".",
"recurse",
":",
"for",
"feed",
"in",
"entry",
".",
"feeds",
":",
"if",
"utils",
".",
"get_domain",
"(",
"feed",
")",
"in",
"self",
".",
"_feed_domains",
":",
"pending",
".",
"append",
"(",
"(",
"\"process feed \"",
"+",
"feed",
",",
"self",
".",
"process_feed",
"(",
"feed",
",",
"send_mentions",
"=",
"send_mentions",
")",
")",
")",
"else",
":",
"LOGGER",
".",
"info",
"(",
"\"Ignoring non-local feed %s\"",
",",
"feed",
")",
"LOGGER",
".",
"debug",
"(",
"\"--- finish process_entry %s\"",
",",
"url",
")",
"if",
"pending",
":",
"LOGGER",
".",
"debug",
"(",
"\"+++WAIT: process_entry(%s): %d subtasks\"",
",",
"url",
",",
"len",
"(",
"pending",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"%s\"",
",",
"[",
"name",
"for",
"(",
"name",
",",
"_",
")",
"in",
"pending",
"]",
")",
"await",
"asyncio",
".",
"wait",
"(",
"[",
"task",
"for",
"(",
"_",
",",
"task",
")",
"in",
"pending",
"]",
")",
"LOGGER",
".",
"debug",
"(",
"\"+++DONE: process_entry(%s): %d subtasks\"",
",",
"url",
",",
"len",
"(",
"pending",
")",
")"
] | 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))
LOGGER.debug("++WAIT: webmentions.get_target %s", url)
target = await webmentions.get_target(self, url)
LOGGER.debug("++DONE: webmentions.get_target %s", url)
if target:
LOGGER.debug("++WAIT: Sending webmention %s -> %s", entry.url, url)
await target.send(self, entry)
LOGGER.debug("++DONE: Sending webmention %s -> %s", 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))
LOGGER.debug("++WAIT: webmentions.get_target %s", url)
target = await webmentions.get_target(self, url)
LOGGER.debug("++DONE: webmentions.get_target %s", url)
if target:
LOGGER.debug("++WAIT: Sending webmention %s -> %s", entry.url, url)
await target.send(self, entry)
LOGGER.debug("++DONE: Sending webmention %s -> %s", 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\"",
",",
"entry",
".",
"url",
",",
"url",
")",
"self",
".",
"_processed_mentions",
".",
"add",
"(",
"(",
"entry",
".",
"url",
",",
"url",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"++WAIT: webmentions.get_target %s\"",
",",
"url",
")",
"target",
"=",
"await",
"webmentions",
".",
"get_target",
"(",
"self",
",",
"url",
")",
"LOGGER",
".",
"debug",
"(",
"\"++DONE: webmentions.get_target %s\"",
",",
"url",
")",
"if",
"target",
":",
"LOGGER",
".",
"debug",
"(",
"\"++WAIT: Sending webmention %s -> %s\"",
",",
"entry",
".",
"url",
",",
"url",
")",
"await",
"target",
".",
"send",
"(",
"self",
",",
"entry",
")",
"LOGGER",
".",
"debug",
"(",
"\"++DONE: Sending webmention %s -> %s\"",
",",
"entry",
".",
"url",
",",
"url",
")"
] | 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",
"=",
"True",
")",
"else",
":",
"call_command",
"(",
"'compilemessages'",
")"
] | 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",
"(",
"'makemessages'",
",",
"locale",
"=",
"(",
"locale",
",",
")",
")"
] | 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 available only if django CMS is installed') | 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 available only if django CMS is installed') | [
"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'",
",",
"'check'",
")",
"except",
"ImportError",
":",
"print",
"(",
"'cms_check available only if django CMS is installed'",
")"
] | 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 += [extra_applications]
elif isinstance(extra_applications, list):
apps += extra_applications
for app in apps:
call_command('makemigrations', *(app,), merge=merge, dry_run=dry_run, empty=empty) | 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 += [extra_applications]
elif isinstance(extra_applications, list):
apps += extra_applications
for app in apps:
call_command('makemigrations', *(app,), merge=merge, dry_run=dry_run, empty=empty) | [
"def",
"makemigrations",
"(",
"application",
",",
"merge",
"=",
"False",
",",
"dry_run",
"=",
"False",
",",
"empty",
"=",
"False",
",",
"extra_applications",
"=",
"None",
")",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"call_command",
"apps",
"=",
"[",
"application",
"]",
"if",
"extra_applications",
":",
"if",
"isinstance",
"(",
"extra_applications",
",",
"text_type",
")",
":",
"apps",
"+=",
"[",
"extra_applications",
"]",
"elif",
"isinstance",
"(",
"extra_applications",
",",
"list",
")",
":",
"apps",
"+=",
"extra_applications",
"for",
"app",
"in",
"apps",
":",
"call_command",
"(",
"'makemigrations'",
",",
"*",
"(",
"app",
",",
")",
",",
"merge",
"=",
"merge",
",",
"dry_run",
"=",
"dry_run",
",",
"empty",
"=",
"empty",
")"
] | 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 = []
authors = []
for authfile in ('AUTHORS', 'AUTHORS.rst'):
if os.path.exists(authfile):
break
with open(authfile, 'r') as f:
for line in f.readlines():
if line.startswith("*"):
author = force_text(line).strip("* \n")
if author.lower() not in seen_authors:
seen_authors.append(author.lower())
authors.append(author)
for author in r.stdout.readlines():
author = force_text(author).strip()
if author.lower() not in seen_authors:
seen_authors.append(author.lower())
authors.append(author)
# Sort our list of Authors by their case insensitive name
authors = sorted(authors, key=lambda x: x.lower())
# Write our authors to the AUTHORS file
print('Authors (%s):\n\n\n* %s' % (len(authors), '\n* '.join(authors))) | 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 = []
authors = []
for authfile in ('AUTHORS', 'AUTHORS.rst'):
if os.path.exists(authfile):
break
with open(authfile, 'r') as f:
for line in f.readlines():
if line.startswith("*"):
author = force_text(line).strip("* \n")
if author.lower() not in seen_authors:
seen_authors.append(author.lower())
authors.append(author)
for author in r.stdout.readlines():
author = force_text(author).strip()
if author.lower() not in seen_authors:
seen_authors.append(author.lower())
authors.append(author)
# Sort our list of Authors by their case insensitive name
authors = sorted(authors, key=lambda x: x.lower())
# Write our authors to the AUTHORS file
print('Authors (%s):\n\n\n* %s' % (len(authors), '\n* '.join(authors))) | [
"def",
"generate_authors",
"(",
")",
":",
"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",
"=",
"[",
"]",
"authors",
"=",
"[",
"]",
"for",
"authfile",
"in",
"(",
"'AUTHORS'",
",",
"'AUTHORS.rst'",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"authfile",
")",
":",
"break",
"with",
"open",
"(",
"authfile",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"*\"",
")",
":",
"author",
"=",
"force_text",
"(",
"line",
")",
".",
"strip",
"(",
"\"* \\n\"",
")",
"if",
"author",
".",
"lower",
"(",
")",
"not",
"in",
"seen_authors",
":",
"seen_authors",
".",
"append",
"(",
"author",
".",
"lower",
"(",
")",
")",
"authors",
".",
"append",
"(",
"author",
")",
"for",
"author",
"in",
"r",
".",
"stdout",
".",
"readlines",
"(",
")",
":",
"author",
"=",
"force_text",
"(",
"author",
")",
".",
"strip",
"(",
")",
"if",
"author",
".",
"lower",
"(",
")",
"not",
"in",
"seen_authors",
":",
"seen_authors",
".",
"append",
"(",
"author",
".",
"lower",
"(",
")",
")",
"authors",
".",
"append",
"(",
"author",
")",
"# Sort our list of Authors by their case insensitive name",
"authors",
"=",
"sorted",
"(",
"authors",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"lower",
"(",
")",
")",
"# Write our authors to the AUTHORS file",
"print",
"(",
"'Authors (%s):\\n\\n\\n* %s'",
"%",
"(",
"len",
"(",
"authors",
")",
",",
"'\\n* '",
".",
"join",
"(",
"authors",
")",
")",
")"
] | 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,))
if type(report) == tuple:
assert report[0] == 0
else:
assert report == 0
except ImportError:
print('Static analysis available only if django CMS is installed') | 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,))
if type(report) == tuple:
assert report[0] == 0
else:
assert report == 0
except ImportError:
print('Static analysis available only if django CMS is installed') | [
"def",
"static_analisys",
"(",
"application",
")",
":",
"try",
":",
"from",
"cms",
".",
"test_utils",
".",
"util",
".",
"static_analysis",
"import",
"pyflakes",
"application_module",
"=",
"__import__",
"(",
"application",
")",
"report",
"=",
"pyflakes",
"(",
"(",
"application_module",
",",
")",
")",
"if",
"type",
"(",
"report",
")",
"==",
"tuple",
":",
"assert",
"report",
"[",
"0",
"]",
"==",
"0",
"else",
":",
"assert",
"report",
"==",
"0",
"except",
"ImportError",
":",
"print",
"(",
"'Static analysis available only if django CMS is installed'",
")"
] | 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("Version mismatch during release, expected={}, found={}"
.format(expected_version, version)) | 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("Version mismatch during release, expected={}, found={}"
.format(expected_version, version)) | [
"def",
"check_version",
"(",
"expected_version",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root_folder",
",",
"'VERSION'",
")",
",",
"'r'",
")",
"as",
"version_file",
":",
"version",
"=",
"version_file",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"if",
"version",
"!=",
"expected_version",
":",
"raise",
"EnvironmentError",
"(",
"\"Version mismatch during release, expected={}, found={}\"",
".",
"format",
"(",
"expected_version",
",",
"version",
")",
")"
] | 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'",
",",
"[",
"'-q'",
",",
"'clean'",
",",
"'--all'",
",",
"'bdist_wheel'",
",",
"'--plat-name'",
",",
"'{}_{}'",
".",
"format",
"(",
"system",
",",
"platform",
")",
"]",
")"
] | 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']
pypi_pass = os.environ['PYPI_PASS']
else:
pypi_user = None
pypi_pass = None
print("No PYPI user information in environment")
packages = glob.glob(dist_dir)
# Invoke upload this way since subprocess call of twine cli has cross platform issues
twine_upload(packages, 'pypi', False, None, pypi_user, pypi_pass, None, None, '~/.pypirc', False, None, None, None) | 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']
pypi_pass = os.environ['PYPI_PASS']
else:
pypi_user = None
pypi_pass = None
print("No PYPI user information in environment")
packages = glob.glob(dist_dir)
# Invoke upload this way since subprocess call of twine cli has cross platform issues
twine_upload(packages, 'pypi', False, None, pypi_user, pypi_pass, None, None, '~/.pypirc', False, None, None, None) | [
"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",
"[",
"'PYPI_PASS'",
"]",
"else",
":",
"pypi_user",
"=",
"None",
"pypi_pass",
"=",
"None",
"print",
"(",
"\"No PYPI user information in environment\"",
")",
"packages",
"=",
"glob",
".",
"glob",
"(",
"dist_dir",
")",
"# Invoke upload this way since subprocess call of twine cli has cross platform issues",
"twine_upload",
"(",
"packages",
",",
"'pypi'",
",",
"False",
",",
"None",
",",
"pypi_user",
",",
"pypi_pass",
",",
"None",
",",
"None",
",",
"'~/.pypirc'",
",",
"False",
",",
"None",
",",
"None",
",",
"None",
")"
] | 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""",
)
parser.add_argument("-f", "--func_name", default="main")
parser.add_argument("-a", "--args", dest="args", nargs="*")
parser.add_argument("-k", "--kwargs", dest="kwargs")
parser.add_argument(
"-i",
"-s",
"--info",
"--show",
"--status",
dest="show",
action="store_true",
help="show the args, kwargs and function's source code.",
)
params = parser.parse_args()
func_name = params.func_name
func = globals().get(func_name)
if not (callable(func)):
Config.utils_logger.warning("invalid func_name: %s" % func_name)
return
args = params.args or []
kwargs = params.kwargs or {}
if kwargs:
items = [re.split("[:=]", i) for i in re.split("[,;]+", kwargs)]
kwargs = dict(items)
if params.show:
from inspect import getsource
Config.utils_logger.info("args: %s; kwargs: %s" % (args, kwargs))
Config.utils_logger.info(getsource(func))
return
func(*args, **kwargs) | 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""",
)
parser.add_argument("-f", "--func_name", default="main")
parser.add_argument("-a", "--args", dest="args", nargs="*")
parser.add_argument("-k", "--kwargs", dest="kwargs")
parser.add_argument(
"-i",
"-s",
"--info",
"--show",
"--status",
dest="show",
action="store_true",
help="show the args, kwargs and function's source code.",
)
params = parser.parse_args()
func_name = params.func_name
func = globals().get(func_name)
if not (callable(func)):
Config.utils_logger.warning("invalid func_name: %s" % func_name)
return
args = params.args or []
kwargs = params.kwargs or {}
if kwargs:
items = [re.split("[:=]", i) for i in re.split("[,;]+", kwargs)]
kwargs = dict(items)
if params.show:
from inspect import getsource
Config.utils_logger.info("args: %s; kwargs: %s" % (args, kwargs))
Config.utils_logger.info(getsource(func))
return
func(*args, **kwargs) | [
"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\"\"\"",
",",
")",
"parser",
".",
"add_argument",
"(",
"\"-f\"",
",",
"\"--func_name\"",
",",
"default",
"=",
"\"main\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-a\"",
",",
"\"--args\"",
",",
"dest",
"=",
"\"args\"",
",",
"nargs",
"=",
"\"*\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-k\"",
",",
"\"--kwargs\"",
",",
"dest",
"=",
"\"kwargs\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-i\"",
",",
"\"-s\"",
",",
"\"--info\"",
",",
"\"--show\"",
",",
"\"--status\"",
",",
"dest",
"=",
"\"show\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"show the args, kwargs and function's source code.\"",
",",
")",
"params",
"=",
"parser",
".",
"parse_args",
"(",
")",
"func_name",
"=",
"params",
".",
"func_name",
"func",
"=",
"globals",
"(",
")",
".",
"get",
"(",
"func_name",
")",
"if",
"not",
"(",
"callable",
"(",
"func",
")",
")",
":",
"Config",
".",
"utils_logger",
".",
"warning",
"(",
"\"invalid func_name: %s\"",
"%",
"func_name",
")",
"return",
"args",
"=",
"params",
".",
"args",
"or",
"[",
"]",
"kwargs",
"=",
"params",
".",
"kwargs",
"or",
"{",
"}",
"if",
"kwargs",
":",
"items",
"=",
"[",
"re",
".",
"split",
"(",
"\"[:=]\"",
",",
"i",
")",
"for",
"i",
"in",
"re",
".",
"split",
"(",
"\"[,;]+\"",
",",
"kwargs",
")",
"]",
"kwargs",
"=",
"dict",
"(",
"items",
")",
"if",
"params",
".",
"show",
":",
"from",
"inspect",
"import",
"getsource",
"Config",
".",
"utils_logger",
".",
"info",
"(",
"\"args: %s; kwargs: %s\"",
"%",
"(",
"args",
",",
"kwargs",
")",
")",
"Config",
".",
"utils_logger",
".",
"info",
"(",
"getsource",
"(",
"func",
")",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | ``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 = vars()[unit]
print_info("memory usage: %.2f(%s)" % (result, unit))
return result
except ImportError:
print_info("pip install psutil first.") | 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 = vars()[unit]
print_info("memory usage: %.2f(%s)" % (result, unit))
return result
except ImportError:
print_info("pip install psutil first.") | [
"def",
"print_mem",
"(",
"unit",
"=",
"\"MB\"",
")",
":",
"try",
":",
"import",
"psutil",
"B",
"=",
"float",
"(",
"psutil",
".",
"Process",
"(",
"os",
".",
"getpid",
"(",
")",
")",
".",
"memory_info",
"(",
")",
".",
"vms",
")",
"KB",
"=",
"B",
"/",
"1024",
"MB",
"=",
"KB",
"/",
"1024",
"GB",
"=",
"MB",
"/",
"1024",
"result",
"=",
"vars",
"(",
")",
"[",
"unit",
"]",
"print_info",
"(",
"\"memory usage: %.2f(%s)\"",
"%",
"(",
"result",
",",
"unit",
")",
")",
"return",
"result",
"except",
"ImportError",
":",
"print_info",
"(",
"\"pip install psutil first.\"",
")"
] | 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 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0' -H 'Pragma: no-cache' -H 'DNT: 1' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Cache-Control: no-cache' -H 'Referer: https://p.3.cn?skuIds=1&nonsense=1&nonce=0' -H 'Cookie: ASPSESSIONIDSQRRSADB=MLHDPOPCAMBDGPFGBEEJKLAF' -H 'Connection: keep-alive' --compressed'''
>>> request_args = curlparse(curl_string)
>>> request_args
{'url': 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0', 'headers': {'Pragma': 'no-cache', 'Dnt': '1', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Cache-Control': 'no-cache', 'Referer': 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0', 'Cookie': 'ASPSESSIONIDSQRRSADB=MLHDPOPCAMBDGPFGBEEJKLAF', 'Connection': 'keep-alive'}, 'method': 'get'}
>>> import requests
>>> requests.request(**request_args)
<Response [200]>
"""
assert "\n" not in string, 'curl-string should not contain \\n, try r"...".'
if string.startswith("http"):
return {"url": string, "method": "get"}
args, unknown = _Curl.parser.parse_known_args(shlex.split(string.strip()))
requests_args = {}
headers = {}
requests_args["url"] = args.url
for header in args.header:
key, value = header.split(":", 1)
headers[key.title()] = value.strip()
if args.user_agent:
headers["User-Agent"] = args.user_agent
if headers:
requests_args["headers"] = headers
if args.user:
requests_args["auth"] = tuple(u for u in args.user.split(":", 1) + [""])[:2]
# if args.proxy:
# pass
data = args.data or args.data_binary or args.form
if data:
if data.startswith("$"):
data = data[1:]
args.method = "post"
if "application/x-www-form-urlencoded" in headers.get("Content-Type", ""):
data = dict(
[
(i.split("=")[0], unquote_plus(i.split("=")[1]))
for i in data.split("&")
]
)
requests_args["data"] = data
else:
data = data.encode(encoding)
requests_args["data"] = data
requests_args["method"] = args.method.lower()
if args.connect_timeout:
requests_args["timeout"] = args.connect_timeout
return requests_args | 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 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0' -H 'Pragma: no-cache' -H 'DNT: 1' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Cache-Control: no-cache' -H 'Referer: https://p.3.cn?skuIds=1&nonsense=1&nonce=0' -H 'Cookie: ASPSESSIONIDSQRRSADB=MLHDPOPCAMBDGPFGBEEJKLAF' -H 'Connection: keep-alive' --compressed'''
>>> request_args = curlparse(curl_string)
>>> request_args
{'url': 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0', 'headers': {'Pragma': 'no-cache', 'Dnt': '1', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Cache-Control': 'no-cache', 'Referer': 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0', 'Cookie': 'ASPSESSIONIDSQRRSADB=MLHDPOPCAMBDGPFGBEEJKLAF', 'Connection': 'keep-alive'}, 'method': 'get'}
>>> import requests
>>> requests.request(**request_args)
<Response [200]>
"""
assert "\n" not in string, 'curl-string should not contain \\n, try r"...".'
if string.startswith("http"):
return {"url": string, "method": "get"}
args, unknown = _Curl.parser.parse_known_args(shlex.split(string.strip()))
requests_args = {}
headers = {}
requests_args["url"] = args.url
for header in args.header:
key, value = header.split(":", 1)
headers[key.title()] = value.strip()
if args.user_agent:
headers["User-Agent"] = args.user_agent
if headers:
requests_args["headers"] = headers
if args.user:
requests_args["auth"] = tuple(u for u in args.user.split(":", 1) + [""])[:2]
# if args.proxy:
# pass
data = args.data or args.data_binary or args.form
if data:
if data.startswith("$"):
data = data[1:]
args.method = "post"
if "application/x-www-form-urlencoded" in headers.get("Content-Type", ""):
data = dict(
[
(i.split("=")[0], unquote_plus(i.split("=")[1]))
for i in data.split("&")
]
)
requests_args["data"] = data
else:
data = data.encode(encoding)
requests_args["data"] = data
requests_args["method"] = args.method.lower()
if args.connect_timeout:
requests_args["timeout"] = args.connect_timeout
return requests_args | [
"def",
"curlparse",
"(",
"string",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"assert",
"\"\\n\"",
"not",
"in",
"string",
",",
"'curl-string should not contain \\\\n, try r\"...\".'",
"if",
"string",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"return",
"{",
"\"url\"",
":",
"string",
",",
"\"method\"",
":",
"\"get\"",
"}",
"args",
",",
"unknown",
"=",
"_Curl",
".",
"parser",
".",
"parse_known_args",
"(",
"shlex",
".",
"split",
"(",
"string",
".",
"strip",
"(",
")",
")",
")",
"requests_args",
"=",
"{",
"}",
"headers",
"=",
"{",
"}",
"requests_args",
"[",
"\"url\"",
"]",
"=",
"args",
".",
"url",
"for",
"header",
"in",
"args",
".",
"header",
":",
"key",
",",
"value",
"=",
"header",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"headers",
"[",
"key",
".",
"title",
"(",
")",
"]",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"args",
".",
"user_agent",
":",
"headers",
"[",
"\"User-Agent\"",
"]",
"=",
"args",
".",
"user_agent",
"if",
"headers",
":",
"requests_args",
"[",
"\"headers\"",
"]",
"=",
"headers",
"if",
"args",
".",
"user",
":",
"requests_args",
"[",
"\"auth\"",
"]",
"=",
"tuple",
"(",
"u",
"for",
"u",
"in",
"args",
".",
"user",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"+",
"[",
"\"\"",
"]",
")",
"[",
":",
"2",
"]",
"# if args.proxy:",
"# pass",
"data",
"=",
"args",
".",
"data",
"or",
"args",
".",
"data_binary",
"or",
"args",
".",
"form",
"if",
"data",
":",
"if",
"data",
".",
"startswith",
"(",
"\"$\"",
")",
":",
"data",
"=",
"data",
"[",
"1",
":",
"]",
"args",
".",
"method",
"=",
"\"post\"",
"if",
"\"application/x-www-form-urlencoded\"",
"in",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
",",
"\"\"",
")",
":",
"data",
"=",
"dict",
"(",
"[",
"(",
"i",
".",
"split",
"(",
"\"=\"",
")",
"[",
"0",
"]",
",",
"unquote_plus",
"(",
"i",
".",
"split",
"(",
"\"=\"",
")",
"[",
"1",
"]",
")",
")",
"for",
"i",
"in",
"data",
".",
"split",
"(",
"\"&\"",
")",
"]",
")",
"requests_args",
"[",
"\"data\"",
"]",
"=",
"data",
"else",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"encoding",
")",
"requests_args",
"[",
"\"data\"",
"]",
"=",
"data",
"requests_args",
"[",
"\"method\"",
"]",
"=",
"args",
".",
"method",
".",
"lower",
"(",
")",
"if",
"args",
".",
"connect_timeout",
":",
"requests_args",
"[",
"\"timeout\"",
"]",
"=",
"args",
".",
"connect_timeout",
"return",
"requests_args"
] | 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 'Pragma: no-cache' -H 'DNT: 1' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Cache-Control: no-cache' -H 'Referer: https://p.3.cn?skuIds=1&nonsense=1&nonce=0' -H 'Cookie: ASPSESSIONIDSQRRSADB=MLHDPOPCAMBDGPFGBEEJKLAF' -H 'Connection: keep-alive' --compressed'''
>>> request_args = curlparse(curl_string)
>>> request_args
{'url': 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0', 'headers': {'Pragma': 'no-cache', 'Dnt': '1', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Cache-Control': 'no-cache', 'Referer': 'https://p.3.cn?skuIds=1&nonsense=1&nonce=0', 'Cookie': 'ASPSESSIONIDSQRRSADB=MLHDPOPCAMBDGPFGBEEJKLAF', 'Connection': 'keep-alive'}, 'method': 'get'}
>>> import requests
>>> requests.request(**request_args)
<Response [200]> | [
"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",
"in",
"slice_by_size",
"(",
"seq",
",",
"size",
")",
":",
"yield",
"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:
yield it | 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:
yield it | [
"def",
"slice_by_size",
"(",
"seq",
",",
"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",
":",
"yield",
"it"
] | 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 with Config.TIMEZONE).
:param fail: while raising an exception, return it.
:param fmt: %Y-%m-%d %H:%M:%S, %z not work.
:rtype: str
>>> ttime()
2018-03-15 01:24:35
>>> ttime(1486572818.421858323)
2017-02-09 00:53:38
"""
tzone = Config.TIMEZONE if tzone is None else tzone
fix_tz = tzone * 3600
if timestamp is None:
timestamp = time.time()
else:
timestamp = float(timestamp)
if 1e12 <= timestamp < 1e13:
# Compatible timestamp with 13-digit milliseconds
timestamp = timestamp / 1000
try:
timestamp = time.time() if timestamp is None else timestamp
return time.strftime(fmt, time.gmtime(timestamp + fix_tz))
except:
import traceback
traceback.print_exc()
return fail | 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 with Config.TIMEZONE).
:param fail: while raising an exception, return it.
:param fmt: %Y-%m-%d %H:%M:%S, %z not work.
:rtype: str
>>> ttime()
2018-03-15 01:24:35
>>> ttime(1486572818.421858323)
2017-02-09 00:53:38
"""
tzone = Config.TIMEZONE if tzone is None else tzone
fix_tz = tzone * 3600
if timestamp is None:
timestamp = time.time()
else:
timestamp = float(timestamp)
if 1e12 <= timestamp < 1e13:
# Compatible timestamp with 13-digit milliseconds
timestamp = timestamp / 1000
try:
timestamp = time.time() if timestamp is None else timestamp
return time.strftime(fmt, time.gmtime(timestamp + fix_tz))
except:
import traceback
traceback.print_exc()
return fail | [
"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",
"=",
"tzone",
"*",
"3600",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"else",
":",
"timestamp",
"=",
"float",
"(",
"timestamp",
")",
"if",
"1e12",
"<=",
"timestamp",
"<",
"1e13",
":",
"# Compatible timestamp with 13-digit milliseconds",
"timestamp",
"=",
"timestamp",
"/",
"1000",
"try",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"if",
"timestamp",
"is",
"None",
"else",
"timestamp",
"return",
"time",
".",
"strftime",
"(",
"fmt",
",",
"time",
".",
"gmtime",
"(",
"timestamp",
"+",
"fix_tz",
")",
")",
"except",
":",
"import",
"traceback",
"traceback",
".",
"print_exc",
"(",
")",
"return",
"fail"
] | 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.
:param fmt: %Y-%m-%d %H:%M:%S, %z not work.
:rtype: str
>>> ttime()
2018-03-15 01:24:35
>>> ttime(1486572818.421858323)
2017-02-09 00:53:38 | [
"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.TIMEZONE).
:param fail: while raising an exception, return it.
:param fmt: %Y-%m-%d %H:%M:%S, %z not work.
:rtype: int
>>> ptime('2018-03-15 01:27:56')
1521048476
"""
tzone = Config.TIMEZONE if tzone is None else tzone
fix_tz = -(tzone * 3600 + time.timezone)
#: str(timestr) for datetime.datetime object
timestr = str(timestr or ttime())
try:
return int(time.mktime(time.strptime(timestr, fmt)) + fix_tz)
except:
return fail | 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.TIMEZONE).
:param fail: while raising an exception, return it.
:param fmt: %Y-%m-%d %H:%M:%S, %z not work.
:rtype: int
>>> ptime('2018-03-15 01:27:56')
1521048476
"""
tzone = Config.TIMEZONE if tzone is None else tzone
fix_tz = -(tzone * 3600 + time.timezone)
#: str(timestr) for datetime.datetime object
timestr = str(timestr or ttime())
try:
return int(time.mktime(time.strptime(timestr, fmt)) + fix_tz)
except:
return fail | [
"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",
"=",
"-",
"(",
"tzone",
"*",
"3600",
"+",
"time",
".",
"timezone",
")",
"#: str(timestr) for datetime.datetime object",
"timestr",
"=",
"str",
"(",
"timestr",
"or",
"ttime",
"(",
")",
")",
"try",
":",
"return",
"int",
"(",
"time",
".",
"mktime",
"(",
"time",
".",
"strptime",
"(",
"timestr",
",",
"fmt",
")",
")",
"+",
"fix_tz",
")",
"except",
":",
"return",
"fail"
] | 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 fmt: %Y-%m-%d %H:%M:%S, %z not work.
:rtype: int
>>> ptime('2018-03-15 01:27:56')
1521048476 | [
"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 = ms, []
for divisor in divisors[::-1]:
quotient, remainder = divmod(quotient, divisor)
result.append(quotient) if divisor == 1 else result.append(remainder)
return result[::-1] | 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 = ms, []
for divisor in divisors[::-1]:
quotient, remainder = divmod(quotient, divisor)
result.append(quotient) if divisor == 1 else result.append(remainder)
return result[::-1] | [
"def",
"split_seconds",
"(",
"seconds",
")",
":",
"ms",
"=",
"seconds",
"*",
"1000",
"divisors",
"=",
"(",
"1",
",",
"24",
",",
"60",
",",
"60",
",",
"1000",
")",
"quotient",
",",
"result",
"=",
"ms",
",",
"[",
"]",
"for",
"divisor",
"in",
"divisors",
"[",
":",
":",
"-",
"1",
"]",
":",
"quotient",
",",
"remainder",
"=",
"divmod",
"(",
"quotient",
",",
"divisor",
")",
"result",
".",
"append",
"(",
"quotient",
")",
"if",
"divisor",
"==",
"1",
"else",
"result",
".",
"append",
"(",
"remainder",
")",
"return",
"result",
"[",
":",
":",
"-",
"1",
"]"
] | 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 or cn.
:param units: day, hour, minute, second, ms.
>>> timeago(93245732.0032424, 5)
'1079 days, 05:35:32,003'
>>> timeago(93245732.0032424, 4, 1)
'1079 days 5 hours 35 minutes 32 seconds'
>>> timeago(-389, 4, 1)
'-6 minutes 29 seconds 0 ms'
"""
assert format in [0, 1, 2], ValueError("format arg should be one of 0, 1, 2")
negative = "-" if seconds < 0 else ""
seconds = abs(seconds)
if lang == "en":
units = ("day", "hour", "minute", "second", "ms")
elif lang == "cn":
units = (u"天", u"小时", u"分钟", u"秒", u"毫秒")
times = split_seconds(seconds)
if format == 2:
return dict(zip(units, times))
day, hour, minute, second, ms = times
if format == 0:
day_str = (
"%d %s%s, " % (day, units[0], "s" if day > 1 and lang == "en" else "")
if day
else ""
)
mid_str = ":".join(("%02d" % i for i in (hour, minute, second)))
if accuracy > 4:
mid_str += ",%03d" % ms
return negative + day_str + mid_str
elif format == 1:
# find longest valid fields index (non-zero in front)
valid_index = 0
for x, i in enumerate(times):
if i > 0:
valid_index = x
break
else:
valid_index = x
result_str = [
"%d %s%s"
% (num, unit, "s" if lang == "en" and num > 1 and unit != "ms" else "")
for num, unit in zip(times, units)
][valid_index:][:accuracy]
result_str = " ".join(result_str)
return negative + result_str | 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 or cn.
:param units: day, hour, minute, second, ms.
>>> timeago(93245732.0032424, 5)
'1079 days, 05:35:32,003'
>>> timeago(93245732.0032424, 4, 1)
'1079 days 5 hours 35 minutes 32 seconds'
>>> timeago(-389, 4, 1)
'-6 minutes 29 seconds 0 ms'
"""
assert format in [0, 1, 2], ValueError("format arg should be one of 0, 1, 2")
negative = "-" if seconds < 0 else ""
seconds = abs(seconds)
if lang == "en":
units = ("day", "hour", "minute", "second", "ms")
elif lang == "cn":
units = (u"天", u"小时", u"分钟", u"秒", u"毫秒")
times = split_seconds(seconds)
if format == 2:
return dict(zip(units, times))
day, hour, minute, second, ms = times
if format == 0:
day_str = (
"%d %s%s, " % (day, units[0], "s" if day > 1 and lang == "en" else "")
if day
else ""
)
mid_str = ":".join(("%02d" % i for i in (hour, minute, second)))
if accuracy > 4:
mid_str += ",%03d" % ms
return negative + day_str + mid_str
elif format == 1:
# find longest valid fields index (non-zero in front)
valid_index = 0
for x, i in enumerate(times):
if i > 0:
valid_index = x
break
else:
valid_index = x
result_str = [
"%d %s%s"
% (num, unit, "s" if lang == "en" and num > 1 and unit != "ms" else "")
for num, unit in zip(times, units)
][valid_index:][:accuracy]
result_str = " ".join(result_str)
return negative + result_str | [
"def",
"timeago",
"(",
"seconds",
"=",
"0",
",",
"accuracy",
"=",
"4",
",",
"format",
"=",
"0",
",",
"lang",
"=",
"\"en\"",
")",
":",
"assert",
"format",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
",",
"ValueError",
"(",
"\"format arg should be one of 0, 1, 2\"",
")",
"negative",
"=",
"\"-\"",
"if",
"seconds",
"<",
"0",
"else",
"\"\"",
"seconds",
"=",
"abs",
"(",
"seconds",
")",
"if",
"lang",
"==",
"\"en\"",
":",
"units",
"=",
"(",
"\"day\"",
",",
"\"hour\"",
",",
"\"minute\"",
",",
"\"second\"",
",",
"\"ms\"",
")",
"elif",
"lang",
"==",
"\"cn\"",
":",
"units",
"=",
"(",
"u\"天\", ",
"u",
"小时\", u\"分钟",
"\"",
" u\"秒\", u\"",
"毫",
"\")",
"",
"",
"",
"times",
"=",
"split_seconds",
"(",
"seconds",
")",
"if",
"format",
"==",
"2",
":",
"return",
"dict",
"(",
"zip",
"(",
"units",
",",
"times",
")",
")",
"day",
",",
"hour",
",",
"minute",
",",
"second",
",",
"ms",
"=",
"times",
"if",
"format",
"==",
"0",
":",
"day_str",
"=",
"(",
"\"%d %s%s, \"",
"%",
"(",
"day",
",",
"units",
"[",
"0",
"]",
",",
"\"s\"",
"if",
"day",
">",
"1",
"and",
"lang",
"==",
"\"en\"",
"else",
"\"\"",
")",
"if",
"day",
"else",
"\"\"",
")",
"mid_str",
"=",
"\":\"",
".",
"join",
"(",
"(",
"\"%02d\"",
"%",
"i",
"for",
"i",
"in",
"(",
"hour",
",",
"minute",
",",
"second",
")",
")",
")",
"if",
"accuracy",
">",
"4",
":",
"mid_str",
"+=",
"\",%03d\"",
"%",
"ms",
"return",
"negative",
"+",
"day_str",
"+",
"mid_str",
"elif",
"format",
"==",
"1",
":",
"# find longest valid fields index (non-zero in front)",
"valid_index",
"=",
"0",
"for",
"x",
",",
"i",
"in",
"enumerate",
"(",
"times",
")",
":",
"if",
"i",
">",
"0",
":",
"valid_index",
"=",
"x",
"break",
"else",
":",
"valid_index",
"=",
"x",
"result_str",
"=",
"[",
"\"%d %s%s\"",
"%",
"(",
"num",
",",
"unit",
",",
"\"s\"",
"if",
"lang",
"==",
"\"en\"",
"and",
"num",
">",
"1",
"and",
"unit",
"!=",
"\"ms\"",
"else",
"\"\"",
")",
"for",
"num",
",",
"unit",
"in",
"zip",
"(",
"times",
",",
"units",
")",
"]",
"[",
"valid_index",
":",
"]",
"[",
":",
"accuracy",
"]",
"result_str",
"=",
"\" \"",
".",
"join",
"(",
"result_str",
")",
"return",
"negative",
"+",
"result_str"
] | 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.
>>> timeago(93245732.0032424, 5)
'1079 days, 05:35:32,003'
>>> timeago(93245732.0032424, 4, 1)
'1079 days 5 hours 35 minutes 32 seconds'
>>> timeago(-389, 4, 1)
'-6 minutes 29 seconds 0 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 = string if skip_encode else unicode(string).encode(encoding)
if n == 32:
return hashlib.md5(todo).hexdigest()
elif isinstance(n, (int, float)):
return hashlib.md5(todo).hexdigest()[(32 - n) // 2 : (n - 32) // 2]
elif isinstance(n, (tuple, list)):
return hashlib.md5(todo).hexdigest()[n[0] : n[1]] | 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 = string if skip_encode else unicode(string).encode(encoding)
if n == 32:
return hashlib.md5(todo).hexdigest()
elif isinstance(n, (int, float)):
return hashlib.md5(todo).hexdigest()[(32 - n) // 2 : (n - 32) // 2]
elif isinstance(n, (tuple, list)):
return hashlib.md5(todo).hexdigest()[n[0] : n[1]] | [
"def",
"md5",
"(",
"string",
",",
"n",
"=",
"32",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"skip_encode",
"=",
"False",
")",
":",
"todo",
"=",
"string",
"if",
"skip_encode",
"else",
"unicode",
"(",
"string",
")",
".",
"encode",
"(",
"encoding",
")",
"if",
"n",
"==",
"32",
":",
"return",
"hashlib",
".",
"md5",
"(",
"todo",
")",
".",
"hexdigest",
"(",
")",
"elif",
"isinstance",
"(",
"n",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"hashlib",
".",
"md5",
"(",
"todo",
")",
".",
"hexdigest",
"(",
")",
"[",
"(",
"32",
"-",
"n",
")",
"//",
"2",
":",
"(",
"n",
"-",
"32",
")",
"//",
"2",
"]",
"elif",
"isinstance",
"(",
"n",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"hashlib",
".",
"md5",
"(",
"todo",
")",
".",
"hexdigest",
"(",
")",
"[",
"n",
"[",
"0",
"]",
":",
"n",
"[",
"1",
"]",
"]"
] | 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.utils import unique
>>> a = [1,2,3,4,2,3,4]
>>> unique(a)
<generator object unique.<locals>.<genexpr> at 0x05720EA0>
>>> unique(a, str)
'1234'
>>> unique(a, list)
[1, 2, 3, 4]
"""
seen = set()
add = seen.add
if key:
generator = (x for x in seq if key(x) not in seen and not add(key(x)))
else:
generator = (x for x in seq if x not in seen and not add(x))
if return_as:
if return_as == str:
return "".join(map(str, generator))
else:
return return_as(generator)
else:
# python2 not support yield from
return generator | 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.utils import unique
>>> a = [1,2,3,4,2,3,4]
>>> unique(a)
<generator object unique.<locals>.<genexpr> at 0x05720EA0>
>>> unique(a, str)
'1234'
>>> unique(a, list)
[1, 2, 3, 4]
"""
seen = set()
add = seen.add
if key:
generator = (x for x in seq if key(x) not in seen and not add(key(x)))
else:
generator = (x for x in seq if x not in seen and not add(x))
if return_as:
if return_as == str:
return "".join(map(str, generator))
else:
return return_as(generator)
else:
# python2 not support yield from
return generator | [
"def",
"unique",
"(",
"seq",
",",
"key",
"=",
"None",
",",
"return_as",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"add",
"=",
"seen",
".",
"add",
"if",
"key",
":",
"generator",
"=",
"(",
"x",
"for",
"x",
"in",
"seq",
"if",
"key",
"(",
"x",
")",
"not",
"in",
"seen",
"and",
"not",
"add",
"(",
"key",
"(",
"x",
")",
")",
")",
"else",
":",
"generator",
"=",
"(",
"x",
"for",
"x",
"in",
"seq",
"if",
"x",
"not",
"in",
"seen",
"and",
"not",
"add",
"(",
"x",
")",
")",
"if",
"return_as",
":",
"if",
"return_as",
"==",
"str",
":",
"return",
"\"\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"generator",
")",
")",
"else",
":",
"return",
"return_as",
"(",
"generator",
")",
"else",
":",
"# python2 not support yield from",
"return",
"generator"
] | 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(a)
<generator object unique.<locals>.<genexpr> at 0x05720EA0>
>>> unique(a, str)
'1234'
>>> unique(a, list)
[1, 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.append(query_name + "=" + quote(value))
return "&".join(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.append(query_name + "=" + quote(value))
return "&".join(result) | [
"def",
"unparse_qs",
"(",
"qs",
",",
"sort",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"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",
".",
"append",
"(",
"query_name",
"+",
"\"=\"",
"+",
"quote",
"(",
"value",
")",
")",
"return",
"\"&\"",
".",
"join",
"(",
"result",
")"
] | 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(values))
return "&".join(result) | 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(values))
return "&".join(result) | [
"def",
"unparse_qsl",
"(",
"qsl",
",",
"sort",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"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",
"(",
"values",
")",
")",
"return",
"\"&\"",
".",
"join",
"(",
"result",
")"
] | 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_after_async",
"(",
"seconds",
"+",
"timeout",
",",
"kill",
",",
"pid",
",",
"9",
")"
] | 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:
if warn:
if warn is True:
Config.utils_logger.warning(
"Module `%s` not found. Install it to remove this warning"
% module_name
)
else:
warn(module_name, names, default)
module = (
ImportErrorModule(module_name) if default is ImportErrorModule else default
)
if not names:
return module
if not isinstance(names, (tuple, set, list)):
names = [names]
result = []
for name in names:
if hasattr(module, name):
result.append(module.__getattribute__(name))
else:
result.append(
ImportErrorModule("%s.%s" % (module_name, name))
if default is ImportErrorModule
else default
)
return result[0] if len(result) == 1 else result | 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:
if warn:
if warn is True:
Config.utils_logger.warning(
"Module `%s` not found. Install it to remove this warning"
% module_name
)
else:
warn(module_name, names, default)
module = (
ImportErrorModule(module_name) if default is ImportErrorModule else default
)
if not names:
return module
if not isinstance(names, (tuple, set, list)):
names = [names]
result = []
for name in names:
if hasattr(module, name):
result.append(module.__getattribute__(name))
else:
result.append(
ImportErrorModule("%s.%s" % (module_name, name))
if default is ImportErrorModule
else default
)
return result[0] if len(result) == 1 else result | [
"def",
"try_import",
"(",
"module_name",
",",
"names",
"=",
"None",
",",
"default",
"=",
"ImportErrorModule",
",",
"warn",
"=",
"True",
")",
":",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"except",
"ImportError",
":",
"if",
"warn",
":",
"if",
"warn",
"is",
"True",
":",
"Config",
".",
"utils_logger",
".",
"warning",
"(",
"\"Module `%s` not found. Install it to remove this warning\"",
"%",
"module_name",
")",
"else",
":",
"warn",
"(",
"module_name",
",",
"names",
",",
"default",
")",
"module",
"=",
"(",
"ImportErrorModule",
"(",
"module_name",
")",
"if",
"default",
"is",
"ImportErrorModule",
"else",
"default",
")",
"if",
"not",
"names",
":",
"return",
"module",
"if",
"not",
"isinstance",
"(",
"names",
",",
"(",
"tuple",
",",
"set",
",",
"list",
")",
")",
":",
"names",
"=",
"[",
"names",
"]",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"if",
"hasattr",
"(",
"module",
",",
"name",
")",
":",
"result",
".",
"append",
"(",
"module",
".",
"__getattribute__",
"(",
"name",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"ImportErrorModule",
"(",
"\"%s.%s\"",
"%",
"(",
"module_name",
",",
"name",
")",
")",
"if",
"default",
"is",
"ImportErrorModule",
"else",
"default",
")",
"return",
"result",
"[",
"0",
"]",
"if",
"len",
"(",
"result",
")",
"==",
"1",
"else",
"result"
] | 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'}
>>> ensure_request('http://test.com')
{'method': 'get', 'url': 'http://test.com'}
>>> ensure_request({'method': 'get', 'url': 'http://test.com'})
{'method': 'get', 'url': 'http://test.com'}
>>> ensure_request({'url': 'http://test.com'})
{'url': 'http://test.com', 'method': 'get'}
"""
if isinstance(request, dict):
result = request
elif isinstance(request, (unicode, str)):
request = request.strip()
if request.startswith("http"):
result = {"method": "get", "url": request}
elif request.startswith("curl "):
result = curlparse(request)
else:
raise ValueError("request should be dict or str.")
result["method"] = result.setdefault("method", "get").lower()
return result | 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'}
>>> ensure_request('http://test.com')
{'method': 'get', 'url': 'http://test.com'}
>>> ensure_request({'method': 'get', 'url': 'http://test.com'})
{'method': 'get', 'url': 'http://test.com'}
>>> ensure_request({'url': 'http://test.com'})
{'url': 'http://test.com', 'method': 'get'}
"""
if isinstance(request, dict):
result = request
elif isinstance(request, (unicode, str)):
request = request.strip()
if request.startswith("http"):
result = {"method": "get", "url": request}
elif request.startswith("curl "):
result = curlparse(request)
else:
raise ValueError("request should be dict or str.")
result["method"] = result.setdefault("method", "get").lower()
return result | [
"def",
"ensure_request",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"request",
",",
"dict",
")",
":",
"result",
"=",
"request",
"elif",
"isinstance",
"(",
"request",
",",
"(",
"unicode",
",",
"str",
")",
")",
":",
"request",
"=",
"request",
".",
"strip",
"(",
")",
"if",
"request",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"result",
"=",
"{",
"\"method\"",
":",
"\"get\"",
",",
"\"url\"",
":",
"request",
"}",
"elif",
"request",
".",
"startswith",
"(",
"\"curl \"",
")",
":",
"result",
"=",
"curlparse",
"(",
"request",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"request should be dict or str.\"",
")",
"result",
"[",
"\"method\"",
"]",
"=",
"result",
".",
"setdefault",
"(",
"\"method\"",
",",
"\"get\"",
")",
".",
"lower",
"(",
")",
"return",
"result"
] | 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')
{'method': 'get', 'url': 'http://test.com'}
>>> ensure_request({'method': 'get', 'url': 'http://test.com'})
{'method': 'get', 'url': 'http://test.com'}
>>> ensure_request({'url': 'http://test.com'})
{'url': 'http://test.com', 'method': 'get'} | [
"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 not all((isinstance(i, unicode) for i in dict_obj.keys())):
return dict_obj
return {key.title(): value for key, value in dict_obj.items()} | 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 not all((isinstance(i, unicode) for i in dict_obj.keys())):
return dict_obj
return {key.title(): value for key, value in dict_obj.items()} | [
"def",
"ensure_dict_key_title",
"(",
"dict_obj",
")",
":",
"if",
"not",
"all",
"(",
"(",
"isinstance",
"(",
"i",
",",
"unicode",
")",
"for",
"i",
"in",
"dict_obj",
".",
"keys",
"(",
")",
")",
")",
":",
"return",
"dict_obj",
"return",
"{",
"key",
".",
"title",
"(",
")",
":",
"value",
"for",
"key",
",",
"value",
"in",
"dict_obj",
".",
"items",
"(",
")",
"}"
] | 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_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40, 41, 54, 62, 69, 75, 79, 82, 88, 97, 99]
# diffs: [8, 7, 10, 6, 13, 8, 7, 6, 6, 9]
# median: 8
"""
if not nums:
return 0
nums = sorted([int(i) for i in nums])
if len(nums) == 1:
return nums[0]
diffs = [nums[i + 1] - nums[i] for i in range(len(nums) - 1)]
diffs = [item for item in diffs if item >= accuracy]
sorted_diff = sorted(diffs)
result = sorted_diff[len(diffs) // 2]
return result | 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_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40, 41, 54, 62, 69, 75, 79, 82, 88, 97, 99]
# diffs: [8, 7, 10, 6, 13, 8, 7, 6, 6, 9]
# median: 8
"""
if not nums:
return 0
nums = sorted([int(i) for i in nums])
if len(nums) == 1:
return nums[0]
diffs = [nums[i + 1] - nums[i] for i in range(len(nums) - 1)]
diffs = [item for item in diffs if item >= accuracy]
sorted_diff = sorted(diffs)
result = sorted_diff[len(diffs) // 2]
return result | [
"def",
"guess_interval",
"(",
"nums",
",",
"accuracy",
"=",
"0",
")",
":",
"if",
"not",
"nums",
":",
"return",
"0",
"nums",
"=",
"sorted",
"(",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"nums",
"]",
")",
"if",
"len",
"(",
"nums",
")",
"==",
"1",
":",
"return",
"nums",
"[",
"0",
"]",
"diffs",
"=",
"[",
"nums",
"[",
"i",
"+",
"1",
"]",
"-",
"nums",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"nums",
")",
"-",
"1",
")",
"]",
"diffs",
"=",
"[",
"item",
"for",
"item",
"in",
"diffs",
"if",
"item",
">=",
"accuracy",
"]",
"sorted_diff",
"=",
"sorted",
"(",
"diffs",
")",
"result",
"=",
"sorted_diff",
"[",
"len",
"(",
"diffs",
")",
"//",
"2",
"]",
"return",
"result"
] | 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, 41, 54, 62, 69, 75, 79, 82, 88, 97, 99]
# diffs: [8, 7, 10, 6, 13, 8, 7, 6, 6, 9]
# median: 8 | [
"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', '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, ['\s+'], reg=1))
# ['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']
"""
deep = len(seps)
if not deep:
return string
return [split_n(i, seps[1:]) for i in _re_split_mixin(string, seps[0], reg=reg)] | 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', '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, ['\s+'], reg=1))
# ['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']
"""
deep = len(seps)
if not deep:
return string
return [split_n(i, seps[1:]) for i in _re_split_mixin(string, seps[0], reg=reg)] | [
"def",
"split_n",
"(",
"string",
",",
"seps",
",",
"reg",
"=",
"False",
")",
":",
"deep",
"=",
"len",
"(",
"seps",
")",
"if",
"not",
"deep",
":",
"return",
"string",
"return",
"[",
"split_n",
"(",
"i",
",",
"seps",
"[",
"1",
":",
"]",
")",
"for",
"i",
"in",
"_re_split_mixin",
"(",
"string",
",",
"seps",
"[",
"0",
"]",
",",
"reg",
"=",
"reg",
")",
"]"
] | 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'], ['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, ['\s+'], reg=1))
# ['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'] | [
"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.sleep(n)
print_info(n, 'done')
test3 = bg(test1)
test2(1)
test3(1)
print_info('not be blocked')
time.sleep(2)
# [2018-06-12 23:46:19](L81): not be blocked
# [2018-06-12 23:46:20](L81): 1 done
# [2018-06-12 23:46:20](L81): 1 done
"""
@wraps(func)
def wrapper(*args, **kwargs):
t = Thread(target=func, args=args, kwargs=kwargs)
t.daemon = True
t.start()
return t
return wrapper | 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.sleep(n)
print_info(n, 'done')
test3 = bg(test1)
test2(1)
test3(1)
print_info('not be blocked')
time.sleep(2)
# [2018-06-12 23:46:19](L81): not be blocked
# [2018-06-12 23:46:20](L81): 1 done
# [2018-06-12 23:46:20](L81): 1 done
"""
@wraps(func)
def wrapper(*args, **kwargs):
t = Thread(target=func, args=args, kwargs=kwargs)
t.daemon = True
t.start()
return t
return wrapper | [
"def",
"bg",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")",
"return",
"t",
"return",
"wrapper"
] | 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)
print_info(n, 'done')
test3 = bg(test1)
test2(1)
test3(1)
print_info('not be blocked')
time.sleep(2)
# [2018-06-12 23:46:19](L81): not be blocked
# [2018-06-12 23:46:20](L81): 1 done
# [2018-06-12 23:46:20](L81): 1 done | [
"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 countdown
countdown(3)
# 3 2 1
# countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58.
countdown('2018-06-13 00:13:29')
# 10 9 8 7 6 5 4 3 2 1
# countdown finished [10 seconds]: 2018-06-13 00:13:18 => 2018-06-13 00:13:28.
"""
def default_tick_callback(s, seconds, *args):
flush_print(s, sep="", end=" ")
def default_finish_callback(seconds, start_time):
flush_print()
def cd(seconds, interval):
for s in range(seconds, 0, -interval):
tick_callback(s, seconds, interval)
time.sleep(interval)
if callable(finish_callback):
finish_callback(seconds, start_time)
start_time = time.time()
tick_callback = tick_callback or default_tick_callback
finish_callback = (
default_finish_callback if finish_callback is None else finish_callback
)
if unicode(seconds).isdigit():
seconds = int(seconds)
elif isinstance(seconds, (unicode, str)):
seconds = int(ptime(seconds) - time.time())
t = Thread(target=cd, args=(seconds, interval))
t.daemon = daemon
t.start()
if block:
t.join() | 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 countdown
countdown(3)
# 3 2 1
# countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58.
countdown('2018-06-13 00:13:29')
# 10 9 8 7 6 5 4 3 2 1
# countdown finished [10 seconds]: 2018-06-13 00:13:18 => 2018-06-13 00:13:28.
"""
def default_tick_callback(s, seconds, *args):
flush_print(s, sep="", end=" ")
def default_finish_callback(seconds, start_time):
flush_print()
def cd(seconds, interval):
for s in range(seconds, 0, -interval):
tick_callback(s, seconds, interval)
time.sleep(interval)
if callable(finish_callback):
finish_callback(seconds, start_time)
start_time = time.time()
tick_callback = tick_callback or default_tick_callback
finish_callback = (
default_finish_callback if finish_callback is None else finish_callback
)
if unicode(seconds).isdigit():
seconds = int(seconds)
elif isinstance(seconds, (unicode, str)):
seconds = int(ptime(seconds) - time.time())
t = Thread(target=cd, args=(seconds, interval))
t.daemon = daemon
t.start()
if block:
t.join() | [
"def",
"countdown",
"(",
"seconds",
"=",
"None",
",",
"block",
"=",
"True",
",",
"interval",
"=",
"1",
",",
"daemon",
"=",
"True",
",",
"tick_callback",
"=",
"None",
",",
"finish_callback",
"=",
"None",
",",
")",
":",
"def",
"default_tick_callback",
"(",
"s",
",",
"seconds",
",",
"*",
"args",
")",
":",
"flush_print",
"(",
"s",
",",
"sep",
"=",
"\"\"",
",",
"end",
"=",
"\" \"",
")",
"def",
"default_finish_callback",
"(",
"seconds",
",",
"start_time",
")",
":",
"flush_print",
"(",
")",
"def",
"cd",
"(",
"seconds",
",",
"interval",
")",
":",
"for",
"s",
"in",
"range",
"(",
"seconds",
",",
"0",
",",
"-",
"interval",
")",
":",
"tick_callback",
"(",
"s",
",",
"seconds",
",",
"interval",
")",
"time",
".",
"sleep",
"(",
"interval",
")",
"if",
"callable",
"(",
"finish_callback",
")",
":",
"finish_callback",
"(",
"seconds",
",",
"start_time",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"tick_callback",
"=",
"tick_callback",
"or",
"default_tick_callback",
"finish_callback",
"=",
"(",
"default_finish_callback",
"if",
"finish_callback",
"is",
"None",
"else",
"finish_callback",
")",
"if",
"unicode",
"(",
"seconds",
")",
".",
"isdigit",
"(",
")",
":",
"seconds",
"=",
"int",
"(",
"seconds",
")",
"elif",
"isinstance",
"(",
"seconds",
",",
"(",
"unicode",
",",
"str",
")",
")",
":",
"seconds",
"=",
"int",
"(",
"ptime",
"(",
"seconds",
")",
"-",
"time",
".",
"time",
"(",
")",
")",
"t",
"=",
"Thread",
"(",
"target",
"=",
"cd",
",",
"args",
"=",
"(",
"seconds",
",",
"interval",
")",
")",
"t",
".",
"daemon",
"=",
"daemon",
"t",
".",
"start",
"(",
")",
"if",
"block",
":",
"t",
".",
"join",
"(",
")"
] | 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.
countdown('2018-06-13 00:13:29')
# 10 9 8 7 6 5 4 3 2 1
# countdown finished [10 seconds]: 2018-06-13 00:13:18 => 2018-06-13 00:13:28. | [
"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("=" * 10)
for _ in range(10):
time.sleep(0.2)
flush_print("=", sep="", end="")
"""
# PY2 raise SyntaxError for : def flush_print(*args, sep='', end=''):
sep, end, flush = (
kwargs.pop("sep", " "),
kwargs.pop("end", "\n"),
kwargs.pop("flush", 1),
)
string = sep.join((unicode(i) for i in args))
sys.stdout.write("%s%s" % (string, end))
if flush:
sys.stdout.flush() | 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("=" * 10)
for _ in range(10):
time.sleep(0.2)
flush_print("=", sep="", end="")
"""
# PY2 raise SyntaxError for : def flush_print(*args, sep='', end=''):
sep, end, flush = (
kwargs.pop("sep", " "),
kwargs.pop("end", "\n"),
kwargs.pop("flush", 1),
)
string = sep.join((unicode(i) for i in args))
sys.stdout.write("%s%s" % (string, end))
if flush:
sys.stdout.flush() | [
"def",
"flush_print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# PY2 raise SyntaxError for : def flush_print(*args, sep='', end=''):",
"sep",
",",
"end",
",",
"flush",
"=",
"(",
"kwargs",
".",
"pop",
"(",
"\"sep\"",
",",
"\" \"",
")",
",",
"kwargs",
".",
"pop",
"(",
"\"end\"",
",",
"\"\\n\"",
")",
",",
"kwargs",
".",
"pop",
"(",
"\"flush\"",
",",
"1",
")",
",",
")",
"string",
"=",
"sep",
".",
"join",
"(",
"(",
"unicode",
"(",
"i",
")",
"for",
"i",
"in",
"args",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"%s%s\"",
"%",
"(",
"string",
",",
"end",
")",
")",
"if",
"flush",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | 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):
time.sleep(0.2)
flush_print("=", sep="", end="") | [
"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"
] | 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
Basic Usage::
from torequests.utils import curlrequests
r = curlrequests('''curl 'http://p.3.cn/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' -H 'DNT: 1' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'If-None-Match: "55dd9090-264"' -H 'If-Modified-Since: Wed, 26 Aug 2015 10:10:24 GMT' --compressed''', retry=1)
print(r.text)
"""
req = kwargs.pop('req', tPool())
kwargs.update(curlparse(curl_string))
return req.request(**kwargs) | 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
Basic Usage::
from torequests.utils import curlrequests
r = curlrequests('''curl 'http://p.3.cn/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' -H 'DNT: 1' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'If-None-Match: "55dd9090-264"' -H 'If-Modified-Since: Wed, 26 Aug 2015 10:10:24 GMT' --compressed''', retry=1)
print(r.text)
"""
req = kwargs.pop('req', tPool())
kwargs.update(curlparse(curl_string))
return req.request(**kwargs) | [
"def",
"curlrequests",
"(",
"curl_string",
",",
"*",
"*",
"kwargs",
")",
":",
"req",
"=",
"kwargs",
".",
"pop",
"(",
"'req'",
",",
"tPool",
"(",
")",
")",
"kwargs",
".",
"update",
"(",
"curlparse",
"(",
"curl_string",
")",
")",
"return",
"req",
".",
"request",
"(",
"*",
"*",
"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
Basic Usage::
from torequests.utils import curlrequests
r = curlrequests('''curl 'http://p.3.cn/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' -H 'DNT: 1' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'If-None-Match: "55dd9090-264"' -H 'If-Modified-Since: Wed, 26 Aug 2015 10:10:24 GMT' --compressed''', retry=1)
print(r.text) | [
"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 the patterns.
:param reg_kwargs: kwargs for re.compile.
"""
assert obj, "bool(obj) should be True."
patterns = patterns if isinstance(patterns, (list, tuple, set)) else [patterns]
instances = instances or []
instances = (
instances if isinstance(instances, (list, tuple, set)) else [instances]
)
for pattern in patterns:
pattern_compiled = re.compile(pattern, **reg_kwargs)
self.container.append((pattern_compiled, obj, instances))
if self.ensure_mapping:
# check all instances to avoid one-to-many instances.
self._check_instances()
else:
# no need to check all instances.
for instance in instances:
assert self.search(instance) == [obj] or self.match(instance) == [
obj
], (
"instance %s should fit at least one pattern %s"
% (instance, pattern)
) | 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 the patterns.
:param reg_kwargs: kwargs for re.compile.
"""
assert obj, "bool(obj) should be True."
patterns = patterns if isinstance(patterns, (list, tuple, set)) else [patterns]
instances = instances or []
instances = (
instances if isinstance(instances, (list, tuple, set)) else [instances]
)
for pattern in patterns:
pattern_compiled = re.compile(pattern, **reg_kwargs)
self.container.append((pattern_compiled, obj, instances))
if self.ensure_mapping:
# check all instances to avoid one-to-many instances.
self._check_instances()
else:
# no need to check all instances.
for instance in instances:
assert self.search(instance) == [obj] or self.match(instance) == [
obj
], (
"instance %s should fit at least one pattern %s"
% (instance, pattern)
) | [
"def",
"register",
"(",
"self",
",",
"patterns",
",",
"obj",
"=",
"None",
",",
"instances",
"=",
"None",
",",
"*",
"*",
"reg_kwargs",
")",
":",
"assert",
"obj",
",",
"\"bool(obj) should be True.\"",
"patterns",
"=",
"patterns",
"if",
"isinstance",
"(",
"patterns",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
"else",
"[",
"patterns",
"]",
"instances",
"=",
"instances",
"or",
"[",
"]",
"instances",
"=",
"(",
"instances",
"if",
"isinstance",
"(",
"instances",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
"else",
"[",
"instances",
"]",
")",
"for",
"pattern",
"in",
"patterns",
":",
"pattern_compiled",
"=",
"re",
".",
"compile",
"(",
"pattern",
",",
"*",
"*",
"reg_kwargs",
")",
"self",
".",
"container",
".",
"append",
"(",
"(",
"pattern_compiled",
",",
"obj",
",",
"instances",
")",
")",
"if",
"self",
".",
"ensure_mapping",
":",
"# check all instances to avoid one-to-many instances.",
"self",
".",
"_check_instances",
"(",
")",
"else",
":",
"# no need to check all instances.",
"for",
"instance",
"in",
"instances",
":",
"assert",
"self",
".",
"search",
"(",
"instance",
")",
"==",
"[",
"obj",
"]",
"or",
"self",
".",
"match",
"(",
"instance",
")",
"==",
"[",
"obj",
"]",
",",
"(",
"\"instance %s should fit at least one pattern %s\"",
"%",
"(",
"instance",
",",
"pattern",
")",
")"
] | 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",
"=",
"instances",
",",
"*",
"*",
"reg_kwargs",
")",
"return",
"function",
"return",
"wrapper"
] | 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 than one pattern: %s" % (
string,
result,
)
return result if result else default | 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 than one pattern: %s" % (
string,
result,
)
return result if result else default | [
"def",
"search",
"(",
"self",
",",
"string",
",",
"default",
"=",
"None",
")",
":",
"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 than one pattern: %s\"",
"%",
"(",
"string",
",",
"result",
",",
")",
"return",
"result",
"if",
"result",
"else",
"default"
] | 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=limit)
return maybe | 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=limit)
return maybe | [
"def",
"fuzzy",
"(",
"self",
",",
"key",
",",
"limit",
"=",
"5",
")",
":",
"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",
"=",
"limit",
")",
"return",
"maybe"
] | 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.