repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
rapidpro/expressions | python/temba_expressions/functions/__init__.py | FunctionManager._get_arg_spec | def _get_arg_spec(func):
"""
Gets the argument spec of the given function, returning defaults as a dict of param names to values
"""
args, varargs, keywords, defaults = inspect.getargspec(func)
# build a mapping from argument names to their default values, if any:
if def... | python | def _get_arg_spec(func):
"""
Gets the argument spec of the given function, returning defaults as a dict of param names to values
"""
args, varargs, keywords, defaults = inspect.getargspec(func)
# build a mapping from argument names to their default values, if any:
if def... | [
"def",
"_get_arg_spec",
"(",
"func",
")",
":",
"args",
",",
"varargs",
",",
"keywords",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"# build a mapping from argument names to their default values, if any:",
"if",
"defaults",
"is",
"None",
":... | Gets the argument spec of the given function, returning defaults as a dict of param names to values | [
"Gets",
"the",
"argument",
"spec",
"of",
"the",
"given",
"function",
"returning",
"defaults",
"as",
"a",
"dict",
"of",
"param",
"names",
"to",
"values"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/__init__.py#L105-L118 |
BlueBrain/nat | nat/runOCR.py | check_ocrmypdf | def check_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and confirmed that a valid file was created"
p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env)
if p.returncode != 0:
print('stdout\n======')
print(out)
print('stderr\n======')
print... | python | def check_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and confirmed that a valid file was created"
p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env)
if p.returncode != 0:
print('stdout\n======')
print(out)
print('stderr\n======')
print... | [
"def",
"check_ocrmypdf",
"(",
"input_file",
",",
"output_file",
",",
"*",
"args",
",",
"env",
"=",
"None",
")",
":",
"p",
",",
"out",
",",
"err",
"=",
"run_ocrmypdf",
"(",
"input_file",
",",
"output_file",
",",
"*",
"args",
",",
"env",
"=",
"env",
")... | Run ocrmypdf and confirmed that a valid file was created | [
"Run",
"ocrmypdf",
"and",
"confirmed",
"that",
"a",
"valid",
"file",
"was",
"created"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/runOCR.py#L24-L36 |
BlueBrain/nat | nat/runOCR.py | run_ocrmypdf | def run_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and let caller deal with results"
if env is None:
env = os.environ
p_args = OCRMYPDF + list(args) + [input_file, output_file]
p = Popen(
p_args, close_fds=True, stdout=PIPE, stderr=PIPE,
universal_newline... | python | def run_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and let caller deal with results"
if env is None:
env = os.environ
p_args = OCRMYPDF + list(args) + [input_file, output_file]
p = Popen(
p_args, close_fds=True, stdout=PIPE, stderr=PIPE,
universal_newline... | [
"def",
"run_ocrmypdf",
"(",
"input_file",
",",
"output_file",
",",
"*",
"args",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
"is",
"None",
":",
"env",
"=",
"os",
".",
"environ",
"p_args",
"=",
"OCRMYPDF",
"+",
"list",
"(",
"args",
")",
"+",
"[",... | Run ocrmypdf and let caller deal with results | [
"Run",
"ocrmypdf",
"and",
"let",
"caller",
"deal",
"with",
"results"
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/runOCR.py#L39-L50 |
ttinies/sc2gameMapRepo | sc2maptool/mapRecord.py | standardizeMapName | def standardizeMapName(mapName):
"""pretty-fy the name for pysc2 map lookup"""
#print("foreignName: %s (%s)"%(mapName, mapName in c.mapNameTranslations))
#if mapName in c.mapNameTranslations:
# return c.mapNameTranslations[mapName]
newName = os.path.basename(mapName)
newName = newName.split(... | python | def standardizeMapName(mapName):
"""pretty-fy the name for pysc2 map lookup"""
#print("foreignName: %s (%s)"%(mapName, mapName in c.mapNameTranslations))
#if mapName in c.mapNameTranslations:
# return c.mapNameTranslations[mapName]
newName = os.path.basename(mapName)
newName = newName.split(... | [
"def",
"standardizeMapName",
"(",
"mapName",
")",
":",
"#print(\"foreignName: %s (%s)\"%(mapName, mapName in c.mapNameTranslations))",
"#if mapName in c.mapNameTranslations:",
"# return c.mapNameTranslations[mapName]",
"newName",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"m... | pretty-fy the name for pysc2 map lookup | [
"pretty",
"-",
"fy",
"the",
"name",
"for",
"pysc2",
"map",
"lookup"
] | train | https://github.com/ttinies/sc2gameMapRepo/blob/3a215067fae8f86f6a3ffe37272fbd7a5461cfab/sc2maptool/mapRecord.py#L9-L24 |
lablup/backend.ai-common | src/ai/backend/common/utils.py | env_info | def env_info():
'''
Returns a string that contains the Python version and runtime path.
'''
v = sys.version_info
pyver = f'Python {v.major}.{v.minor}.{v.micro}'
if v.releaselevel == 'alpha':
pyver += 'a'
if v.releaselevel == 'beta':
pyver += 'b'
if v.releaselevel == 'cand... | python | def env_info():
'''
Returns a string that contains the Python version and runtime path.
'''
v = sys.version_info
pyver = f'Python {v.major}.{v.minor}.{v.micro}'
if v.releaselevel == 'alpha':
pyver += 'a'
if v.releaselevel == 'beta':
pyver += 'b'
if v.releaselevel == 'cand... | [
"def",
"env_info",
"(",
")",
":",
"v",
"=",
"sys",
".",
"version_info",
"pyver",
"=",
"f'Python {v.major}.{v.minor}.{v.micro}'",
"if",
"v",
".",
"releaselevel",
"==",
"'alpha'",
":",
"pyver",
"+=",
"'a'",
"if",
"v",
".",
"releaselevel",
"==",
"'beta'",
":",
... | Returns a string that contains the Python version and runtime path. | [
"Returns",
"a",
"string",
"that",
"contains",
"the",
"Python",
"version",
"and",
"runtime",
"path",
"."
] | train | https://github.com/lablup/backend.ai-common/blob/20b3a2551ee5bb3b88e7836471bc244a70ad0ae6/src/ai/backend/common/utils.py#L17-L31 |
lablup/backend.ai-common | src/ai/backend/common/utils.py | dict2kvlist | def dict2kvlist(o):
'''
Serializes a dict-like object into a generator of the flatten list of
repeating key-value pairs. It is useful when using HMSET method in Redis.
Example:
>>> list(dict2kvlist({'a': 1, 'b': 2}))
['a', 1, 'b', 2]
'''
return chain.from_iterable((k, v) for k, v in o.... | python | def dict2kvlist(o):
'''
Serializes a dict-like object into a generator of the flatten list of
repeating key-value pairs. It is useful when using HMSET method in Redis.
Example:
>>> list(dict2kvlist({'a': 1, 'b': 2}))
['a', 1, 'b', 2]
'''
return chain.from_iterable((k, v) for k, v in o.... | [
"def",
"dict2kvlist",
"(",
"o",
")",
":",
"return",
"chain",
".",
"from_iterable",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"o",
".",
"items",
"(",
")",
")"
] | Serializes a dict-like object into a generator of the flatten list of
repeating key-value pairs. It is useful when using HMSET method in Redis.
Example:
>>> list(dict2kvlist({'a': 1, 'b': 2}))
['a', 1, 'b', 2] | [
"Serializes",
"a",
"dict",
"-",
"like",
"object",
"into",
"a",
"generator",
"of",
"the",
"flatten",
"list",
"of",
"repeating",
"key",
"-",
"value",
"pairs",
".",
"It",
"is",
"useful",
"when",
"using",
"HMSET",
"method",
"in",
"Redis",
"."
] | train | https://github.com/lablup/backend.ai-common/blob/20b3a2551ee5bb3b88e7836471bc244a70ad0ae6/src/ai/backend/common/utils.py#L43-L52 |
lablup/backend.ai-common | src/ai/backend/common/utils.py | nmget | def nmget(o, key_path, def_val=None, path_delimiter='.', null_as_default=True):
'''
A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given key exists and return the default value whenever
fails.
Exampl... | python | def nmget(o, key_path, def_val=None, path_delimiter='.', null_as_default=True):
'''
A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given key exists and return the default value whenever
fails.
Exampl... | [
"def",
"nmget",
"(",
"o",
",",
"key_path",
",",
"def_val",
"=",
"None",
",",
"path_delimiter",
"=",
"'.'",
",",
"null_as_default",
"=",
"True",
")",
":",
"pieces",
"=",
"key_path",
".",
"split",
"(",
"path_delimiter",
")",
"while",
"pieces",
":",
"p",
... | A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given key exists and return the default value whenever
fails.
Example:
>>> o = {'a':{'b':1}, 'x': None}
>>> nmget(o, 'a', 0)
{'b': 1}
>>> nmget(... | [
"A",
"short",
"-",
"hand",
"for",
"retrieving",
"a",
"value",
"from",
"nested",
"mappings",
"(",
"nested",
"-",
"mapping",
"-",
"get",
")",
".",
"At",
"each",
"level",
"it",
"checks",
"if",
"the",
"given",
"path",
"component",
"in",
"the",
"given",
"ke... | train | https://github.com/lablup/backend.ai-common/blob/20b3a2551ee5bb3b88e7836471bc244a70ad0ae6/src/ai/backend/common/utils.py#L61-L91 |
ska-sa/katversion | katversion/build.py | patch_init_py | def patch_init_py(base_dir, name, version):
"""Patch __init__.py to remove version check and append hard-coded version."""
# Ensure main package dir is there (may be absent in script-only packages)
package_dir = os.path.join(base_dir, name)
if not os.path.isdir(package_dir):
os.makedirs(package_... | python | def patch_init_py(base_dir, name, version):
"""Patch __init__.py to remove version check and append hard-coded version."""
# Ensure main package dir is there (may be absent in script-only packages)
package_dir = os.path.join(base_dir, name)
if not os.path.isdir(package_dir):
os.makedirs(package_... | [
"def",
"patch_init_py",
"(",
"base_dir",
",",
"name",
",",
"version",
")",
":",
"# Ensure main package dir is there (may be absent in script-only packages)",
"package_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"name",
")",
"if",
"not",
"os",
... | Patch __init__.py to remove version check and append hard-coded version. | [
"Patch",
"__init__",
".",
"py",
"to",
"remove",
"version",
"check",
"and",
"append",
"hard",
"-",
"coded",
"version",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/build.py#L32-L58 |
ska-sa/katversion | katversion/build.py | setuptools_entry | def setuptools_entry(dist, keyword, value):
"""Setuptools entry point for setting version and baking it into package."""
# If 'use_katversion' is False, ignore the rest
if not value:
return
# Enforce the version obtained by katversion, overriding user setting
version = get_version()
if d... | python | def setuptools_entry(dist, keyword, value):
"""Setuptools entry point for setting version and baking it into package."""
# If 'use_katversion' is False, ignore the rest
if not value:
return
# Enforce the version obtained by katversion, overriding user setting
version = get_version()
if d... | [
"def",
"setuptools_entry",
"(",
"dist",
",",
"keyword",
",",
"value",
")",
":",
"# If 'use_katversion' is False, ignore the rest",
"if",
"not",
"value",
":",
"return",
"# Enforce the version obtained by katversion, overriding user setting",
"version",
"=",
"get_version",
"(",... | Setuptools entry point for setting version and baking it into package. | [
"Setuptools",
"entry",
"point",
"for",
"setting",
"version",
"and",
"baking",
"it",
"into",
"package",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/build.py#L102-L122 |
beregond/super_state_machine | super_state_machine/utils.py | is_ | def is_(self, state):
"""Check if machine is in given state."""
translator = self._meta['translator']
state = translator.translate(state)
return self.actual_state == state | python | def is_(self, state):
"""Check if machine is in given state."""
translator = self._meta['translator']
state = translator.translate(state)
return self.actual_state == state | [
"def",
"is_",
"(",
"self",
",",
"state",
")",
":",
"translator",
"=",
"self",
".",
"_meta",
"[",
"'translator'",
"]",
"state",
"=",
"translator",
".",
"translate",
"(",
"state",
")",
"return",
"self",
".",
"actual_state",
"==",
"state"
] | Check if machine is in given state. | [
"Check",
"if",
"machine",
"is",
"in",
"given",
"state",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L9-L13 |
beregond/super_state_machine | super_state_machine/utils.py | can_be_ | def can_be_(self, state):
"""Check if machine can transit to given state."""
translator = self._meta['translator']
state = translator.translate(state)
if self._meta['complete']:
return True
if self.actual_state is None:
return True
transitions = self._meta['transitions'][self.... | python | def can_be_(self, state):
"""Check if machine can transit to given state."""
translator = self._meta['translator']
state = translator.translate(state)
if self._meta['complete']:
return True
if self.actual_state is None:
return True
transitions = self._meta['transitions'][self.... | [
"def",
"can_be_",
"(",
"self",
",",
"state",
")",
":",
"translator",
"=",
"self",
".",
"_meta",
"[",
"'translator'",
"]",
"state",
"=",
"translator",
".",
"translate",
"(",
"state",
")",
"if",
"self",
".",
"_meta",
"[",
"'complete'",
"]",
":",
"return"... | Check if machine can transit to given state. | [
"Check",
"if",
"machine",
"can",
"transit",
"to",
"given",
"state",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L16-L28 |
beregond/super_state_machine | super_state_machine/utils.py | force_set | def force_set(self, state):
"""Set new state without checking if transition is allowed."""
translator = self._meta['translator']
state = translator.translate(state)
attr = self._meta['state_attribute_name']
setattr(self, attr, state) | python | def force_set(self, state):
"""Set new state without checking if transition is allowed."""
translator = self._meta['translator']
state = translator.translate(state)
attr = self._meta['state_attribute_name']
setattr(self, attr, state) | [
"def",
"force_set",
"(",
"self",
",",
"state",
")",
":",
"translator",
"=",
"self",
".",
"_meta",
"[",
"'translator'",
"]",
"state",
"=",
"translator",
".",
"translate",
"(",
"state",
")",
"attr",
"=",
"self",
".",
"_meta",
"[",
"'state_attribute_name'",
... | Set new state without checking if transition is allowed. | [
"Set",
"new",
"state",
"without",
"checking",
"if",
"transition",
"is",
"allowed",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L31-L36 |
beregond/super_state_machine | super_state_machine/utils.py | set_ | def set_(self, state):
"""Set new state for machine."""
if not self.can_be_(state):
state = self._meta['translator'].translate(state)
raise TransitionError(
"Cannot transit from '{actual_value}' to '{value}'."
.format(actual_value=self.actual_state.value, value=state.valu... | python | def set_(self, state):
"""Set new state for machine."""
if not self.can_be_(state):
state = self._meta['translator'].translate(state)
raise TransitionError(
"Cannot transit from '{actual_value}' to '{value}'."
.format(actual_value=self.actual_state.value, value=state.valu... | [
"def",
"set_",
"(",
"self",
",",
"state",
")",
":",
"if",
"not",
"self",
".",
"can_be_",
"(",
"state",
")",
":",
"state",
"=",
"self",
".",
"_meta",
"[",
"'translator'",
"]",
".",
"translate",
"(",
"state",
")",
"raise",
"TransitionError",
"(",
"\"Ca... | Set new state for machine. | [
"Set",
"new",
"state",
"for",
"machine",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L39-L48 |
beregond/super_state_machine | super_state_machine/utils.py | generate_getter | def generate_getter(value):
"""Generate getter for given value."""
@property
@wraps(is_)
def getter(self):
return self.is_(value)
return getter | python | def generate_getter(value):
"""Generate getter for given value."""
@property
@wraps(is_)
def getter(self):
return self.is_(value)
return getter | [
"def",
"generate_getter",
"(",
"value",
")",
":",
"@",
"property",
"@",
"wraps",
"(",
"is_",
")",
"def",
"getter",
"(",
"self",
")",
":",
"return",
"self",
".",
"is_",
"(",
"value",
")",
"return",
"getter"
] | Generate getter for given value. | [
"Generate",
"getter",
"for",
"given",
"value",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L64-L71 |
beregond/super_state_machine | super_state_machine/utils.py | generate_checker | def generate_checker(value):
"""Generate state checker for given value."""
@property
@wraps(can_be_)
def checker(self):
return self.can_be_(value)
return checker | python | def generate_checker(value):
"""Generate state checker for given value."""
@property
@wraps(can_be_)
def checker(self):
return self.can_be_(value)
return checker | [
"def",
"generate_checker",
"(",
"value",
")",
":",
"@",
"property",
"@",
"wraps",
"(",
"can_be_",
")",
"def",
"checker",
"(",
"self",
")",
":",
"return",
"self",
".",
"can_be_",
"(",
"value",
")",
"return",
"checker"
] | Generate state checker for given value. | [
"Generate",
"state",
"checker",
"for",
"given",
"value",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L74-L81 |
beregond/super_state_machine | super_state_machine/utils.py | generate_setter | def generate_setter(value):
"""Generate setter for given value."""
@wraps(set_)
def setter(self):
self.set_(value)
return setter | python | def generate_setter(value):
"""Generate setter for given value."""
@wraps(set_)
def setter(self):
self.set_(value)
return setter | [
"def",
"generate_setter",
"(",
"value",
")",
":",
"@",
"wraps",
"(",
"set_",
")",
"def",
"setter",
"(",
"self",
")",
":",
"self",
".",
"set_",
"(",
"value",
")",
"return",
"setter"
] | Generate setter for given value. | [
"Generate",
"setter",
"for",
"given",
"value",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L84-L90 |
beregond/super_state_machine | super_state_machine/utils.py | EnumValueTranslator.translate | def translate(self, value):
"""Translate value to enum instance.
If value is already enum instance, check if this value belongs to base
enum.
"""
if self._check_if_already_proper(value):
return value
try:
return self.search_table[value]
... | python | def translate(self, value):
"""Translate value to enum instance.
If value is already enum instance, check if this value belongs to base
enum.
"""
if self._check_if_already_proper(value):
return value
try:
return self.search_table[value]
... | [
"def",
"translate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_check_if_already_proper",
"(",
"value",
")",
":",
"return",
"value",
"try",
":",
"return",
"self",
".",
"search_table",
"[",
"value",
"]",
"except",
"KeyError",
":",
"raise",
"... | Translate value to enum instance.
If value is already enum instance, check if this value belongs to base
enum. | [
"Translate",
"value",
"to",
"enum",
"instance",
"."
] | train | https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L127-L142 |
vkosuri/dialogflow-lite | dialogflow_lite/dialogflow.py | Dialogflow._query | def _query(self, text):
"""
Takes natural language text and information as query parameters and returns information as JSON.
"""
params = (
('v', self.api_version),
('query', text),
('lang', self.language),
('sessionId', self.session_id),
... | python | def _query(self, text):
"""
Takes natural language text and information as query parameters and returns information as JSON.
"""
params = (
('v', self.api_version),
('query', text),
('lang', self.language),
('sessionId', self.session_id),
... | [
"def",
"_query",
"(",
"self",
",",
"text",
")",
":",
"params",
"=",
"(",
"(",
"'v'",
",",
"self",
".",
"api_version",
")",
",",
"(",
"'query'",
",",
"text",
")",
",",
"(",
"'lang'",
",",
"self",
".",
"language",
")",
",",
"(",
"'sessionId'",
",",... | Takes natural language text and information as query parameters and returns information as JSON. | [
"Takes",
"natural",
"language",
"text",
"and",
"information",
"as",
"query",
"parameters",
"and",
"returns",
"information",
"as",
"JSON",
"."
] | train | https://github.com/vkosuri/dialogflow-lite/blob/488d6ffb4128471e672c8304995514a3c8982edc/dialogflow_lite/dialogflow.py#L88-L105 |
MacHu-GWU/dataIO-project | dataIO/zzz_manual_install.py | is_venv | def is_venv():
"""Check whether if this workspace is a virtualenv.
"""
dir_path = os.path.dirname(SRC)
is_venv_flag = True
if SYS_NAME == "Windows":
executable_list = ["activate", "pip.exe", "python.exe"]
elif SYS_NAME in ["Darwin", "Linux"]:
executable_list = ["activate", "pip"... | python | def is_venv():
"""Check whether if this workspace is a virtualenv.
"""
dir_path = os.path.dirname(SRC)
is_venv_flag = True
if SYS_NAME == "Windows":
executable_list = ["activate", "pip.exe", "python.exe"]
elif SYS_NAME in ["Darwin", "Linux"]:
executable_list = ["activate", "pip"... | [
"def",
"is_venv",
"(",
")",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"SRC",
")",
"is_venv_flag",
"=",
"True",
"if",
"SYS_NAME",
"==",
"\"Windows\"",
":",
"executable_list",
"=",
"[",
"\"activate\"",
",",
"\"pip.exe\"",
",",
"\"python.e... | Check whether if this workspace is a virtualenv. | [
"Check",
"whether",
"if",
"this",
"workspace",
"is",
"a",
"virtualenv",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/zzz_manual_install.py#L47-L63 |
MacHu-GWU/dataIO-project | dataIO/zzz_manual_install.py | find_linux_venv_py_version | def find_linux_venv_py_version():
"""Find python version name used in this virtualenv.
For example: ``python2.7``, ``python3.4``
"""
available_python_version = [
"python2.6",
"python2.7",
"python3.3",
"python3.4",
"python3.5",
"python3.6",
]
dir_p... | python | def find_linux_venv_py_version():
"""Find python version name used in this virtualenv.
For example: ``python2.7``, ``python3.4``
"""
available_python_version = [
"python2.6",
"python2.7",
"python3.3",
"python3.4",
"python3.5",
"python3.6",
]
dir_p... | [
"def",
"find_linux_venv_py_version",
"(",
")",
":",
"available_python_version",
"=",
"[",
"\"python2.6\"",
",",
"\"python2.7\"",
",",
"\"python3.3\"",
",",
"\"python3.4\"",
",",
"\"python3.5\"",
",",
"\"python3.6\"",
",",
"]",
"dir_path",
"=",
"os",
".",
"path",
"... | Find python version name used in this virtualenv.
For example: ``python2.7``, ``python3.4`` | [
"Find",
"python",
"version",
"name",
"used",
"in",
"this",
"virtualenv",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/zzz_manual_install.py#L66-L84 |
MacHu-GWU/dataIO-project | dataIO/zzz_manual_install.py | find_venv_DST | def find_venv_DST():
"""Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
"""
dir_path = os.path.dirname(SRC)
if SYS_NAME == "Windows":
DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME)
... | python | def find_venv_DST():
"""Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
"""
dir_path = os.path.dirname(SRC)
if SYS_NAME == "Windows":
DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME)
... | [
"def",
"find_venv_DST",
"(",
")",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"SRC",
")",
"if",
"SYS_NAME",
"==",
"\"Windows\"",
":",
"DST",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"\"Lib\"",
",",
"\"site-packages\"... | Find where this package should be installed to in this virtualenv.
For example: ``/path-to-venv/lib/python2.7/site-packages/package-name`` | [
"Find",
"where",
"this",
"package",
"should",
"be",
"installed",
"to",
"in",
"this",
"virtualenv",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/zzz_manual_install.py#L87-L100 |
MacHu-GWU/dataIO-project | dataIO/zzz_manual_install.py | find_DST | def find_DST():
"""Find where this package should be installed to.
"""
if SYS_NAME == "Windows":
return os.path.join(site.getsitepackages()[1], PKG_NAME)
elif SYS_NAME in ["Darwin", "Linux"]:
return os.path.join(site.getsitepackages()[0], PKG_NAME) | python | def find_DST():
"""Find where this package should be installed to.
"""
if SYS_NAME == "Windows":
return os.path.join(site.getsitepackages()[1], PKG_NAME)
elif SYS_NAME in ["Darwin", "Linux"]:
return os.path.join(site.getsitepackages()[0], PKG_NAME) | [
"def",
"find_DST",
"(",
")",
":",
"if",
"SYS_NAME",
"==",
"\"Windows\"",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"site",
".",
"getsitepackages",
"(",
")",
"[",
"1",
"]",
",",
"PKG_NAME",
")",
"elif",
"SYS_NAME",
"in",
"[",
"\"Darwin\"",
"... | Find where this package should be installed to. | [
"Find",
"where",
"this",
"package",
"should",
"be",
"installed",
"to",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/zzz_manual_install.py#L103-L109 |
MacHu-GWU/dataIO-project | dataIO/zzz_manual_install.py | md5_of_file | def md5_of_file(abspath):
"""Md5 value of a file.
"""
chunk_size = 1024 * 1024
m = hashlib.md5()
with open(abspath, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
m.update(data)
return m.hexdigest() | python | def md5_of_file(abspath):
"""Md5 value of a file.
"""
chunk_size = 1024 * 1024
m = hashlib.md5()
with open(abspath, "rb") as f:
while True:
data = f.read(chunk_size)
if not data:
break
m.update(data)
return m.hexdigest() | [
"def",
"md5_of_file",
"(",
"abspath",
")",
":",
"chunk_size",
"=",
"1024",
"*",
"1024",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"abspath",
",",
"\"rb\"",
")",
"as",
"f",
":",
"while",
"True",
":",
"data",
"=",
"f",
".",
"r... | Md5 value of a file. | [
"Md5",
"value",
"of",
"a",
"file",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/zzz_manual_install.py#L118-L129 |
MacHu-GWU/dataIO-project | dataIO/zzz_manual_install.py | check_need_install | def check_need_install():
"""Check if installed package are exactly the same to this one.
By checking md5 value of all files.
"""
need_install_flag = False
for root, _, basename_list in os.walk(SRC):
if os.path.basename(root) != "__pycache__":
for basename in basename_list:
... | python | def check_need_install():
"""Check if installed package are exactly the same to this one.
By checking md5 value of all files.
"""
need_install_flag = False
for root, _, basename_list in os.walk(SRC):
if os.path.basename(root) != "__pycache__":
for basename in basename_list:
... | [
"def",
"check_need_install",
"(",
")",
":",
"need_install_flag",
"=",
"False",
"for",
"root",
",",
"_",
",",
"basename_list",
"in",
"os",
".",
"walk",
"(",
"SRC",
")",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"!=",
"\"__pycache_... | Check if installed package are exactly the same to this one.
By checking md5 value of all files. | [
"Check",
"if",
"installed",
"package",
"are",
"exactly",
"the",
"same",
"to",
"this",
"one",
".",
"By",
"checking",
"md5",
"value",
"of",
"all",
"files",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/zzz_manual_install.py#L132-L147 |
MacHu-GWU/dataIO-project | dataIO/zzz_manual_install.py | install | def install():
"""Manual install main script.
"""
# check installed package
print("Compare to '%s' ..." % DST)
need_install_flag = check_need_install()
if not need_install_flag:
print(" package is up-to-date, no need to install.")
return
print("Difference been found, start... | python | def install():
"""Manual install main script.
"""
# check installed package
print("Compare to '%s' ..." % DST)
need_install_flag = check_need_install()
if not need_install_flag:
print(" package is up-to-date, no need to install.")
return
print("Difference been found, start... | [
"def",
"install",
"(",
")",
":",
"# check installed package",
"print",
"(",
"\"Compare to '%s' ...\"",
"%",
"DST",
")",
"need_install_flag",
"=",
"check_need_install",
"(",
")",
"if",
"not",
"need_install_flag",
":",
"print",
"(",
"\" package is up-to-date, no need t... | Manual install main script. | [
"Manual",
"install",
"main",
"script",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/zzz_manual_install.py#L150-L182 |
lablup/backend.ai-common | src/ai/backend/common/docker.py | login | async def login(
sess: aiohttp.ClientSession,
registry_url: yarl.URL,
credentials: dict,
scope: str) -> dict:
'''
Authorize to the docker registry using the given credentials and token scope, and returns a set
of required aiohttp.ClientSession.request() keyword arguments for ... | python | async def login(
sess: aiohttp.ClientSession,
registry_url: yarl.URL,
credentials: dict,
scope: str) -> dict:
'''
Authorize to the docker registry using the given credentials and token scope, and returns a set
of required aiohttp.ClientSession.request() keyword arguments for ... | [
"async",
"def",
"login",
"(",
"sess",
":",
"aiohttp",
".",
"ClientSession",
",",
"registry_url",
":",
"yarl",
".",
"URL",
",",
"credentials",
":",
"dict",
",",
"scope",
":",
"str",
")",
"->",
"dict",
":",
"if",
"credentials",
".",
"get",
"(",
"'usernam... | Authorize to the docker registry using the given credentials and token scope, and returns a set
of required aiohttp.ClientSession.request() keyword arguments for further API requests.
Some registry servers only rely on HTTP Basic Authentication without token-based access controls
(usually via nginx proxy).... | [
"Authorize",
"to",
"the",
"docker",
"registry",
"using",
"the",
"given",
"credentials",
"and",
"token",
"scope",
"and",
"returns",
"a",
"set",
"of",
"required",
"aiohttp",
".",
"ClientSession",
".",
"request",
"()",
"keyword",
"arguments",
"for",
"further",
"A... | train | https://github.com/lablup/backend.ai-common/blob/20b3a2551ee5bb3b88e7836471bc244a70ad0ae6/src/ai/backend/common/docker.py#L33-L85 |
ska-sa/katversion | katversion/version.py | is_git | def is_git(path):
"""Return True if this is a git repo."""
try:
repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')
return True if repo_dir else False
except (OSError, RuntimeError):
return False | python | def is_git(path):
"""Return True if this is a git repo."""
try:
repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')
return True if repo_dir else False
except (OSError, RuntimeError):
return False | [
"def",
"is_git",
"(",
"path",
")",
":",
"try",
":",
"repo_dir",
"=",
"run_cmd",
"(",
"path",
",",
"'git'",
",",
"'rev-parse'",
",",
"'--git-dir'",
")",
"return",
"True",
"if",
"repo_dir",
"else",
"False",
"except",
"(",
"OSError",
",",
"RuntimeError",
")... | Return True if this is a git repo. | [
"Return",
"True",
"if",
"this",
"is",
"a",
"git",
"repo",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L45-L51 |
ska-sa/katversion | katversion/version.py | date_version | def date_version(scm=None):
"""Generate a version string based on the SCM type and the date."""
dt = str(time.strftime('%Y%m%d%H%M'))
if scm:
version = "0.0+unknown.{0}.{1}".format(scm, dt)
else:
version = "0.0+unknown." + dt
return version | python | def date_version(scm=None):
"""Generate a version string based on the SCM type and the date."""
dt = str(time.strftime('%Y%m%d%H%M'))
if scm:
version = "0.0+unknown.{0}.{1}".format(scm, dt)
else:
version = "0.0+unknown." + dt
return version | [
"def",
"date_version",
"(",
"scm",
"=",
"None",
")",
":",
"dt",
"=",
"str",
"(",
"time",
".",
"strftime",
"(",
"'%Y%m%d%H%M'",
")",
")",
"if",
"scm",
":",
"version",
"=",
"\"0.0+unknown.{0}.{1}\"",
".",
"format",
"(",
"scm",
",",
"dt",
")",
"else",
"... | Generate a version string based on the SCM type and the date. | [
"Generate",
"a",
"version",
"string",
"based",
"on",
"the",
"SCM",
"type",
"and",
"the",
"date",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L63-L70 |
ska-sa/katversion | katversion/version.py | get_git_cleaned_branch_name | def get_git_cleaned_branch_name(path):
"""Get the git branch name of the current HEAD in path. The branch name is
scrubbed to conform to PEP-440.
PEP-440 Local version identifiers shall only consist out of:
- ASCII letters ( [a-zA-Z] )
- ASCII digits ( [0-9] )
- periods ( . )
https://www.py... | python | def get_git_cleaned_branch_name(path):
"""Get the git branch name of the current HEAD in path. The branch name is
scrubbed to conform to PEP-440.
PEP-440 Local version identifiers shall only consist out of:
- ASCII letters ( [a-zA-Z] )
- ASCII digits ( [0-9] )
- periods ( . )
https://www.py... | [
"def",
"get_git_cleaned_branch_name",
"(",
"path",
")",
":",
"# Get name of current branch (or 'HEAD' for a detached HEAD)",
"branch_name",
"=",
"run_cmd",
"(",
"path",
",",
"'git'",
",",
"'rev-parse'",
",",
"'--abbrev-ref'",
",",
"'HEAD'",
")",
"branch_name",
"=",
"re"... | Get the git branch name of the current HEAD in path. The branch name is
scrubbed to conform to PEP-440.
PEP-440 Local version identifiers shall only consist out of:
- ASCII letters ( [a-zA-Z] )
- ASCII digits ( [0-9] )
- periods ( . )
https://www.python.org/dev/peps/pep-0440/#local-version-iden... | [
"Get",
"the",
"git",
"branch",
"name",
"of",
"the",
"current",
"HEAD",
"in",
"path",
".",
"The",
"branch",
"name",
"is",
"scrubbed",
"to",
"conform",
"to",
"PEP",
"-",
"440",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L73-L91 |
ska-sa/katversion | katversion/version.py | get_git_version | def get_git_version(path):
"""Get the GIT version."""
branch_name = get_git_cleaned_branch_name(path)
# Determine whether working copy is dirty (i.e. contains modified files)
mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
dirty = '.dirty' if mods else ''
# Get a lis... | python | def get_git_version(path):
"""Get the GIT version."""
branch_name = get_git_cleaned_branch_name(path)
# Determine whether working copy is dirty (i.e. contains modified files)
mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
dirty = '.dirty' if mods else ''
# Get a lis... | [
"def",
"get_git_version",
"(",
"path",
")",
":",
"branch_name",
"=",
"get_git_cleaned_branch_name",
"(",
"path",
")",
"# Determine whether working copy is dirty (i.e. contains modified files)",
"mods",
"=",
"run_cmd",
"(",
"path",
",",
"'git'",
",",
"'status'",
",",
"'-... | Get the GIT version. | [
"Get",
"the",
"GIT",
"version",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L94-L137 |
ska-sa/katversion | katversion/version.py | get_version_from_scm | def get_version_from_scm(path=None):
"""Get the current version string of this package using SCM tool.
Parameters
----------
path : None or string, optional
The SCM checkout path (default is current directory)
Returns
-------
version : string
The version string for this pac... | python | def get_version_from_scm(path=None):
"""Get the current version string of this package using SCM tool.
Parameters
----------
path : None or string, optional
The SCM checkout path (default is current directory)
Returns
-------
version : string
The version string for this pac... | [
"def",
"get_version_from_scm",
"(",
"path",
"=",
"None",
")",
":",
"if",
"is_git",
"(",
"path",
")",
":",
"return",
"'git'",
",",
"get_git_version",
"(",
"path",
")",
"elif",
"is_svn",
"(",
"path",
")",
":",
"return",
"'svn'",
",",
"get_svn_version",
"("... | Get the current version string of this package using SCM tool.
Parameters
----------
path : None or string, optional
The SCM checkout path (default is current directory)
Returns
-------
version : string
The version string for this package | [
"Get",
"the",
"current",
"version",
"string",
"of",
"this",
"package",
"using",
"SCM",
"tool",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L147-L165 |
ska-sa/katversion | katversion/version.py | get_version_from_module | def get_version_from_module(module):
"""Use pkg_resources to get version of installed module by name."""
if module is not None:
# Setup.py will not pass in a module, but creating __version__ from
# __init__ will.
module = str(module).split('.', 1)[0]
try:
package = pk... | python | def get_version_from_module(module):
"""Use pkg_resources to get version of installed module by name."""
if module is not None:
# Setup.py will not pass in a module, but creating __version__ from
# __init__ will.
module = str(module).split('.', 1)[0]
try:
package = pk... | [
"def",
"get_version_from_module",
"(",
"module",
")",
":",
"if",
"module",
"is",
"not",
"None",
":",
"# Setup.py will not pass in a module, but creating __version__ from",
"# __init__ will.",
"module",
"=",
"str",
"(",
"module",
")",
".",
"split",
"(",
"'.'",
",",
"... | Use pkg_resources to get version of installed module by name. | [
"Use",
"pkg_resources",
"to",
"get",
"version",
"of",
"installed",
"module",
"by",
"name",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L168-L179 |
ska-sa/katversion | katversion/version.py | _must_decode | def _must_decode(value):
"""Copied from pkginfo 1.4.1, _compat module."""
if type(value) is bytes:
try:
return value.decode('utf-8')
except UnicodeDecodeError:
return value.decode('latin1')
return value | python | def _must_decode(value):
"""Copied from pkginfo 1.4.1, _compat module."""
if type(value) is bytes:
try:
return value.decode('utf-8')
except UnicodeDecodeError:
return value.decode('latin1')
return value | [
"def",
"_must_decode",
"(",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"bytes",
":",
"try",
":",
"return",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"value",
".",
"decode",
"(",
"'latin1'",... | Copied from pkginfo 1.4.1, _compat module. | [
"Copied",
"from",
"pkginfo",
"1",
".",
"4",
".",
"1",
"_compat",
"module",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L182-L189 |
ska-sa/katversion | katversion/version.py | get_version_from_unpacked_sdist | def get_version_from_unpacked_sdist(path):
"""Assume path points to unpacked source distribution and get version."""
# This is a condensed version of the relevant code in pkginfo 1.4.1
try:
with open(os.path.join(path, 'PKG-INFO')) as f:
data = f.read()
except IOError:
# Coul... | python | def get_version_from_unpacked_sdist(path):
"""Assume path points to unpacked source distribution and get version."""
# This is a condensed version of the relevant code in pkginfo 1.4.1
try:
with open(os.path.join(path, 'PKG-INFO')) as f:
data = f.read()
except IOError:
# Coul... | [
"def",
"get_version_from_unpacked_sdist",
"(",
"path",
")",
":",
"# This is a condensed version of the relevant code in pkginfo 1.4.1",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'PKG-INFO'",
")",
")",
"as",
"f",
":",
"data... | Assume path points to unpacked source distribution and get version. | [
"Assume",
"path",
"points",
"to",
"unpacked",
"source",
"distribution",
"and",
"get",
"version",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L192-L205 |
ska-sa/katversion | katversion/version.py | get_version_from_file | def get_version_from_file(path):
"""Find the VERSION_FILE and return its contents.
Returns
-------
version : string or None
"""
filename = os.path.join(path, VERSION_FILE)
if not os.path.isfile(filename):
# Look in the parent directory of path instead.
filename = os.path.jo... | python | def get_version_from_file(path):
"""Find the VERSION_FILE and return its contents.
Returns
-------
version : string or None
"""
filename = os.path.join(path, VERSION_FILE)
if not os.path.isfile(filename):
# Look in the parent directory of path instead.
filename = os.path.jo... | [
"def",
"get_version_from_file",
"(",
"path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"VERSION_FILE",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"# Look in the parent directory of path i... | Find the VERSION_FILE and return its contents.
Returns
-------
version : string or None | [
"Find",
"the",
"VERSION_FILE",
"and",
"return",
"its",
"contents",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L208-L227 |
ska-sa/katversion | katversion/version.py | normalised | def normalised(version):
"""Normalise a version string according to PEP 440, if possible."""
norm_version = pkg_resources.parse_version(version)
if not isinstance(norm_version, tuple):
# Let setuptools (>= 8) do the normalisation
return str(norm_version)
else:
# Homegrown normali... | python | def normalised(version):
"""Normalise a version string according to PEP 440, if possible."""
norm_version = pkg_resources.parse_version(version)
if not isinstance(norm_version, tuple):
# Let setuptools (>= 8) do the normalisation
return str(norm_version)
else:
# Homegrown normali... | [
"def",
"normalised",
"(",
"version",
")",
":",
"norm_version",
"=",
"pkg_resources",
".",
"parse_version",
"(",
"version",
")",
"if",
"not",
"isinstance",
"(",
"norm_version",
",",
"tuple",
")",
":",
"# Let setuptools (>= 8) do the normalisation",
"return",
"str",
... | Normalise a version string according to PEP 440, if possible. | [
"Normalise",
"a",
"version",
"string",
"according",
"to",
"PEP",
"440",
"if",
"possible",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L230-L245 |
ska-sa/katversion | katversion/version.py | get_version | def get_version(path=None, module=None):
"""Return the version string.
This function ensures that the version string complies with PEP 440.
The format of our version string is:
- for RELEASE builds:
<major>.<minor>
e.g.
0.1
2.4
- for DEVELOPME... | python | def get_version(path=None, module=None):
"""Return the version string.
This function ensures that the version string complies with PEP 440.
The format of our version string is:
- for RELEASE builds:
<major>.<minor>
e.g.
0.1
2.4
- for DEVELOPME... | [
"def",
"get_version",
"(",
"path",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"# Check the module option first.",
"version",
"=",
"get_version_from_module",
"(",
"module",
")",
"if",
"version",
":",
"return",
"normalised",
"(",
"version",
")",
"# Turn pa... | Return the version string.
This function ensures that the version string complies with PEP 440.
The format of our version string is:
- for RELEASE builds:
<major>.<minor>
e.g.
0.1
2.4
- for DEVELOPMENT builds:
<major>.<minor>.dev<num_b... | [
"Return",
"the",
"version",
"string",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L248-L321 |
ska-sa/katversion | katversion/version.py | _sane_version_list | def _sane_version_list(version):
"""Ensure the major and minor are int.
Parameters
----------
version: list
Version components
Returns
-------
version: list
List of components where first two components has been sanitised
"""
v0 = str(version[0])
if v0:
... | python | def _sane_version_list(version):
"""Ensure the major and minor are int.
Parameters
----------
version: list
Version components
Returns
-------
version: list
List of components where first two components has been sanitised
"""
v0 = str(version[0])
if v0:
... | [
"def",
"_sane_version_list",
"(",
"version",
")",
":",
"v0",
"=",
"str",
"(",
"version",
"[",
"0",
"]",
")",
"if",
"v0",
":",
"# Test if the major is a number.",
"try",
":",
"v0",
"=",
"v0",
".",
"lstrip",
"(",
"\"v\"",
")",
".",
"lstrip",
"(",
"\"V\""... | Ensure the major and minor are int.
Parameters
----------
version: list
Version components
Returns
-------
version: list
List of components where first two components has been sanitised | [
"Ensure",
"the",
"major",
"and",
"minor",
"are",
"int",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L324-L360 |
ska-sa/katversion | katversion/version.py | get_version_list | def get_version_list(path=None, module=None):
"""Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion.
"""
major = 0
minor = 0
patch = '' # PEP440 calls this prerelease, postreleas... | python | def get_version_list(path=None, module=None):
"""Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion.
"""
major = 0
minor = 0
patch = '' # PEP440 calls this prerelease, postreleas... | [
"def",
"get_version_list",
"(",
"path",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"major",
"=",
"0",
"minor",
"=",
"0",
"patch",
"=",
"''",
"# PEP440 calls this prerelease, postrelease or devrelease",
"ver",
"=",
"get_version",
"(",
"path",
",",
"modu... | Return the version information as a tuple.
This uses get_version and breaks the string up. Would make more sense if
the version was a tuple throughout katversion. | [
"Return",
"the",
"version",
"information",
"as",
"a",
"tuple",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L363-L381 |
ska-sa/katversion | katversion/version.py | build_info | def build_info(name, path=None, module=None):
"""Return the build info tuple."""
verlist = get_version_list(path, module)
verlist[0] = name
return tuple(verlist) | python | def build_info(name, path=None, module=None):
"""Return the build info tuple."""
verlist = get_version_list(path, module)
verlist[0] = name
return tuple(verlist) | [
"def",
"build_info",
"(",
"name",
",",
"path",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"verlist",
"=",
"get_version_list",
"(",
"path",
",",
"module",
")",
"verlist",
"[",
"0",
"]",
"=",
"name",
"return",
"tuple",
"(",
"verlist",
")"
] | Return the build info tuple. | [
"Return",
"the",
"build",
"info",
"tuple",
"."
] | train | https://github.com/ska-sa/katversion/blob/f507e46e6c5610aec89a08dd480c9b3721da0f8a/katversion/version.py#L384-L388 |
rainwoodman/kdcount | kdcount/cluster.py | fof.find | def find(self, groupid):
""" return all of the indices of particles of groupid """
return self.indices[self.offset[groupid]
:self.offset[groupid]+ self.length[groupid]] | python | def find(self, groupid):
""" return all of the indices of particles of groupid """
return self.indices[self.offset[groupid]
:self.offset[groupid]+ self.length[groupid]] | [
"def",
"find",
"(",
"self",
",",
"groupid",
")",
":",
"return",
"self",
".",
"indices",
"[",
"self",
".",
"offset",
"[",
"groupid",
"]",
":",
"self",
".",
"offset",
"[",
"groupid",
"]",
"+",
"self",
".",
"length",
"[",
"groupid",
"]",
"]"
] | return all of the indices of particles of groupid | [
"return",
"all",
"of",
"the",
"indices",
"of",
"particles",
"of",
"groupid"
] | train | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/cluster.py#L79-L82 |
rainwoodman/kdcount | kdcount/cluster.py | fof.sum | def sum(self, weights=None):
""" return the sum of weights of each object """
if weights is None:
weights = self.data.weights
return utils.bincount(self.labels, weights, self.N) | python | def sum(self, weights=None):
""" return the sum of weights of each object """
if weights is None:
weights = self.data.weights
return utils.bincount(self.labels, weights, self.N) | [
"def",
"sum",
"(",
"self",
",",
"weights",
"=",
"None",
")",
":",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"self",
".",
"data",
".",
"weights",
"return",
"utils",
".",
"bincount",
"(",
"self",
".",
"labels",
",",
"weights",
",",
"self",
... | return the sum of weights of each object | [
"return",
"the",
"sum",
"of",
"weights",
"of",
"each",
"object"
] | train | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/cluster.py#L84-L88 |
rainwoodman/kdcount | kdcount/cluster.py | fof.center | def center(self, weights=None):
""" return the center of each object """
if weights is None:
weights = self.data.weights
mass = utils.bincount(self.labels, weights, self.N)
cp = numpy.empty((len(mass), self.data.pos.shape[-1]), 'f8')
for d in range(self.data.pos.shape... | python | def center(self, weights=None):
""" return the center of each object """
if weights is None:
weights = self.data.weights
mass = utils.bincount(self.labels, weights, self.N)
cp = numpy.empty((len(mass), self.data.pos.shape[-1]), 'f8')
for d in range(self.data.pos.shape... | [
"def",
"center",
"(",
"self",
",",
"weights",
"=",
"None",
")",
":",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"self",
".",
"data",
".",
"weights",
"mass",
"=",
"utils",
".",
"bincount",
"(",
"self",
".",
"labels",
",",
"weights",
",",
"s... | return the center of each object | [
"return",
"the",
"center",
"of",
"each",
"object"
] | train | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/cluster.py#L90-L100 |
BlueBrain/nat | nat/paramSample.py | ParamSample.getParamValues | def getParamValues(self, paramName=None, paramId=None, useOnlyValids=True):
"""
Return the rows of sampleDF that are associated to the parameter
specified in paramName.
"""
if not paramName is None:
if not paramId is None:
if getParameterTypeN... | python | def getParamValues(self, paramName=None, paramId=None, useOnlyValids=True):
"""
Return the rows of sampleDF that are associated to the parameter
specified in paramName.
"""
if not paramName is None:
if not paramId is None:
if getParameterTypeN... | [
"def",
"getParamValues",
"(",
"self",
",",
"paramName",
"=",
"None",
",",
"paramId",
"=",
"None",
",",
"useOnlyValids",
"=",
"True",
")",
":",
"if",
"not",
"paramName",
"is",
"None",
":",
"if",
"not",
"paramId",
"is",
"None",
":",
"if",
"getParameterType... | Return the rows of sampleDF that are associated to the parameter
specified in paramName. | [
"Return",
"the",
"rows",
"of",
"sampleDF",
"that",
"are",
"associated",
"to",
"the",
"parameter",
"specified",
"in",
"paramName",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/paramSample.py#L365-L388 |
BlueBrain/nat | nat/paramSample.py | ParamSample.interpolate | def interpolate(self, interpValues):
"""
interpValues should be a dictionnary where the keys are the parameter names
for the independant variable for which interpolation should be run and
the values are the value to which the parameter should be interpolated.
"""
... | python | def interpolate(self, interpValues):
"""
interpValues should be a dictionnary where the keys are the parameter names
for the independant variable for which interpolation should be run and
the values are the value to which the parameter should be interpolated.
"""
... | [
"def",
"interpolate",
"(",
"self",
",",
"interpValues",
")",
":",
"self",
".",
"__operations",
".",
"append",
"(",
"[",
"\"interpolate\"",
",",
"interpValues",
"]",
")",
"df",
"=",
"self",
".",
"sampleDF",
"self",
".",
"interpValues",
"=",
"interpValues",
... | interpValues should be a dictionnary where the keys are the parameter names
for the independant variable for which interpolation should be run and
the values are the value to which the parameter should be interpolated. | [
"interpValues",
"should",
"be",
"a",
"dictionnary",
"where",
"the",
"keys",
"are",
"the",
"parameter",
"names",
"for",
"the",
"independant",
"variable",
"for",
"which",
"interpolation",
"should",
"be",
"run",
"and",
"the",
"values",
"are",
"the",
"value",
"to"... | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/paramSample.py#L391-L412 |
hammerlab/stanity | stanity/psisloo.py | loo_compare | def loo_compare(psisloo1, psisloo2):
"""
Compares two models using pointwise approximate leave-one-out cross validation.
For the method to be valid, the two models should have been fit on the same input data.
Parameters
-------------------
psisloo1 : Psisloo object for model1
psisloo2... | python | def loo_compare(psisloo1, psisloo2):
"""
Compares two models using pointwise approximate leave-one-out cross validation.
For the method to be valid, the two models should have been fit on the same input data.
Parameters
-------------------
psisloo1 : Psisloo object for model1
psisloo2... | [
"def",
"loo_compare",
"(",
"psisloo1",
",",
"psisloo2",
")",
":",
"## TODO: confirm that dimensions for psisloo1 & psisloo2 are the same",
"loores",
"=",
"psisloo1",
".",
"pointwise",
".",
"join",
"(",
"psisloo2",
".",
"pointwise",
",",
"lsuffix",
"=",
"'_m1'",
",",
... | Compares two models using pointwise approximate leave-one-out cross validation.
For the method to be valid, the two models should have been fit on the same input data.
Parameters
-------------------
psisloo1 : Psisloo object for model1
psisloo2 : Psisloo object for model2
Returns
---... | [
"Compares",
"two",
"models",
"using",
"pointwise",
"approximate",
"leave",
"-",
"one",
"-",
"out",
"cross",
"validation",
".",
"For",
"the",
"method",
"to",
"be",
"valid",
"the",
"two",
"models",
"should",
"have",
"been",
"fit",
"on",
"the",
"same",
"input... | train | https://github.com/hammerlab/stanity/blob/6c36abc207c4ce94f78968501dab839a56f35a41/stanity/psisloo.py#L104-L143 |
hammerlab/stanity | stanity/psisloo.py | Psisloo.plot | def plot(self):
""" Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y axis) for each observation unit (on the x axis)
"""
seaborn.pointplot(
y = self.pointwise.pareto_k,
x = self.pointwise.index,
... | python | def plot(self):
""" Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y axis) for each observation unit (on the x axis)
"""
seaborn.pointplot(
y = self.pointwise.pareto_k,
x = self.pointwise.index,
... | [
"def",
"plot",
"(",
"self",
")",
":",
"seaborn",
".",
"pointplot",
"(",
"y",
"=",
"self",
".",
"pointwise",
".",
"pareto_k",
",",
"x",
"=",
"self",
".",
"pointwise",
".",
"index",
",",
"join",
"=",
"False",
")"
] | Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y axis) for each observation unit (on the x axis) | [
"Graphical",
"summary",
"of",
"pointwise",
"pareto",
"-",
"k",
"importance",
"-",
"sampling",
"indices"
] | train | https://github.com/hammerlab/stanity/blob/6c36abc207c4ce94f78968501dab839a56f35a41/stanity/psisloo.py#L65-L74 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.add_layer | def add_layer(self, formula='', thickness=np.NaN, density=np.NaN):
"""provide another way to define the layers (stack)
Parameters:
===========
formula: string
ex: 'CoAg2'
ex: 'Al'
thickness: float (in mm)
density: float (g/cm3)
"""
i... | python | def add_layer(self, formula='', thickness=np.NaN, density=np.NaN):
"""provide another way to define the layers (stack)
Parameters:
===========
formula: string
ex: 'CoAg2'
ex: 'Al'
thickness: float (in mm)
density: float (g/cm3)
"""
i... | [
"def",
"add_layer",
"(",
"self",
",",
"formula",
"=",
"''",
",",
"thickness",
"=",
"np",
".",
"NaN",
",",
"density",
"=",
"np",
".",
"NaN",
")",
":",
"if",
"formula",
"==",
"''",
":",
"return",
"_new_stack",
"=",
"_utilities",
".",
"formula_to_dictiona... | provide another way to define the layers (stack)
Parameters:
===========
formula: string
ex: 'CoAg2'
ex: 'Al'
thickness: float (in mm)
density: float (g/cm3) | [
"provide",
"another",
"way",
"to",
"define",
"the",
"layers",
"(",
"stack",
")"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L118-L143 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.get_isotopic_ratio | def get_isotopic_ratio(self, compound='', element=''):
"""returns the list of isotopes for the element of the compound defined with their stoichiometric values
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element... | python | def get_isotopic_ratio(self, compound='', element=''):
"""returns the list of isotopes for the element of the compound defined with their stoichiometric values
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element... | [
"def",
"get_isotopic_ratio",
"(",
"self",
",",
"compound",
"=",
"''",
",",
"element",
"=",
"''",
")",
":",
"_stack",
"=",
"self",
".",
"stack",
"compound",
"=",
"str",
"(",
"compound",
")",
"if",
"compound",
"==",
"''",
":",
"_list_compounds",
"=",
"_s... | returns the list of isotopes for the element of the compound defined with their stoichiometric values
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is same as compound).
Raises:
=... | [
"returns",
"the",
"list",
"of",
"isotopes",
"for",
"the",
"element",
"of",
"the",
"compound",
"defined",
"with",
"their",
"stoichiometric",
"values"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L145-L196 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.set_isotopic_ratio | def set_isotopic_ratio(self, compound='', element='', list_ratio=[]):
"""defines the new set of ratio of the compound/element and trigger the calculation to update the density
Parameters:
===========
compound: string (default is ''). Name of compound
element: string (default is ... | python | def set_isotopic_ratio(self, compound='', element='', list_ratio=[]):
"""defines the new set of ratio of the compound/element and trigger the calculation to update the density
Parameters:
===========
compound: string (default is ''). Name of compound
element: string (default is ... | [
"def",
"set_isotopic_ratio",
"(",
"self",
",",
"compound",
"=",
"''",
",",
"element",
"=",
"''",
",",
"list_ratio",
"=",
"[",
"]",
")",
":",
"_stack",
"=",
"self",
".",
"stack",
"list_compounds",
"=",
"_stack",
".",
"keys",
"(",
")",
"if",
"compound",
... | defines the new set of ratio of the compound/element and trigger the calculation to update the density
Parameters:
===========
compound: string (default is ''). Name of compound
element: string (default is ''). Name of element
list_ratio: list (default is []). list of new stoich... | [
"defines",
"the",
"new",
"set",
"of",
"ratio",
"of",
"the",
"compound",
"/",
"element",
"and",
"trigger",
"the",
"calculation",
"to",
"update",
"the",
"density"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L198-L238 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.get_density | def get_density(self, compound='', element=''):
"""returns the list of isotopes for the element of the compound defined with their density
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is ... | python | def get_density(self, compound='', element=''):
"""returns the list of isotopes for the element of the compound defined with their density
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is ... | [
"def",
"get_density",
"(",
"self",
",",
"compound",
"=",
"''",
",",
"element",
"=",
"''",
")",
":",
"_stack",
"=",
"self",
".",
"stack",
"if",
"compound",
"==",
"''",
":",
"_list_compounds",
"=",
"_stack",
".",
"keys",
"(",
")",
"list_all_dict",
"=",
... | returns the list of isotopes for the element of the compound defined with their density
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is same as compound).
Raises:
=======
... | [
"returns",
"the",
"list",
"of",
"isotopes",
"for",
"the",
"element",
"of",
"the",
"compound",
"defined",
"with",
"their",
"density"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L240-L281 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__math_on_stack | def __math_on_stack(self, used_lock=False):
"""will perform all the various update of the stack, such as populating the stack_sigma, caluclate the density of the
layers....etc. """
# populate stack_sigma (Sigma vs Energy for every element)
self.__get_sigmas()
# populate compoun... | python | def __math_on_stack(self, used_lock=False):
"""will perform all the various update of the stack, such as populating the stack_sigma, caluclate the density of the
layers....etc. """
# populate stack_sigma (Sigma vs Energy for every element)
self.__get_sigmas()
# populate compoun... | [
"def",
"__math_on_stack",
"(",
"self",
",",
"used_lock",
"=",
"False",
")",
":",
"# populate stack_sigma (Sigma vs Energy for every element)",
"self",
".",
"__get_sigmas",
"(",
")",
"# populate compound density (if none provided)",
"self",
".",
"__update_layer_density",
"(",
... | will perform all the various update of the stack, such as populating the stack_sigma, caluclate the density of the
layers....etc. | [
"will",
"perform",
"all",
"the",
"various",
"update",
"of",
"the",
"stack",
"such",
"as",
"populating",
"the",
"stack_sigma",
"caluclate",
"the",
"density",
"of",
"the",
"layers",
"....",
"etc",
"."
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L283-L300 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__lock_density_if_defined | def __lock_density_if_defined(self, stack: dict):
"""lock (True) the density lock if the density has been been defined during initialization
Store the resulting dictionary into density_lock
Parameters:
===========
stack: dictionary (optional)
if not provided, the entir... | python | def __lock_density_if_defined(self, stack: dict):
"""lock (True) the density lock if the density has been been defined during initialization
Store the resulting dictionary into density_lock
Parameters:
===========
stack: dictionary (optional)
if not provided, the entir... | [
"def",
"__lock_density_if_defined",
"(",
"self",
",",
"stack",
":",
"dict",
")",
":",
"if",
"self",
".",
"stack",
"==",
"{",
"}",
":",
"density_lock",
"=",
"{",
"}",
"else",
":",
"density_lock",
"=",
"self",
".",
"density_lock",
"for",
"_compound",
"in",... | lock (True) the density lock if the density has been been defined during initialization
Store the resulting dictionary into density_lock
Parameters:
===========
stack: dictionary (optional)
if not provided, the entire stack will be used | [
"lock",
"(",
"True",
")",
"the",
"density",
"lock",
"if",
"the",
"density",
"has",
"been",
"been",
"defined",
"during",
"initialization",
"Store",
"the",
"resulting",
"dictionary",
"into",
"density_lock"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L302-L323 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__calculate_atoms_per_cm3 | def __calculate_atoms_per_cm3(self, used_lock=False):
"""calculate for each element, the atoms per cm3"""
stack = self.stack
_density_lock = self.density_lock
for _name_of_compound in stack.keys():
if used_lock and _density_lock[_name_of_compound]:
continue
... | python | def __calculate_atoms_per_cm3(self, used_lock=False):
"""calculate for each element, the atoms per cm3"""
stack = self.stack
_density_lock = self.density_lock
for _name_of_compound in stack.keys():
if used_lock and _density_lock[_name_of_compound]:
continue
... | [
"def",
"__calculate_atoms_per_cm3",
"(",
"self",
",",
"used_lock",
"=",
"False",
")",
":",
"stack",
"=",
"self",
".",
"stack",
"_density_lock",
"=",
"self",
".",
"density_lock",
"for",
"_name_of_compound",
"in",
"stack",
".",
"keys",
"(",
")",
":",
"if",
"... | calculate for each element, the atoms per cm3 | [
"calculate",
"for",
"each",
"element",
"the",
"atoms",
"per",
"cm3"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L396-L415 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__update_stack_with_isotopes_infos | def __update_stack_with_isotopes_infos(self, stack: dict):
"""retrieve the isotopes, isotopes file names, mass and atomic_ratio from each element in stack"""
for _key in stack:
_elements = stack[_key]['elements']
for _element in _elements:
_dict = _utilities.get_i... | python | def __update_stack_with_isotopes_infos(self, stack: dict):
"""retrieve the isotopes, isotopes file names, mass and atomic_ratio from each element in stack"""
for _key in stack:
_elements = stack[_key]['elements']
for _element in _elements:
_dict = _utilities.get_i... | [
"def",
"__update_stack_with_isotopes_infos",
"(",
"self",
",",
"stack",
":",
"dict",
")",
":",
"for",
"_key",
"in",
"stack",
":",
"_elements",
"=",
"stack",
"[",
"_key",
"]",
"[",
"'elements'",
"]",
"for",
"_element",
"in",
"_elements",
":",
"_dict",
"=",
... | retrieve the isotopes, isotopes file names, mass and atomic_ratio from each element in stack | [
"retrieve",
"the",
"isotopes",
"isotopes",
"file",
"names",
"mass",
"and",
"atomic_ratio",
"from",
"each",
"element",
"in",
"stack"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L432-L441 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__update_layer_density | def __update_layer_density(self):
"""calculate or update the layer density"""
_stack = self.stack
_density_lock = self.density_lock
list_compound = _stack.keys()
for _key in list_compound:
if _density_lock[_key]:
continue
_list_ratio = _st... | python | def __update_layer_density(self):
"""calculate or update the layer density"""
_stack = self.stack
_density_lock = self.density_lock
list_compound = _stack.keys()
for _key in list_compound:
if _density_lock[_key]:
continue
_list_ratio = _st... | [
"def",
"__update_layer_density",
"(",
"self",
")",
":",
"_stack",
"=",
"self",
".",
"stack",
"_density_lock",
"=",
"self",
".",
"density_lock",
"list_compound",
"=",
"_stack",
".",
"keys",
"(",
")",
"for",
"_key",
"in",
"list_compound",
":",
"if",
"_density_... | calculate or update the layer density | [
"calculate",
"or",
"update",
"the",
"layer",
"density"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L443-L460 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__update_density | def __update_density(self, compound='', element=''):
"""Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
elemen... | python | def __update_density(self, compound='', element=''):
"""Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
elemen... | [
"def",
"__update_density",
"(",
"self",
",",
"compound",
"=",
"''",
",",
"element",
"=",
"''",
")",
":",
"_density_element",
"=",
"0",
"list_ratio",
"=",
"self",
".",
"stack",
"[",
"compound",
"]",
"[",
"element",
"]",
"[",
"'isotopes'",
"]",
"[",
"'is... | Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
element: string (default is '') name of element | [
"Re",
"-",
"calculate",
"the",
"density",
"of",
"the",
"element",
"given",
"due",
"to",
"stoichiometric",
"changes",
"as",
"well",
"as",
"the",
"compound",
"density",
"(",
"if",
"density",
"is",
"not",
"locked",
")"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L462-L481 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__update_molar_mass | def __update_molar_mass(self, compound='', element=''):
"""Re-calculate the molar mass of the element given due to stoichiometric changes
Parameters:
==========
compound: string (default is '') name of compound
element: string (default is '') name of element
"""
... | python | def __update_molar_mass(self, compound='', element=''):
"""Re-calculate the molar mass of the element given due to stoichiometric changes
Parameters:
==========
compound: string (default is '') name of compound
element: string (default is '') name of element
"""
... | [
"def",
"__update_molar_mass",
"(",
"self",
",",
"compound",
"=",
"''",
",",
"element",
"=",
"''",
")",
":",
"_molar_mass_element",
"=",
"0",
"list_ratio",
"=",
"self",
".",
"stack",
"[",
"compound",
"]",
"[",
"element",
"]",
"[",
"'isotopes'",
"]",
"[",
... | Re-calculate the molar mass of the element given due to stoichiometric changes
Parameters:
==========
compound: string (default is '') name of compound
element: string (default is '') name of element | [
"Re",
"-",
"calculate",
"the",
"molar",
"mass",
"of",
"the",
"element",
"given",
"due",
"to",
"stoichiometric",
"changes"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L498-L512 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.__get_sigmas | def __get_sigmas(self):
"""will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes"""
stack_sigma = {}
_stack = self.stack
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_... | python | def __get_sigmas(self):
"""will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes"""
stack_sigma = {}
_stack = self.stack
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_... | [
"def",
"__get_sigmas",
"(",
"self",
")",
":",
"stack_sigma",
"=",
"{",
"}",
"_stack",
"=",
"self",
".",
"stack",
"_file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"_database_folder"... | will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes | [
"will",
"populate",
"the",
"stack_sigma",
"dictionary",
"with",
"the",
"energy",
"and",
"sigma",
"array",
"for",
"all",
"the",
"compound",
"/",
"element",
"and",
"isotopes"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L514-L560 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.plot | def plot(self, y_axis='attenuation', x_axis='energy',
logx=False, logy=False,
mixed=True, all_layers=False, all_elements=False,
all_isotopes=False, items_to_plot=None,
time_unit='us', offset_us=0., source_to_detector_m=16.,
time_resolution_us=0.16, t_star... | python | def plot(self, y_axis='attenuation', x_axis='energy',
logx=False, logy=False,
mixed=True, all_layers=False, all_elements=False,
all_isotopes=False, items_to_plot=None,
time_unit='us', offset_us=0., source_to_detector_m=16.,
time_resolution_us=0.16, t_star... | [
"def",
"plot",
"(",
"self",
",",
"y_axis",
"=",
"'attenuation'",
",",
"x_axis",
"=",
"'energy'",
",",
"logx",
"=",
"False",
",",
"logy",
"=",
"False",
",",
"mixed",
"=",
"True",
",",
"all_layers",
"=",
"False",
",",
"all_elements",
"=",
"False",
",",
... | display the transmission or attenuation of compound, element and/or isotopes specified
Parameters:
===========
:param x_axis: x type for export. Must be either ['energy'|'lambda'|'time'|'number']
:type x_axis: str
:param y_axis: y type for export. Must be either ['transmission'|... | [
"display",
"the",
"transmission",
"or",
"attenuation",
"of",
"compound",
"element",
"and",
"/",
"or",
"isotopes",
"specified"
] | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L562-L783 |
ornlneutronimaging/ImagingReso | ImagingReso/resonance.py | Resonance.export | def export(self, output_type='df', filename=None, x_axis='energy', y_axis='attenuation', mixed=True,
all_layers=False, all_elements=False, all_isotopes=False, items_to_export=None,
offset_us=0., source_to_detector_m=16.,
t_start_us=1, time_resolution_us=0.16, time_unit='us')... | python | def export(self, output_type='df', filename=None, x_axis='energy', y_axis='attenuation', mixed=True,
all_layers=False, all_elements=False, all_isotopes=False, items_to_export=None,
offset_us=0., source_to_detector_m=16.,
t_start_us=1, time_resolution_us=0.16, time_unit='us')... | [
"def",
"export",
"(",
"self",
",",
"output_type",
"=",
"'df'",
",",
"filename",
"=",
"None",
",",
"x_axis",
"=",
"'energy'",
",",
"y_axis",
"=",
"'attenuation'",
",",
"mixed",
"=",
"True",
",",
"all_layers",
"=",
"False",
",",
"all_elements",
"=",
"False... | output x and y values to clipboard or .csv file
output the transmission or attenuation or sigma of compound, element and/or isotopes specified
'sigma_b' exported for each isotope is the product resulted from (sigma * isotopic ratio)
'atoms_per_cm3' of each element is also exported in 'sigma' mod... | [
"output",
"x",
"and",
"y",
"values",
"to",
"clipboard",
"or",
".",
"csv",
"file",
"output",
"the",
"transmission",
"or",
"attenuation",
"or",
"sigma",
"of",
"compound",
"element",
"and",
"/",
"or",
"isotopes",
"specified",
"sigma_b",
"exported",
"for",
"each... | train | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/resonance.py#L785-L978 |
spockNinja/py-yaml-builder | yaml_builder/__init__.py | main | def main():
"""Builds a yaml file"""
parser = argparse.ArgumentParser(description='Compose a yaml file.')
parser.add_argument(
'root',
type=argparse.FileType('r'),
help='The root yaml file to compose.'
)
args = parser.parse_args()
result = yaml.load(args.root, Loader=Co... | python | def main():
"""Builds a yaml file"""
parser = argparse.ArgumentParser(description='Compose a yaml file.')
parser.add_argument(
'root',
type=argparse.FileType('r'),
help='The root yaml file to compose.'
)
args = parser.parse_args()
result = yaml.load(args.root, Loader=Co... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Compose a yaml file.'",
")",
"parser",
".",
"add_argument",
"(",
"'root'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'r'",
")",
",",
"help... | Builds a yaml file | [
"Builds",
"a",
"yaml",
"file"
] | train | https://github.com/spockNinja/py-yaml-builder/blob/9a7fb3067afe107397cebd07d950dbb4238a8730/yaml_builder/__init__.py#L7-L20 |
rapidpro/expressions | python/temba_expressions/dates.py | DateParser._parse | def _parse(self, text, mode):
"""
Returns a date, datetime or time depending on what information is available
"""
if text is None or not text.strip():
return None
# first try to parse as an ISO8601 date, if it doesn't work we'll try other options
if len(text)... | python | def _parse(self, text, mode):
"""
Returns a date, datetime or time depending on what information is available
"""
if text is None or not text.strip():
return None
# first try to parse as an ISO8601 date, if it doesn't work we'll try other options
if len(text)... | [
"def",
"_parse",
"(",
"self",
",",
"text",
",",
"mode",
")",
":",
"if",
"text",
"is",
"None",
"or",
"not",
"text",
".",
"strip",
"(",
")",
":",
"return",
"None",
"# first try to parse as an ISO8601 date, if it doesn't work we'll try other options",
"if",
"len",
... | Returns a date, datetime or time depending on what information is available | [
"Returns",
"a",
"date",
"datetime",
"or",
"time",
"depending",
"on",
"what",
"information",
"is",
"available"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/dates.py#L98-L145 |
rapidpro/expressions | python/temba_expressions/dates.py | DateParser._get_possible_sequences | def _get_possible_sequences(cls, mode, length, date_style):
"""
Gets possible component sequences in the given mode
:param mode: the mode
:param length: the length (only returns sequences of this length)
:param date_style: whether dates are usually entered day first or month firs... | python | def _get_possible_sequences(cls, mode, length, date_style):
"""
Gets possible component sequences in the given mode
:param mode: the mode
:param length: the length (only returns sequences of this length)
:param date_style: whether dates are usually entered day first or month firs... | [
"def",
"_get_possible_sequences",
"(",
"cls",
",",
"mode",
",",
"length",
",",
"date_style",
")",
":",
"sequences",
"=",
"[",
"]",
"date_sequences",
"=",
"cls",
".",
"DATE_SEQUENCES_DAY_FIRST",
"if",
"date_style",
"==",
"DateStyle",
".",
"DAY_FIRST",
"else",
"... | Gets possible component sequences in the given mode
:param mode: the mode
:param length: the length (only returns sequences of this length)
:param date_style: whether dates are usually entered day first or month first
:return: | [
"Gets",
"possible",
"component",
"sequences",
"in",
"the",
"given",
"mode",
":",
"param",
"mode",
":",
"the",
"mode",
":",
"param",
"length",
":",
"the",
"length",
"(",
"only",
"returns",
"sequences",
"of",
"this",
"length",
")",
":",
"param",
"date_style"... | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/dates.py#L148-L175 |
rapidpro/expressions | python/temba_expressions/dates.py | DateParser._get_token_possibilities | def _get_token_possibilities(cls, token, mode):
"""
Returns all possible component types of a token without regard to its context. For example "26" could be year,
date or minute, but can't be a month or an hour.
:param token: the token to classify
:param mode: the parse mode
... | python | def _get_token_possibilities(cls, token, mode):
"""
Returns all possible component types of a token without regard to its context. For example "26" could be year,
date or minute, but can't be a month or an hour.
:param token: the token to classify
:param mode: the parse mode
... | [
"def",
"_get_token_possibilities",
"(",
"cls",
",",
"token",
",",
"mode",
")",
":",
"token",
"=",
"token",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"possibilities",
"=",
"{",
"}",
"try",
":",
"as_int",
"=",
"int",
"(",
"token",
")",
"if",
"m... | Returns all possible component types of a token without regard to its context. For example "26" could be year,
date or minute, but can't be a month or an hour.
:param token: the token to classify
:param mode: the parse mode
:return: the dict of possible types and values if token was of t... | [
"Returns",
"all",
"possible",
"component",
"types",
"of",
"a",
"token",
"without",
"regard",
"to",
"its",
"context",
".",
"For",
"example",
"26",
"could",
"be",
"year",
"date",
"or",
"minute",
"but",
"can",
"t",
"be",
"a",
"month",
"or",
"an",
"hour",
... | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/dates.py#L178-L239 |
rapidpro/expressions | python/temba_expressions/dates.py | DateParser._make_result | def _make_result(cls, values, now, timezone):
"""
Makes a date or datetime or time object from a map of component values
:param values: the component values
:param now: the current now
:param timezone: the current timezone
:return: the date, datetime, time or none if valu... | python | def _make_result(cls, values, now, timezone):
"""
Makes a date or datetime or time object from a map of component values
:param values: the component values
:param now: the current now
:param timezone: the current timezone
:return: the date, datetime, time or none if valu... | [
"def",
"_make_result",
"(",
"cls",
",",
"values",
",",
"now",
",",
"timezone",
")",
":",
"date",
"=",
"None",
"time",
"=",
"None",
"if",
"Component",
".",
"MONTH",
"in",
"values",
":",
"year",
"=",
"cls",
".",
"_year_from_2digits",
"(",
"values",
".",
... | Makes a date or datetime or time object from a map of component values
:param values: the component values
:param now: the current now
:param timezone: the current timezone
:return: the date, datetime, time or none if values are invalid | [
"Makes",
"a",
"date",
"or",
"datetime",
"or",
"time",
"object",
"from",
"a",
"map",
"of",
"component",
"values",
":",
"param",
"values",
":",
"the",
"component",
"values",
":",
"param",
"now",
":",
"the",
"current",
"now",
":",
"param",
"timezone",
":",
... | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/dates.py#L242-L295 |
rapidpro/expressions | python/temba_expressions/dates.py | DateParser._year_from_2digits | def _year_from_2digits(short_year, current_year):
"""
Converts a relative 2-digit year to an absolute 4-digit year
:param short_year: the relative year
:param current_year: the current year
:return: the absolute year
"""
if short_year < 100:
short_year... | python | def _year_from_2digits(short_year, current_year):
"""
Converts a relative 2-digit year to an absolute 4-digit year
:param short_year: the relative year
:param current_year: the current year
:return: the absolute year
"""
if short_year < 100:
short_year... | [
"def",
"_year_from_2digits",
"(",
"short_year",
",",
"current_year",
")",
":",
"if",
"short_year",
"<",
"100",
":",
"short_year",
"+=",
"current_year",
"-",
"(",
"current_year",
"%",
"100",
")",
"if",
"abs",
"(",
"short_year",
"-",
"current_year",
")",
">=",... | Converts a relative 2-digit year to an absolute 4-digit year
:param short_year: the relative year
:param current_year: the current year
:return: the absolute year | [
"Converts",
"a",
"relative",
"2",
"-",
"digit",
"year",
"to",
"an",
"absolute",
"4",
"-",
"digit",
"year",
":",
"param",
"short_year",
":",
"the",
"relative",
"year",
":",
"param",
"current_year",
":",
"the",
"current",
"year",
":",
"return",
":",
"the",... | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/dates.py#L298-L312 |
anteater/anteater | anteater/src/patch_scan.py | prepare_patchset | def prepare_patchset(project, patchset, binaries, ips, urls):
""" Create black/white lists and default / project waivers
and iterates over patchset file """
# Get Various Lists / Project Waivers
lists = get_lists.GetLists()
# Get file name black list and project waivers
file_audit_list, fil... | python | def prepare_patchset(project, patchset, binaries, ips, urls):
""" Create black/white lists and default / project waivers
and iterates over patchset file """
# Get Various Lists / Project Waivers
lists = get_lists.GetLists()
# Get file name black list and project waivers
file_audit_list, fil... | [
"def",
"prepare_patchset",
"(",
"project",
",",
"patchset",
",",
"binaries",
",",
"ips",
",",
"urls",
")",
":",
"# Get Various Lists / Project Waivers",
"lists",
"=",
"get_lists",
".",
"GetLists",
"(",
")",
"# Get file name black list and project waivers",
"file_audit_l... | Create black/white lists and default / project waivers
and iterates over patchset file | [
"Create",
"black",
"/",
"white",
"lists",
"and",
"default",
"/",
"project",
"waivers",
"and",
"iterates",
"over",
"patchset",
"file"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L42-L101 |
anteater/anteater | anteater/src/patch_scan.py | scan_patch | def scan_patch(project, patch_file, binaries, ips, urls, file_audit_list,
file_audit_project_list, flag_list, ignore_list, file_ignore,
ignore_directories, url_ignore, ip_ignore, apikey):
"""
Scan actions for each commited file in patch set
"""
global failure
split_pat... | python | def scan_patch(project, patch_file, binaries, ips, urls, file_audit_list,
file_audit_project_list, flag_list, ignore_list, file_ignore,
ignore_directories, url_ignore, ip_ignore, apikey):
"""
Scan actions for each commited file in patch set
"""
global failure
split_pat... | [
"def",
"scan_patch",
"(",
"project",
",",
"patch_file",
",",
"binaries",
",",
"ips",
",",
"urls",
",",
"file_audit_list",
",",
"file_audit_project_list",
",",
"flag_list",
",",
"ignore_list",
",",
"file_ignore",
",",
"ignore_directories",
",",
"url_ignore",
",",
... | Scan actions for each commited file in patch set | [
"Scan",
"actions",
"for",
"each",
"commited",
"file",
"in",
"patch",
"set"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L104-L206 |
anteater/anteater | anteater/src/patch_scan.py | scan_binary | def scan_binary(patch_file, project, sha256hash, apikey):
"""
Sends Binary (sha256hash) to Virus Total API
"""
v_api = virus_total.VirusTotal()
while True:
binary_report = v_api.binary_report(sha256hash, apikey)
response_code = binary_report['response_code']
# report does n... | python | def scan_binary(patch_file, project, sha256hash, apikey):
"""
Sends Binary (sha256hash) to Virus Total API
"""
v_api = virus_total.VirusTotal()
while True:
binary_report = v_api.binary_report(sha256hash, apikey)
response_code = binary_report['response_code']
# report does n... | [
"def",
"scan_binary",
"(",
"patch_file",
",",
"project",
",",
"sha256hash",
",",
"apikey",
")",
":",
"v_api",
"=",
"virus_total",
".",
"VirusTotal",
"(",
")",
"while",
"True",
":",
"binary_report",
"=",
"v_api",
".",
"binary_report",
"(",
"sha256hash",
",",
... | Sends Binary (sha256hash) to Virus Total API | [
"Sends",
"Binary",
"(",
"sha256hash",
")",
"to",
"Virus",
"Total",
"API"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L209-L240 |
anteater/anteater | anteater/src/patch_scan.py | negative_report | def negative_report(binary_report, sha256hash, project, patch_file):
"""
If no match is made and file is clean
"""
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.info('File scan date for %s shows a clean status on: %s', patch_file, scan_date)
logger.inf... | python | def negative_report(binary_report, sha256hash, project, patch_file):
"""
If no match is made and file is clean
"""
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.info('File scan date for %s shows a clean status on: %s', patch_file, scan_date)
logger.inf... | [
"def",
"negative_report",
"(",
"binary_report",
",",
"sha256hash",
",",
"project",
",",
"patch_file",
")",
":",
"report_url",
"=",
"binary_report",
"[",
"'permalink'",
"]",
"scan_date",
"=",
"binary_report",
"[",
"'scan_date'",
"]",
"logger",
".",
"info",
"(",
... | If no match is made and file is clean | [
"If",
"no",
"match",
"is",
"made",
"and",
"file",
"is",
"clean"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L243-L257 |
anteater/anteater | anteater/src/patch_scan.py | positive_report | def positive_report(binary_report, sha256hash, project, patch_file):
"""
If a Positive match is found
"""
failure = True
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.error("Virus Found!")
logger.info('File scan date for %s shows a infected status ... | python | def positive_report(binary_report, sha256hash, project, patch_file):
"""
If a Positive match is found
"""
failure = True
report_url = binary_report['permalink']
scan_date = binary_report['scan_date']
logger.error("Virus Found!")
logger.info('File scan date for %s shows a infected status ... | [
"def",
"positive_report",
"(",
"binary_report",
",",
"sha256hash",
",",
"project",
",",
"patch_file",
")",
":",
"failure",
"=",
"True",
"report_url",
"=",
"binary_report",
"[",
"'permalink'",
"]",
"scan_date",
"=",
"binary_report",
"[",
"'scan_date'",
"]",
"logg... | If a Positive match is found | [
"If",
"a",
"Positive",
"match",
"is",
"found"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L260-L269 |
anteater/anteater | anteater/src/patch_scan.py | scan_ipaddr | def scan_ipaddr(ipaddr, apikey):
"""
If an IP Address is found, scan it
"""
logger.info('Query VirusTotal API for Public IP Found: %s', ipaddr)
v_api = virus_total.VirusTotal()
scan_ip = v_api.send_ip(ipaddr, apikey)
response_code = scan_ip['response_code']
verbose_msg = scan_ip['verbose... | python | def scan_ipaddr(ipaddr, apikey):
"""
If an IP Address is found, scan it
"""
logger.info('Query VirusTotal API for Public IP Found: %s', ipaddr)
v_api = virus_total.VirusTotal()
scan_ip = v_api.send_ip(ipaddr, apikey)
response_code = scan_ip['response_code']
verbose_msg = scan_ip['verbose... | [
"def",
"scan_ipaddr",
"(",
"ipaddr",
",",
"apikey",
")",
":",
"logger",
".",
"info",
"(",
"'Query VirusTotal API for Public IP Found: %s'",
",",
"ipaddr",
")",
"v_api",
"=",
"virus_total",
".",
"VirusTotal",
"(",
")",
"scan_ip",
"=",
"v_api",
".",
"send_ip",
"... | If an IP Address is found, scan it | [
"If",
"an",
"IP",
"Address",
"is",
"found",
"scan",
"it"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L272-L289 |
anteater/anteater | anteater/src/patch_scan.py | scan_url | def scan_url(url, apikey):
"""
If URL is found, scan it
"""
logger.info('Found what I believe is a URL: %s', url)
v_api = virus_total.VirusTotal()
while True:
url_report = v_api.url_report(url, apikey)
response_code = url_report['response_code']
# report does not exist, ... | python | def scan_url(url, apikey):
"""
If URL is found, scan it
"""
logger.info('Found what I believe is a URL: %s', url)
v_api = virus_total.VirusTotal()
while True:
url_report = v_api.url_report(url, apikey)
response_code = url_report['response_code']
# report does not exist, ... | [
"def",
"scan_url",
"(",
"url",
",",
"apikey",
")",
":",
"logger",
".",
"info",
"(",
"'Found what I believe is a URL: %s'",
",",
"url",
")",
"v_api",
"=",
"virus_total",
".",
"VirusTotal",
"(",
")",
"while",
"True",
":",
"url_report",
"=",
"v_api",
".",
"ur... | If URL is found, scan it | [
"If",
"URL",
"is",
"found",
"scan",
"it"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L292-L327 |
anteater/anteater | anteater/src/patch_scan.py | process_failure | def process_failure(project):
"""
If any scan operations register a failure, sys.exit(1) is called
to allow build to register a failure
"""
if failure:
lists = get_lists.GetLists()
report_url = lists.report_url(project)
if report_url:
print(report_url)
sys... | python | def process_failure(project):
"""
If any scan operations register a failure, sys.exit(1) is called
to allow build to register a failure
"""
if failure:
lists = get_lists.GetLists()
report_url = lists.report_url(project)
if report_url:
print(report_url)
sys... | [
"def",
"process_failure",
"(",
"project",
")",
":",
"if",
"failure",
":",
"lists",
"=",
"get_lists",
".",
"GetLists",
"(",
")",
"report_url",
"=",
"lists",
".",
"report_url",
"(",
"project",
")",
"if",
"report_url",
":",
"print",
"(",
"report_url",
")",
... | If any scan operations register a failure, sys.exit(1) is called
to allow build to register a failure | [
"If",
"any",
"scan",
"operations",
"register",
"a",
"failure",
"sys",
".",
"exit",
"(",
"1",
")",
"is",
"called",
"to",
"allow",
"build",
"to",
"register",
"a",
"failure"
] | train | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/patch_scan.py#L330-L340 |
RI-imaging/nrefocus | nrefocus/metrics.py | average_gradient | def average_gradient(data, *kwargs):
""" Compute average gradient norm of an image
"""
return np.average(np.array(np.gradient(data))**2) | python | def average_gradient(data, *kwargs):
""" Compute average gradient norm of an image
"""
return np.average(np.array(np.gradient(data))**2) | [
"def",
"average_gradient",
"(",
"data",
",",
"*",
"kwargs",
")",
":",
"return",
"np",
".",
"average",
"(",
"np",
".",
"array",
"(",
"np",
".",
"gradient",
"(",
"data",
")",
")",
"**",
"2",
")"
] | Compute average gradient norm of an image | [
"Compute",
"average",
"gradient",
"norm",
"of",
"an",
"image"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/metrics.py#L4-L7 |
RI-imaging/nrefocus | nrefocus/metrics.py | contrast_rms | def contrast_rms(data, *kwargs):
""" Compute RMS contrast norm of an image
"""
av = np.average(data, *kwargs)
mal = 1 / (data.shape[0] * data.shape[1])
return np.sqrt(mal * np.sum(np.square(data - av))) | python | def contrast_rms(data, *kwargs):
""" Compute RMS contrast norm of an image
"""
av = np.average(data, *kwargs)
mal = 1 / (data.shape[0] * data.shape[1])
return np.sqrt(mal * np.sum(np.square(data - av))) | [
"def",
"contrast_rms",
"(",
"data",
",",
"*",
"kwargs",
")",
":",
"av",
"=",
"np",
".",
"average",
"(",
"data",
",",
"*",
"kwargs",
")",
"mal",
"=",
"1",
"/",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
"*",
"data",
".",
"shape",
"[",
"1",
"]",... | Compute RMS contrast norm of an image | [
"Compute",
"RMS",
"contrast",
"norm",
"of",
"an",
"image"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/metrics.py#L10-L15 |
RI-imaging/nrefocus | nrefocus/metrics.py | spectral | def spectral(data, lambd, *kwargs):
""" Compute spectral contrast of image
Performs bandpass filtering in Fourier space according to optical
limit of detection system, approximated by twice the wavelength.
Parameters
----------
data : 2d ndarray
the image to compute the norm from
... | python | def spectral(data, lambd, *kwargs):
""" Compute spectral contrast of image
Performs bandpass filtering in Fourier space according to optical
limit of detection system, approximated by twice the wavelength.
Parameters
----------
data : 2d ndarray
the image to compute the norm from
... | [
"def",
"spectral",
"(",
"data",
",",
"lambd",
",",
"*",
"kwargs",
")",
":",
"# Set up fast fourier transform",
"# if not data.dtype == np.dtype(np.complex):",
"# data = np.array(data, dtype=np.complex)",
"# fftplan = fftw3.Plan(data.copy(), None, nthreads = _ncores,",
"# ... | Compute spectral contrast of image
Performs bandpass filtering in Fourier space according to optical
limit of detection system, approximated by twice the wavelength.
Parameters
----------
data : 2d ndarray
the image to compute the norm from
lambd : float
wavelength of the ligh... | [
"Compute",
"spectral",
"contrast",
"of",
"image"
] | train | https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/metrics.py#L18-L52 |
MacHu-GWU/dataIO-project | dataIO/textfile.py | is_gzip_file | def is_gzip_file(abspath):
"""Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
"""
abspath = abspath.lower()
_, ext = os.path.splitext(abspath)
if ext in [".gz", ".zip"]:
is_gzip = True
else:
is_gzip = False
... | python | def is_gzip_file(abspath):
"""Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
"""
abspath = abspath.lower()
_, ext = os.path.splitext(abspath)
if ext in [".gz", ".zip"]:
is_gzip = True
else:
is_gzip = False
... | [
"def",
"is_gzip_file",
"(",
"abspath",
")",
":",
"abspath",
"=",
"abspath",
".",
"lower",
"(",
")",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"abspath",
")",
"if",
"ext",
"in",
"[",
"\".gz\"",
",",
"\".zip\"",
"]",
":",
"is_gzi... | Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file | [
"Parse",
"file",
"extension",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/textfile.py#L29-L41 |
MacHu-GWU/dataIO-project | dataIO/textfile.py | write | def write(s, path, encoding="utf-8"):
"""Write string to text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "wb") as f:
if is_gzip:
f.write(zlib.compress(s.encode(encoding)))
else:
f.write(s.encode(encoding)) | python | def write(s, path, encoding="utf-8"):
"""Write string to text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "wb") as f:
if is_gzip:
f.write(zlib.compress(s.encode(encoding)))
else:
f.write(s.encode(encoding)) | [
"def",
"write",
"(",
"s",
",",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"is_gzip",
"=",
"is_gzip_file",
"(",
"path",
")",
"with",
"open",
"(",
"path",
",",
"\"wb\"",
")",
"as",
"f",
":",
"if",
"is_gzip",
":",
"f",
".",
"write",
"(",
"... | Write string to text file. | [
"Write",
"string",
"to",
"text",
"file",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/textfile.py#L44-L53 |
MacHu-GWU/dataIO-project | dataIO/textfile.py | read | def read(path, encoding="utf-8"):
"""Read string from text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "rb") as f:
if is_gzip:
return zlib.decompress(f.read()).decode(encoding)
else:
return f.read().decode(encoding) | python | def read(path, encoding="utf-8"):
"""Read string from text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "rb") as f:
if is_gzip:
return zlib.decompress(f.read()).decode(encoding)
else:
return f.read().decode(encoding) | [
"def",
"read",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"is_gzip",
"=",
"is_gzip_file",
"(",
"path",
")",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"if",
"is_gzip",
":",
"return",
"zlib",
".",
"decompress",
"("... | Read string from text file. | [
"Read",
"string",
"from",
"text",
"file",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/textfile.py#L63-L72 |
MacHu-GWU/dataIO-project | dataIO/textfile.py | smartread | def smartread(path):
"""Read text from file, automatically detect encoding. ``chardet`` required.
"""
with open(path, "rb") as f:
content = f.read()
result = chardet.detect(content)
return content.decode(result["encoding"]) | python | def smartread(path):
"""Read text from file, automatically detect encoding. ``chardet`` required.
"""
with open(path, "rb") as f:
content = f.read()
result = chardet.detect(content)
return content.decode(result["encoding"]) | [
"def",
"smartread",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"result",
"=",
"chardet",
".",
"detect",
"(",
"content",
")",
"return",
"content",
".",
"decode"... | Read text from file, automatically detect encoding. ``chardet`` required. | [
"Read",
"text",
"from",
"file",
"automatically",
"detect",
"encoding",
".",
"chardet",
"required",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/textfile.py#L82-L88 |
MacHu-GWU/dataIO-project | dataIO/textfile.py | to_utf8 | def to_utf8(path, output_path=None):
"""Convert any text file to utf8 encoding.
"""
if output_path is None:
basename, ext = os.path.splitext(path)
output_path = basename + "-UTF8Encode" + ext
text = smartread(path)
write(text, output_path) | python | def to_utf8(path, output_path=None):
"""Convert any text file to utf8 encoding.
"""
if output_path is None:
basename, ext = os.path.splitext(path)
output_path = basename + "-UTF8Encode" + ext
text = smartread(path)
write(text, output_path) | [
"def",
"to_utf8",
"(",
"path",
",",
"output_path",
"=",
"None",
")",
":",
"if",
"output_path",
"is",
"None",
":",
"basename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"output_path",
"=",
"basename",
"+",
"\"-UTF8Encode\"",
... | Convert any text file to utf8 encoding. | [
"Convert",
"any",
"text",
"file",
"to",
"utf8",
"encoding",
"."
] | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/textfile.py#L91-L99 |
MacHu-GWU/dataIO-project | dataIO/textfile.py | readlines | def readlines(path, encoding="utf-8", skiplines=None, nlines=None, strip='right'):
"""skip n lines and fetch the next n lines.
:param skiplines: default None, skip first n lines
:param nlines: default None, yield next n lines
:param strip: default None, available option 'left', 'right', 'both'
... | python | def readlines(path, encoding="utf-8", skiplines=None, nlines=None, strip='right'):
"""skip n lines and fetch the next n lines.
:param skiplines: default None, skip first n lines
:param nlines: default None, yield next n lines
:param strip: default None, available option 'left', 'right', 'both'
... | [
"def",
"readlines",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"skiplines",
"=",
"None",
",",
"nlines",
"=",
"None",
",",
"strip",
"=",
"'right'",
")",
":",
"strip_method",
"=",
"str",
"(",
"strip",
")",
".",
"lower",
"(",
")",
"if",
"strip... | skip n lines and fetch the next n lines.
:param skiplines: default None, skip first n lines
:param nlines: default None, yield next n lines
:param strip: default None, available option 'left', 'right', 'both'
**中文文档**
跳过前#skiplines行, 然后读取#nlines行。可对字符串进行strip预处理。 | [
"skip",
"n",
"lines",
"and",
"fetch",
"the",
"next",
"n",
"lines",
".",
":",
"param",
"skiplines",
":",
"default",
"None",
"skip",
"first",
"n",
"lines",
":",
"param",
"nlines",
":",
"default",
"None",
"yield",
"next",
"n",
"lines",
":",
"param",
"stri... | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/textfile.py#L127-L155 |
MacHu-GWU/dataIO-project | dataIO/textfile.py | readchunks | def readchunks(path, encoding="utf-8", skiplines=None, chunksize=None, strip='right'):
"""skip n lines and fetch the next n lines as a chunk, and repeat fetching.
:param skiplines: default None, skip first n lines
:param chunksize: default None (size-1 chunk), lines chunk size
:param strip: default... | python | def readchunks(path, encoding="utf-8", skiplines=None, chunksize=None, strip='right'):
"""skip n lines and fetch the next n lines as a chunk, and repeat fetching.
:param skiplines: default None, skip first n lines
:param chunksize: default None (size-1 chunk), lines chunk size
:param strip: default... | [
"def",
"readchunks",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"skiplines",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"strip",
"=",
"'right'",
")",
":",
"strip_method",
"=",
"str",
"(",
"strip",
")",
".",
"lower",
"(",
")",
"if",
"s... | skip n lines and fetch the next n lines as a chunk, and repeat fetching.
:param skiplines: default None, skip first n lines
:param chunksize: default None (size-1 chunk), lines chunk size
:param strip: default None, avaliable option 'left', 'right', 'both'
**中文文档**
跳过前#skiplines行, 每次读... | [
"skip",
"n",
"lines",
"and",
"fetch",
"the",
"next",
"n",
"lines",
"as",
"a",
"chunk",
"and",
"repeat",
"fetching",
".",
":",
"param",
"skiplines",
":",
"default",
"None",
"skip",
"first",
"n",
"lines",
":",
"param",
"chunksize",
":",
"default",
"None",
... | train | https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/textfile.py#L158-L194 |
rapidpro/expressions | python/temba_expressions/evaluator.py | EvaluationContext._coerce_to_supported_type | def _coerce_to_supported_type(cls, value):
"""
Since we let users populate the context with whatever they want, this ensures the resolved value is something
which the expression engine understands.
:param value: the resolved value
:return: the value converted to a supported data ... | python | def _coerce_to_supported_type(cls, value):
"""
Since we let users populate the context with whatever they want, this ensures the resolved value is something
which the expression engine understands.
:param value: the resolved value
:return: the value converted to a supported data ... | [
"def",
"_coerce_to_supported_type",
"(",
"cls",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"\"\"",
"# empty string rather than none",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if",
"'*'",
"in",
"value",
":",
"return... | Since we let users populate the context with whatever they want, this ensures the resolved value is something
which the expression engine understands.
:param value: the resolved value
:return: the value converted to a supported data type | [
"Since",
"we",
"let",
"users",
"populate",
"the",
"context",
"with",
"whatever",
"they",
"want",
"this",
"ensures",
"the",
"resolved",
"value",
"is",
"something",
"which",
"the",
"expression",
"engine",
"understands",
".",
":",
"param",
"value",
":",
"the",
... | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L87-L108 |
rapidpro/expressions | python/temba_expressions/evaluator.py | Evaluator.evaluate_template | def evaluate_template(self, template, context, url_encode=False, strategy=EvaluationStrategy.COMPLETE):
"""
Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
:param template: the template string
:param context: the evaluation context
... | python | def evaluate_template(self, template, context, url_encode=False, strategy=EvaluationStrategy.COMPLETE):
"""
Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
:param template: the template string
:param context: the evaluation context
... | [
"def",
"evaluate_template",
"(",
"self",
",",
"template",
",",
"context",
",",
"url_encode",
"=",
"False",
",",
"strategy",
"=",
"EvaluationStrategy",
".",
"COMPLETE",
")",
":",
"input_chars",
"=",
"list",
"(",
"template",
")",
"output_chars",
"=",
"[",
"]",... | Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
:param template: the template string
:param context: the evaluation context
:param url_encode: whether or not values should be URL encoded
:return: a tuple of the evaluated template and a list... | [
"Evaluates",
"a",
"template",
"string",
"e",
".",
"g",
".",
"Hello"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L143-L234 |
rapidpro/expressions | python/temba_expressions/evaluator.py | Evaluator._resolve_expression_block | def _resolve_expression_block(self, expression, context, url_encode, strategy, errors):
"""
Resolves an expression block found in the template, e.g. @(...). If an evaluation error occurs, expression is
returned as is.
"""
try:
body = expression[1:] # strip prefix
... | python | def _resolve_expression_block(self, expression, context, url_encode, strategy, errors):
"""
Resolves an expression block found in the template, e.g. @(...). If an evaluation error occurs, expression is
returned as is.
"""
try:
body = expression[1:] # strip prefix
... | [
"def",
"_resolve_expression_block",
"(",
"self",
",",
"expression",
",",
"context",
",",
"url_encode",
",",
"strategy",
",",
"errors",
")",
":",
"try",
":",
"body",
"=",
"expression",
"[",
"1",
":",
"]",
"# strip prefix",
"# if expression doesn't start with ( then... | Resolves an expression block found in the template, e.g. @(...). If an evaluation error occurs, expression is
returned as is. | [
"Resolves",
"an",
"expression",
"block",
"found",
"in",
"the",
"template",
"e",
".",
"g",
"."
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L236-L261 |
rapidpro/expressions | python/temba_expressions/evaluator.py | Evaluator.evaluate_expression | def evaluate_expression(self, expression, context, strategy=EvaluationStrategy.COMPLETE):
"""
Evaluates a single expression, e.g. "contact.reports * 2"
:param expression: the expression string
:param context: the evaluation context
:param strategy: the evaluation strategy
... | python | def evaluate_expression(self, expression, context, strategy=EvaluationStrategy.COMPLETE):
"""
Evaluates a single expression, e.g. "contact.reports * 2"
:param expression: the expression string
:param context: the evaluation context
:param strategy: the evaluation strategy
... | [
"def",
"evaluate_expression",
"(",
"self",
",",
"expression",
",",
"context",
",",
"strategy",
"=",
"EvaluationStrategy",
".",
"COMPLETE",
")",
":",
"from",
".",
"gen",
".",
"ExcellentLexer",
"import",
"ExcellentLexer",
"from",
".",
"gen",
".",
"ExcellentParser"... | Evaluates a single expression, e.g. "contact.reports * 2"
:param expression: the expression string
:param context: the evaluation context
:param strategy: the evaluation strategy
:return: the evaluated expression value | [
"Evaluates",
"a",
"single",
"expression",
"e",
".",
"g",
".",
"contact",
".",
"reports",
"*",
"2",
":",
"param",
"expression",
":",
"the",
"expression",
"string",
":",
"param",
"context",
":",
"the",
"evaluation",
"context",
":",
"param",
"strategy",
":",
... | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L263-L304 |
rapidpro/expressions | python/temba_expressions/evaluator.py | Evaluator._resolve_available | def _resolve_available(self, tokens, context):
"""
Checks the token stream for context references and if there are missing references - substitutes available
references and returns a partially evaluated expression.
:param tokens: the token stream (all tokens fetched)
:param conte... | python | def _resolve_available(self, tokens, context):
"""
Checks the token stream for context references and if there are missing references - substitutes available
references and returns a partially evaluated expression.
:param tokens: the token stream (all tokens fetched)
:param conte... | [
"def",
"_resolve_available",
"(",
"self",
",",
"tokens",
",",
"context",
")",
":",
"from",
".",
"gen",
".",
"ExcellentParser",
"import",
"ExcellentParser",
"has_missing",
"=",
"False",
"output_components",
"=",
"[",
"]",
"for",
"t",
"in",
"range",
"(",
"len"... | Checks the token stream for context references and if there are missing references - substitutes available
references and returns a partially evaluated expression.
:param tokens: the token stream (all tokens fetched)
:param context: the evaluation context
:return: the partially evaluated... | [
"Checks",
"the",
"token",
"stream",
"for",
"context",
"references",
"and",
"if",
"there",
"are",
"missing",
"references",
"-",
"substitutes",
"available",
"references",
"and",
"returns",
"a",
"partially",
"evaluated",
"expression",
".",
":",
"param",
"tokens",
"... | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L306-L347 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitFunctionCall | def visitFunctionCall(self, ctx):
"""
expression : fnname LPAREN parameters? RPAREN
"""
func_name = ctx.fnname().getText()
if ctx.parameters() is not None:
parameters = self.visit(ctx.parameters())
else:
parameters = []
return self._funct... | python | def visitFunctionCall(self, ctx):
"""
expression : fnname LPAREN parameters? RPAREN
"""
func_name = ctx.fnname().getText()
if ctx.parameters() is not None:
parameters = self.visit(ctx.parameters())
else:
parameters = []
return self._funct... | [
"def",
"visitFunctionCall",
"(",
"self",
",",
"ctx",
")",
":",
"func_name",
"=",
"ctx",
".",
"fnname",
"(",
")",
".",
"getText",
"(",
")",
"if",
"ctx",
".",
"parameters",
"(",
")",
"is",
"not",
"None",
":",
"parameters",
"=",
"self",
".",
"visit",
... | expression : fnname LPAREN parameters? RPAREN | [
"expression",
":",
"fnname",
"LPAREN",
"parameters?",
"RPAREN"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L359-L370 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitNegation | def visitNegation(self, ctx):
"""
expression: MINUS expression
"""
return -conversions.to_decimal(self.visit(ctx.expression()), self._eval_context) | python | def visitNegation(self, ctx):
"""
expression: MINUS expression
"""
return -conversions.to_decimal(self.visit(ctx.expression()), self._eval_context) | [
"def",
"visitNegation",
"(",
"self",
",",
"ctx",
")",
":",
"return",
"-",
"conversions",
".",
"to_decimal",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
")",
")",
",",
"self",
".",
"_eval_context",
")"
] | expression: MINUS expression | [
"expression",
":",
"MINUS",
"expression"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L378-L382 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitExponentExpression | def visitExponentExpression(self, ctx):
"""
expression: expression EXPONENT expression
"""
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context)
return conversions.... | python | def visitExponentExpression(self, ctx):
"""
expression: expression EXPONENT expression
"""
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(ctx.expression(1)), self._eval_context)
return conversions.... | [
"def",
"visitExponentExpression",
"(",
"self",
",",
"ctx",
")",
":",
"arg1",
"=",
"conversions",
".",
"to_decimal",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
"0",
")",
")",
",",
"self",
".",
"_eval_context",
")",
"arg2",
"=",
"conv... | expression: expression EXPONENT expression | [
"expression",
":",
"expression",
"EXPONENT",
"expression"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L384-L390 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitMultiplicationOrDivisionExpression | def visitMultiplicationOrDivisionExpression(self, ctx):
"""
expression: expression (TIMES | DIVIDE) expression
"""
is_mul = ctx.TIMES() is not None
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(c... | python | def visitMultiplicationOrDivisionExpression(self, ctx):
"""
expression: expression (TIMES | DIVIDE) expression
"""
is_mul = ctx.TIMES() is not None
arg1 = conversions.to_decimal(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_decimal(self.visit(c... | [
"def",
"visitMultiplicationOrDivisionExpression",
"(",
"self",
",",
"ctx",
")",
":",
"is_mul",
"=",
"ctx",
".",
"TIMES",
"(",
")",
"is",
"not",
"None",
"arg1",
"=",
"conversions",
".",
"to_decimal",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",... | expression: expression (TIMES | DIVIDE) expression | [
"expression",
":",
"expression",
"(",
"TIMES",
"|",
"DIVIDE",
")",
"expression"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L392-L404 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitAdditionOrSubtractionExpression | def visitAdditionOrSubtractionExpression(self, ctx):
"""
expression: expression (PLUS | MINUS) expression
"""
is_add = ctx.PLUS() is not None
arg1 = self.visit(ctx.expression(0))
arg2 = self.visit(ctx.expression(1))
# first try as decimals
try:
... | python | def visitAdditionOrSubtractionExpression(self, ctx):
"""
expression: expression (PLUS | MINUS) expression
"""
is_add = ctx.PLUS() is not None
arg1 = self.visit(ctx.expression(0))
arg2 = self.visit(ctx.expression(1))
# first try as decimals
try:
... | [
"def",
"visitAdditionOrSubtractionExpression",
"(",
"self",
",",
"ctx",
")",
":",
"is_add",
"=",
"ctx",
".",
"PLUS",
"(",
")",
"is",
"not",
"None",
"arg1",
"=",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
"0",
")",
")",
"arg2",
"=",
"se... | expression: expression (PLUS | MINUS) expression | [
"expression",
":",
"expression",
"(",
"PLUS",
"|",
"MINUS",
")",
"expression"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L406-L438 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitComparisonExpression | def visitComparisonExpression(self, ctx):
"""
expression: expression (LTE | LT | GTE | GT) expression
"""
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
if isinstance(arg1, str):
# string comparison ... | python | def visitComparisonExpression(self, ctx):
"""
expression: expression (LTE | LT | GTE | GT) expression
"""
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
if isinstance(arg1, str):
# string comparison ... | [
"def",
"visitComparisonExpression",
"(",
"self",
",",
"ctx",
")",
":",
"arg1",
",",
"arg2",
"=",
"conversions",
".",
"to_same",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
"0",
")",
")",
",",
"self",
".",
"visit",
"(",
"ctx",
".",
... | expression: expression (LTE | LT | GTE | GT) expression | [
"expression",
":",
"expression",
"(",
"LTE",
"|",
"LT",
"|",
"GTE",
"|",
"GT",
")",
"expression"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L440-L459 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitEqualityExpression | def visitEqualityExpression(self, ctx):
"""
expression: expression (EQ | NEQ) expression
"""
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
if isinstance(arg1, str):
# string equality is case-insensi... | python | def visitEqualityExpression(self, ctx):
"""
expression: expression (EQ | NEQ) expression
"""
arg1, arg2 = conversions.to_same(self.visit(ctx.expression(0)), self.visit(ctx.expression(1)), self._eval_context)
if isinstance(arg1, str):
# string equality is case-insensi... | [
"def",
"visitEqualityExpression",
"(",
"self",
",",
"ctx",
")",
":",
"arg1",
",",
"arg2",
"=",
"conversions",
".",
"to_same",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
"0",
")",
")",
",",
"self",
".",
"visit",
"(",
"ctx",
".",
... | expression: expression (EQ | NEQ) expression | [
"expression",
":",
"expression",
"(",
"EQ",
"|",
"NEQ",
")",
"expression"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L461-L473 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitConcatenation | def visitConcatenation(self, ctx):
"""
expression: expression AMPERSAND expression
"""
arg1 = conversions.to_string(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_string(self.visit(ctx.expression(1)), self._eval_context)
return arg1 + arg2 | python | def visitConcatenation(self, ctx):
"""
expression: expression AMPERSAND expression
"""
arg1 = conversions.to_string(self.visit(ctx.expression(0)), self._eval_context)
arg2 = conversions.to_string(self.visit(ctx.expression(1)), self._eval_context)
return arg1 + arg2 | [
"def",
"visitConcatenation",
"(",
"self",
",",
"ctx",
")",
":",
"arg1",
"=",
"conversions",
".",
"to_string",
"(",
"self",
".",
"visit",
"(",
"ctx",
".",
"expression",
"(",
"0",
")",
")",
",",
"self",
".",
"_eval_context",
")",
"arg2",
"=",
"conversion... | expression: expression AMPERSAND expression | [
"expression",
":",
"expression",
"AMPERSAND",
"expression"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L475-L481 |
rapidpro/expressions | python/temba_expressions/evaluator.py | ExcellentVisitor.visitContextReference | def visitContextReference(self, ctx):
"""
expression: NAME
"""
identifier = ctx.NAME().getText()
return self._eval_context.resolve_variable(identifier) | python | def visitContextReference(self, ctx):
"""
expression: NAME
"""
identifier = ctx.NAME().getText()
return self._eval_context.resolve_variable(identifier) | [
"def",
"visitContextReference",
"(",
"self",
",",
"ctx",
")",
":",
"identifier",
"=",
"ctx",
".",
"NAME",
"(",
")",
".",
"getText",
"(",
")",
"return",
"self",
".",
"_eval_context",
".",
"resolve_variable",
"(",
"identifier",
")"
] | expression: NAME | [
"expression",
":",
"NAME"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L508-L513 |
BlueBrain/nat | nat/zotero_wrap.py | ZoteroWrap.load_cache | def load_cache(self):
"""Load the cached Zotero data."""
with open(self.cache_path, "rb") as f:
print("Loading cached Zotero data...")
cache = pickle.load(f)
self._references = cache[self.CACHE_REFERENCE_LIST]
self.reference_types = cache[self.CACHE_REFERE... | python | def load_cache(self):
"""Load the cached Zotero data."""
with open(self.cache_path, "rb") as f:
print("Loading cached Zotero data...")
cache = pickle.load(f)
self._references = cache[self.CACHE_REFERENCE_LIST]
self.reference_types = cache[self.CACHE_REFERE... | [
"def",
"load_cache",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"cache_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"print",
"(",
"\"Loading cached Zotero data...\"",
")",
"cache",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"self",
".",
"_r... | Load the cached Zotero data. | [
"Load",
"the",
"cached",
"Zotero",
"data",
"."
] | train | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L38-L46 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.