nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/serial/serialjava.py | python | Serial.read | (self, size=1) | return bytes(read) | \
Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read. | \
Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read. | [
"\\",
"Read",
"size",
"bytes",
"from",
"the",
"serial",
"port",
".",
"If",
"a",
"timeout",
"is",
"set",
"it",
"may",
"return",
"less",
"characters",
"as",
"requested",
".",
"With",
"no",
"timeout",
"it",
"will",
"block",
"until",
"the",
"requested",
"number",
"of",
"bytes",
"is",
"read",
"."
] | def read(self, size=1):
"""\
Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read.
"""
if not self.sPort:
raise portNotOpenError
read = bytearray()
if size > 0:
while len(read) < size:
x = self._instream.read()
if x == -1:
if self.timeout >= 0:
break
else:
read.append(x)
return bytes(read) | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"sPort",
":",
"raise",
"portNotOpenError",
"read",
"=",
"bytearray",
"(",
")",
"if",
"size",
">",
"0",
":",
"while",
"len",
"(",
"read",
")",
"<",
"size",
":",
"x",
"=",
"self",
".",
"_instream",
".",
"read",
"(",
")",
"if",
"x",
"==",
"-",
"1",
":",
"if",
"self",
".",
"timeout",
">=",
"0",
":",
"break",
"else",
":",
"read",
".",
"append",
"(",
"x",
")",
"return",
"bytes",
"(",
"read",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialjava.py#L156-L173 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/newclasscalc/calc.py | python | Calc.p_expression_group | (self, p) | expression : LPAREN expression RPAREN | expression : LPAREN expression RPAREN | [
"expression",
":",
"LPAREN",
"expression",
"RPAREN"
] | def p_expression_group(self, p):
'expression : LPAREN expression RPAREN'
p[0] = p[2] | [
"def",
"p_expression_group",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"2",
"]"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/newclasscalc/calc.py#L136-L138 | ||
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/ecl_ekf/process_logdata_ekf.py | python | create_results_table | (
check_table_filename: str, master_status: str, check_status: Dict[str, str],
metrics: Dict[str, float], airtime_info: Dict[str, float]) | return test_results_table | creates the output results table
:param check_table_filename:
:param master_status:
:param check_status:
:param metrics:
:param airtime_info:
:return: | creates the output results table
:param check_table_filename:
:param master_status:
:param check_status:
:param metrics:
:param airtime_info:
:return: | [
"creates",
"the",
"output",
"results",
"table",
":",
"param",
"check_table_filename",
":",
":",
"param",
"master_status",
":",
":",
"param",
"check_status",
":",
":",
"param",
"metrics",
":",
":",
"param",
"airtime_info",
":",
":",
"return",
":"
] | def create_results_table(
check_table_filename: str, master_status: str, check_status: Dict[str, str],
metrics: Dict[str, float], airtime_info: Dict[str, float]) -> Dict[str, list]:
"""
creates the output results table
:param check_table_filename:
:param master_status:
:param check_status:
:param metrics:
:param airtime_info:
:return:
"""
try:
with open(check_table_filename, 'r') as file:
reader = csv.DictReader(file)
test_results_table = {
row['check_id']: [float('NaN'), row['check_description']] for row in reader}
print('Using test description loaded from {:s}'.format(check_table_filename))
except:
raise PreconditionError('could not find {:s}'.format(check_table_filename))
# store metrics
for key, value in metrics.items():
test_results_table[key][0] = value
# store check results
for key, value in check_status.items():
test_results_table[key][0] = value
# store check results
for key, value in test_results_table.items():
if key.endswith('_status'):
test_results_table[key][0] = str(value[0])
# store master status
test_results_table['master_status'][0] = master_status
# store take_off and landing information
test_results_table['in_air_transition_time'][0] = airtime_info['in_air_transition_time']
test_results_table['on_ground_transition_time'][0] = airtime_info['on_ground_transition_time']
return test_results_table | [
"def",
"create_results_table",
"(",
"check_table_filename",
":",
"str",
",",
"master_status",
":",
"str",
",",
"check_status",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"metrics",
":",
"Dict",
"[",
"str",
",",
"float",
"]",
",",
"airtime_info",
":",
"Dict",
"[",
"str",
",",
"float",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"list",
"]",
":",
"try",
":",
"with",
"open",
"(",
"check_table_filename",
",",
"'r'",
")",
"as",
"file",
":",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"file",
")",
"test_results_table",
"=",
"{",
"row",
"[",
"'check_id'",
"]",
":",
"[",
"float",
"(",
"'NaN'",
")",
",",
"row",
"[",
"'check_description'",
"]",
"]",
"for",
"row",
"in",
"reader",
"}",
"print",
"(",
"'Using test description loaded from {:s}'",
".",
"format",
"(",
"check_table_filename",
")",
")",
"except",
":",
"raise",
"PreconditionError",
"(",
"'could not find {:s}'",
".",
"format",
"(",
"check_table_filename",
")",
")",
"# store metrics",
"for",
"key",
",",
"value",
"in",
"metrics",
".",
"items",
"(",
")",
":",
"test_results_table",
"[",
"key",
"]",
"[",
"0",
"]",
"=",
"value",
"# store check results",
"for",
"key",
",",
"value",
"in",
"check_status",
".",
"items",
"(",
")",
":",
"test_results_table",
"[",
"key",
"]",
"[",
"0",
"]",
"=",
"value",
"# store check results",
"for",
"key",
",",
"value",
"in",
"test_results_table",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"endswith",
"(",
"'_status'",
")",
":",
"test_results_table",
"[",
"key",
"]",
"[",
"0",
"]",
"=",
"str",
"(",
"value",
"[",
"0",
"]",
")",
"# store master status",
"test_results_table",
"[",
"'master_status'",
"]",
"[",
"0",
"]",
"=",
"master_status",
"# store take_off and landing information",
"test_results_table",
"[",
"'in_air_transition_time'",
"]",
"[",
"0",
"]",
"=",
"airtime_info",
"[",
"'in_air_transition_time'",
"]",
"test_results_table",
"[",
"'on_ground_transition_time'",
"]",
"[",
"0",
"]",
"=",
"airtime_info",
"[",
"'on_ground_transition_time'",
"]",
"return",
"test_results_table"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/ecl_ekf/process_logdata_ekf.py#L38-L80 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hypertreelist.py | python | HyperTreeList.SetHeaderFont | (self, font) | Sets the default font for the header window..
:param `font`: a valid :class:`Font` object. | Sets the default font for the header window.. | [
"Sets",
"the",
"default",
"font",
"for",
"the",
"header",
"window",
".."
] | def SetHeaderFont(self, font):
"""
Sets the default font for the header window..
:param `font`: a valid :class:`Font` object.
"""
if not self._header_win:
return
for column in xrange(self.GetColumnCount()):
self._header_win.SetColumn(column, self.GetColumn(column).SetFont(font))
self._header_win.Refresh() | [
"def",
"SetHeaderFont",
"(",
"self",
",",
"font",
")",
":",
"if",
"not",
"self",
".",
"_header_win",
":",
"return",
"for",
"column",
"in",
"xrange",
"(",
"self",
".",
"GetColumnCount",
"(",
")",
")",
":",
"self",
".",
"_header_win",
".",
"SetColumn",
"(",
"column",
",",
"self",
".",
"GetColumn",
"(",
"column",
")",
".",
"SetFont",
"(",
"font",
")",
")",
"self",
".",
"_header_win",
".",
"Refresh",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L4248-L4261 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | configs/common/ObjectList.py | python | EnumList._add_objects | (self) | Add all enum values to the ObjectList | Add all enum values to the ObjectList | [
"Add",
"all",
"enum",
"values",
"to",
"the",
"ObjectList"
] | def _add_objects(self):
""" Add all enum values to the ObjectList """
self._sub_classes = {}
for (key, value) in list(self.base_cls.__members__.items()):
# All Enums have a value Num_NAME at the end which we
# do not want to include
if not key.startswith("Num_"):
self._sub_classes[key] = value | [
"def",
"_add_objects",
"(",
"self",
")",
":",
"self",
".",
"_sub_classes",
"=",
"{",
"}",
"for",
"(",
"key",
",",
"value",
")",
"in",
"list",
"(",
"self",
".",
"base_cls",
".",
"__members__",
".",
"items",
"(",
")",
")",
":",
"# All Enums have a value Num_NAME at the end which we",
"# do not want to include",
"if",
"not",
"key",
".",
"startswith",
"(",
"\"Num_\"",
")",
":",
"self",
".",
"_sub_classes",
"[",
"key",
"]",
"=",
"value"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/configs/common/ObjectList.py#L154-L161 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py | python | _signature_fromstr | (cls, obj, s, skip_bound_arg=True) | return cls(parameters, return_annotation=cls.empty) | Private helper to parse content of '__text_signature__'
and return a Signature based on it. | Private helper to parse content of '__text_signature__'
and return a Signature based on it. | [
"Private",
"helper",
"to",
"parse",
"content",
"of",
"__text_signature__",
"and",
"return",
"a",
"Signature",
"based",
"on",
"it",
"."
] | def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
"""Private helper to parse content of '__text_signature__'
and return a Signature based on it.
"""
# Lazy import ast because it's relatively heavy and
# it's not used for other than this function.
import ast
Parameter = cls._parameter_cls
clean_signature, self_parameter, last_positional_only = \
_signature_strip_non_python_syntax(s)
program = "def foo" + clean_signature + ": pass"
try:
module = ast.parse(program)
except SyntaxError:
module = None
if not isinstance(module, ast.Module):
raise ValueError("{!r} builtin has invalid signature".format(obj))
f = module.body[0]
parameters = []
empty = Parameter.empty
invalid = object()
module = None
module_dict = {}
module_name = getattr(obj, '__module__', None)
if module_name:
module = sys.modules.get(module_name, None)
if module:
module_dict = module.__dict__
sys_module_dict = sys.modules.copy()
def parse_name(node):
assert isinstance(node, ast.arg)
if node.annotation != None:
raise ValueError("Annotations are not currently supported")
return node.arg
def wrap_value(s):
try:
value = eval(s, module_dict)
except NameError:
try:
value = eval(s, sys_module_dict)
except NameError:
raise RuntimeError()
if isinstance(value, str):
return ast.Str(value)
if isinstance(value, (int, float)):
return ast.Num(value)
if isinstance(value, bytes):
return ast.Bytes(value)
if value in (True, False, None):
return ast.NameConstant(value)
raise RuntimeError()
class RewriteSymbolics(ast.NodeTransformer):
def visit_Attribute(self, node):
a = []
n = node
while isinstance(n, ast.Attribute):
a.append(n.attr)
n = n.value
if not isinstance(n, ast.Name):
raise RuntimeError()
a.append(n.id)
value = ".".join(reversed(a))
return wrap_value(value)
def visit_Name(self, node):
if not isinstance(node.ctx, ast.Load):
raise ValueError()
return wrap_value(node.id)
def p(name_node, default_node, default=empty):
name = parse_name(name_node)
if name is invalid:
return None
if default_node and default_node is not _empty:
try:
default_node = RewriteSymbolics().visit(default_node)
o = ast.literal_eval(default_node)
except ValueError:
o = invalid
if o is invalid:
return None
default = o if o is not invalid else default
parameters.append(Parameter(name, kind, default=default, annotation=empty))
# non-keyword-only parameters
args = reversed(f.args.args)
defaults = reversed(f.args.defaults)
iter = itertools.zip_longest(args, defaults, fillvalue=None)
if last_positional_only is not None:
kind = Parameter.POSITIONAL_ONLY
else:
kind = Parameter.POSITIONAL_OR_KEYWORD
for i, (name, default) in enumerate(reversed(list(iter))):
p(name, default)
if i == last_positional_only:
kind = Parameter.POSITIONAL_OR_KEYWORD
# *args
if f.args.vararg:
kind = Parameter.VAR_POSITIONAL
p(f.args.vararg, empty)
# keyword-only arguments
kind = Parameter.KEYWORD_ONLY
for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
p(name, default)
# **kwargs
if f.args.kwarg:
kind = Parameter.VAR_KEYWORD
p(f.args.kwarg, empty)
if self_parameter is not None:
# Possibly strip the bound argument:
# - We *always* strip first bound argument if
# it is a module.
# - We don't strip first bound argument if
# skip_bound_arg is False.
assert parameters
_self = getattr(obj, '__self__', None)
self_isbound = _self is not None
self_ismodule = ismodule(_self)
if self_isbound and (self_ismodule or skip_bound_arg):
parameters.pop(0)
else:
# for builtins, self parameter is always positional-only!
p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
parameters[0] = p
return cls(parameters, return_annotation=cls.empty) | [
"def",
"_signature_fromstr",
"(",
"cls",
",",
"obj",
",",
"s",
",",
"skip_bound_arg",
"=",
"True",
")",
":",
"# Lazy import ast because it's relatively heavy and",
"# it's not used for other than this function.",
"import",
"ast",
"Parameter",
"=",
"cls",
".",
"_parameter_cls",
"clean_signature",
",",
"self_parameter",
",",
"last_positional_only",
"=",
"_signature_strip_non_python_syntax",
"(",
"s",
")",
"program",
"=",
"\"def foo\"",
"+",
"clean_signature",
"+",
"\": pass\"",
"try",
":",
"module",
"=",
"ast",
".",
"parse",
"(",
"program",
")",
"except",
"SyntaxError",
":",
"module",
"=",
"None",
"if",
"not",
"isinstance",
"(",
"module",
",",
"ast",
".",
"Module",
")",
":",
"raise",
"ValueError",
"(",
"\"{!r} builtin has invalid signature\"",
".",
"format",
"(",
"obj",
")",
")",
"f",
"=",
"module",
".",
"body",
"[",
"0",
"]",
"parameters",
"=",
"[",
"]",
"empty",
"=",
"Parameter",
".",
"empty",
"invalid",
"=",
"object",
"(",
")",
"module",
"=",
"None",
"module_dict",
"=",
"{",
"}",
"module_name",
"=",
"getattr",
"(",
"obj",
",",
"'__module__'",
",",
"None",
")",
"if",
"module_name",
":",
"module",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"module_name",
",",
"None",
")",
"if",
"module",
":",
"module_dict",
"=",
"module",
".",
"__dict__",
"sys_module_dict",
"=",
"sys",
".",
"modules",
".",
"copy",
"(",
")",
"def",
"parse_name",
"(",
"node",
")",
":",
"assert",
"isinstance",
"(",
"node",
",",
"ast",
".",
"arg",
")",
"if",
"node",
".",
"annotation",
"!=",
"None",
":",
"raise",
"ValueError",
"(",
"\"Annotations are not currently supported\"",
")",
"return",
"node",
".",
"arg",
"def",
"wrap_value",
"(",
"s",
")",
":",
"try",
":",
"value",
"=",
"eval",
"(",
"s",
",",
"module_dict",
")",
"except",
"NameError",
":",
"try",
":",
"value",
"=",
"eval",
"(",
"s",
",",
"sys_module_dict",
")",
"except",
"NameError",
":",
"raise",
"RuntimeError",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"ast",
".",
"Str",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"ast",
".",
"Num",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return",
"ast",
".",
"Bytes",
"(",
"value",
")",
"if",
"value",
"in",
"(",
"True",
",",
"False",
",",
"None",
")",
":",
"return",
"ast",
".",
"NameConstant",
"(",
"value",
")",
"raise",
"RuntimeError",
"(",
")",
"class",
"RewriteSymbolics",
"(",
"ast",
".",
"NodeTransformer",
")",
":",
"def",
"visit_Attribute",
"(",
"self",
",",
"node",
")",
":",
"a",
"=",
"[",
"]",
"n",
"=",
"node",
"while",
"isinstance",
"(",
"n",
",",
"ast",
".",
"Attribute",
")",
":",
"a",
".",
"append",
"(",
"n",
".",
"attr",
")",
"n",
"=",
"n",
".",
"value",
"if",
"not",
"isinstance",
"(",
"n",
",",
"ast",
".",
"Name",
")",
":",
"raise",
"RuntimeError",
"(",
")",
"a",
".",
"append",
"(",
"n",
".",
"id",
")",
"value",
"=",
"\".\"",
".",
"join",
"(",
"reversed",
"(",
"a",
")",
")",
"return",
"wrap_value",
"(",
"value",
")",
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Load",
")",
":",
"raise",
"ValueError",
"(",
")",
"return",
"wrap_value",
"(",
"node",
".",
"id",
")",
"def",
"p",
"(",
"name_node",
",",
"default_node",
",",
"default",
"=",
"empty",
")",
":",
"name",
"=",
"parse_name",
"(",
"name_node",
")",
"if",
"name",
"is",
"invalid",
":",
"return",
"None",
"if",
"default_node",
"and",
"default_node",
"is",
"not",
"_empty",
":",
"try",
":",
"default_node",
"=",
"RewriteSymbolics",
"(",
")",
".",
"visit",
"(",
"default_node",
")",
"o",
"=",
"ast",
".",
"literal_eval",
"(",
"default_node",
")",
"except",
"ValueError",
":",
"o",
"=",
"invalid",
"if",
"o",
"is",
"invalid",
":",
"return",
"None",
"default",
"=",
"o",
"if",
"o",
"is",
"not",
"invalid",
"else",
"default",
"parameters",
".",
"append",
"(",
"Parameter",
"(",
"name",
",",
"kind",
",",
"default",
"=",
"default",
",",
"annotation",
"=",
"empty",
")",
")",
"# non-keyword-only parameters",
"args",
"=",
"reversed",
"(",
"f",
".",
"args",
".",
"args",
")",
"defaults",
"=",
"reversed",
"(",
"f",
".",
"args",
".",
"defaults",
")",
"iter",
"=",
"itertools",
".",
"zip_longest",
"(",
"args",
",",
"defaults",
",",
"fillvalue",
"=",
"None",
")",
"if",
"last_positional_only",
"is",
"not",
"None",
":",
"kind",
"=",
"Parameter",
".",
"POSITIONAL_ONLY",
"else",
":",
"kind",
"=",
"Parameter",
".",
"POSITIONAL_OR_KEYWORD",
"for",
"i",
",",
"(",
"name",
",",
"default",
")",
"in",
"enumerate",
"(",
"reversed",
"(",
"list",
"(",
"iter",
")",
")",
")",
":",
"p",
"(",
"name",
",",
"default",
")",
"if",
"i",
"==",
"last_positional_only",
":",
"kind",
"=",
"Parameter",
".",
"POSITIONAL_OR_KEYWORD",
"# *args",
"if",
"f",
".",
"args",
".",
"vararg",
":",
"kind",
"=",
"Parameter",
".",
"VAR_POSITIONAL",
"p",
"(",
"f",
".",
"args",
".",
"vararg",
",",
"empty",
")",
"# keyword-only arguments",
"kind",
"=",
"Parameter",
".",
"KEYWORD_ONLY",
"for",
"name",
",",
"default",
"in",
"zip",
"(",
"f",
".",
"args",
".",
"kwonlyargs",
",",
"f",
".",
"args",
".",
"kw_defaults",
")",
":",
"p",
"(",
"name",
",",
"default",
")",
"# **kwargs",
"if",
"f",
".",
"args",
".",
"kwarg",
":",
"kind",
"=",
"Parameter",
".",
"VAR_KEYWORD",
"p",
"(",
"f",
".",
"args",
".",
"kwarg",
",",
"empty",
")",
"if",
"self_parameter",
"is",
"not",
"None",
":",
"# Possibly strip the bound argument:",
"# - We *always* strip first bound argument if",
"# it is a module.",
"# - We don't strip first bound argument if",
"# skip_bound_arg is False.",
"assert",
"parameters",
"_self",
"=",
"getattr",
"(",
"obj",
",",
"'__self__'",
",",
"None",
")",
"self_isbound",
"=",
"_self",
"is",
"not",
"None",
"self_ismodule",
"=",
"ismodule",
"(",
"_self",
")",
"if",
"self_isbound",
"and",
"(",
"self_ismodule",
"or",
"skip_bound_arg",
")",
":",
"parameters",
".",
"pop",
"(",
"0",
")",
"else",
":",
"# for builtins, self parameter is always positional-only!",
"p",
"=",
"parameters",
"[",
"0",
"]",
".",
"replace",
"(",
"kind",
"=",
"Parameter",
".",
"POSITIONAL_ONLY",
")",
"parameters",
"[",
"0",
"]",
"=",
"p",
"return",
"cls",
"(",
"parameters",
",",
"return_annotation",
"=",
"cls",
".",
"empty",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L1957-L2098 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/handlers.py | python | MemoryHandler.close | (self) | Flush, set the target to None and lose the buffer. | Flush, set the target to None and lose the buffer. | [
"Flush",
"set",
"the",
"target",
"to",
"None",
"and",
"lose",
"the",
"buffer",
"."
] | def close(self):
"""
Flush, set the target to None and lose the buffer.
"""
self.flush()
self.acquire()
try:
self.target = None
BufferingHandler.close(self)
finally:
self.release() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"target",
"=",
"None",
"BufferingHandler",
".",
"close",
"(",
"self",
")",
"finally",
":",
"self",
".",
"release",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/handlers.py#L1211-L1221 | ||
microsoft/LightGBM | 904b2d5158703c4900b68008617951dd2f9ff21b | python-package/lightgbm/dask.py | python | _assign_open_ports_to_workers | (
client: Client,
host_to_workers: Dict[str, _HostWorkers]
) | return worker_to_port | Assign an open port to each worker.
Returns
-------
worker_to_port: dict
mapping from worker address to an open port. | Assign an open port to each worker. | [
"Assign",
"an",
"open",
"port",
"to",
"each",
"worker",
"."
] | def _assign_open_ports_to_workers(
client: Client,
host_to_workers: Dict[str, _HostWorkers]
) -> Dict[str, int]:
"""Assign an open port to each worker.
Returns
-------
worker_to_port: dict
mapping from worker address to an open port.
"""
host_ports_futures = {}
for hostname, workers in host_to_workers.items():
n_workers_in_host = len(workers.all)
host_ports_futures[hostname] = client.submit(
_find_n_open_ports,
n=n_workers_in_host,
workers=[workers.default],
pure=False,
allow_other_workers=False,
)
found_ports = client.gather(host_ports_futures)
worker_to_port = {}
for hostname, workers in host_to_workers.items():
for worker, port in zip(workers.all, found_ports[hostname]):
worker_to_port[worker] = port
return worker_to_port | [
"def",
"_assign_open_ports_to_workers",
"(",
"client",
":",
"Client",
",",
"host_to_workers",
":",
"Dict",
"[",
"str",
",",
"_HostWorkers",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"int",
"]",
":",
"host_ports_futures",
"=",
"{",
"}",
"for",
"hostname",
",",
"workers",
"in",
"host_to_workers",
".",
"items",
"(",
")",
":",
"n_workers_in_host",
"=",
"len",
"(",
"workers",
".",
"all",
")",
"host_ports_futures",
"[",
"hostname",
"]",
"=",
"client",
".",
"submit",
"(",
"_find_n_open_ports",
",",
"n",
"=",
"n_workers_in_host",
",",
"workers",
"=",
"[",
"workers",
".",
"default",
"]",
",",
"pure",
"=",
"False",
",",
"allow_other_workers",
"=",
"False",
",",
")",
"found_ports",
"=",
"client",
".",
"gather",
"(",
"host_ports_futures",
")",
"worker_to_port",
"=",
"{",
"}",
"for",
"hostname",
",",
"workers",
"in",
"host_to_workers",
".",
"items",
"(",
")",
":",
"for",
"worker",
",",
"port",
"in",
"zip",
"(",
"workers",
".",
"all",
",",
"found_ports",
"[",
"hostname",
"]",
")",
":",
"worker_to_port",
"[",
"worker",
"]",
"=",
"port",
"return",
"worker_to_port"
] | https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/dask.py#L108-L134 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Wrapping/Generators/Python/itk/support/extras.py | python | GetVnlMatrixFromArray | (arr: ArrayLike, ttype=None) | return _GetVnlObjectFromArray(arr, "GetVnlMatrixFromArray", ttype) | Get a vnl matrix from a Python array. | Get a vnl matrix from a Python array. | [
"Get",
"a",
"vnl",
"matrix",
"from",
"a",
"Python",
"array",
"."
] | def GetVnlMatrixFromArray(arr: ArrayLike, ttype=None):
"""Get a vnl matrix from a Python array."""
return _GetVnlObjectFromArray(arr, "GetVnlMatrixFromArray", ttype) | [
"def",
"GetVnlMatrixFromArray",
"(",
"arr",
":",
"ArrayLike",
",",
"ttype",
"=",
"None",
")",
":",
"return",
"_GetVnlObjectFromArray",
"(",
"arr",
",",
"\"GetVnlMatrixFromArray\"",
",",
"ttype",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Wrapping/Generators/Python/itk/support/extras.py#L580-L582 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/entity_object/conversion/aoc/genie_tech.py | python | BuildingLineUpgrade.get_line_id | (self) | return self.building_line_id | Returns the line id of the upgraded line. | Returns the line id of the upgraded line. | [
"Returns",
"the",
"line",
"id",
"of",
"the",
"upgraded",
"line",
"."
] | def get_line_id(self):
"""
Returns the line id of the upgraded line.
"""
return self.building_line_id | [
"def",
"get_line_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"building_line_id"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/conversion/aoc/genie_tech.py#L274-L278 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/fitfunctions.py | python | CompositeFunctionWrapper.__len__ | (self) | return composite.__len__() | Return number of items in composite function.
Implement len() function.
**It should not be called directly.** | Return number of items in composite function.
Implement len() function. | [
"Return",
"number",
"of",
"items",
"in",
"composite",
"function",
".",
"Implement",
"len",
"()",
"function",
"."
] | def __len__(self):
"""
Return number of items in composite function.
Implement len() function.
**It should not be called directly.**
"""
composite = self.fun
return composite.__len__() | [
"def",
"__len__",
"(",
"self",
")",
":",
"composite",
"=",
"self",
".",
"fun",
"return",
"composite",
".",
"__len__",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/fitfunctions.py#L557-L566 | |
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py | python | _FunctionState.End | (self) | Stop analyzing function body. | Stop analyzing function body. | [
"Stop",
"analyzing",
"function",
"body",
"."
] | def End(self):
"""Stop analyzing function body."""
self.in_a_function = False | [
"def",
"End",
"(",
"self",
")",
":",
"self",
".",
"in_a_function",
"=",
"False"
] | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L861-L863 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridTableBase.SetColAttr | (*args, **kwargs) | return _grid.GridTableBase_SetColAttr(*args, **kwargs) | SetColAttr(self, GridCellAttr attr, int col) | SetColAttr(self, GridCellAttr attr, int col) | [
"SetColAttr",
"(",
"self",
"GridCellAttr",
"attr",
"int",
"col",
")"
] | def SetColAttr(*args, **kwargs):
"""SetColAttr(self, GridCellAttr attr, int col)"""
return _grid.GridTableBase_SetColAttr(*args, **kwargs) | [
"def",
"SetColAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_SetColAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L918-L920 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/reroute.py | python | swap_outputs | (sgv0, sgv1) | return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.swap) | Swap all the outputs of sgv0 and sgv1 (see reroute_outputs). | Swap all the outputs of sgv0 and sgv1 (see reroute_outputs). | [
"Swap",
"all",
"the",
"outputs",
"of",
"sgv0",
"and",
"sgv1",
"(",
"see",
"reroute_outputs",
")",
"."
] | def swap_outputs(sgv0, sgv1):
"""Swap all the outputs of sgv0 and sgv1 (see reroute_outputs)."""
return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.swap) | [
"def",
"swap_outputs",
"(",
"sgv0",
",",
"sgv1",
")",
":",
"return",
"_reroute_sgv_outputs",
"(",
"sgv0",
",",
"sgv1",
",",
"_RerouteMode",
".",
"swap",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/reroute.py#L419-L421 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiToolBar.DeleteByIndex | (*args, **kwargs) | return _aui.AuiToolBar_DeleteByIndex(*args, **kwargs) | DeleteByIndex(self, int toolId) -> bool | DeleteByIndex(self, int toolId) -> bool | [
"DeleteByIndex",
"(",
"self",
"int",
"toolId",
")",
"-",
">",
"bool"
] | def DeleteByIndex(*args, **kwargs):
"""DeleteByIndex(self, int toolId) -> bool"""
return _aui.AuiToolBar_DeleteByIndex(*args, **kwargs) | [
"def",
"DeleteByIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBar_DeleteByIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L2082-L2084 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/mod_impl.py | python | _mod_scalar | (x, y) | return F.scalar_mod(x, y) | Returns x % y where x and y are all scalars. | Returns x % y where x and y are all scalars. | [
"Returns",
"x",
"%",
"y",
"where",
"x",
"and",
"y",
"are",
"all",
"scalars",
"."
] | def _mod_scalar(x, y):
"""Returns x % y where x and y are all scalars."""
return F.scalar_mod(x, y) | [
"def",
"_mod_scalar",
"(",
"x",
",",
"y",
")",
":",
"return",
"F",
".",
"scalar_mod",
"(",
"x",
",",
"y",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/mod_impl.py#L31-L33 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/utils/multiclass.py | python | check_classification_targets | (y) | Ensure that target y is of a non-regression type.
Only the following target types (as defined in type_of_target) are allowed:
'binary', 'multiclass', 'multiclass-multioutput',
'multilabel-indicator', 'multilabel-sequences'
Parameters
----------
y : array-like | Ensure that target y is of a non-regression type. | [
"Ensure",
"that",
"target",
"y",
"is",
"of",
"a",
"non",
"-",
"regression",
"type",
"."
] | def check_classification_targets(y):
"""Ensure that target y is of a non-regression type.
Only the following target types (as defined in type_of_target) are allowed:
'binary', 'multiclass', 'multiclass-multioutput',
'multilabel-indicator', 'multilabel-sequences'
Parameters
----------
y : array-like
"""
y_type = type_of_target(y)
if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
'multilabel-indicator', 'multilabel-sequences']:
raise ValueError("Unknown label type: %r" % y_type) | [
"def",
"check_classification_targets",
"(",
"y",
")",
":",
"y_type",
"=",
"type_of_target",
"(",
"y",
")",
"if",
"y_type",
"not",
"in",
"[",
"'binary'",
",",
"'multiclass'",
",",
"'multiclass-multioutput'",
",",
"'multilabel-indicator'",
",",
"'multilabel-sequences'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unknown label type: %r\"",
"%",
"y_type",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/multiclass.py#L155-L169 | ||
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | PascalMultilabelDataLayerSync.reshape | (self, bottom, top) | There is no need to reshape the data, since the input is of fixed size
(rows and columns) | There is no need to reshape the data, since the input is of fixed size
(rows and columns) | [
"There",
"is",
"no",
"need",
"to",
"reshape",
"the",
"data",
"since",
"the",
"input",
"is",
"of",
"fixed",
"size",
"(",
"rows",
"and",
"columns",
")"
] | def reshape(self, bottom, top):
"""
There is no need to reshape the data, since the input is of fixed size
(rows and columns)
"""
pass | [
"def",
"reshape",
"(",
"self",
",",
"bottom",
",",
"top",
")",
":",
"pass"
] | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L67-L72 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.setProperty | (self, prop, value) | return self.dispatcher._checkResult(
Indigo._lib.indigoSetProperty(
self.id,
prop.encode(ENCODE_ENCODING),
value.encode(ENCODE_ENCODING),
)
) | Object method sets property
Args:
prop (str): property name
value (str): property value
Returns:
int: 1 if there are no errors | Object method sets property | [
"Object",
"method",
"sets",
"property"
] | def setProperty(self, prop, value):
"""Object method sets property
Args:
prop (str): property name
value (str): property value
Returns:
int: 1 if there are no errors
"""
self.dispatcher._setSessionId()
return self.dispatcher._checkResult(
Indigo._lib.indigoSetProperty(
self.id,
prop.encode(ENCODE_ENCODING),
value.encode(ENCODE_ENCODING),
)
) | [
"def",
"setProperty",
"(",
"self",
",",
"prop",
",",
"value",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"dispatcher",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoSetProperty",
"(",
"self",
".",
"id",
",",
"prop",
".",
"encode",
"(",
"ENCODE_ENCODING",
")",
",",
"value",
".",
"encode",
"(",
"ENCODE_ENCODING",
")",
",",
")",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L3511-L3528 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/idtracking.py | python | FrameSymbolVisitor.visit_AssignBlock | (self, node, **kwargs) | Stop visiting at block assigns. | Stop visiting at block assigns. | [
"Stop",
"visiting",
"at",
"block",
"assigns",
"."
] | def visit_AssignBlock(self, node, **kwargs):
"""Stop visiting at block assigns."""
self.visit(node.target, **kwargs) | [
"def",
"visit_AssignBlock",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"target",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/idtracking.py#L275-L277 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBFileSpec.SetFilename | (self, filename) | return _lldb.SBFileSpec_SetFilename(self, filename) | SetFilename(SBFileSpec self, char const * filename) | SetFilename(SBFileSpec self, char const * filename) | [
"SetFilename",
"(",
"SBFileSpec",
"self",
"char",
"const",
"*",
"filename",
")"
] | def SetFilename(self, filename):
"""SetFilename(SBFileSpec self, char const * filename)"""
return _lldb.SBFileSpec_SetFilename(self, filename) | [
"def",
"SetFilename",
"(",
"self",
",",
"filename",
")",
":",
"return",
"_lldb",
".",
"SBFileSpec_SetFilename",
"(",
"self",
",",
"filename",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L5267-L5269 | |
cinder/Cinder | e83f5bb9c01a63eec20168d02953a0879e5100f7 | docs/libs/markdown/blockprocessors.py | python | build_block_parser | (md_instance, **kwargs) | return parser | Build the default block parser used by Markdown. | Build the default block parser used by Markdown. | [
"Build",
"the",
"default",
"block",
"parser",
"used",
"by",
"Markdown",
"."
] | def build_block_parser(md_instance, **kwargs):
""" Build the default block parser used by Markdown. """
parser = BlockParser(md_instance)
parser.blockprocessors['empty'] = EmptyBlockProcessor(parser)
parser.blockprocessors['indent'] = ListIndentProcessor(parser)
parser.blockprocessors['code'] = CodeBlockProcessor(parser)
parser.blockprocessors['hashheader'] = HashHeaderProcessor(parser)
parser.blockprocessors['setextheader'] = SetextHeaderProcessor(parser)
parser.blockprocessors['hr'] = HRProcessor(parser)
parser.blockprocessors['olist'] = OListProcessor(parser)
parser.blockprocessors['ulist'] = UListProcessor(parser)
parser.blockprocessors['quote'] = BlockQuoteProcessor(parser)
parser.blockprocessors['paragraph'] = ParagraphProcessor(parser)
return parser | [
"def",
"build_block_parser",
"(",
"md_instance",
",",
"*",
"*",
"kwargs",
")",
":",
"parser",
"=",
"BlockParser",
"(",
"md_instance",
")",
"parser",
".",
"blockprocessors",
"[",
"'empty'",
"]",
"=",
"EmptyBlockProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'indent'",
"]",
"=",
"ListIndentProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'code'",
"]",
"=",
"CodeBlockProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'hashheader'",
"]",
"=",
"HashHeaderProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'setextheader'",
"]",
"=",
"SetextHeaderProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'hr'",
"]",
"=",
"HRProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'olist'",
"]",
"=",
"OListProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'ulist'",
"]",
"=",
"UListProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'quote'",
"]",
"=",
"BlockQuoteProcessor",
"(",
"parser",
")",
"parser",
".",
"blockprocessors",
"[",
"'paragraph'",
"]",
"=",
"ParagraphProcessor",
"(",
"parser",
")",
"return",
"parser"
] | https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/markdown/blockprocessors.py#L25-L38 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/configparser/backports/configparser/helpers.py | python | _ChainMap.new_child | (self) | return self.__class__({}, *self.maps) | New ChainMap with a new dict followed by all previous maps. | New ChainMap with a new dict followed by all previous maps. | [
"New",
"ChainMap",
"with",
"a",
"new",
"dict",
"followed",
"by",
"all",
"previous",
"maps",
"."
] | def new_child(self): # like Django's Context.push()
'New ChainMap with a new dict followed by all previous maps.'
return self.__class__({}, *self.maps) | [
"def",
"new_child",
"(",
"self",
")",
":",
"# like Django's Context.push()",
"return",
"self",
".",
"__class__",
"(",
"{",
"}",
",",
"*",
"self",
".",
"maps",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/configparser/backports/configparser/helpers.py#L156-L158 | |
google-coral/edgetpu | 5020de9386ff370dcc1f63291a2d0f98eeb98adb | examples/imprinting_learning.py | python | _parse_args | () | return args | Parses args, set default values if it's not passed.
Returns:
Object with attributes. Each attribute represents an argument. | Parses args, set default values if it's not passed. | [
"Parses",
"args",
"set",
"default",
"values",
"if",
"it",
"s",
"not",
"passed",
"."
] | def _parse_args():
"""Parses args, set default values if it's not passed.
Returns:
Object with attributes. Each attribute represents an argument.
"""
print('---------------------- Args ----------------------')
parser = argparse.ArgumentParser()
parser.add_argument(
'--model_path', help='Path to the model path.', required=True)
parser.add_argument(
'--data', help=('Path to the training set, images are stored'
'under sub-directory named by category.'), required=True)
parser.add_argument(
'--output', help='Name of the trained model.')
parser.add_argument(
'--test_ratio', type=float,
help='Float number in (0,1), ratio of data used for test data.')
parser.add_argument(
'--keep_classes', action='store_true',
help='Whether to keep base model classes.')
args = parser.parse_args()
if not args.output:
model_name = os.path.basename(args.model_path)
args.output = model_name.replace('.tflite', '_retrained.tflite')
print('Output path :', args.output)
# By default, choose 25% data for test.
if not args.test_ratio:
args.test_ratio = 0.25
assert args.test_ratio > 0
assert args.test_ratio < 1.0
print('Ratio of test images: {:.0%}'.format(args.test_ratio))
return args | [
"def",
"_parse_args",
"(",
")",
":",
"print",
"(",
"'---------------------- Args ----------------------'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--model_path'",
",",
"help",
"=",
"'Path to the model path.'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--data'",
",",
"help",
"=",
"(",
"'Path to the training set, images are stored'",
"'under sub-directory named by category.'",
")",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--output'",
",",
"help",
"=",
"'Name of the trained model.'",
")",
"parser",
".",
"add_argument",
"(",
"'--test_ratio'",
",",
"type",
"=",
"float",
",",
"help",
"=",
"'Float number in (0,1), ratio of data used for test data.'",
")",
"parser",
".",
"add_argument",
"(",
"'--keep_classes'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Whether to keep base model classes.'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"not",
"args",
".",
"output",
":",
"model_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"args",
".",
"model_path",
")",
"args",
".",
"output",
"=",
"model_name",
".",
"replace",
"(",
"'.tflite'",
",",
"'_retrained.tflite'",
")",
"print",
"(",
"'Output path :'",
",",
"args",
".",
"output",
")",
"# By default, choose 25% data for test.",
"if",
"not",
"args",
".",
"test_ratio",
":",
"args",
".",
"test_ratio",
"=",
"0.25",
"assert",
"args",
".",
"test_ratio",
">",
"0",
"assert",
"args",
".",
"test_ratio",
"<",
"1.0",
"print",
"(",
"'Ratio of test images: {:.0%}'",
".",
"format",
"(",
"args",
".",
"test_ratio",
")",
")",
"return",
"args"
] | https://github.com/google-coral/edgetpu/blob/5020de9386ff370dcc1f63291a2d0f98eeb98adb/examples/imprinting_learning.py#L143-L175 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/urllib/request.py | python | noheaders | () | return _noheaders | Return an empty email Message object. | Return an empty email Message object. | [
"Return",
"an",
"empty",
"email",
"Message",
"object",
"."
] | def noheaders():
"""Return an empty email Message object."""
global _noheaders
if _noheaders is None:
_noheaders = email.message_from_string("")
return _noheaders | [
"def",
"noheaders",
"(",
")",
":",
"global",
"_noheaders",
"if",
"_noheaders",
"is",
"None",
":",
"_noheaders",
"=",
"email",
".",
"message_from_string",
"(",
"\"\"",
")",
"return",
"_noheaders"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/urllib/request.py#L2384-L2389 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/pydoc.py | python | _split_list | (s, predicate) | return yes, no | Split sequence s via predicate, and return pair ([true], [false]).
The return value is a 2-tuple of lists,
([x for x in s if predicate(x)],
[x for x in s if not predicate(x)]) | Split sequence s via predicate, and return pair ([true], [false]). | [
"Split",
"sequence",
"s",
"via",
"predicate",
"and",
"return",
"pair",
"(",
"[",
"true",
"]",
"[",
"false",
"]",
")",
"."
] | def _split_list(s, predicate):
"""Split sequence s via predicate, and return pair ([true], [false]).
The return value is a 2-tuple of lists,
([x for x in s if predicate(x)],
[x for x in s if not predicate(x)])
"""
yes = []
no = []
for x in s:
if predicate(x):
yes.append(x)
else:
no.append(x)
return yes, no | [
"def",
"_split_list",
"(",
"s",
",",
"predicate",
")",
":",
"yes",
"=",
"[",
"]",
"no",
"=",
"[",
"]",
"for",
"x",
"in",
"s",
":",
"if",
"predicate",
"(",
"x",
")",
":",
"yes",
".",
"append",
"(",
"x",
")",
"else",
":",
"no",
".",
"append",
"(",
"x",
")",
"return",
"yes",
",",
"no"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L144-L159 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | autooptions/__init__.py | python | AutoOption._check | (self, conf, required) | return all_found | This private method checks all dependencies. It checks all
dependencies (even if some dependency was not found) so that the
user can install all missing dependencies in one go, instead of
playing the infamous hit-configure-hit-configure game.
This function returns True if all dependencies were found and
False otherwise. | This private method checks all dependencies. It checks all
dependencies (even if some dependency was not found) so that the
user can install all missing dependencies in one go, instead of
playing the infamous hit-configure-hit-configure game. | [
"This",
"private",
"method",
"checks",
"all",
"dependencies",
".",
"It",
"checks",
"all",
"dependencies",
"(",
"even",
"if",
"some",
"dependency",
"was",
"not",
"found",
")",
"so",
"that",
"the",
"user",
"can",
"install",
"all",
"missing",
"dependencies",
"in",
"one",
"go",
"instead",
"of",
"playing",
"the",
"infamous",
"hit",
"-",
"configure",
"-",
"hit",
"-",
"configure",
"game",
"."
] | def _check(self, conf, required):
"""
This private method checks all dependencies. It checks all
dependencies (even if some dependency was not found) so that the
user can install all missing dependencies in one go, instead of
playing the infamous hit-configure-hit-configure game.
This function returns True if all dependencies were found and
False otherwise.
"""
all_found = True
for (f,k,kw) in self.deps:
if hasattr(f, '__call__'):
# This is a function supplied by add_function.
func = f
k = list(k)
k.insert(0, conf)
k = tuple(k)
else:
func = getattr(conf, f)
try:
func(*k, **kw)
except conf.errors.ConfigurationError:
all_found = False
if required:
Logs.error('The above check failed, but the '
'checkee is required for %s.' %
self.yes_option)
return all_found | [
"def",
"_check",
"(",
"self",
",",
"conf",
",",
"required",
")",
":",
"all_found",
"=",
"True",
"for",
"(",
"f",
",",
"k",
",",
"kw",
")",
"in",
"self",
".",
"deps",
":",
"if",
"hasattr",
"(",
"f",
",",
"'__call__'",
")",
":",
"# This is a function supplied by add_function.",
"func",
"=",
"f",
"k",
"=",
"list",
"(",
"k",
")",
"k",
".",
"insert",
"(",
"0",
",",
"conf",
")",
"k",
"=",
"tuple",
"(",
"k",
")",
"else",
":",
"func",
"=",
"getattr",
"(",
"conf",
",",
"f",
")",
"try",
":",
"func",
"(",
"*",
"k",
",",
"*",
"*",
"kw",
")",
"except",
"conf",
".",
"errors",
".",
"ConfigurationError",
":",
"all_found",
"=",
"False",
"if",
"required",
":",
"Logs",
".",
"error",
"(",
"'The above check failed, but the '",
"'checkee is required for %s.'",
"%",
"self",
".",
"yes_option",
")",
"return",
"all_found"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/autooptions/__init__.py#L207-L238 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/sysconfig.py | python | get_scheme_names | () | return tuple(schemes) | Returns a tuple containing the schemes names. | Returns a tuple containing the schemes names. | [
"Returns",
"a",
"tuple",
"containing",
"the",
"schemes",
"names",
"."
] | def get_scheme_names():
"""Returns a tuple containing the schemes names."""
schemes = _INSTALL_SCHEMES.keys()
schemes.sort()
return tuple(schemes) | [
"def",
"get_scheme_names",
"(",
")",
":",
"schemes",
"=",
"_INSTALL_SCHEMES",
".",
"keys",
"(",
")",
"schemes",
".",
"sort",
"(",
")",
"return",
"tuple",
"(",
"schemes",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sysconfig.py#L417-L421 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/signaltools.py | python | cmplx_sort | (p) | return take(p, indx, 0), indx | Sort roots based on magnitude.
Parameters
----------
p : array_like
The roots to sort, as a 1-D array.
Returns
-------
p_sorted : ndarray
Sorted roots.
indx : ndarray
Array of indices needed to sort the input `p`. | Sort roots based on magnitude. | [
"Sort",
"roots",
"based",
"on",
"magnitude",
"."
] | def cmplx_sort(p):
"""Sort roots based on magnitude.
Parameters
----------
p : array_like
The roots to sort, as a 1-D array.
Returns
-------
p_sorted : ndarray
Sorted roots.
indx : ndarray
Array of indices needed to sort the input `p`.
"""
p = asarray(p)
if iscomplexobj(p):
indx = argsort(abs(p))
else:
indx = argsort(p)
return take(p, indx, 0), indx | [
"def",
"cmplx_sort",
"(",
"p",
")",
":",
"p",
"=",
"asarray",
"(",
"p",
")",
"if",
"iscomplexobj",
"(",
"p",
")",
":",
"indx",
"=",
"argsort",
"(",
"abs",
"(",
"p",
")",
")",
"else",
":",
"indx",
"=",
"argsort",
"(",
"p",
")",
"return",
"take",
"(",
"p",
",",
"indx",
",",
"0",
")",
",",
"indx"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/signaltools.py#L1666-L1687 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/profiler/internal/flops_registry.py | python | _zero_flops | (graph, node) | return ops.OpStats("flops", 0) | Returns zero flops. | Returns zero flops. | [
"Returns",
"zero",
"flops",
"."
] | def _zero_flops(graph, node):
"""Returns zero flops."""
del graph, node # graph and node are unused
return ops.OpStats("flops", 0) | [
"def",
"_zero_flops",
"(",
"graph",
",",
"node",
")",
":",
"del",
"graph",
",",
"node",
"# graph and node are unused",
"return",
"ops",
".",
"OpStats",
"(",
"\"flops\"",
",",
"0",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/profiler/internal/flops_registry.py#L46-L49 | |
p4lang/p4c | 3272e79369f20813cc1a555a5eb26f44432f84a4 | tools/stf/stf_parser.py | python | STFParser.p_action | (self, p) | action : qualified_name LPAREN args RPAREN | action : qualified_name LPAREN args RPAREN | [
"action",
":",
"qualified_name",
"LPAREN",
"args",
"RPAREN"
] | def p_action(self, p):
'action : qualified_name LPAREN args RPAREN'
p[0] = (p[1], p[3]) | [
"def",
"p_action",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
")"
] | https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/stf/stf_parser.py#L247-L249 | ||
Genius-x/genius-x | 9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0 | cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | CursorKind.is_unexposed | (self) | return conf.lib.clang_isUnexposed(self) | Test if this is an unexposed kind. | Test if this is an unexposed kind. | [
"Test",
"if",
"this",
"is",
"an",
"unexposed",
"kind",
"."
] | def is_unexposed(self):
"""Test if this is an unexposed kind."""
return conf.lib.clang_isUnexposed(self) | [
"def",
"is_unexposed",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isUnexposed",
"(",
"self",
")"
] | https://github.com/Genius-x/genius-x/blob/9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0/cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L551-L553 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/holiday.py | python | next_monday | (dt) | return dt | If holiday falls on Saturday, use following Monday instead;
if holiday falls on Sunday, use Monday instead | If holiday falls on Saturday, use following Monday instead;
if holiday falls on Sunday, use Monday instead | [
"If",
"holiday",
"falls",
"on",
"Saturday",
"use",
"following",
"Monday",
"instead",
";",
"if",
"holiday",
"falls",
"on",
"Sunday",
"use",
"Monday",
"instead"
] | def next_monday(dt):
"""
If holiday falls on Saturday, use following Monday instead;
if holiday falls on Sunday, use Monday instead
"""
if dt.weekday() == 5:
return dt + timedelta(2)
elif dt.weekday() == 6:
return dt + timedelta(1)
return dt | [
"def",
"next_monday",
"(",
"dt",
")",
":",
"if",
"dt",
".",
"weekday",
"(",
")",
"==",
"5",
":",
"return",
"dt",
"+",
"timedelta",
"(",
"2",
")",
"elif",
"dt",
".",
"weekday",
"(",
")",
"==",
"6",
":",
"return",
"dt",
"+",
"timedelta",
"(",
"1",
")",
"return",
"dt"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/holiday.py#L15-L24 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/application.py | python | BaseIPythonApplication.stage_default_config_file | (self) | auto generate default config file, and stage it into the profile. | auto generate default config file, and stage it into the profile. | [
"auto",
"generate",
"default",
"config",
"file",
"and",
"stage",
"it",
"into",
"the",
"profile",
"."
] | def stage_default_config_file(self):
"""auto generate default config file, and stage it into the profile."""
s = self.generate_config_file()
fname = os.path.join(self.profile_dir.location, self.config_file_name)
if self.overwrite or not os.path.exists(fname):
self.log.warning("Generating default config file: %r"%(fname))
with open(fname, 'w') as f:
f.write(s) | [
"def",
"stage_default_config_file",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"generate_config_file",
"(",
")",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"profile_dir",
".",
"location",
",",
"self",
".",
"config_file_name",
")",
"if",
"self",
".",
"overwrite",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"Generating default config file: %r\"",
"%",
"(",
"fname",
")",
")",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"s",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/application.py#L438-L445 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/resampler/python/ops/resampler_ops.py | python | resampler | (data, warp, name="resampler") | Resamples input data at user defined coordinates.
The resampler currently only supports bilinear interpolation of 2D data.
Args:
data: Tensor of shape `[batch_size, data_height, data_width,
data_num_channels]` containing 2D data that will be resampled.
warp: Tensor of minimum rank 2 containing the coordinates at which
resampling will be performed. Since only bilinear interpolation is
currently supported, the last dimension of the `warp` tensor must be 2.
name: Optional name of the op.
Returns:
Tensor of resampled values from `data`. The output tensor shape is
determined by the shape of the warp tensor. For example, if `data` is of
shape `[batch_size, data_height, data_width, data_num_channels]` and warp of
shape `[batch_size, dim_0, ... , dim_n, 2]` the output will be of shape
`[batch_size, dim_0, ... , dim_n, data_num_channels]`.
Raises:
ImportError: if the wrapper generated during compilation is not present when
the function is called. | Resamples input data at user defined coordinates. | [
"Resamples",
"input",
"data",
"at",
"user",
"defined",
"coordinates",
"."
] | def resampler(data, warp, name="resampler"):
"""Resamples input data at user defined coordinates.
The resampler currently only supports bilinear interpolation of 2D data.
Args:
data: Tensor of shape `[batch_size, data_height, data_width,
data_num_channels]` containing 2D data that will be resampled.
warp: Tensor of minimum rank 2 containing the coordinates at which
resampling will be performed. Since only bilinear interpolation is
currently supported, the last dimension of the `warp` tensor must be 2.
name: Optional name of the op.
Returns:
Tensor of resampled values from `data`. The output tensor shape is
determined by the shape of the warp tensor. For example, if `data` is of
shape `[batch_size, data_height, data_width, data_num_channels]` and warp of
shape `[batch_size, dim_0, ... , dim_n, 2]` the output will be of shape
`[batch_size, dim_0, ... , dim_n, data_num_channels]`.
Raises:
ImportError: if the wrapper generated during compilation is not present when
the function is called.
"""
with ops.name_scope(name, "resampler", [data, warp]):
data_tensor = ops.convert_to_tensor(data, name="data")
warp_tensor = ops.convert_to_tensor(warp, name="warp")
return gen_resampler_ops.resampler(data_tensor, warp_tensor) | [
"def",
"resampler",
"(",
"data",
",",
"warp",
",",
"name",
"=",
"\"resampler\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"resampler\"",
",",
"[",
"data",
",",
"warp",
"]",
")",
":",
"data_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"data",
",",
"name",
"=",
"\"data\"",
")",
"warp_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"warp",
",",
"name",
"=",
"\"warp\"",
")",
"return",
"gen_resampler_ops",
".",
"resampler",
"(",
"data_tensor",
",",
"warp_tensor",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/resampler/python/ops/resampler_ops.py#L32-L59 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tempfile.py | python | gettempdir | () | return tempdir | Accessor for tempfile.tempdir. | Accessor for tempfile.tempdir. | [
"Accessor",
"for",
"tempfile",
".",
"tempdir",
"."
] | def gettempdir():
"""Accessor for tempfile.tempdir."""
global tempdir
if tempdir is None:
_once_lock.acquire()
try:
if tempdir is None:
tempdir = _get_default_tempdir()
finally:
_once_lock.release()
return tempdir | [
"def",
"gettempdir",
"(",
")",
":",
"global",
"tempdir",
"if",
"tempdir",
"is",
"None",
":",
"_once_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"tempdir",
"is",
"None",
":",
"tempdir",
"=",
"_get_default_tempdir",
"(",
")",
"finally",
":",
"_once_lock",
".",
"release",
"(",
")",
"return",
"tempdir"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tempfile.py#L287-L297 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/hermite.py | python | hermgauss | (deg) | return x, w | Gauss-Hermite quadrature.
Computes the sample points and weights for Gauss-Hermite quadrature.
These sample points and weights will correctly integrate polynomials of
degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`
with the weight function :math:`f(x) = \\exp(-x^2)`.
Parameters
----------
deg : int
Number of sample points and weights. It must be >= 1.
Returns
-------
x : ndarray
1-D ndarray containing the sample points.
y : ndarray
1-D ndarray containing the weights.
Notes
-----
.. versionadded:: 1.7.0
The results have only been tested up to degree 100, higher degrees may
be problematic. The weights are determined by using the fact that
.. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k))
where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
is the k'th root of :math:`H_n`, and then scaling the results to get
the right value when integrating 1. | Gauss-Hermite quadrature. | [
"Gauss",
"-",
"Hermite",
"quadrature",
"."
] | def hermgauss(deg):
"""
Gauss-Hermite quadrature.
Computes the sample points and weights for Gauss-Hermite quadrature.
These sample points and weights will correctly integrate polynomials of
degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`
with the weight function :math:`f(x) = \\exp(-x^2)`.
Parameters
----------
deg : int
Number of sample points and weights. It must be >= 1.
Returns
-------
x : ndarray
1-D ndarray containing the sample points.
y : ndarray
1-D ndarray containing the weights.
Notes
-----
.. versionadded:: 1.7.0
The results have only been tested up to degree 100, higher degrees may
be problematic. The weights are determined by using the fact that
.. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k))
where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
is the k'th root of :math:`H_n`, and then scaling the results to get
the right value when integrating 1.
"""
ideg = pu._deprecate_as_int(deg, "deg")
if ideg <= 0:
raise ValueError("deg must be a positive integer")
# first approximation of roots. We use the fact that the companion
# matrix is symmetric in this case in order to obtain better zeros.
c = np.array([0]*deg + [1], dtype=np.float64)
m = hermcompanion(c)
x = la.eigvalsh(m)
# improve roots by one application of Newton
dy = _normed_hermite_n(x, ideg)
df = _normed_hermite_n(x, ideg - 1) * np.sqrt(2*ideg)
x -= dy/df
# compute the weights. We scale the factor to avoid possible numerical
# overflow.
fm = _normed_hermite_n(x, ideg - 1)
fm /= np.abs(fm).max()
w = 1/(fm * fm)
# for Hermite we can also symmetrize
w = (w + w[::-1])/2
x = (x - x[::-1])/2
# scale w to get the right value
w *= np.sqrt(np.pi) / w.sum()
return x, w | [
"def",
"hermgauss",
"(",
"deg",
")",
":",
"ideg",
"=",
"pu",
".",
"_deprecate_as_int",
"(",
"deg",
",",
"\"deg\"",
")",
"if",
"ideg",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"deg must be a positive integer\"",
")",
"# first approximation of roots. We use the fact that the companion",
"# matrix is symmetric in this case in order to obtain better zeros.",
"c",
"=",
"np",
".",
"array",
"(",
"[",
"0",
"]",
"*",
"deg",
"+",
"[",
"1",
"]",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"m",
"=",
"hermcompanion",
"(",
"c",
")",
"x",
"=",
"la",
".",
"eigvalsh",
"(",
"m",
")",
"# improve roots by one application of Newton",
"dy",
"=",
"_normed_hermite_n",
"(",
"x",
",",
"ideg",
")",
"df",
"=",
"_normed_hermite_n",
"(",
"x",
",",
"ideg",
"-",
"1",
")",
"*",
"np",
".",
"sqrt",
"(",
"2",
"*",
"ideg",
")",
"x",
"-=",
"dy",
"/",
"df",
"# compute the weights. We scale the factor to avoid possible numerical",
"# overflow.",
"fm",
"=",
"_normed_hermite_n",
"(",
"x",
",",
"ideg",
"-",
"1",
")",
"fm",
"/=",
"np",
".",
"abs",
"(",
"fm",
")",
".",
"max",
"(",
")",
"w",
"=",
"1",
"/",
"(",
"fm",
"*",
"fm",
")",
"# for Hermite we can also symmetrize",
"w",
"=",
"(",
"w",
"+",
"w",
"[",
":",
":",
"-",
"1",
"]",
")",
"/",
"2",
"x",
"=",
"(",
"x",
"-",
"x",
"[",
":",
":",
"-",
"1",
"]",
")",
"/",
"2",
"# scale w to get the right value",
"w",
"*=",
"np",
".",
"sqrt",
"(",
"np",
".",
"pi",
")",
"/",
"w",
".",
"sum",
"(",
")",
"return",
"x",
",",
"w"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/hermite.py#L1558-L1622 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextBuffer.GetRenderer | (*args, **kwargs) | return _richtext.RichTextBuffer_GetRenderer(*args, **kwargs) | GetRenderer() -> RichTextRenderer | GetRenderer() -> RichTextRenderer | [
"GetRenderer",
"()",
"-",
">",
"RichTextRenderer"
] | def GetRenderer(*args, **kwargs):
"""GetRenderer() -> RichTextRenderer"""
return _richtext.RichTextBuffer_GetRenderer(*args, **kwargs) | [
"def",
"GetRenderer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_GetRenderer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2605-L2607 | |
Manu343726/siplasplas | 9fae7559f87087cf8ef34f04bd1e774b84b2ea9c | reference/cindex.py | python | Cursor.get_bitfield_width | (self) | return conf.lib.clang_getFieldDeclBitWidth(self) | Retrieve the width of a bitfield. | Retrieve the width of a bitfield. | [
"Retrieve",
"the",
"width",
"of",
"a",
"bitfield",
"."
] | def get_bitfield_width(self):
"""
Retrieve the width of a bitfield.
"""
return conf.lib.clang_getFieldDeclBitWidth(self) | [
"def",
"get_bitfield_width",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getFieldDeclBitWidth",
"(",
"self",
")"
] | https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1553-L1557 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/dataset/dataset.py | python | InMemoryDataset._init_distributed_settings | (self, **kwargs) | :api_attr: Static Graph
should be called only once in user's python scripts to initialize distributed-related setings of dataset instance
Args:
kwargs: Keyword arguments. Currently, we support following keys in **kwargs:
merge_size(int): ins size to merge, if merge_size > 0, set merge by line id,
instances of same line id will be merged after shuffle,
you should parse line id in data generator. default is -1.
parse_ins_id(bool): Set if Dataset need to parse ins_id. default is False.
parse_content(bool): Set if Dataset need to parse content. default is False.
fleet_send_batch_size(int): Set fleet send batch size in one rpc, default is 1024
fleet_send_sleep_seconds(int): Set fleet send sleep time, default is 0
fea_eval(bool): Set if Dataset need to do feature importance evaluation using slots shuffle.
default is False.
candidate_size(int): if fea_eval is set True, set the candidate size used in slots shuffle.
Examples:
.. code-block:: python
import paddle
paddle.enable_static()
dataset = paddle.distributed.InMemoryDataset()
dataset.init(
batch_size=1,
thread_num=2,
input_type=1,
pipe_command="cat",
use_var=[])
dataset._init_distributed_settings(
parse_ins_id=True,
parse_content=True,
fea_eval=True,
candidate_size=10000) | :api_attr: Static Graph | [
":",
"api_attr",
":",
"Static",
"Graph"
] | def _init_distributed_settings(self, **kwargs):
"""
:api_attr: Static Graph
should be called only once in user's python scripts to initialize distributed-related setings of dataset instance
Args:
kwargs: Keyword arguments. Currently, we support following keys in **kwargs:
merge_size(int): ins size to merge, if merge_size > 0, set merge by line id,
instances of same line id will be merged after shuffle,
you should parse line id in data generator. default is -1.
parse_ins_id(bool): Set if Dataset need to parse ins_id. default is False.
parse_content(bool): Set if Dataset need to parse content. default is False.
fleet_send_batch_size(int): Set fleet send batch size in one rpc, default is 1024
fleet_send_sleep_seconds(int): Set fleet send sleep time, default is 0
fea_eval(bool): Set if Dataset need to do feature importance evaluation using slots shuffle.
default is False.
candidate_size(int): if fea_eval is set True, set the candidate size used in slots shuffle.
Examples:
.. code-block:: python
import paddle
paddle.enable_static()
dataset = paddle.distributed.InMemoryDataset()
dataset.init(
batch_size=1,
thread_num=2,
input_type=1,
pipe_command="cat",
use_var=[])
dataset._init_distributed_settings(
parse_ins_id=True,
parse_content=True,
fea_eval=True,
candidate_size=10000)
"""
merge_size = kwargs.get("merge_size", -1)
if merge_size > 0:
self._set_merge_by_lineid(merge_size)
parse_ins_id = kwargs.get("parse_ins_id", False)
self._set_parse_ins_id(parse_ins_id)
parse_content = kwargs.get("parse_content", False)
self._set_parse_content(parse_content)
fleet_send_batch_size = kwargs.get("fleet_send_batch_size", None)
if fleet_send_batch_size:
self._set_fleet_send_batch_size(fleet_send_batch_size)
fleet_send_sleep_seconds = kwargs.get("fleet_send_sleep_seconds", None)
if fleet_send_sleep_seconds:
self._set_fleet_send_sleep_seconds(fleet_send_sleep_seconds)
fea_eval = kwargs.get("fea_eval", False)
if fea_eval:
candidate_size = kwargs.get("candidate_size", 10000)
self._set_fea_eval(candidate_size, True) | [
"def",
"_init_distributed_settings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"merge_size",
"=",
"kwargs",
".",
"get",
"(",
"\"merge_size\"",
",",
"-",
"1",
")",
"if",
"merge_size",
">",
"0",
":",
"self",
".",
"_set_merge_by_lineid",
"(",
"merge_size",
")",
"parse_ins_id",
"=",
"kwargs",
".",
"get",
"(",
"\"parse_ins_id\"",
",",
"False",
")",
"self",
".",
"_set_parse_ins_id",
"(",
"parse_ins_id",
")",
"parse_content",
"=",
"kwargs",
".",
"get",
"(",
"\"parse_content\"",
",",
"False",
")",
"self",
".",
"_set_parse_content",
"(",
"parse_content",
")",
"fleet_send_batch_size",
"=",
"kwargs",
".",
"get",
"(",
"\"fleet_send_batch_size\"",
",",
"None",
")",
"if",
"fleet_send_batch_size",
":",
"self",
".",
"_set_fleet_send_batch_size",
"(",
"fleet_send_batch_size",
")",
"fleet_send_sleep_seconds",
"=",
"kwargs",
".",
"get",
"(",
"\"fleet_send_sleep_seconds\"",
",",
"None",
")",
"if",
"fleet_send_sleep_seconds",
":",
"self",
".",
"_set_fleet_send_sleep_seconds",
"(",
"fleet_send_sleep_seconds",
")",
"fea_eval",
"=",
"kwargs",
".",
"get",
"(",
"\"fea_eval\"",
",",
"False",
")",
"if",
"fea_eval",
":",
"candidate_size",
"=",
"kwargs",
".",
"get",
"(",
"\"candidate_size\"",
",",
"10000",
")",
"self",
".",
"_set_fea_eval",
"(",
"candidate_size",
",",
"True",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/dataset/dataset.py#L371-L430 | ||
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/msvs.py | python | _CreateProjectObjects | (target_list, target_dicts, options, msvs_version) | return projects | Create a MSVSProject object for the targets found in target list.
Arguments:
target_list: the list of targets to generate project objects for.
target_dicts: the dictionary of specifications.
options: global generator options.
version: the MSVSVersion object.
Returns:
A set of created projects, keyed by target. | Create a MSVSProject object for the targets found in target list. | [
"Create",
"a",
"MSVSProject",
"object",
"for",
"the",
"targets",
"found",
"in",
"target",
"list",
"."
] | def _CreateProjectObjects(target_list, target_dicts, options, msvs_version):
"""Create a MSVSProject object for the targets found in target list.
Arguments:
target_list: the list of targets to generate project objects for.
target_dicts: the dictionary of specifications.
options: global generator options.
version: the MSVSVersion object.
Returns:
A set of created projects, keyed by target.
"""
global fixpath_prefix
# Generate each project.
projects = {}
for qualified_target in target_list:
spec = target_dicts[qualified_target]
if spec['toolset'] != 'target':
raise Exception(
'Multiple toolsets not supported in msvs build (target %s)' %
qualified_target)
proj_path, fixpath_prefix = _GetPathOfProject(qualified_target, spec,
options, msvs_version)
guid = _GetGuidOfProject(proj_path, spec)
overrides = _GetPlatformOverridesOfProject(spec)
build_file = gyp.common.BuildFile(qualified_target)
# Create object for this project.
obj = MSVSNew.MSVSProject(
_FixPath(proj_path),
name=spec['target_name'],
guid=guid,
spec=spec,
build_file=build_file,
config_platform_overrides=overrides,
fixpath_prefix=fixpath_prefix)
projects[qualified_target] = obj
# Set all the dependencies
for project in projects.values():
deps = project.spec.get('dependencies', [])
deps = [projects[d] for d in deps]
project.set_dependencies(deps)
return projects | [
"def",
"_CreateProjectObjects",
"(",
"target_list",
",",
"target_dicts",
",",
"options",
",",
"msvs_version",
")",
":",
"global",
"fixpath_prefix",
"# Generate each project.",
"projects",
"=",
"{",
"}",
"for",
"qualified_target",
"in",
"target_list",
":",
"spec",
"=",
"target_dicts",
"[",
"qualified_target",
"]",
"if",
"spec",
"[",
"'toolset'",
"]",
"!=",
"'target'",
":",
"raise",
"Exception",
"(",
"'Multiple toolsets not supported in msvs build (target %s)'",
"%",
"qualified_target",
")",
"proj_path",
",",
"fixpath_prefix",
"=",
"_GetPathOfProject",
"(",
"qualified_target",
",",
"spec",
",",
"options",
",",
"msvs_version",
")",
"guid",
"=",
"_GetGuidOfProject",
"(",
"proj_path",
",",
"spec",
")",
"overrides",
"=",
"_GetPlatformOverridesOfProject",
"(",
"spec",
")",
"build_file",
"=",
"gyp",
".",
"common",
".",
"BuildFile",
"(",
"qualified_target",
")",
"# Create object for this project.",
"obj",
"=",
"MSVSNew",
".",
"MSVSProject",
"(",
"_FixPath",
"(",
"proj_path",
")",
",",
"name",
"=",
"spec",
"[",
"'target_name'",
"]",
",",
"guid",
"=",
"guid",
",",
"spec",
"=",
"spec",
",",
"build_file",
"=",
"build_file",
",",
"config_platform_overrides",
"=",
"overrides",
",",
"fixpath_prefix",
"=",
"fixpath_prefix",
")",
"projects",
"[",
"qualified_target",
"]",
"=",
"obj",
"# Set all the dependencies",
"for",
"project",
"in",
"projects",
".",
"values",
"(",
")",
":",
"deps",
"=",
"project",
".",
"spec",
".",
"get",
"(",
"'dependencies'",
",",
"[",
"]",
")",
"deps",
"=",
"[",
"projects",
"[",
"d",
"]",
"for",
"d",
"in",
"deps",
"]",
"project",
".",
"set_dependencies",
"(",
"deps",
")",
"return",
"projects"
] | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/msvs.py#L1417-L1457 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/depot_tools/cpplint.py | python | _ClassifyInclude | (fileinfo, include, is_system) | return _OTHER_HEADER | Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER | Figures out what kind of header 'include' is. | [
"Figures",
"out",
"what",
"kind",
"of",
"header",
"include",
"is",
"."
] | def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
is_cpp_h = include in _CPP_HEADERS
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
# If the target file and the include we're checking share a
# basename when we drop common extensions, and the include
# lives in . , then it's likely to be owned by the target file.
target_dir, target_base = (
os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
if target_base == include_base and (
include_dir == target_dir or
include_dir == os.path.normpath(target_dir + '/../public')):
return _LIKELY_MY_HEADER
# If the target and include share some initial basename
# component, it's possible the target is implementing the
# include, so it's allowed to be first, but we'll never
# complain if it's not there.
target_first_component = _RE_FIRST_COMPONENT.match(target_base)
include_first_component = _RE_FIRST_COMPONENT.match(include_base)
if (target_first_component and include_first_component and
target_first_component.group(0) ==
include_first_component.group(0)):
return _POSSIBLE_MY_HEADER
return _OTHER_HEADER | [
"def",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
":",
"# This is a list of all standard c++ header files, except",
"# those already checked for above.",
"is_cpp_h",
"=",
"include",
"in",
"_CPP_HEADERS",
"if",
"is_system",
":",
"if",
"is_cpp_h",
":",
"return",
"_CPP_SYS_HEADER",
"else",
":",
"return",
"_C_SYS_HEADER",
"# If the target file and the include we're checking share a",
"# basename when we drop common extensions, and the include",
"# lives in . , then it's likely to be owned by the target file.",
"target_dir",
",",
"target_base",
"=",
"(",
"os",
".",
"path",
".",
"split",
"(",
"_DropCommonSuffixes",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
")",
")",
")",
"include_dir",
",",
"include_base",
"=",
"os",
".",
"path",
".",
"split",
"(",
"_DropCommonSuffixes",
"(",
"include",
")",
")",
"if",
"target_base",
"==",
"include_base",
"and",
"(",
"include_dir",
"==",
"target_dir",
"or",
"include_dir",
"==",
"os",
".",
"path",
".",
"normpath",
"(",
"target_dir",
"+",
"'/../public'",
")",
")",
":",
"return",
"_LIKELY_MY_HEADER",
"# If the target and include share some initial basename",
"# component, it's possible the target is implementing the",
"# include, so it's allowed to be first, but we'll never",
"# complain if it's not there.",
"target_first_component",
"=",
"_RE_FIRST_COMPONENT",
".",
"match",
"(",
"target_base",
")",
"include_first_component",
"=",
"_RE_FIRST_COMPONENT",
".",
"match",
"(",
"include_base",
")",
"if",
"(",
"target_first_component",
"and",
"include_first_component",
"and",
"target_first_component",
".",
"group",
"(",
"0",
")",
"==",
"include_first_component",
".",
"group",
"(",
"0",
")",
")",
":",
"return",
"_POSSIBLE_MY_HEADER",
"return",
"_OTHER_HEADER"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L4330-L4386 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/ert/importData.py | python | importRes2dInv | (filename, verbose=False, return_header=False) | Read res2dinv format
Parameters
----------
filename : str
verbose : bool [False]
return_header : bool [False]
Returns
-------
pg.DataContainerERT and (in case of return_header=True)
header dictionary
Format
------
str - title
float - unit spacing [m]
int - Array Number (1-Wenner, 3-Dipole-dipole atm only)
int - Number of Datapoints
float - x-location given in terms of first electrode
use 1 if mid-point location is given
int - 0 for no IP, use 1 if IP present
str - Phase Angle if IP present
str - mrad if IP present
0,90.0 - if IP present
dataBody | Read res2dinv format | [
"Read",
"res2dinv",
"format"
] | def importRes2dInv(filename, verbose=False, return_header=False):
"""Read res2dinv format
Parameters
----------
filename : str
verbose : bool [False]
return_header : bool [False]
Returns
-------
pg.DataContainerERT and (in case of return_header=True)
header dictionary
Format
------
str - title
float - unit spacing [m]
int - Array Number (1-Wenner, 3-Dipole-dipole atm only)
int - Number of Datapoints
float - x-location given in terms of first electrode
use 1 if mid-point location is given
int - 0 for no IP, use 1 if IP present
str - Phase Angle if IP present
str - mrad if IP present
0,90.0 - if IP present
dataBody
"""
def getNonEmptyRow(i, comment='#'):
s = next(i)
while s[0] is comment:
s = next(i)
return s.split('\r\n')[0]
# def getNonEmptyRow(...)
with open(filename, 'r') as fi:
content = fi.readlines()
it = iter(content)
header = {}
header['name'] = getNonEmptyRow(it, comment=';')
header['spacing'] = float(getNonEmptyRow(it, comment=';'))
typrow = getNonEmptyRow(it, comment=';')
typ = int(typrow.rstrip('\n').rstrip('R').rstrip('L'))
if typ == 11:
# independent electrode positions
header['subtype'] = int(getNonEmptyRow(it, comment=';'))
header['dummy'] = getNonEmptyRow(it, comment=';')
isR = int(getNonEmptyRow(it, comment=';'))
nData = int(getNonEmptyRow(it, comment=';'))
xLoc = float(getNonEmptyRow(it, comment=';'))
hasIP = int(getNonEmptyRow(it, comment=';'))
if hasIP:
header['ipQuantity'] = getNonEmptyRow(it, comment=';')
header['ipUnit'] = getNonEmptyRow(it, comment=';')
header['ipData'] = getNonEmptyRow(it, comment=';')
ipline = header['ipData'].rstrip('\n').rstrip('\r').split(' ')
if len(ipline) > 2: # obviously spectral data?
header['ipNumGates'] = int(ipline[0])
header['ipDelay'] = float(ipline[1])
header['onTime'] = float(ipline[-2])
header['offTime'] = float(ipline[-1])
header['ipDT'] = np.array(ipline[2:-2], dtype=float)
header['ipGateT'] = np.cumsum(np.hstack((header['ipDelay'],
header['ipDT'])))
data = pg.DataContainerERT()
data.resize(nData)
if typ == 9 or typ == 10:
raise Exception("Don't know how to read:" + str(typ))
if typ == 11 or typ == 12 or typ == 13: # mixed array
res = pg.Vector(nData, 0.0)
ip = pg.Vector(nData, 0.0)
specIP = []
for i in range(nData):
vals = getNonEmptyRow(it, comment=';').replace(',', ' ').split()
# row starts with 4
if int(vals[0]) == 4:
eaID = data.createSensor(pg.Pos(float(vals[1]),
float(vals[2])))
ebID = data.createSensor(pg.Pos(float(vals[3]),
float(vals[4])))
emID = data.createSensor(pg.Pos(float(vals[5]),
float(vals[6])))
enID = data.createSensor(pg.Pos(float(vals[7]),
float(vals[8])))
elif int(vals[0]) == 3:
eaID = data.createSensor(pg.Pos(float(vals[1]),
float(vals[2])))
ebID = -1
emID = data.createSensor(pg.Pos(float(vals[3]),
float(vals[4])))
enID = data.createSensor(pg.Pos(float(vals[5]),
float(vals[6])))
elif int(vals[0]) == 2:
eaID = data.createSensor(pg.Pos(float(vals[1]),
float(vals[2])))
ebID = -1
emID = data.createSensor(pg.Pos(float(vals[3]),
float(vals[4])))
enID = -1
else:
raise Exception('dont know how to handle row', vals[0])
res[i] = float(vals[int(vals[0])*2+1])
if hasIP:
# ip[i] = float(vals[int(vals[0])*2+2])
ipCol = int(vals[0])*2+2
ip[i] = float(vals[ipCol])
if 'ipNumGates' in header:
specIP.append(vals[ipCol:])
data.createFourPointData(i, eaID, ebID, emID, enID)
if isR:
data.set('r', res)
else:
data.set('rhoa', res)
if hasIP:
data.set('ip', ip)
if 'ipNumGates' in header:
A = np.array(specIP, dtype=float)
A[A > 1000] = -999
A[A < -1000] = -999
for i in range(header['ipNumGates']):
data.set('ip'+str(i+1), A[:, i])
data.sortSensorsX()
data.sortSensorsIndex()
if return_header:
return data, header
else:
return data
# amount of values per collumn per typ
nntyp = [0, 3, 3, 4, 3, 3, 4, 4, 3, 0, 0, 8, 10]
nn = nntyp[typ] + hasIP
# dataBody = pg.Matrix(nn, nData)
dataBody = np.zeros((nn, nData))
for i in range(nData):
vals = getNonEmptyRow(it, comment=';').replace(',', ' ').split()
dataBody[:, i] = np.array(vals, dtype=float)
# for j in range(nn):
# dataBody[j][i] = float(vals[j])
XX = dataBody[0]
EL = dataBody[1]
SP = pg.Vector(nData, 1.0)
if nn - hasIP == 4:
SP = dataBody[2]
AA = None
BB = None
NN = None
MM = None
if typ == 1: # Wenner
AA = XX - xLoc * EL * 1.5
MM = AA + EL
NN = MM + EL
BB = NN + EL
elif typ == 2: # Pole-Pole
AA = XX - xLoc * EL * 0.5
MM = AA + EL
elif typ == 3: # Dipole-Dipole
AA = XX - xLoc * EL * (SP / 2. + 1.)
BB = AA + EL
MM = BB + SP * EL
NN = MM + EL
pass
elif typ == 3: # Dipole-Dipole
AA = XX - xLoc * EL * (SP / 2. + 1.)
BB = AA + EL
MM = BB + SP * EL
NN = MM + EL
elif typ == 4: # WENNER-BETA
AA = XX - xLoc * EL * 1.5
BB = AA + EL
MM = BB + EL
NN = MM + EL
elif typ == 5: # WENNER-GAMMA
AA = XX - xLoc * EL * 1.5
MM = AA + EL
BB = MM + EL
NN = BB + EL
elif typ == 6: # POLE-DIPOLE
AA = XX - xLoc * SP * EL - (SP - 1.) * (SP < 0.) * EL
MM = AA + SP * EL
NN = MM + pg.sign(SP) * EL
elif typ == 7: # SCHLUMBERGER
AA = XX - xLoc * EL * (SP + 0.5)
MM = AA + SP * EL
NN = MM + EL
BB = NN + SP * EL
else:
raise Exception('Datatype ' + str(typ) + ' not yet suppoted')
for i in range(len(AA)):
if AA is not None:
eaID = data.createSensor(pg.Pos(AA[i], 0.0))
else:
eaID = -1
if BB is not None:
ebID = data.createSensor(pg.Pos(BB[i], 0.0))
else:
ebID = -1
if MM is not None:
emID = data.createSensor(pg.Pos(MM[i], 0.0))
else:
emID = -1
if NN is not None:
enID = data.createSensor(pg.Pos(NN[i], 0.0))
else:
enID = -1
data.createFourPointData(i, eaID, ebID, emID, enID)
data.set('rhoa', dataBody[nn - hasIP - 1])
if hasIP:
data.set('ip', dataBody[nn - 1])
data.sortSensorsX()
if return_header:
return data, header
else:
return data | [
"def",
"importRes2dInv",
"(",
"filename",
",",
"verbose",
"=",
"False",
",",
"return_header",
"=",
"False",
")",
":",
"def",
"getNonEmptyRow",
"(",
"i",
",",
"comment",
"=",
"'#'",
")",
":",
"s",
"=",
"next",
"(",
"i",
")",
"while",
"s",
"[",
"0",
"]",
"is",
"comment",
":",
"s",
"=",
"next",
"(",
"i",
")",
"return",
"s",
".",
"split",
"(",
"'\\r\\n'",
")",
"[",
"0",
"]",
"# def getNonEmptyRow(...)",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fi",
":",
"content",
"=",
"fi",
".",
"readlines",
"(",
")",
"it",
"=",
"iter",
"(",
"content",
")",
"header",
"=",
"{",
"}",
"header",
"[",
"'name'",
"]",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
"header",
"[",
"'spacing'",
"]",
"=",
"float",
"(",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
")",
"typrow",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
"typ",
"=",
"int",
"(",
"typrow",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"rstrip",
"(",
"'R'",
")",
".",
"rstrip",
"(",
"'L'",
")",
")",
"if",
"typ",
"==",
"11",
":",
"# independent electrode positions",
"header",
"[",
"'subtype'",
"]",
"=",
"int",
"(",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
")",
"header",
"[",
"'dummy'",
"]",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
"isR",
"=",
"int",
"(",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
")",
"nData",
"=",
"int",
"(",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
")",
"xLoc",
"=",
"float",
"(",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
")",
"hasIP",
"=",
"int",
"(",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
")",
"if",
"hasIP",
":",
"header",
"[",
"'ipQuantity'",
"]",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
"header",
"[",
"'ipUnit'",
"]",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
"header",
"[",
"'ipData'",
"]",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
"ipline",
"=",
"header",
"[",
"'ipData'",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"rstrip",
"(",
"'\\r'",
")",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"ipline",
")",
">",
"2",
":",
"# obviously spectral data?",
"header",
"[",
"'ipNumGates'",
"]",
"=",
"int",
"(",
"ipline",
"[",
"0",
"]",
")",
"header",
"[",
"'ipDelay'",
"]",
"=",
"float",
"(",
"ipline",
"[",
"1",
"]",
")",
"header",
"[",
"'onTime'",
"]",
"=",
"float",
"(",
"ipline",
"[",
"-",
"2",
"]",
")",
"header",
"[",
"'offTime'",
"]",
"=",
"float",
"(",
"ipline",
"[",
"-",
"1",
"]",
")",
"header",
"[",
"'ipDT'",
"]",
"=",
"np",
".",
"array",
"(",
"ipline",
"[",
"2",
":",
"-",
"2",
"]",
",",
"dtype",
"=",
"float",
")",
"header",
"[",
"'ipGateT'",
"]",
"=",
"np",
".",
"cumsum",
"(",
"np",
".",
"hstack",
"(",
"(",
"header",
"[",
"'ipDelay'",
"]",
",",
"header",
"[",
"'ipDT'",
"]",
")",
")",
")",
"data",
"=",
"pg",
".",
"DataContainerERT",
"(",
")",
"data",
".",
"resize",
"(",
"nData",
")",
"if",
"typ",
"==",
"9",
"or",
"typ",
"==",
"10",
":",
"raise",
"Exception",
"(",
"\"Don't know how to read:\"",
"+",
"str",
"(",
"typ",
")",
")",
"if",
"typ",
"==",
"11",
"or",
"typ",
"==",
"12",
"or",
"typ",
"==",
"13",
":",
"# mixed array",
"res",
"=",
"pg",
".",
"Vector",
"(",
"nData",
",",
"0.0",
")",
"ip",
"=",
"pg",
".",
"Vector",
"(",
"nData",
",",
"0.0",
")",
"specIP",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"nData",
")",
":",
"vals",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"# row starts with 4",
"if",
"int",
"(",
"vals",
"[",
"0",
"]",
")",
"==",
"4",
":",
"eaID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"1",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"2",
"]",
")",
")",
")",
"ebID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"3",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"4",
"]",
")",
")",
")",
"emID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"5",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"6",
"]",
")",
")",
")",
"enID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"7",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"8",
"]",
")",
")",
")",
"elif",
"int",
"(",
"vals",
"[",
"0",
"]",
")",
"==",
"3",
":",
"eaID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"1",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"2",
"]",
")",
")",
")",
"ebID",
"=",
"-",
"1",
"emID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"3",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"4",
"]",
")",
")",
")",
"enID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"5",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"6",
"]",
")",
")",
")",
"elif",
"int",
"(",
"vals",
"[",
"0",
"]",
")",
"==",
"2",
":",
"eaID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"1",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"2",
"]",
")",
")",
")",
"ebID",
"=",
"-",
"1",
"emID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"float",
"(",
"vals",
"[",
"3",
"]",
")",
",",
"float",
"(",
"vals",
"[",
"4",
"]",
")",
")",
")",
"enID",
"=",
"-",
"1",
"else",
":",
"raise",
"Exception",
"(",
"'dont know how to handle row'",
",",
"vals",
"[",
"0",
"]",
")",
"res",
"[",
"i",
"]",
"=",
"float",
"(",
"vals",
"[",
"int",
"(",
"vals",
"[",
"0",
"]",
")",
"*",
"2",
"+",
"1",
"]",
")",
"if",
"hasIP",
":",
"# ip[i] = float(vals[int(vals[0])*2+2])",
"ipCol",
"=",
"int",
"(",
"vals",
"[",
"0",
"]",
")",
"*",
"2",
"+",
"2",
"ip",
"[",
"i",
"]",
"=",
"float",
"(",
"vals",
"[",
"ipCol",
"]",
")",
"if",
"'ipNumGates'",
"in",
"header",
":",
"specIP",
".",
"append",
"(",
"vals",
"[",
"ipCol",
":",
"]",
")",
"data",
".",
"createFourPointData",
"(",
"i",
",",
"eaID",
",",
"ebID",
",",
"emID",
",",
"enID",
")",
"if",
"isR",
":",
"data",
".",
"set",
"(",
"'r'",
",",
"res",
")",
"else",
":",
"data",
".",
"set",
"(",
"'rhoa'",
",",
"res",
")",
"if",
"hasIP",
":",
"data",
".",
"set",
"(",
"'ip'",
",",
"ip",
")",
"if",
"'ipNumGates'",
"in",
"header",
":",
"A",
"=",
"np",
".",
"array",
"(",
"specIP",
",",
"dtype",
"=",
"float",
")",
"A",
"[",
"A",
">",
"1000",
"]",
"=",
"-",
"999",
"A",
"[",
"A",
"<",
"-",
"1000",
"]",
"=",
"-",
"999",
"for",
"i",
"in",
"range",
"(",
"header",
"[",
"'ipNumGates'",
"]",
")",
":",
"data",
".",
"set",
"(",
"'ip'",
"+",
"str",
"(",
"i",
"+",
"1",
")",
",",
"A",
"[",
":",
",",
"i",
"]",
")",
"data",
".",
"sortSensorsX",
"(",
")",
"data",
".",
"sortSensorsIndex",
"(",
")",
"if",
"return_header",
":",
"return",
"data",
",",
"header",
"else",
":",
"return",
"data",
"# amount of values per collumn per typ",
"nntyp",
"=",
"[",
"0",
",",
"3",
",",
"3",
",",
"4",
",",
"3",
",",
"3",
",",
"4",
",",
"4",
",",
"3",
",",
"0",
",",
"0",
",",
"8",
",",
"10",
"]",
"nn",
"=",
"nntyp",
"[",
"typ",
"]",
"+",
"hasIP",
"# dataBody = pg.Matrix(nn, nData)",
"dataBody",
"=",
"np",
".",
"zeros",
"(",
"(",
"nn",
",",
"nData",
")",
")",
"for",
"i",
"in",
"range",
"(",
"nData",
")",
":",
"vals",
"=",
"getNonEmptyRow",
"(",
"it",
",",
"comment",
"=",
"';'",
")",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"dataBody",
"[",
":",
",",
"i",
"]",
"=",
"np",
".",
"array",
"(",
"vals",
",",
"dtype",
"=",
"float",
")",
"# for j in range(nn):",
"# dataBody[j][i] = float(vals[j])",
"XX",
"=",
"dataBody",
"[",
"0",
"]",
"EL",
"=",
"dataBody",
"[",
"1",
"]",
"SP",
"=",
"pg",
".",
"Vector",
"(",
"nData",
",",
"1.0",
")",
"if",
"nn",
"-",
"hasIP",
"==",
"4",
":",
"SP",
"=",
"dataBody",
"[",
"2",
"]",
"AA",
"=",
"None",
"BB",
"=",
"None",
"NN",
"=",
"None",
"MM",
"=",
"None",
"if",
"typ",
"==",
"1",
":",
"# Wenner",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"EL",
"*",
"1.5",
"MM",
"=",
"AA",
"+",
"EL",
"NN",
"=",
"MM",
"+",
"EL",
"BB",
"=",
"NN",
"+",
"EL",
"elif",
"typ",
"==",
"2",
":",
"# Pole-Pole",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"EL",
"*",
"0.5",
"MM",
"=",
"AA",
"+",
"EL",
"elif",
"typ",
"==",
"3",
":",
"# Dipole-Dipole",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"EL",
"*",
"(",
"SP",
"/",
"2.",
"+",
"1.",
")",
"BB",
"=",
"AA",
"+",
"EL",
"MM",
"=",
"BB",
"+",
"SP",
"*",
"EL",
"NN",
"=",
"MM",
"+",
"EL",
"pass",
"elif",
"typ",
"==",
"3",
":",
"# Dipole-Dipole",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"EL",
"*",
"(",
"SP",
"/",
"2.",
"+",
"1.",
")",
"BB",
"=",
"AA",
"+",
"EL",
"MM",
"=",
"BB",
"+",
"SP",
"*",
"EL",
"NN",
"=",
"MM",
"+",
"EL",
"elif",
"typ",
"==",
"4",
":",
"# WENNER-BETA",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"EL",
"*",
"1.5",
"BB",
"=",
"AA",
"+",
"EL",
"MM",
"=",
"BB",
"+",
"EL",
"NN",
"=",
"MM",
"+",
"EL",
"elif",
"typ",
"==",
"5",
":",
"# WENNER-GAMMA",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"EL",
"*",
"1.5",
"MM",
"=",
"AA",
"+",
"EL",
"BB",
"=",
"MM",
"+",
"EL",
"NN",
"=",
"BB",
"+",
"EL",
"elif",
"typ",
"==",
"6",
":",
"# POLE-DIPOLE",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"SP",
"*",
"EL",
"-",
"(",
"SP",
"-",
"1.",
")",
"*",
"(",
"SP",
"<",
"0.",
")",
"*",
"EL",
"MM",
"=",
"AA",
"+",
"SP",
"*",
"EL",
"NN",
"=",
"MM",
"+",
"pg",
".",
"sign",
"(",
"SP",
")",
"*",
"EL",
"elif",
"typ",
"==",
"7",
":",
"# SCHLUMBERGER",
"AA",
"=",
"XX",
"-",
"xLoc",
"*",
"EL",
"*",
"(",
"SP",
"+",
"0.5",
")",
"MM",
"=",
"AA",
"+",
"SP",
"*",
"EL",
"NN",
"=",
"MM",
"+",
"EL",
"BB",
"=",
"NN",
"+",
"SP",
"*",
"EL",
"else",
":",
"raise",
"Exception",
"(",
"'Datatype '",
"+",
"str",
"(",
"typ",
")",
"+",
"' not yet suppoted'",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"AA",
")",
")",
":",
"if",
"AA",
"is",
"not",
"None",
":",
"eaID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"AA",
"[",
"i",
"]",
",",
"0.0",
")",
")",
"else",
":",
"eaID",
"=",
"-",
"1",
"if",
"BB",
"is",
"not",
"None",
":",
"ebID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"BB",
"[",
"i",
"]",
",",
"0.0",
")",
")",
"else",
":",
"ebID",
"=",
"-",
"1",
"if",
"MM",
"is",
"not",
"None",
":",
"emID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"MM",
"[",
"i",
"]",
",",
"0.0",
")",
")",
"else",
":",
"emID",
"=",
"-",
"1",
"if",
"NN",
"is",
"not",
"None",
":",
"enID",
"=",
"data",
".",
"createSensor",
"(",
"pg",
".",
"Pos",
"(",
"NN",
"[",
"i",
"]",
",",
"0.0",
")",
")",
"else",
":",
"enID",
"=",
"-",
"1",
"data",
".",
"createFourPointData",
"(",
"i",
",",
"eaID",
",",
"ebID",
",",
"emID",
",",
"enID",
")",
"data",
".",
"set",
"(",
"'rhoa'",
",",
"dataBody",
"[",
"nn",
"-",
"hasIP",
"-",
"1",
"]",
")",
"if",
"hasIP",
":",
"data",
".",
"set",
"(",
"'ip'",
",",
"dataBody",
"[",
"nn",
"-",
"1",
"]",
")",
"data",
".",
"sortSensorsX",
"(",
")",
"if",
"return_header",
":",
"return",
"data",
",",
"header",
"else",
":",
"return",
"data"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/importData.py#L57-L299 | ||
vusec/vuzzer64 | 2b1b0ed757a3dca114db0192fa4ab1add92348bc | fuzzer-code/operators.py | python | GAoperator.double_crossover | (self, original1, original2) | return child1, child2 | This function computes 2-point crossover on two parents and returns two children. | This function computes 2-point crossover on two parents and returns two children. | [
"This",
"function",
"computes",
"2",
"-",
"point",
"crossover",
"on",
"two",
"parents",
"and",
"returns",
"two",
"children",
"."
] | def double_crossover(self, original1, original2):
"""This function computes 2-point crossover on two parents and returns two children.
"""
point1=self.r.uniform(0.1,0.3)
point2=self.r.uniform(0.6,0.8)
len1=len(original1)
len2=len(original2)
cut11=int(point1*len1)
cut12=int(point2*len1)
cut21=int(point1*len2)
cut22=int(point2*len2)
child1=original1[:cut11]+original2[cut21:cut22]+original1[cut12:]
child2=original2[:cut21]+original1[cut11:cut12]+original2[cut22:]
return child1, child2 | [
"def",
"double_crossover",
"(",
"self",
",",
"original1",
",",
"original2",
")",
":",
"point1",
"=",
"self",
".",
"r",
".",
"uniform",
"(",
"0.1",
",",
"0.3",
")",
"point2",
"=",
"self",
".",
"r",
".",
"uniform",
"(",
"0.6",
",",
"0.8",
")",
"len1",
"=",
"len",
"(",
"original1",
")",
"len2",
"=",
"len",
"(",
"original2",
")",
"cut11",
"=",
"int",
"(",
"point1",
"*",
"len1",
")",
"cut12",
"=",
"int",
"(",
"point2",
"*",
"len1",
")",
"cut21",
"=",
"int",
"(",
"point1",
"*",
"len2",
")",
"cut22",
"=",
"int",
"(",
"point2",
"*",
"len2",
")",
"child1",
"=",
"original1",
"[",
":",
"cut11",
"]",
"+",
"original2",
"[",
"cut21",
":",
"cut22",
"]",
"+",
"original1",
"[",
"cut12",
":",
"]",
"child2",
"=",
"original2",
"[",
":",
"cut21",
"]",
"+",
"original1",
"[",
"cut11",
":",
"cut12",
"]",
"+",
"original2",
"[",
"cut22",
":",
"]",
"return",
"child1",
",",
"child2"
] | https://github.com/vusec/vuzzer64/blob/2b1b0ed757a3dca114db0192fa4ab1add92348bc/fuzzer-code/operators.py#L275-L288 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/Nodes.py | python | CnameDecoratorNode.generate_function_definitions | (self, env, code) | Ensure a prototype for every @cname method in the right place | Ensure a prototype for every | [
"Ensure",
"a",
"prototype",
"for",
"every"
] | def generate_function_definitions(self, env, code):
"Ensure a prototype for every @cname method in the right place"
if self.is_function and env.is_c_class_scope:
# method in cdef class, generate a prototype in the header
h_code = code.globalstate['utility_code_proto']
if isinstance(self.node, DefNode):
self.node.generate_function_header(
h_code, with_pymethdef=False, proto_only=True)
else:
from . import ModuleNode
entry = self.node.entry
cname = entry.cname
entry.cname = entry.func_cname
ModuleNode.generate_cfunction_declaration(
entry,
env.global_scope(),
h_code,
definition=True)
entry.cname = cname
self.node.generate_function_definitions(env, code) | [
"def",
"generate_function_definitions",
"(",
"self",
",",
"env",
",",
"code",
")",
":",
"if",
"self",
".",
"is_function",
"and",
"env",
".",
"is_c_class_scope",
":",
"# method in cdef class, generate a prototype in the header",
"h_code",
"=",
"code",
".",
"globalstate",
"[",
"'utility_code_proto'",
"]",
"if",
"isinstance",
"(",
"self",
".",
"node",
",",
"DefNode",
")",
":",
"self",
".",
"node",
".",
"generate_function_header",
"(",
"h_code",
",",
"with_pymethdef",
"=",
"False",
",",
"proto_only",
"=",
"True",
")",
"else",
":",
"from",
".",
"import",
"ModuleNode",
"entry",
"=",
"self",
".",
"node",
".",
"entry",
"cname",
"=",
"entry",
".",
"cname",
"entry",
".",
"cname",
"=",
"entry",
".",
"func_cname",
"ModuleNode",
".",
"generate_cfunction_declaration",
"(",
"entry",
",",
"env",
".",
"global_scope",
"(",
")",
",",
"h_code",
",",
"definition",
"=",
"True",
")",
"entry",
".",
"cname",
"=",
"cname",
"self",
".",
"node",
".",
"generate_function_definitions",
"(",
"env",
",",
"code",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/Nodes.py#L9344-L9367 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/summary/summary_iterator.py | python | SummaryWriter.add_summary | (self, summary, global_step=None) | Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer
and adds it to the event file.
You can pass the result of evaluating any summary op, using
@{tf.Session.run} or
@{tf.Tensor.eval}, to this
function. Alternatively, you can pass a `tf.Summary` protocol
buffer that you populate with your own data. The latter is
commonly done to report evaluation results in event files.
Args:
summary: A `Summary` protocol buffer, optionally serialized as a string.
global_step: Number. Optional global step value to record with the
summary. | Adds a `Summary` protocol buffer to the event file. | [
"Adds",
"a",
"Summary",
"protocol",
"buffer",
"to",
"the",
"event",
"file",
"."
] | def add_summary(self, summary, global_step=None):
"""Adds a `Summary` protocol buffer to the event file.
This method wraps the provided summary in an `Event` protocol buffer
and adds it to the event file.
You can pass the result of evaluating any summary op, using
@{tf.Session.run} or
@{tf.Tensor.eval}, to this
function. Alternatively, you can pass a `tf.Summary` protocol
buffer that you populate with your own data. The latter is
commonly done to report evaluation results in event files.
Args:
summary: A `Summary` protocol buffer, optionally serialized as a string.
global_step: Number. Optional global step value to record with the
summary.
"""
if isinstance(summary, bytes):
summ = summary_pb2.Summary()
summ.ParseFromString(summary)
summary = summ
event = event_pb2.Event(wall_time=time.time(), summary=summary)
if global_step is not None:
event.step = int(global_step)
self.add_event(event) | [
"def",
"add_summary",
"(",
"self",
",",
"summary",
",",
"global_step",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"summary",
",",
"bytes",
")",
":",
"summ",
"=",
"summary_pb2",
".",
"Summary",
"(",
")",
"summ",
".",
"ParseFromString",
"(",
"summary",
")",
"summary",
"=",
"summ",
"event",
"=",
"event_pb2",
".",
"Event",
"(",
"wall_time",
"=",
"time",
".",
"time",
"(",
")",
",",
"summary",
"=",
"summary",
")",
"if",
"global_step",
"is",
"not",
"None",
":",
"event",
".",
"step",
"=",
"int",
"(",
"global_step",
")",
"self",
".",
"add_event",
"(",
"event",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/summary/summary_iterator.py#L120-L145 | ||
stack-of-tasks/pinocchio | 593d4d43fded997bb9aa2421f4e55294dbd233c4 | bindings/python/pinocchio/visualize/base_visualizer.py | python | BaseVisualizer.__init__ | (self, model = pin.Model(), collision_model = None, visual_model = None, copy_models = False, data = None, collision_data = None, visual_data = None) | Construct a display from the given model, collision model, and visual model.
If copy_models is True, the models are copied. Otherwise, they are simply kept as a reference. | Construct a display from the given model, collision model, and visual model.
If copy_models is True, the models are copied. Otherwise, they are simply kept as a reference. | [
"Construct",
"a",
"display",
"from",
"the",
"given",
"model",
"collision",
"model",
"and",
"visual",
"model",
".",
"If",
"copy_models",
"is",
"True",
"the",
"models",
"are",
"copied",
".",
"Otherwise",
"they",
"are",
"simply",
"kept",
"as",
"a",
"reference",
"."
] | def __init__(self, model = pin.Model(), collision_model = None, visual_model = None, copy_models = False, data = None, collision_data = None, visual_data = None):
"""Construct a display from the given model, collision model, and visual model.
If copy_models is True, the models are copied. Otherwise, they are simply kept as a reference."""
if copy_models:
self.model = model.copy()
self.collision_model = collision_model.copy()
self.visual_model = visual_model.copy()
else:
self.model = model
self.collision_model = collision_model
self.visual_model = visual_model
if data is None:
self.data = self.model.createData()
else:
self.data = data
if collision_data is None and self.collision_model is not None:
self.collision_data = self.collision_model.createData()
else:
self.collision_data = collision_data
if visual_data is None and self.visual_model is not None:
self.visual_data = self.visual_model.createData()
else:
self.visual_data = visual_data | [
"def",
"__init__",
"(",
"self",
",",
"model",
"=",
"pin",
".",
"Model",
"(",
")",
",",
"collision_model",
"=",
"None",
",",
"visual_model",
"=",
"None",
",",
"copy_models",
"=",
"False",
",",
"data",
"=",
"None",
",",
"collision_data",
"=",
"None",
",",
"visual_data",
"=",
"None",
")",
":",
"if",
"copy_models",
":",
"self",
".",
"model",
"=",
"model",
".",
"copy",
"(",
")",
"self",
".",
"collision_model",
"=",
"collision_model",
".",
"copy",
"(",
")",
"self",
".",
"visual_model",
"=",
"visual_model",
".",
"copy",
"(",
")",
"else",
":",
"self",
".",
"model",
"=",
"model",
"self",
".",
"collision_model",
"=",
"collision_model",
"self",
".",
"visual_model",
"=",
"visual_model",
"if",
"data",
"is",
"None",
":",
"self",
".",
"data",
"=",
"self",
".",
"model",
".",
"createData",
"(",
")",
"else",
":",
"self",
".",
"data",
"=",
"data",
"if",
"collision_data",
"is",
"None",
"and",
"self",
".",
"collision_model",
"is",
"not",
"None",
":",
"self",
".",
"collision_data",
"=",
"self",
".",
"collision_model",
".",
"createData",
"(",
")",
"else",
":",
"self",
".",
"collision_data",
"=",
"collision_data",
"if",
"visual_data",
"is",
"None",
"and",
"self",
".",
"visual_model",
"is",
"not",
"None",
":",
"self",
".",
"visual_data",
"=",
"self",
".",
"visual_model",
".",
"createData",
"(",
")",
"else",
":",
"self",
".",
"visual_data",
"=",
"visual_data"
] | https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/visualize/base_visualizer.py#L12-L38 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/weakref.py | python | WeakValueDictionary.itervaluerefs | (self) | return self.data.itervalues() | Return an iterator that yields the weak references to the values.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the values around longer than needed. | Return an iterator that yields the weak references to the values. | [
"Return",
"an",
"iterator",
"that",
"yields",
"the",
"weak",
"references",
"to",
"the",
"values",
"."
] | def itervaluerefs(self):
"""Return an iterator that yields the weak references to the values.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the values around longer than needed.
"""
return self.data.itervalues() | [
"def",
"itervaluerefs",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"itervalues",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/weakref.py#L134-L144 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/contacts/client.py | python | ContactsClient.get_group | (self, uri=None, desired_class=gdata.contacts.data.GroupEntry,
auth_token=None, **kwargs) | return self.get(uri, desired_class=desired_class, auth_token=auth_token, **kwargs) | Get a single groups details
Args:
uri: the group uri or id | Get a single groups details
Args:
uri: the group uri or id | [
"Get",
"a",
"single",
"groups",
"details",
"Args",
":",
"uri",
":",
"the",
"group",
"uri",
"or",
"id"
] | def get_group(self, uri=None, desired_class=gdata.contacts.data.GroupEntry,
auth_token=None, **kwargs):
""" Get a single groups details
Args:
uri: the group uri or id
"""
return self.get(uri, desired_class=desired_class, auth_token=auth_token, **kwargs) | [
"def",
"get_group",
"(",
"self",
",",
"uri",
"=",
"None",
",",
"desired_class",
"=",
"gdata",
".",
"contacts",
".",
"data",
".",
"GroupEntry",
",",
"auth_token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get",
"(",
"uri",
",",
"desired_class",
"=",
"desired_class",
",",
"auth_token",
"=",
"auth_token",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/contacts/client.py#L180-L186 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Node/__init__.py | python | Node.get_contents | (self) | return _get_contents_map[self._func_get_contents](self) | Fetch the contents of the entry. | Fetch the contents of the entry. | [
"Fetch",
"the",
"contents",
"of",
"the",
"entry",
"."
] | def get_contents(self):
"""Fetch the contents of the entry."""
return _get_contents_map[self._func_get_contents](self) | [
"def",
"get_contents",
"(",
"self",
")",
":",
"return",
"_get_contents_map",
"[",
"self",
".",
"_func_get_contents",
"]",
"(",
"self",
")"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/__init__.py#L1258-L1260 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/search/plugin/federated_search_handler.py | python | FederatedSearch.HandleSearchRequest | (self, environ) | return (search_results, response_type) | Fetches the search tokens from form and performs the federated search.
Args:
environ: A list of environment variables as supplied by the
WSGI interface to the federated search application interface.
Returns:
search_results: A KML/JSONP formatted string which contains search results.
response_type: Response type can be KML or JSONP, depending on the client. | Fetches the search tokens from form and performs the federated search. | [
"Fetches",
"the",
"search",
"tokens",
"from",
"form",
"and",
"performs",
"the",
"federated",
"search",
"."
] | def HandleSearchRequest(self, environ):
"""Fetches the search tokens from form and performs the federated search.
Args:
environ: A list of environment variables as supplied by the
WSGI interface to the federated search application interface.
Returns:
search_results: A KML/JSONP formatted string which contains search results.
response_type: Response type can be KML or JSONP, depending on the client.
"""
search_results = ""
search_status = False
# Fetch all the attributes provided by the user.
parameters = self.utils.GetParameters(environ)
self._geplaces.parameters = parameters
self._coordinate.parameters = parameters
# Retrieve the function call back name for JSONP response.
self.f_callback = self.utils.GetCallback(parameters)
# Fetch additional query parameters 'flyToFirstElement' and
# 'displayKeys' from URL.
self.fly_to_first_element = self.utils.GetValue(
parameters, "flyToFirstElement")
self.display_keys_string = self.utils.GetValue(
parameters, "displayKeys")
response_type = self.utils.GetResponseType(environ)
original_query = self.utils.GetValue(parameters, "q")
if original_query:
(search_status, search_results) = self.DoSearch(
original_query, response_type)
else:
self.logger.debug("Empty search query received")
if not search_status:
folder_name = "No results were returned."
search_results = self.utils.NoSearchResults(
folder_name, self._style, response_type, self.f_callback)
return (search_results, response_type) | [
"def",
"HandleSearchRequest",
"(",
"self",
",",
"environ",
")",
":",
"search_results",
"=",
"\"\"",
"search_status",
"=",
"False",
"# Fetch all the attributes provided by the user.",
"parameters",
"=",
"self",
".",
"utils",
".",
"GetParameters",
"(",
"environ",
")",
"self",
".",
"_geplaces",
".",
"parameters",
"=",
"parameters",
"self",
".",
"_coordinate",
".",
"parameters",
"=",
"parameters",
"# Retrieve the function call back name for JSONP response.",
"self",
".",
"f_callback",
"=",
"self",
".",
"utils",
".",
"GetCallback",
"(",
"parameters",
")",
"# Fetch additional query parameters 'flyToFirstElement' and",
"# 'displayKeys' from URL.",
"self",
".",
"fly_to_first_element",
"=",
"self",
".",
"utils",
".",
"GetValue",
"(",
"parameters",
",",
"\"flyToFirstElement\"",
")",
"self",
".",
"display_keys_string",
"=",
"self",
".",
"utils",
".",
"GetValue",
"(",
"parameters",
",",
"\"displayKeys\"",
")",
"response_type",
"=",
"self",
".",
"utils",
".",
"GetResponseType",
"(",
"environ",
")",
"original_query",
"=",
"self",
".",
"utils",
".",
"GetValue",
"(",
"parameters",
",",
"\"q\"",
")",
"if",
"original_query",
":",
"(",
"search_status",
",",
"search_results",
")",
"=",
"self",
".",
"DoSearch",
"(",
"original_query",
",",
"response_type",
")",
"else",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Empty search query received\"",
")",
"if",
"not",
"search_status",
":",
"folder_name",
"=",
"\"No results were returned.\"",
"search_results",
"=",
"self",
".",
"utils",
".",
"NoSearchResults",
"(",
"folder_name",
",",
"self",
".",
"_style",
",",
"response_type",
",",
"self",
".",
"f_callback",
")",
"return",
"(",
"search_results",
",",
"response_type",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/search/plugin/federated_search_handler.py#L53-L97 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/PeacockApp.py | python | PeacockApp.__init__ | (self, args, qapp=None, **kwds) | Constructor.
Takes a QApplication in the constructor to allow for easier testing with unittest.
Input args:
args: Command line arguments
qapp: QApplication | Constructor.
Takes a QApplication in the constructor to allow for easier testing with unittest. | [
"Constructor",
".",
"Takes",
"a",
"QApplication",
"in",
"the",
"constructor",
"to",
"allow",
"for",
"easier",
"testing",
"with",
"unittest",
"."
] | def __init__(self, args, qapp=None, **kwds):
"""
Constructor.
Takes a QApplication in the constructor to allow for easier testing with unittest.
Input args:
args: Command line arguments
qapp: QApplication
"""
super(PeacockApp, self).__init__(**kwds)
# don't include args[0] since that is the executable name
parser = argparse.ArgumentParser(description='MOOSE GUI Application')
PeacockMainWindow.commandLineArgs(parser)
parsed_args = parser.parse_args(args)
peacock_dir = os.path.dirname(os.path.realpath(__file__))
icon_path = os.path.join(peacock_dir, "icons", "peacock_logo.ico")
if qapp is None:
qapp = QApplication.instance()
qapp.setWindowIcon(QIcon(icon_path))
qtutils.setAppInformation("peacock_peacockapp")
if parsed_args.exodus or parsed_args.postprocessors or parsed_args.vectorpostprocessors:
# If the user wants to view files then don't try to automatically find an executable.
# This should help speed up startup times.
parsed_args.exe_search = False
self.main_widget = PeacockMainWindow()
self.main_widget.initialize(parsed_args)
self.main_widget.show()
self.main_widget.raise_()
input_plugin = self.main_widget.tab_plugin.InputFileEditorWithMesh
tree = input_plugin.InputFileEditorPlugin.tree
exe_plugin = self.main_widget.tab_plugin.ExecuteTabPlugin
exodus_plugin = self.main_widget.tab_plugin.ExodusViewer
pp_plugin = self.main_widget.tab_plugin.PostprocessorViewer
vpp_plugin = self.main_widget.tab_plugin.VectorPostprocessorViewer
# issue #9255
# For some unknown reason, the Execute tab doesn't work
# properly on Mac low resolution displays (and some widgets
# on the input tab ).
# If you switch to the ExodusViewer tab then back again, it works.
# If the Execute tab is created after the ExodusViewer
# tab, it works. If the VTKWindowPlugin of the ExodusViewer
# tab is removed, it works. So there is some resizing issue
# or something.
# This ugly hack seems to fix the immediate problem.
if sys.platform == 'darwin':
for idx in range(self.main_widget.tab_plugin.count()):
self.main_widget.tab_plugin.setCurrentIndex(idx)
if parsed_args.vectorpostprocessors:
self.main_widget.setTab(vpp_plugin.tabName())
elif parsed_args.postprocessors:
self.main_widget.setTab(pp_plugin.tabName())
elif parsed_args.exodus:
self.main_widget.setTab(exodus_plugin.tabName())
elif tree.app_info.valid():
if tree.input_filename and parsed_args.auto_run:
self.main_widget.setTab(exe_plugin.tabName())
# These processEvents() seem to be needed on linux so
# that the ExodusViewer gets updated properly
qapp.processEvents()
exe_plugin.ExecuteRunnerPlugin.runClicked()
qapp.processEvents()
self.main_widget.setTab(exodus_plugin.tabName())
qapp.processEvents()
else:
self.main_widget.setTab(input_plugin.tabName())
else:
self.main_widget.setTab(exe_plugin.tabName())
self.main_widget.setPythonVariable("PeacockApp", self) | [
"def",
"__init__",
"(",
"self",
",",
"args",
",",
"qapp",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"super",
"(",
"PeacockApp",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"*",
"kwds",
")",
"# don't include args[0] since that is the executable name",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'MOOSE GUI Application'",
")",
"PeacockMainWindow",
".",
"commandLineArgs",
"(",
"parser",
")",
"parsed_args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"peacock_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"icon_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"peacock_dir",
",",
"\"icons\"",
",",
"\"peacock_logo.ico\"",
")",
"if",
"qapp",
"is",
"None",
":",
"qapp",
"=",
"QApplication",
".",
"instance",
"(",
")",
"qapp",
".",
"setWindowIcon",
"(",
"QIcon",
"(",
"icon_path",
")",
")",
"qtutils",
".",
"setAppInformation",
"(",
"\"peacock_peacockapp\"",
")",
"if",
"parsed_args",
".",
"exodus",
"or",
"parsed_args",
".",
"postprocessors",
"or",
"parsed_args",
".",
"vectorpostprocessors",
":",
"# If the user wants to view files then don't try to automatically find an executable.",
"# This should help speed up startup times.",
"parsed_args",
".",
"exe_search",
"=",
"False",
"self",
".",
"main_widget",
"=",
"PeacockMainWindow",
"(",
")",
"self",
".",
"main_widget",
".",
"initialize",
"(",
"parsed_args",
")",
"self",
".",
"main_widget",
".",
"show",
"(",
")",
"self",
".",
"main_widget",
".",
"raise_",
"(",
")",
"input_plugin",
"=",
"self",
".",
"main_widget",
".",
"tab_plugin",
".",
"InputFileEditorWithMesh",
"tree",
"=",
"input_plugin",
".",
"InputFileEditorPlugin",
".",
"tree",
"exe_plugin",
"=",
"self",
".",
"main_widget",
".",
"tab_plugin",
".",
"ExecuteTabPlugin",
"exodus_plugin",
"=",
"self",
".",
"main_widget",
".",
"tab_plugin",
".",
"ExodusViewer",
"pp_plugin",
"=",
"self",
".",
"main_widget",
".",
"tab_plugin",
".",
"PostprocessorViewer",
"vpp_plugin",
"=",
"self",
".",
"main_widget",
".",
"tab_plugin",
".",
"VectorPostprocessorViewer",
"# issue #9255",
"# For some unknown reason, the Execute tab doesn't work",
"# properly on Mac low resolution displays (and some widgets",
"# on the input tab ).",
"# If you switch to the ExodusViewer tab then back again, it works.",
"# If the Execute tab is created after the ExodusViewer",
"# tab, it works. If the VTKWindowPlugin of the ExodusViewer",
"# tab is removed, it works. So there is some resizing issue",
"# or something.",
"# This ugly hack seems to fix the immediate problem.",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"for",
"idx",
"in",
"range",
"(",
"self",
".",
"main_widget",
".",
"tab_plugin",
".",
"count",
"(",
")",
")",
":",
"self",
".",
"main_widget",
".",
"tab_plugin",
".",
"setCurrentIndex",
"(",
"idx",
")",
"if",
"parsed_args",
".",
"vectorpostprocessors",
":",
"self",
".",
"main_widget",
".",
"setTab",
"(",
"vpp_plugin",
".",
"tabName",
"(",
")",
")",
"elif",
"parsed_args",
".",
"postprocessors",
":",
"self",
".",
"main_widget",
".",
"setTab",
"(",
"pp_plugin",
".",
"tabName",
"(",
")",
")",
"elif",
"parsed_args",
".",
"exodus",
":",
"self",
".",
"main_widget",
".",
"setTab",
"(",
"exodus_plugin",
".",
"tabName",
"(",
")",
")",
"elif",
"tree",
".",
"app_info",
".",
"valid",
"(",
")",
":",
"if",
"tree",
".",
"input_filename",
"and",
"parsed_args",
".",
"auto_run",
":",
"self",
".",
"main_widget",
".",
"setTab",
"(",
"exe_plugin",
".",
"tabName",
"(",
")",
")",
"# These processEvents() seem to be needed on linux so",
"# that the ExodusViewer gets updated properly",
"qapp",
".",
"processEvents",
"(",
")",
"exe_plugin",
".",
"ExecuteRunnerPlugin",
".",
"runClicked",
"(",
")",
"qapp",
".",
"processEvents",
"(",
")",
"self",
".",
"main_widget",
".",
"setTab",
"(",
"exodus_plugin",
".",
"tabName",
"(",
")",
")",
"qapp",
".",
"processEvents",
"(",
")",
"else",
":",
"self",
".",
"main_widget",
".",
"setTab",
"(",
"input_plugin",
".",
"tabName",
"(",
")",
")",
"else",
":",
"self",
".",
"main_widget",
".",
"setTab",
"(",
"exe_plugin",
".",
"tabName",
"(",
")",
")",
"self",
".",
"main_widget",
".",
"setPythonVariable",
"(",
"\"PeacockApp\"",
",",
"self",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/PeacockApp.py#L21-L95 | ||
uber/neuropod | de304c40ec0634a868d7ef41ba7bf89ebc364f10 | source/python/neuropod/utils/config_utils.py | python | write_neuropod_config | (
neuropod_path,
model_name,
platform,
input_spec,
output_spec,
platform_version_semver="*",
custom_ops=None,
input_tensor_device=None,
default_input_tensor_device="GPU",
**kwargs
) | Creates the neuropod config file
:param neuropod_path: The path to a neuropod package
:param model_name: The name of the model (e.g. "my_addition_model")
:param platform: The model type (e.g. "python", "pytorch", "tensorflow", etc.)
:param platform_version_semver: The required platform version specified as semver range
See https://semver.org/, https://docs.npmjs.com/misc/semver#ranges
or https://docs.npmjs.com/misc/semver#advanced-range-syntax for
examples and more info. Default is `*` (any version is okay)
Ex: `1.13.1` or `> 1.13.1`
:param input_spec: A list of dicts specifying the input to the model.
Ex: [{"name": "x", "dtype": "float32", "shape": (None, )}]
:param output_spec: A list of dicts specifying the output of the model.
Ex: [{"name": "y", "dtype": "float32", "shape": (None, )}]
:param input_tensor_device: A dict mapping input tensor names to the device
that the model expects them to be on. This can
either be `GPU` or `CPU`. Any tensors in `input_spec`
not specified in this mapping will use the
`default_input_tensor_device` specified below.
If a GPU is selected at inference time, Neuropod
will move tensors to the appropriate devices before
running the model. Otherwise, it will attempt to run
the model on CPU and move all tensors (and the model)
to CPU.
See the docstring for `load_neuropod` for more info.
Ex: `{"x": "GPU"}`
:param default_input_tensor_device: The default device that input tensors are expected
to be on. This can either be `GPU` or `CPU`. | Creates the neuropod config file | [
"Creates",
"the",
"neuropod",
"config",
"file"
] | def write_neuropod_config(
neuropod_path,
model_name,
platform,
input_spec,
output_spec,
platform_version_semver="*",
custom_ops=None,
input_tensor_device=None,
default_input_tensor_device="GPU",
**kwargs
):
"""
Creates the neuropod config file
:param neuropod_path: The path to a neuropod package
:param model_name: The name of the model (e.g. "my_addition_model")
:param platform: The model type (e.g. "python", "pytorch", "tensorflow", etc.)
:param platform_version_semver: The required platform version specified as semver range
See https://semver.org/, https://docs.npmjs.com/misc/semver#ranges
or https://docs.npmjs.com/misc/semver#advanced-range-syntax for
examples and more info. Default is `*` (any version is okay)
Ex: `1.13.1` or `> 1.13.1`
:param input_spec: A list of dicts specifying the input to the model.
Ex: [{"name": "x", "dtype": "float32", "shape": (None, )}]
:param output_spec: A list of dicts specifying the output of the model.
Ex: [{"name": "y", "dtype": "float32", "shape": (None, )}]
:param input_tensor_device: A dict mapping input tensor names to the device
that the model expects them to be on. This can
either be `GPU` or `CPU`. Any tensors in `input_spec`
not specified in this mapping will use the
`default_input_tensor_device` specified below.
If a GPU is selected at inference time, Neuropod
will move tensors to the appropriate devices before
running the model. Otherwise, it will attempt to run
the model on CPU and move all tensors (and the model)
to CPU.
See the docstring for `load_neuropod` for more info.
Ex: `{"x": "GPU"}`
:param default_input_tensor_device: The default device that input tensors are expected
to be on. This can either be `GPU` or `CPU`.
"""
if custom_ops is None:
custom_ops = []
if input_tensor_device is None:
input_tensor_device = {}
# Canonicalize the specs
input_spec = canonicalize_tensor_spec(input_spec)
output_spec = canonicalize_tensor_spec(output_spec)
# Set up the device mapping
device_mapping = {}
for item in input_spec:
name = item["name"]
if name in input_tensor_device:
# Use the device specified by the user
device_mapping[name] = input_tensor_device[name]
else:
# Use the default device
device_mapping[name] = default_input_tensor_device
# TODO: Switch to prototext
with open(os.path.join(neuropod_path, "config.json"), "w") as config_file:
config = {
"name": model_name,
"platform": platform,
"platform_version_semver": platform_version_semver,
"input_spec": input_spec,
"output_spec": output_spec,
"custom_ops": custom_ops,
"input_tensor_device": device_mapping,
}
# Verify that the config is correct
validate_neuropod_config(config)
# Write out the config as JSON
json.dump(config, config_file, indent=4) | [
"def",
"write_neuropod_config",
"(",
"neuropod_path",
",",
"model_name",
",",
"platform",
",",
"input_spec",
",",
"output_spec",
",",
"platform_version_semver",
"=",
"\"*\"",
",",
"custom_ops",
"=",
"None",
",",
"input_tensor_device",
"=",
"None",
",",
"default_input_tensor_device",
"=",
"\"GPU\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"custom_ops",
"is",
"None",
":",
"custom_ops",
"=",
"[",
"]",
"if",
"input_tensor_device",
"is",
"None",
":",
"input_tensor_device",
"=",
"{",
"}",
"# Canonicalize the specs",
"input_spec",
"=",
"canonicalize_tensor_spec",
"(",
"input_spec",
")",
"output_spec",
"=",
"canonicalize_tensor_spec",
"(",
"output_spec",
")",
"# Set up the device mapping",
"device_mapping",
"=",
"{",
"}",
"for",
"item",
"in",
"input_spec",
":",
"name",
"=",
"item",
"[",
"\"name\"",
"]",
"if",
"name",
"in",
"input_tensor_device",
":",
"# Use the device specified by the user",
"device_mapping",
"[",
"name",
"]",
"=",
"input_tensor_device",
"[",
"name",
"]",
"else",
":",
"# Use the default device",
"device_mapping",
"[",
"name",
"]",
"=",
"default_input_tensor_device",
"# TODO: Switch to prototext",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"neuropod_path",
",",
"\"config.json\"",
")",
",",
"\"w\"",
")",
"as",
"config_file",
":",
"config",
"=",
"{",
"\"name\"",
":",
"model_name",
",",
"\"platform\"",
":",
"platform",
",",
"\"platform_version_semver\"",
":",
"platform_version_semver",
",",
"\"input_spec\"",
":",
"input_spec",
",",
"\"output_spec\"",
":",
"output_spec",
",",
"\"custom_ops\"",
":",
"custom_ops",
",",
"\"input_tensor_device\"",
":",
"device_mapping",
",",
"}",
"# Verify that the config is correct",
"validate_neuropod_config",
"(",
"config",
")",
"# Write out the config as JSON",
"json",
".",
"dump",
"(",
"config",
",",
"config_file",
",",
"indent",
"=",
"4",
")"
] | https://github.com/uber/neuropod/blob/de304c40ec0634a868d7ef41ba7bf89ebc364f10/source/python/neuropod/utils/config_utils.py#L170-L258 | ||
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/internal/decoder.py | python | _FieldSkipper | () | return SkipField | Constructs the SkipField function. | Constructs the SkipField function. | [
"Constructs",
"the",
"SkipField",
"function",
"."
] | def _FieldSkipper():
"""Constructs the SkipField function."""
WIRETYPE_TO_SKIPPER = [
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
]
wiretype_mask = wire_format.TAG_TYPE_MASK
def SkipField(buffer, pos, end, tag_bytes):
"""Skips a field with the specified tag.
|pos| should point to the byte immediately after the tag.
Returns:
The new position (after the tag value), or -1 if the tag is an end-group
tag (in which case the calling loop should break).
"""
# The wire type is always in the first byte since varints are little-endian.
wire_type = ord(tag_bytes[0:1]) & wiretype_mask
return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)
return SkipField | [
"def",
"_FieldSkipper",
"(",
")",
":",
"WIRETYPE_TO_SKIPPER",
"=",
"[",
"_SkipVarint",
",",
"_SkipFixed64",
",",
"_SkipLengthDelimited",
",",
"_SkipGroup",
",",
"_EndGroup",
",",
"_SkipFixed32",
",",
"_RaiseInvalidWireType",
",",
"_RaiseInvalidWireType",
",",
"]",
"wiretype_mask",
"=",
"wire_format",
".",
"TAG_TYPE_MASK",
"def",
"SkipField",
"(",
"buffer",
",",
"pos",
",",
"end",
",",
"tag_bytes",
")",
":",
"\"\"\"Skips a field with the specified tag.\n\n |pos| should point to the byte immediately after the tag.\n\n Returns:\n The new position (after the tag value), or -1 if the tag is an end-group\n tag (in which case the calling loop should break).\n \"\"\"",
"# The wire type is always in the first byte since varints are little-endian.",
"wire_type",
"=",
"ord",
"(",
"tag_bytes",
"[",
"0",
":",
"1",
"]",
")",
"&",
"wiretype_mask",
"return",
"WIRETYPE_TO_SKIPPER",
"[",
"wire_type",
"]",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
"return",
"SkipField"
] | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/internal/decoder.py#L799-L829 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py | python | _BaseV6._parse_hextet | (cls, hextet_str) | return int(hextet_str, 16) | Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn't strictly a hex number from
[0..FFFF]. | Convert an IPv6 hextet string into an integer. | [
"Convert",
"an",
"IPv6",
"hextet",
"string",
"into",
"an",
"integer",
"."
] | def _parse_hextet(cls, hextet_str):
"""Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn't strictly a hex number from
[0..FFFF].
"""
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not cls._HEX_DIGITS.issuperset(hextet_str):
raise ValueError("Only hex digits permitted in %r" % hextet_str)
# We do the length check second, since the invalid character error
# is likely to be more informative for the user
if len(hextet_str) > 4:
msg = "At most 4 characters permitted in %r"
raise ValueError(msg % hextet_str)
# Length check means we can skip checking the integer value
return int(hextet_str, 16) | [
"def",
"_parse_hextet",
"(",
"cls",
",",
"hextet_str",
")",
":",
"# Whitelist the characters, since int() allows a lot of bizarre stuff.",
"if",
"not",
"cls",
".",
"_HEX_DIGITS",
".",
"issuperset",
"(",
"hextet_str",
")",
":",
"raise",
"ValueError",
"(",
"\"Only hex digits permitted in %r\"",
"%",
"hextet_str",
")",
"# We do the length check second, since the invalid character error",
"# is likely to be more informative for the user",
"if",
"len",
"(",
"hextet_str",
")",
">",
"4",
":",
"msg",
"=",
"\"At most 4 characters permitted in %r\"",
"raise",
"ValueError",
"(",
"msg",
"%",
"hextet_str",
")",
"# Length check means we can skip checking the integer value",
"return",
"int",
"(",
"hextet_str",
",",
"16",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py#L1730-L1753 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | WorkingSet._build_from_requirements | (cls, req_spec) | return ws | Build a working set from a requirement spec. Rewrites sys.path. | Build a working set from a requirement spec. Rewrites sys.path. | [
"Build",
"a",
"working",
"set",
"from",
"a",
"requirement",
"spec",
".",
"Rewrites",
"sys",
".",
"path",
"."
] | def _build_from_requirements(cls, req_spec):
"""
Build a working set from a requirement spec. Rewrites sys.path.
"""
# try it without defaults already on sys.path
# by starting with an empty path
ws = cls([])
reqs = parse_requirements(req_spec)
dists = ws.resolve(reqs, Environment())
for dist in dists:
ws.add(dist)
# add any missing entries from sys.path
for entry in sys.path:
if entry not in ws.entries:
ws.add_entry(entry)
# then copy back to sys.path
sys.path[:] = ws.entries
return ws | [
"def",
"_build_from_requirements",
"(",
"cls",
",",
"req_spec",
")",
":",
"# try it without defaults already on sys.path",
"# by starting with an empty path",
"ws",
"=",
"cls",
"(",
"[",
"]",
")",
"reqs",
"=",
"parse_requirements",
"(",
"req_spec",
")",
"dists",
"=",
"ws",
".",
"resolve",
"(",
"reqs",
",",
"Environment",
"(",
")",
")",
"for",
"dist",
"in",
"dists",
":",
"ws",
".",
"add",
"(",
"dist",
")",
"# add any missing entries from sys.path",
"for",
"entry",
"in",
"sys",
".",
"path",
":",
"if",
"entry",
"not",
"in",
"ws",
".",
"entries",
":",
"ws",
".",
"add_entry",
"(",
"entry",
")",
"# then copy back to sys.path",
"sys",
".",
"path",
"[",
":",
"]",
"=",
"ws",
".",
"entries",
"return",
"ws"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L640-L659 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/deep_memory_profiler/visualizer/services.py | python | CreateTemplates | (blob_info) | return default_key | Create Template entities for all templates of uploaded file. Return ndb.Key
of default template or None if not indicated or found in templates. | Create Template entities for all templates of uploaded file. Return ndb.Key
of default template or None if not indicated or found in templates. | [
"Create",
"Template",
"entities",
"for",
"all",
"templates",
"of",
"uploaded",
"file",
".",
"Return",
"ndb",
".",
"Key",
"of",
"default",
"template",
"or",
"None",
"if",
"not",
"indicated",
"or",
"found",
"in",
"templates",
"."
] | def CreateTemplates(blob_info):
"""Create Template entities for all templates of uploaded file. Return ndb.Key
of default template or None if not indicated or found in templates."""
json_str = blob_info.open().read()
json_obj = json.loads(json_str)
# Return None when no default template indicated.
if 'default_template' not in json_obj:
return None
# Return None when no default template found in templates.
if json_obj['default_template'] not in json_obj['templates']:
return None
# Check the uniqueness of template content and store new one.
for tag, content in json_obj['templates'].iteritems():
content_str = json.dumps(content)
tmpl_key = ndb.Key('Template', content_str)
if tag == json_obj['default_template']:
default_key = tmpl_key
if not tmpl_key.get():
# Template of the same content does not exist.
template = Template(id=content_str, content=content)
template.put()
return default_key | [
"def",
"CreateTemplates",
"(",
"blob_info",
")",
":",
"json_str",
"=",
"blob_info",
".",
"open",
"(",
")",
".",
"read",
"(",
")",
"json_obj",
"=",
"json",
".",
"loads",
"(",
"json_str",
")",
"# Return None when no default template indicated.",
"if",
"'default_template'",
"not",
"in",
"json_obj",
":",
"return",
"None",
"# Return None when no default template found in templates.",
"if",
"json_obj",
"[",
"'default_template'",
"]",
"not",
"in",
"json_obj",
"[",
"'templates'",
"]",
":",
"return",
"None",
"# Check the uniqueness of template content and store new one.",
"for",
"tag",
",",
"content",
"in",
"json_obj",
"[",
"'templates'",
"]",
".",
"iteritems",
"(",
")",
":",
"content_str",
"=",
"json",
".",
"dumps",
"(",
"content",
")",
"tmpl_key",
"=",
"ndb",
".",
"Key",
"(",
"'Template'",
",",
"content_str",
")",
"if",
"tag",
"==",
"json_obj",
"[",
"'default_template'",
"]",
":",
"default_key",
"=",
"tmpl_key",
"if",
"not",
"tmpl_key",
".",
"get",
"(",
")",
":",
"# Template of the same content does not exist.",
"template",
"=",
"Template",
"(",
"id",
"=",
"content_str",
",",
"content",
"=",
"content",
")",
"template",
".",
"put",
"(",
")",
"return",
"default_key"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/deep_memory_profiler/visualizer/services.py#L50-L74 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/keras_tensor.py | python | KerasTensor.name | (self) | return self._name | Returns the (non-unique, optional) name of this symbolic Keras value. | Returns the (non-unique, optional) name of this symbolic Keras value. | [
"Returns",
"the",
"(",
"non",
"-",
"unique",
"optional",
")",
"name",
"of",
"this",
"symbolic",
"Keras",
"value",
"."
] | def name(self):
"""Returns the (non-unique, optional) name of this symbolic Keras value."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/keras_tensor.py#L357-L359 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/ConfigSet.py | python | ConfigSet.__setattr__ | (self, name, value) | Attribute access provided for convenience. The following forms are equivalent::
def configure(conf):
conf.env.value = x
env['value'] = x | Attribute access provided for convenience. The following forms are equivalent:: | [
"Attribute",
"access",
"provided",
"for",
"convenience",
".",
"The",
"following",
"forms",
"are",
"equivalent",
"::"
] | def __setattr__(self, name, value):
"""
Attribute access provided for convenience. The following forms are equivalent::
def configure(conf):
conf.env.value = x
env['value'] = x
"""
if name in self.__slots__:
object.__setattr__(self, name, value)
else:
self[name] = value | [
"def",
"__setattr__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"in",
"self",
".",
"__slots__",
":",
"object",
".",
"__setattr__",
"(",
"self",
",",
"name",
",",
"value",
")",
"else",
":",
"self",
"[",
"name",
"]",
"=",
"value"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/ConfigSet.py#L114-L125 | ||
calamares/calamares | 9f6f82405b3074af7c99dc26487d2e46e4ece3e5 | src/modules/mount/main.py | python | run | () | Mount all the partitions from GlobalStorage and from the job configuration.
Partitions are mounted in-lexical-order of their mountPoint. | Mount all the partitions from GlobalStorage and from the job configuration.
Partitions are mounted in-lexical-order of their mountPoint. | [
"Mount",
"all",
"the",
"partitions",
"from",
"GlobalStorage",
"and",
"from",
"the",
"job",
"configuration",
".",
"Partitions",
"are",
"mounted",
"in",
"-",
"lexical",
"-",
"order",
"of",
"their",
"mountPoint",
"."
] | def run():
"""
Mount all the partitions from GlobalStorage and from the job configuration.
Partitions are mounted in-lexical-order of their mountPoint.
"""
partitions = libcalamares.globalstorage.value("partitions")
if not partitions:
libcalamares.utils.warning("partitions is empty, {!s}".format(partitions))
return (_("Configuration Error"),
_("No partitions are defined for <pre>{!s}</pre> to use.").format("mount"))
root_mount_point = tempfile.mkdtemp(prefix="calamares-root-")
# Guard against missing keys (generally a sign that the config file is bad)
extra_mounts = libcalamares.job.configuration.get("extraMounts") or []
extra_mounts_efi = libcalamares.job.configuration.get("extraMountsEfi") or []
if not extra_mounts and not extra_mounts_efi:
libcalamares.utils.warning("No extra mounts defined. Does mount.conf exist?")
if libcalamares.globalstorage.value("firmwareType") == "efi":
extra_mounts.extend(extra_mounts_efi)
# Add extra mounts to the partitions list and sort by mount points.
# This way, we ensure / is mounted before the rest, and every mount point
# is created on the right partition (e.g. if a partition is to be mounted
# under /tmp, we make sure /tmp is mounted before the partition)
mountable_partitions = [p for p in partitions + extra_mounts if "mountPoint" in p and p["mountPoint"]]
mountable_partitions.sort(key=lambda x: x["mountPoint"])
try:
for partition in mountable_partitions:
mount_partition(root_mount_point, partition, partitions)
except ZfsException as ze:
return _("zfs mounting error"), ze.message
libcalamares.globalstorage.insert("rootMountPoint", root_mount_point)
# Remember the extra mounts for the unpackfs module
libcalamares.globalstorage.insert("extraMounts", extra_mounts) | [
"def",
"run",
"(",
")",
":",
"partitions",
"=",
"libcalamares",
".",
"globalstorage",
".",
"value",
"(",
"\"partitions\"",
")",
"if",
"not",
"partitions",
":",
"libcalamares",
".",
"utils",
".",
"warning",
"(",
"\"partitions is empty, {!s}\"",
".",
"format",
"(",
"partitions",
")",
")",
"return",
"(",
"_",
"(",
"\"Configuration Error\"",
")",
",",
"_",
"(",
"\"No partitions are defined for <pre>{!s}</pre> to use.\"",
")",
".",
"format",
"(",
"\"mount\"",
")",
")",
"root_mount_point",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"\"calamares-root-\"",
")",
"# Guard against missing keys (generally a sign that the config file is bad)",
"extra_mounts",
"=",
"libcalamares",
".",
"job",
".",
"configuration",
".",
"get",
"(",
"\"extraMounts\"",
")",
"or",
"[",
"]",
"extra_mounts_efi",
"=",
"libcalamares",
".",
"job",
".",
"configuration",
".",
"get",
"(",
"\"extraMountsEfi\"",
")",
"or",
"[",
"]",
"if",
"not",
"extra_mounts",
"and",
"not",
"extra_mounts_efi",
":",
"libcalamares",
".",
"utils",
".",
"warning",
"(",
"\"No extra mounts defined. Does mount.conf exist?\"",
")",
"if",
"libcalamares",
".",
"globalstorage",
".",
"value",
"(",
"\"firmwareType\"",
")",
"==",
"\"efi\"",
":",
"extra_mounts",
".",
"extend",
"(",
"extra_mounts_efi",
")",
"# Add extra mounts to the partitions list and sort by mount points.",
"# This way, we ensure / is mounted before the rest, and every mount point",
"# is created on the right partition (e.g. if a partition is to be mounted",
"# under /tmp, we make sure /tmp is mounted before the partition)",
"mountable_partitions",
"=",
"[",
"p",
"for",
"p",
"in",
"partitions",
"+",
"extra_mounts",
"if",
"\"mountPoint\"",
"in",
"p",
"and",
"p",
"[",
"\"mountPoint\"",
"]",
"]",
"mountable_partitions",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"\"mountPoint\"",
"]",
")",
"try",
":",
"for",
"partition",
"in",
"mountable_partitions",
":",
"mount_partition",
"(",
"root_mount_point",
",",
"partition",
",",
"partitions",
")",
"except",
"ZfsException",
"as",
"ze",
":",
"return",
"_",
"(",
"\"zfs mounting error\"",
")",
",",
"ze",
".",
"message",
"libcalamares",
".",
"globalstorage",
".",
"insert",
"(",
"\"rootMountPoint\"",
",",
"root_mount_point",
")",
"# Remember the extra mounts for the unpackfs module",
"libcalamares",
".",
"globalstorage",
".",
"insert",
"(",
"\"extraMounts\"",
",",
"extra_mounts",
")"
] | https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/mount/main.py#L220-L258 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/guiutility.py | python | get_value | (parent=None) | return value, result == QDialog.Accepted | Get value from a pop-up dialog
:param parent:
:return: | Get value from a pop-up dialog
:param parent:
:return: | [
"Get",
"value",
"from",
"a",
"pop",
"-",
"up",
"dialog",
":",
"param",
"parent",
":",
":",
"return",
":"
] | def get_value(parent=None):
""" Get value from a pop-up dialog
:param parent:
:return:
"""
dialog = GetValueDialog(parent)
result = dialog.exec_()
value = dialog.get_value()
return value, result == QDialog.Accepted | [
"def",
"get_value",
"(",
"parent",
"=",
"None",
")",
":",
"dialog",
"=",
"GetValueDialog",
"(",
"parent",
")",
"result",
"=",
"dialog",
".",
"exec_",
"(",
")",
"value",
"=",
"dialog",
".",
"get_value",
"(",
")",
"return",
"value",
",",
"result",
"==",
"QDialog",
".",
"Accepted"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/guiutility.py#L508-L517 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntIntVH.GetKeyDatPrV | (self, *args) | return _snap.TIntIntVH_GetKeyDatPrV(self, *args) | GetKeyDatPrV(TIntIntVH self, TVec< TPair< TInt,TVec< TInt,int > > > & KeyDatPrV)
Parameters:
KeyDatPrV: TVec< TPair< TInt,TVec< TInt,int > > > & | GetKeyDatPrV(TIntIntVH self, TVec< TPair< TInt,TVec< TInt,int > > > & KeyDatPrV) | [
"GetKeyDatPrV",
"(",
"TIntIntVH",
"self",
"TVec<",
"TPair<",
"TInt",
"TVec<",
"TInt",
"int",
">",
">",
">",
"&",
"KeyDatPrV",
")"
] | def GetKeyDatPrV(self, *args):
"""
GetKeyDatPrV(TIntIntVH self, TVec< TPair< TInt,TVec< TInt,int > > > & KeyDatPrV)
Parameters:
KeyDatPrV: TVec< TPair< TInt,TVec< TInt,int > > > &
"""
return _snap.TIntIntVH_GetKeyDatPrV(self, *args) | [
"def",
"GetKeyDatPrV",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntIntVH_GetKeyDatPrV",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L18058-L18066 | |
dartsim/dart | 495c82120c836005f2d136d4a50c8cc997fb879b | tools/cpplint.py | python | CheckCStyleCast | (filename, linenum, line, raw_line, cast_type, pattern,
error) | return True | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise. | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C",
"-",
"style",
"cast",
"by",
"looking",
"for",
"the",
"pattern",
"."
] | def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
match = Search(pattern, line)
if not match:
return False
# Exclude lines with sizeof, since sizeof looks like a cast.
sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
if sizeof_match:
return False
# operator++(int) and operator--(int)
if (line[0:match.start(1) - 1].endswith(' operator++') or
line[0:match.start(1) - 1].endswith(' operator--')):
return False
# A single unnamed argument for a function tends to look like old
# style cast. If we see those, don't issue warnings for deprecated
# casts, instead issue warnings for unnamed arguments where
# appropriate.
#
# These are things that we want warnings for, since the style guide
# explicitly require all parameters to be named:
# Function(int);
# Function(int) {
# ConstMember(int) const;
# ConstMember(int) const {
# ExceptionMember(int) throw (...);
# ExceptionMember(int) throw (...) {
# PureVirtual(int) = 0;
#
# These are functions of some sort, where the compiler would be fine
# if they had named parameters, but people often omit those
# identifiers to reduce clutter:
# (FunctionPointer)(int);
# (FunctionPointer)(int) = value;
# Function((function_pointer_arg)(int))
# <TemplateArgument(int)>;
# <(FunctionPointerTemplateArgument)(int)>;
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder):
# Looks like an unnamed parameter.
# Don't warn on any kind of template arguments.
if Match(r'^\s*>', remainder):
return False
# Don't warn on assignments to function pointers, but keep warnings for
# unnamed parameters to pure virtual functions. Note that this pattern
# will also pass on assignments of "0" to function pointers, but the
# preferred values for those would be "nullptr" or "NULL".
matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
if matched_zero and matched_zero.group(1) != '0':
return False
# Don't warn on function pointer declarations. For this we need
# to check what came before the "(type)" string.
if Match(r'.*\)\s*$', line[0:match.start(0)]):
return False
# Don't warn if the parameter is named with block comments, e.g.:
# Function(int /*unused_param*/);
if '/*' in raw_line:
return False
# Passed all filters, issue warning here.
error(filename, linenum, 'readability/function', 3,
'All parameters should be named in a function')
return True
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True | [
"def",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"raw_line",
",",
"cast_type",
",",
"pattern",
",",
"error",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"not",
"match",
":",
"return",
"False",
"# Exclude lines with sizeof, since sizeof looks like a cast.",
"sizeof_match",
"=",
"Match",
"(",
"r'.*sizeof\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
")",
"if",
"sizeof_match",
":",
"return",
"False",
"# operator++(int) and operator--(int)",
"if",
"(",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
".",
"endswith",
"(",
"' operator++'",
")",
"or",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
".",
"endswith",
"(",
"' operator--'",
")",
")",
":",
"return",
"False",
"# A single unnamed argument for a function tends to look like old",
"# style cast. If we see those, don't issue warnings for deprecated",
"# casts, instead issue warnings for unnamed arguments where",
"# appropriate.",
"#",
"# These are things that we want warnings for, since the style guide",
"# explicitly require all parameters to be named:",
"# Function(int);",
"# Function(int) {",
"# ConstMember(int) const;",
"# ConstMember(int) const {",
"# ExceptionMember(int) throw (...);",
"# ExceptionMember(int) throw (...) {",
"# PureVirtual(int) = 0;",
"#",
"# These are functions of some sort, where the compiler would be fine",
"# if they had named parameters, but people often omit those",
"# identifiers to reduce clutter:",
"# (FunctionPointer)(int);",
"# (FunctionPointer)(int) = value;",
"# Function((function_pointer_arg)(int))",
"# <TemplateArgument(int)>;",
"# <(FunctionPointerTemplateArgument)(int)>;",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"0",
")",
":",
"]",
"if",
"Match",
"(",
"r'^\\s*(?:;|const\\b|throw\\b|=|>|\\{|\\))'",
",",
"remainder",
")",
":",
"# Looks like an unnamed parameter.",
"# Don't warn on any kind of template arguments.",
"if",
"Match",
"(",
"r'^\\s*>'",
",",
"remainder",
")",
":",
"return",
"False",
"# Don't warn on assignments to function pointers, but keep warnings for",
"# unnamed parameters to pure virtual functions. Note that this pattern",
"# will also pass on assignments of \"0\" to function pointers, but the",
"# preferred values for those would be \"nullptr\" or \"NULL\".",
"matched_zero",
"=",
"Match",
"(",
"r'^\\s=\\s*(\\S+)\\s*;'",
",",
"remainder",
")",
"if",
"matched_zero",
"and",
"matched_zero",
".",
"group",
"(",
"1",
")",
"!=",
"'0'",
":",
"return",
"False",
"# Don't warn on function pointer declarations. For this we need",
"# to check what came before the \"(type)\" string.",
"if",
"Match",
"(",
"r'.*\\)\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"0",
")",
"]",
")",
":",
"return",
"False",
"# Don't warn if the parameter is named with block comments, e.g.:",
"# Function(int /*unused_param*/);",
"if",
"'/*'",
"in",
"raw_line",
":",
"return",
"False",
"# Passed all filters, issue warning here.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/function'",
",",
"3",
",",
"'All parameters should be named in a function'",
")",
"return",
"True",
"# At this point, all that should be left is actual casts.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using C-style cast. Use %s<%s>(...) instead'",
"%",
"(",
"cast_type",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"return",
"True"
] | https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/tools/cpplint.py#L4150-L4241 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/GardenSnake/GardenSnake.py | python | t_WS | (t) | r' [ ]+ | r' [ ]+ | [
"r",
"[",
"]",
"+"
] | def t_WS(t):
r' [ ]+ '
if t.lexer.at_line_start and t.lexer.paren_count == 0:
return t | [
"def",
"t_WS",
"(",
"t",
")",
":",
"if",
"t",
".",
"lexer",
".",
"at_line_start",
"and",
"t",
".",
"lexer",
".",
"paren_count",
"==",
"0",
":",
"return",
"t"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/GardenSnake/GardenSnake.py#L120-L123 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/CoSimulationApplication/python_scripts/base_classes/co_simulation_convergence_accelerator.py | python | CoSimulationConvergenceAccelerator.PrintInfo | (self) | Function to print Info abt the Object
Can be overridden in derived classes to print more information | Function to print Info abt the Object
Can be overridden in derived classes to print more information | [
"Function",
"to",
"print",
"Info",
"abt",
"the",
"Object",
"Can",
"be",
"overridden",
"in",
"derived",
"classes",
"to",
"print",
"more",
"information"
] | def PrintInfo(self):
'''Function to print Info abt the Object
Can be overridden in derived classes to print more information
'''
cs_tools.cs_print_info("Convergence Accelerator", colors.bold(self._ClassName())) | [
"def",
"PrintInfo",
"(",
"self",
")",
":",
"cs_tools",
".",
"cs_print_info",
"(",
"\"Convergence Accelerator\"",
",",
"colors",
".",
"bold",
"(",
"self",
".",
"_ClassName",
"(",
")",
")",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/CoSimulationApplication/python_scripts/base_classes/co_simulation_convergence_accelerator.py#L39-L43 | ||
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/recognizers.py | python | BaseRecognizer.getGrammarFileName | (self) | return self.grammarFileName | For debugging and other purposes, might want the grammar name.
Have ANTLR generate an implementation for this method. | For debugging and other purposes, might want the grammar name.
Have ANTLR generate an implementation for this method. | [
"For",
"debugging",
"and",
"other",
"purposes",
"might",
"want",
"the",
"grammar",
"name",
".",
"Have",
"ANTLR",
"generate",
"an",
"implementation",
"for",
"this",
"method",
"."
] | def getGrammarFileName(self):
"""For debugging and other purposes, might want the grammar name.
Have ANTLR generate an implementation for this method.
"""
return self.grammarFileName | [
"def",
"getGrammarFileName",
"(",
"self",
")",
":",
"return",
"self",
".",
"grammarFileName"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/recognizers.py#L927-L933 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/mapmatching/wxgui.py | python | WxGui.on_plot_alternative_routes | (self, event=None) | Plot alternative route results in Matplotlib plotting envitonment. | Plot alternative route results in Matplotlib plotting envitonment. | [
"Plot",
"alternative",
"route",
"results",
"in",
"Matplotlib",
"plotting",
"envitonment",
"."
] | def on_plot_alternative_routes(self, event=None):
"""
Plot alternative route results in Matplotlib plotting envitonment.
"""
if is_mpl:
resultplotter = results_mpl.AlternativeRoutesPlotter(self._results,
logger=self._mainframe.get_logger()
)
dlg = results_mpl.ResultDialog(self._mainframe, resultplotter)
dlg.CenterOnScreen()
# this does not return until the dialog is closed.
val = dlg.ShowModal()
# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
# print ' status =',dlg.get_status()
if dlg.get_status() != 'success': # val == wx.ID_CANCEL:
# print ">>>>>>>>>Unsuccessful\n"
dlg.Destroy()
if dlg.get_status() == 'success':
# print ">>>>>>>>>successful\n"
# apply current widget values to scenario instance
dlg.apply()
dlg.Destroy() | [
"def",
"on_plot_alternative_routes",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"is_mpl",
":",
"resultplotter",
"=",
"results_mpl",
".",
"AlternativeRoutesPlotter",
"(",
"self",
".",
"_results",
",",
"logger",
"=",
"self",
".",
"_mainframe",
".",
"get_logger",
"(",
")",
")",
"dlg",
"=",
"results_mpl",
".",
"ResultDialog",
"(",
"self",
".",
"_mainframe",
",",
"resultplotter",
")",
"dlg",
".",
"CenterOnScreen",
"(",
")",
"# this does not return until the dialog is closed.",
"val",
"=",
"dlg",
".",
"ShowModal",
"(",
")",
"# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL",
"# print ' status =',dlg.get_status()",
"if",
"dlg",
".",
"get_status",
"(",
")",
"!=",
"'success'",
":",
"# val == wx.ID_CANCEL:",
"# print \">>>>>>>>>Unsuccessful\\n\"",
"dlg",
".",
"Destroy",
"(",
")",
"if",
"dlg",
".",
"get_status",
"(",
")",
"==",
"'success'",
":",
"# print \">>>>>>>>>successful\\n\"",
"# apply current widget values to scenario instance",
"dlg",
".",
"apply",
"(",
")",
"dlg",
".",
"Destroy",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/mapmatching/wxgui.py#L844-L868 | ||
KDE/krita | 10ea63984e00366865769c193ab298de73a59c5c | plugins/python/channels2layers/channels2layers.py | python | ChannelsToLayers.run | (self) | Run process for current layer | Run process for current layer | [
"Run",
"process",
"for",
"current",
"layer"
] | def run(self):
"""Run process for current layer"""
pdlgProgress = QProgressDialog(self.__outputOptions['outputMode'], None, 0, 100, Application.activeWindow().qwindow())
pdlgProgress.setWindowTitle(PLUGIN_DIALOG_TITLE)
pdlgProgress.setMinimumSize(640, 200)
pdlgProgress.setModal(True)
pdlgProgress.show()
self.process(self.__sourceDocument, self.__sourceLayer, pdlgProgress)
pdlgProgress.close() | [
"def",
"run",
"(",
"self",
")",
":",
"pdlgProgress",
"=",
"QProgressDialog",
"(",
"self",
".",
"__outputOptions",
"[",
"'outputMode'",
"]",
",",
"None",
",",
"0",
",",
"100",
",",
"Application",
".",
"activeWindow",
"(",
")",
".",
"qwindow",
"(",
")",
")",
"pdlgProgress",
".",
"setWindowTitle",
"(",
"PLUGIN_DIALOG_TITLE",
")",
"pdlgProgress",
".",
"setMinimumSize",
"(",
"640",
",",
"200",
")",
"pdlgProgress",
".",
"setModal",
"(",
"True",
")",
"pdlgProgress",
".",
"show",
"(",
")",
"self",
".",
"process",
"(",
"self",
".",
"__sourceDocument",
",",
"self",
".",
"__sourceLayer",
",",
"pdlgProgress",
")",
"pdlgProgress",
".",
"close",
"(",
")"
] | https://github.com/KDE/krita/blob/10ea63984e00366865769c193ab298de73a59c5c/plugins/python/channels2layers/channels2layers.py#L1190-L1201 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/ops.py | python | Operation._set_device | (self, device) | Set the device of this operation.
Args:
device: string or device.. The device to set. | Set the device of this operation. | [
"Set",
"the",
"device",
"of",
"this",
"operation",
"."
] | def _set_device(self, device):
"""Set the device of this operation.
Args:
device: string or device.. The device to set.
"""
self._node_def.device = _device_string(device) | [
"def",
"_set_device",
"(",
"self",
",",
"device",
")",
":",
"self",
".",
"_node_def",
".",
"device",
"=",
"_device_string",
"(",
"device",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L1310-L1316 | ||
Netflix/NfWebCrypto | 499faf4eb9f9ccf0b21dc728e974970f54bd6c52 | plugin/ppapi/ppapi/cpp/documentation/doxy_cleanup.py | python | HTMLFixer.FixTableHeadings | (self) | Fixes the doxygen table headings.
This includes:
- Using bare <h2> title row instead of row embedded in <tr><td> in table
- Putting the "name" attribute into the "id" attribute of the <tr> tag.
- Splitting up tables into multiple separate tables if a table
heading appears in the middle of a table.
For example, this html:
<table>
<tr><td colspan="2"><h2><a name="pub-attribs"></a>
Data Fields List</h2></td></tr>
...
</table>
would be converted to this:
<h2>Data Fields List</h2>
<table>
...
</table> | Fixes the doxygen table headings. | [
"Fixes",
"the",
"doxygen",
"table",
"headings",
"."
] | def FixTableHeadings(self):
'''Fixes the doxygen table headings.
This includes:
- Using bare <h2> title row instead of row embedded in <tr><td> in table
- Putting the "name" attribute into the "id" attribute of the <tr> tag.
- Splitting up tables into multiple separate tables if a table
heading appears in the middle of a table.
For example, this html:
<table>
<tr><td colspan="2"><h2><a name="pub-attribs"></a>
Data Fields List</h2></td></tr>
...
</table>
would be converted to this:
<h2>Data Fields List</h2>
<table>
...
</table>
'''
table_headers = []
for tag in self.soup.findAll('tr'):
if tag.td and tag.td.h2 and tag.td.h2.a and tag.td.h2.a['name']:
#tag['id'] = tag.td.h2.a['name']
tag.string = tag.td.h2.a.next
tag.name = 'h2'
table_headers.append(tag)
# reverse the list so that earlier tags don't delete later tags
table_headers.reverse()
# Split up tables that have multiple table header (th) rows
for tag in table_headers:
print "Header tag: %s is %s" % (tag.name, tag.string.strip())
# Is this a heading in the middle of a table?
if tag.findPreviousSibling('tr') and tag.parent.name == 'table':
print "Splitting Table named %s" % tag.string.strip()
table = tag.parent
table_parent = table.parent
table_index = table_parent.contents.index(table)
new_table = Tag(self.soup, name='table', attrs=table.attrs)
table_parent.insert(table_index + 1, new_table)
tag_index = table.contents.index(tag)
for index, row in enumerate(table.contents[tag_index:]):
new_table.insert(index, row)
# Now move the <h2> tag to be in front of the <table> tag
assert tag.parent.name == 'table'
table = tag.parent
table_parent = table.parent
table_index = table_parent.contents.index(table)
table_parent.insert(table_index, tag) | [
"def",
"FixTableHeadings",
"(",
"self",
")",
":",
"table_headers",
"=",
"[",
"]",
"for",
"tag",
"in",
"self",
".",
"soup",
".",
"findAll",
"(",
"'tr'",
")",
":",
"if",
"tag",
".",
"td",
"and",
"tag",
".",
"td",
".",
"h2",
"and",
"tag",
".",
"td",
".",
"h2",
".",
"a",
"and",
"tag",
".",
"td",
".",
"h2",
".",
"a",
"[",
"'name'",
"]",
":",
"#tag['id'] = tag.td.h2.a['name']",
"tag",
".",
"string",
"=",
"tag",
".",
"td",
".",
"h2",
".",
"a",
".",
"next",
"tag",
".",
"name",
"=",
"'h2'",
"table_headers",
".",
"append",
"(",
"tag",
")",
"# reverse the list so that earlier tags don't delete later tags",
"table_headers",
".",
"reverse",
"(",
")",
"# Split up tables that have multiple table header (th) rows",
"for",
"tag",
"in",
"table_headers",
":",
"print",
"\"Header tag: %s is %s\"",
"%",
"(",
"tag",
".",
"name",
",",
"tag",
".",
"string",
".",
"strip",
"(",
")",
")",
"# Is this a heading in the middle of a table?",
"if",
"tag",
".",
"findPreviousSibling",
"(",
"'tr'",
")",
"and",
"tag",
".",
"parent",
".",
"name",
"==",
"'table'",
":",
"print",
"\"Splitting Table named %s\"",
"%",
"tag",
".",
"string",
".",
"strip",
"(",
")",
"table",
"=",
"tag",
".",
"parent",
"table_parent",
"=",
"table",
".",
"parent",
"table_index",
"=",
"table_parent",
".",
"contents",
".",
"index",
"(",
"table",
")",
"new_table",
"=",
"Tag",
"(",
"self",
".",
"soup",
",",
"name",
"=",
"'table'",
",",
"attrs",
"=",
"table",
".",
"attrs",
")",
"table_parent",
".",
"insert",
"(",
"table_index",
"+",
"1",
",",
"new_table",
")",
"tag_index",
"=",
"table",
".",
"contents",
".",
"index",
"(",
"tag",
")",
"for",
"index",
",",
"row",
"in",
"enumerate",
"(",
"table",
".",
"contents",
"[",
"tag_index",
":",
"]",
")",
":",
"new_table",
".",
"insert",
"(",
"index",
",",
"row",
")",
"# Now move the <h2> tag to be in front of the <table> tag",
"assert",
"tag",
".",
"parent",
".",
"name",
"==",
"'table'",
"table",
"=",
"tag",
".",
"parent",
"table_parent",
"=",
"table",
".",
"parent",
"table_index",
"=",
"table_parent",
".",
"contents",
".",
"index",
"(",
"table",
")",
"table_parent",
".",
"insert",
"(",
"table_index",
",",
"tag",
")"
] | https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/cpp/documentation/doxy_cleanup.py#L33-L85 | ||
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/win/Source/bin/jinja2/filters.py | python | do_int | (value, default=0) | Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. | Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. | [
"Convert",
"the",
"value",
"into",
"an",
"integer",
".",
"If",
"the",
"conversion",
"doesn",
"t",
"work",
"it",
"will",
"return",
"0",
".",
"You",
"can",
"override",
"this",
"default",
"using",
"the",
"first",
"parameter",
"."
] | def do_int(value, default=0):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter.
"""
try:
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
return int(float(value))
except (TypeError, ValueError):
return default | [
"def",
"do_int",
"(",
"value",
",",
"default",
"=",
"0",
")",
":",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"# this quirk is necessary so that \"42.23\"|int gives 42.",
"try",
":",
"return",
"int",
"(",
"float",
"(",
"value",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/filters.py#L398-L410 | ||
sailing-pmls/pmls-caffe | 49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a | scripts/cpp_lint.py | python | CheckSpacingForFunctionCall | (filename, line, linenum, error) | Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for the correctness of various spacing around function calls. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"around",
"function",
"calls",
"."
] | def CheckSpacingForFunctionCall(filename, line, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'#\s*define|typedef', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )') | [
"def",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"line",
",",
"linenum",
",",
"error",
")",
":",
"# Since function calls often occur inside if/for/while/switch",
"# expressions - which have their own, more liberal conventions - we",
"# first see if we should be looking inside such an expression for a",
"# function call, to which we can apply more strict standards.",
"fncall",
"=",
"line",
"# if there's no control flow construct, look at whole line",
"for",
"pattern",
"in",
"(",
"r'\\bif\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bfor\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'",
",",
"r'\\bswitch\\s*\\((.*)\\)\\s*{'",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"match",
":",
"fncall",
"=",
"match",
".",
"group",
"(",
"1",
")",
"# look inside the parens for function calls",
"break",
"# Except in if/for/while/switch, there should never be space",
"# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception",
"# for nested parens ( (a+b) + c ). Likewise, there should never be",
"# a space before a ( when it's a function argument. I assume it's a",
"# function argument when the char before the whitespace is legal in",
"# a function name (alnum + _) and we're not starting a macro. Also ignore",
"# pointers and references to arrays and functions coz they're too tricky:",
"# we use a very simple way to recognize these:",
"# \" (something)(maybe-something)\" or",
"# \" (something)(maybe-something,\" or",
"# \" (something)[something]\"",
"# Note that we assume the contents of [] to be short enough that",
"# they'll never need to wrap.",
"if",
"(",
"# Ignore control structures.",
"not",
"Search",
"(",
"r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to functions.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\([^)]*(\\)|,$)'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to arrays.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\[[^\\]]+\\]'",
",",
"fncall",
")",
")",
":",
"if",
"Search",
"(",
"r'\\w\\s*\\(\\s(?!\\s*\\\\$)'",
",",
"fncall",
")",
":",
"# a ( used for a fn call",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space after ( in function call'",
")",
"elif",
"Search",
"(",
"r'\\(\\s+(?!(\\s*\\\\)|\\()'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space after ('",
")",
"if",
"(",
"Search",
"(",
"r'\\w\\s+\\('",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'#\\s*define|typedef'",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('",
",",
"fncall",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space before ( in function call'",
")",
"# If the ) is followed only by a newline or a { + newline, assume it's",
"# part of a control statement (if/while/etc), and don't complain",
"if",
"Search",
"(",
"r'[^)]\\s+\\)\\s*[^{\\s]'",
",",
"fncall",
")",
":",
"# If the closing parenthesis is preceded by only whitespaces,",
"# try to give a more descriptive error message.",
"if",
"Search",
"(",
"r'^\\s+\\)'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Closing ) should be moved to the previous line'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space before )'",
")"
] | https://github.com/sailing-pmls/pmls-caffe/blob/49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a/scripts/cpp_lint.py#L2301-L2366 | ||
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | docs/generate_thumbnails.py | python | search_and_replace | (filename, fromString, toString) | Search and replace string in a file. | Search and replace string in a file. | [
"Search",
"and",
"replace",
"string",
"in",
"a",
"file",
"."
] | def search_and_replace(filename, fromString, toString):
"""Search and replace string in a file."""
with open(filename, 'r') as file:
data = file.read()
data = data.replace(fromString, toString)
with open(filename, 'w') as file:
file.write(data) | [
"def",
"search_and_replace",
"(",
"filename",
",",
"fromString",
",",
"toString",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"file",
":",
"data",
"=",
"file",
".",
"read",
"(",
")",
"data",
"=",
"data",
".",
"replace",
"(",
"fromString",
",",
"toString",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"data",
")"
] | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/docs/generate_thumbnails.py#L24-L30 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/ppo/utility.py | python | diag_normal_kl | (mean0, logstd0, mean1, logstd1) | return 0.5 * (tf.reduce_sum(tf.exp(logstd0_2 - logstd1_2), -1) + tf.reduce_sum(
(mean1 - mean0)**2 / tf.exp(logstd1_2), -1) + tf.reduce_sum(logstd1_2, -1) -
tf.reduce_sum(logstd0_2, -1) - mean0.shape[-1].value) | Epirical KL divergence of two normals with diagonal covariance. | Epirical KL divergence of two normals with diagonal covariance. | [
"Epirical",
"KL",
"divergence",
"of",
"two",
"normals",
"with",
"diagonal",
"covariance",
"."
] | def diag_normal_kl(mean0, logstd0, mean1, logstd1):
"""Epirical KL divergence of two normals with diagonal covariance."""
logstd0_2, logstd1_2 = 2 * logstd0, 2 * logstd1
return 0.5 * (tf.reduce_sum(tf.exp(logstd0_2 - logstd1_2), -1) + tf.reduce_sum(
(mean1 - mean0)**2 / tf.exp(logstd1_2), -1) + tf.reduce_sum(logstd1_2, -1) -
tf.reduce_sum(logstd0_2, -1) - mean0.shape[-1].value) | [
"def",
"diag_normal_kl",
"(",
"mean0",
",",
"logstd0",
",",
"mean1",
",",
"logstd1",
")",
":",
"logstd0_2",
",",
"logstd1_2",
"=",
"2",
"*",
"logstd0",
",",
"2",
"*",
"logstd1",
"return",
"0.5",
"*",
"(",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"exp",
"(",
"logstd0_2",
"-",
"logstd1_2",
")",
",",
"-",
"1",
")",
"+",
"tf",
".",
"reduce_sum",
"(",
"(",
"mean1",
"-",
"mean0",
")",
"**",
"2",
"/",
"tf",
".",
"exp",
"(",
"logstd1_2",
")",
",",
"-",
"1",
")",
"+",
"tf",
".",
"reduce_sum",
"(",
"logstd1_2",
",",
"-",
"1",
")",
"-",
"tf",
".",
"reduce_sum",
"(",
"logstd0_2",
",",
"-",
"1",
")",
"-",
"mean0",
".",
"shape",
"[",
"-",
"1",
"]",
".",
"value",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/ppo/utility.py#L124-L129 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/scons_helper.py | python | create_fast_link_builders | (env) | Creates fast link builders - Program and SharedLibrary. | Creates fast link builders - Program and SharedLibrary. | [
"Creates",
"fast",
"link",
"builders",
"-",
"Program",
"and",
"SharedLibrary",
"."
] | def create_fast_link_builders(env):
"""Creates fast link builders - Program and SharedLibrary. """
# Check requirement
acquire_temp_place = "df | grep tmpfs | awk '{print $5, $6}'"
p = subprocess.Popen(
acquire_temp_place,
env=os.environ,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
universal_newlines=True)
std_out, std_err = p.communicate()
# Do not try to overwrite builder with error
if p.returncode:
console.warning('you have link on tmp enabled, but it is not fullfilled to make it.')
return
# No tmpfs to do fastlink, will not overwrite the builder
if not std_out:
console.warning('you have link on tmp enabled, but there is no tmpfs to make it.')
return
# Use the first one
global linking_tmp_dir
usage, linking_tmp_dir = tuple(std_out.splitlines(False)[0].split())
# Do not try to do that if there is no memory space left
usage = int(usage.replace('%', ''))
if usage > 90:
console.warning('you have link on tmp enabled, '
'but there is not enough space on %s to make it.' %
linking_tmp_dir)
return
console.info('building in link on tmpfs mode')
create_fast_link_sharelib_builder(env)
create_fast_link_prog_builder(env) | [
"def",
"create_fast_link_builders",
"(",
"env",
")",
":",
"# Check requirement",
"acquire_temp_place",
"=",
"\"df | grep tmpfs | awk '{print $5, $6}'\"",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"acquire_temp_place",
",",
"env",
"=",
"os",
".",
"environ",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"True",
",",
"universal_newlines",
"=",
"True",
")",
"std_out",
",",
"std_err",
"=",
"p",
".",
"communicate",
"(",
")",
"# Do not try to overwrite builder with error",
"if",
"p",
".",
"returncode",
":",
"console",
".",
"warning",
"(",
"'you have link on tmp enabled, but it is not fullfilled to make it.'",
")",
"return",
"# No tmpfs to do fastlink, will not overwrite the builder",
"if",
"not",
"std_out",
":",
"console",
".",
"warning",
"(",
"'you have link on tmp enabled, but there is no tmpfs to make it.'",
")",
"return",
"# Use the first one",
"global",
"linking_tmp_dir",
"usage",
",",
"linking_tmp_dir",
"=",
"tuple",
"(",
"std_out",
".",
"splitlines",
"(",
"False",
")",
"[",
"0",
"]",
".",
"split",
"(",
")",
")",
"# Do not try to do that if there is no memory space left",
"usage",
"=",
"int",
"(",
"usage",
".",
"replace",
"(",
"'%'",
",",
"''",
")",
")",
"if",
"usage",
">",
"90",
":",
"console",
".",
"warning",
"(",
"'you have link on tmp enabled, '",
"'but there is not enough space on %s to make it.'",
"%",
"linking_tmp_dir",
")",
"return",
"console",
".",
"info",
"(",
"'building in link on tmpfs mode'",
")",
"create_fast_link_sharelib_builder",
"(",
"env",
")",
"create_fast_link_prog_builder",
"(",
"env",
")"
] | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/scons_helper.py#L401-L439 | ||
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/dox/proc_doc.py | python | splitSecondLevelEntry | (name) | return (None, name) | Split second-level entry and return (first, second) pair.
If name is not a second level entry then (None, name) is returned. | Split second-level entry and return (first, second) pair. | [
"Split",
"second",
"-",
"level",
"entry",
"and",
"return",
"(",
"first",
"second",
")",
"pair",
"."
] | def splitSecondLevelEntry(name):
"""Split second-level entry and return (first, second) pair.
If name is not a second level entry then (None, name) is returned.
"""
xs = None
if name.count('::') > 1 and ' ' in name:
xs = name.split(' ', 1)
elif '#' in name:
xs = name.split('#', 1)
elif '::' in name:
xs = name.rsplit('::', 1)
if xs:
return xs
return (None, name) | [
"def",
"splitSecondLevelEntry",
"(",
"name",
")",
":",
"xs",
"=",
"None",
"if",
"name",
".",
"count",
"(",
"'::'",
")",
">",
"1",
"and",
"' '",
"in",
"name",
":",
"xs",
"=",
"name",
".",
"split",
"(",
"' '",
",",
"1",
")",
"elif",
"'#'",
"in",
"name",
":",
"xs",
"=",
"name",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"elif",
"'::'",
"in",
"name",
":",
"xs",
"=",
"name",
".",
"rsplit",
"(",
"'::'",
",",
"1",
")",
"if",
"xs",
":",
"return",
"xs",
"return",
"(",
"None",
",",
"name",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/proc_doc.py#L43-L57 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/experiment.py | python | Experiment._has_training_stopped | (self, eval_result) | return global_step and self._train_steps and (
global_step >= self._train_steps) | Determines whether the training has stopped. | Determines whether the training has stopped. | [
"Determines",
"whether",
"the",
"training",
"has",
"stopped",
"."
] | def _has_training_stopped(self, eval_result):
"""Determines whether the training has stopped."""
if not eval_result:
return False
global_step = eval_result.get(ops.GraphKeys.GLOBAL_STEP)
return global_step and self._train_steps and (
global_step >= self._train_steps) | [
"def",
"_has_training_stopped",
"(",
"self",
",",
"eval_result",
")",
":",
"if",
"not",
"eval_result",
":",
"return",
"False",
"global_step",
"=",
"eval_result",
".",
"get",
"(",
"ops",
".",
"GraphKeys",
".",
"GLOBAL_STEP",
")",
"return",
"global_step",
"and",
"self",
".",
"_train_steps",
"and",
"(",
"global_step",
">=",
"self",
".",
"_train_steps",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/experiment.py#L519-L526 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py | python | IMAP4.send | (self, data) | Send data to remote. | Send data to remote. | [
"Send",
"data",
"to",
"remote",
"."
] | def send(self, data):
"""Send data to remote."""
self.sock.sendall(data) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py#L316-L318 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/optimizer/optimizer.py | python | Optimizer._add_accumulator | (self,
name,
param,
dtype=None,
fill_value=0.0,
shape=None,
type=None,
device=None) | return var | Utility function to add an accumulator for a parameter
Args:
block: the block in which the loss tensor is present
name: name of the accumulator
param: parameter tensor for which accumulator is to be added
dtype: data type of the accumulator tensor
fill_value: value to initialize the accumulator tensor | Utility function to add an accumulator for a parameter | [
"Utility",
"function",
"to",
"add",
"an",
"accumulator",
"for",
"a",
"parameter"
] | def _add_accumulator(self,
name,
param,
dtype=None,
fill_value=0.0,
shape=None,
type=None,
device=None):
"""Utility function to add an accumulator for a parameter
Args:
block: the block in which the loss tensor is present
name: name of the accumulator
param: parameter tensor for which accumulator is to be added
dtype: data type of the accumulator tensor
fill_value: value to initialize the accumulator tensor
"""
if self._name is not None:
name = self._name + "_" + name
if (name in self._accumulators and
param.name in self._accumulators[name]):
if framework.in_dygraph_mode():
return self._accumulators[name][param.name]
raise Exception("Accumulator {} already exists for parameter {}".
format(name, param.name))
if shape == None:
shape = param.shape
assert isinstance(self.helper, LayerHelper)
var_name = param.name + "_" + name
var_name = unique_name.generate(var_name)
self._opti_name_list.append(var_name)
var = self.helper.create_global_variable(
name=var_name,
persistable=True,
dtype=dtype or param.dtype,
type=core.VarDesc.VarType.LOD_TENSOR
if framework._in_eager_mode() else (param.type
if type is None else type),
shape=shape,
belong_to_optimizer=True)
if device is None:
device = self._get_device_for_param(param.name)
with device_guard(device):
self.helper.set_variable_initializer(
var, initializer=Constant(value=float(fill_value)))
if framework.in_dygraph_mode():
if len(self._accumulators_holder) > 0:
assert var_name in self._accumulators_holder, \
"Optimizer set error, {} should in state dict".format( var_name )
var.set_value(self._accumulators_holder[var_name])
self._accumulators[name][param.name] = var
return var | [
"def",
"_add_accumulator",
"(",
"self",
",",
"name",
",",
"param",
",",
"dtype",
"=",
"None",
",",
"fill_value",
"=",
"0.0",
",",
"shape",
"=",
"None",
",",
"type",
"=",
"None",
",",
"device",
"=",
"None",
")",
":",
"if",
"self",
".",
"_name",
"is",
"not",
"None",
":",
"name",
"=",
"self",
".",
"_name",
"+",
"\"_\"",
"+",
"name",
"if",
"(",
"name",
"in",
"self",
".",
"_accumulators",
"and",
"param",
".",
"name",
"in",
"self",
".",
"_accumulators",
"[",
"name",
"]",
")",
":",
"if",
"framework",
".",
"in_dygraph_mode",
"(",
")",
":",
"return",
"self",
".",
"_accumulators",
"[",
"name",
"]",
"[",
"param",
".",
"name",
"]",
"raise",
"Exception",
"(",
"\"Accumulator {} already exists for parameter {}\"",
".",
"format",
"(",
"name",
",",
"param",
".",
"name",
")",
")",
"if",
"shape",
"==",
"None",
":",
"shape",
"=",
"param",
".",
"shape",
"assert",
"isinstance",
"(",
"self",
".",
"helper",
",",
"LayerHelper",
")",
"var_name",
"=",
"param",
".",
"name",
"+",
"\"_\"",
"+",
"name",
"var_name",
"=",
"unique_name",
".",
"generate",
"(",
"var_name",
")",
"self",
".",
"_opti_name_list",
".",
"append",
"(",
"var_name",
")",
"var",
"=",
"self",
".",
"helper",
".",
"create_global_variable",
"(",
"name",
"=",
"var_name",
",",
"persistable",
"=",
"True",
",",
"dtype",
"=",
"dtype",
"or",
"param",
".",
"dtype",
",",
"type",
"=",
"core",
".",
"VarDesc",
".",
"VarType",
".",
"LOD_TENSOR",
"if",
"framework",
".",
"_in_eager_mode",
"(",
")",
"else",
"(",
"param",
".",
"type",
"if",
"type",
"is",
"None",
"else",
"type",
")",
",",
"shape",
"=",
"shape",
",",
"belong_to_optimizer",
"=",
"True",
")",
"if",
"device",
"is",
"None",
":",
"device",
"=",
"self",
".",
"_get_device_for_param",
"(",
"param",
".",
"name",
")",
"with",
"device_guard",
"(",
"device",
")",
":",
"self",
".",
"helper",
".",
"set_variable_initializer",
"(",
"var",
",",
"initializer",
"=",
"Constant",
"(",
"value",
"=",
"float",
"(",
"fill_value",
")",
")",
")",
"if",
"framework",
".",
"in_dygraph_mode",
"(",
")",
":",
"if",
"len",
"(",
"self",
".",
"_accumulators_holder",
")",
">",
"0",
":",
"assert",
"var_name",
"in",
"self",
".",
"_accumulators_holder",
",",
"\"Optimizer set error, {} should in state dict\"",
".",
"format",
"(",
"var_name",
")",
"var",
".",
"set_value",
"(",
"self",
".",
"_accumulators_holder",
"[",
"var_name",
"]",
")",
"self",
".",
"_accumulators",
"[",
"name",
"]",
"[",
"param",
".",
"name",
"]",
"=",
"var",
"return",
"var"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/optimizer/optimizer.py#L569-L624 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/combo.py | python | ComboPopup.GetStringValue | (*args, **kwargs) | return _combo.ComboPopup_GetStringValue(*args, **kwargs) | GetStringValue(self) -> String
Gets the string representation of the currently selected value to be
used to display in the combo widget. | GetStringValue(self) -> String | [
"GetStringValue",
"(",
"self",
")",
"-",
">",
"String"
] | def GetStringValue(*args, **kwargs):
"""
GetStringValue(self) -> String
Gets the string representation of the currently selected value to be
used to display in the combo widget.
"""
return _combo.ComboPopup_GetStringValue(*args, **kwargs) | [
"def",
"GetStringValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"ComboPopup_GetStringValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L677-L684 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | SimRobotController.setPIDCommand | (self, *args) | return _robotsim.SimRobotController_setPIDCommand(self, *args) | r"""
Sets a PID command controller. If tfeedforward is provided, it is the
feedforward torque vector.
setPIDCommand (qdes,dqdes)
setPIDCommand (qdes,dqdes,tfeedforward)
Args:
qdes (:obj:`list of floats`):
dqdes (:obj:`list of floats`):
tfeedforward (:obj:`list of floats`, optional): | r"""
Sets a PID command controller. If tfeedforward is provided, it is the
feedforward torque vector. | [
"r",
"Sets",
"a",
"PID",
"command",
"controller",
".",
"If",
"tfeedforward",
"is",
"provided",
"it",
"is",
"the",
"feedforward",
"torque",
"vector",
"."
] | def setPIDCommand(self, *args) ->None:
r"""
Sets a PID command controller. If tfeedforward is provided, it is the
feedforward torque vector.
setPIDCommand (qdes,dqdes)
setPIDCommand (qdes,dqdes,tfeedforward)
Args:
qdes (:obj:`list of floats`):
dqdes (:obj:`list of floats`):
tfeedforward (:obj:`list of floats`, optional):
"""
return _robotsim.SimRobotController_setPIDCommand(self, *args) | [
"def",
"setPIDCommand",
"(",
"self",
",",
"*",
"args",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"SimRobotController_setPIDCommand",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7323-L7338 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/basic.py | python | load_auto_suggestion_bindings | () | return registry | Key bindings for accepting auto suggestion text. | Key bindings for accepting auto suggestion text. | [
"Key",
"bindings",
"for",
"accepting",
"auto",
"suggestion",
"text",
"."
] | def load_auto_suggestion_bindings():
"""
Key bindings for accepting auto suggestion text.
"""
registry = Registry()
handle = registry.add_binding
suggestion_available = Condition(
lambda cli:
cli.current_buffer.suggestion is not None and
cli.current_buffer.document.is_cursor_at_the_end)
@handle(Keys.ControlF, filter=suggestion_available)
@handle(Keys.ControlE, filter=suggestion_available)
@handle(Keys.Right, filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
return registry | [
"def",
"load_auto_suggestion_bindings",
"(",
")",
":",
"registry",
"=",
"Registry",
"(",
")",
"handle",
"=",
"registry",
".",
"add_binding",
"suggestion_available",
"=",
"Condition",
"(",
"lambda",
"cli",
":",
"cli",
".",
"current_buffer",
".",
"suggestion",
"is",
"not",
"None",
"and",
"cli",
".",
"current_buffer",
".",
"document",
".",
"is_cursor_at_the_end",
")",
"@",
"handle",
"(",
"Keys",
".",
"ControlF",
",",
"filter",
"=",
"suggestion_available",
")",
"@",
"handle",
"(",
"Keys",
".",
"ControlE",
",",
"filter",
"=",
"suggestion_available",
")",
"@",
"handle",
"(",
"Keys",
".",
"Right",
",",
"filter",
"=",
"suggestion_available",
")",
"def",
"_",
"(",
"event",
")",
":",
"\" Accept suggestion. \"",
"b",
"=",
"event",
".",
"current_buffer",
"suggestion",
"=",
"b",
".",
"suggestion",
"if",
"suggestion",
":",
"b",
".",
"insert_text",
"(",
"suggestion",
".",
"text",
")",
"return",
"registry"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/basic.py#L384-L407 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Action.py | python | Action | (act, *args, **kw) | return _do_create_action(act, kw) | A factory for action objects. | A factory for action objects. | [
"A",
"factory",
"for",
"action",
"objects",
"."
] | def Action(act, *args, **kw):
"""A factory for action objects."""
# Really simple: the _do_create_* routines do the heavy lifting.
_do_create_keywords(args, kw)
if is_List(act):
return _do_create_list_action(act, kw)
return _do_create_action(act, kw) | [
"def",
"Action",
"(",
"act",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Really simple: the _do_create_* routines do the heavy lifting.",
"_do_create_keywords",
"(",
"args",
",",
"kw",
")",
"if",
"is_List",
"(",
"act",
")",
":",
"return",
"_do_create_list_action",
"(",
"act",
",",
"kw",
")",
"return",
"_do_create_action",
"(",
"act",
",",
"kw",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Action.py#L401-L407 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py | python | run_bootstrap | (conf) | Execute the bootstrap process
:param conf: Configuration context | Execute the bootstrap process | [
"Execute",
"the",
"bootstrap",
"process"
] | def run_bootstrap(conf):
"""
Execute the bootstrap process
:param conf: Configuration context
"""
# Deprecated
# Bootstrap is only ran within the engine folder
if not conf.is_engine_local():
return
conf.run_linkless_bootstrap() | [
"def",
"run_bootstrap",
"(",
"conf",
")",
":",
"# Deprecated",
"# Bootstrap is only ran within the engine folder",
"if",
"not",
"conf",
".",
"is_engine_local",
"(",
")",
":",
"return",
"conf",
".",
"run_linkless_bootstrap",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py#L344-L356 | ||
synfig/synfig | a5ec91db5b751dc12e4400ccfb5c063fd6d2d928 | synfig-studio/plugins/lottie-exporter/common/ActivepointList.py | python | ActivepointList.amount_at_time | (self, frame, rising = None) | return float((next_itr.time - frame)/(next_itr.time - prev_itr.time)) | https://github.com/synfig/synfig/blob/15607089680af560ad031465d31878425af927eb/synfig-core/src/synfig/valuenodes/valuenode_dynamiclist.cpp#L394 | https://github.com/synfig/synfig/blob/15607089680af560ad031465d31878425af927eb/synfig-core/src/synfig/valuenodes/valuenode_dynamiclist.cpp#L394 | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"synfig",
"/",
"synfig",
"/",
"blob",
"/",
"15607089680af560ad031465d31878425af927eb",
"/",
"synfig",
"-",
"core",
"/",
"src",
"/",
"synfig",
"/",
"valuenodes",
"/",
"valuenode_dynamiclist",
".",
"cpp#L394"
] | def amount_at_time(self, frame, rising = None):
"""
https://github.com/synfig/synfig/blob/15607089680af560ad031465d31878425af927eb/synfig-core/src/synfig/valuenodes/valuenode_dynamiclist.cpp#L394
"""
if self.empty():
return 1
try:
itr = self.find(frame)
return 1 if itr.state else 0
except Exception as e:
pass
try:
prev_itr = self.find_prev(frame)
except Exception as e:
return 1 if self.find_next(frame).state else 0
try:
next_itr = self.find_next(frame)
except Exception as e:
return 1 if prev_itr.state else 0
if next_itr.state == prev_itr.state:
return 1 if next_itr.state else 0
if rising is not None:
rising[0] = next_itr.state
if next_itr.state == True:
return float((frame - prev_itr.time)/(next_itr.time - prev_itr.time))
return float((next_itr.time - frame)/(next_itr.time - prev_itr.time)) | [
"def",
"amount_at_time",
"(",
"self",
",",
"frame",
",",
"rising",
"=",
"None",
")",
":",
"if",
"self",
".",
"empty",
"(",
")",
":",
"return",
"1",
"try",
":",
"itr",
"=",
"self",
".",
"find",
"(",
"frame",
")",
"return",
"1",
"if",
"itr",
".",
"state",
"else",
"0",
"except",
"Exception",
"as",
"e",
":",
"pass",
"try",
":",
"prev_itr",
"=",
"self",
".",
"find_prev",
"(",
"frame",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"1",
"if",
"self",
".",
"find_next",
"(",
"frame",
")",
".",
"state",
"else",
"0",
"try",
":",
"next_itr",
"=",
"self",
".",
"find_next",
"(",
"frame",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"1",
"if",
"prev_itr",
".",
"state",
"else",
"0",
"if",
"next_itr",
".",
"state",
"==",
"prev_itr",
".",
"state",
":",
"return",
"1",
"if",
"next_itr",
".",
"state",
"else",
"0",
"if",
"rising",
"is",
"not",
"None",
":",
"rising",
"[",
"0",
"]",
"=",
"next_itr",
".",
"state",
"if",
"next_itr",
".",
"state",
"==",
"True",
":",
"return",
"float",
"(",
"(",
"frame",
"-",
"prev_itr",
".",
"time",
")",
"/",
"(",
"next_itr",
".",
"time",
"-",
"prev_itr",
".",
"time",
")",
")",
"return",
"float",
"(",
"(",
"next_itr",
".",
"time",
"-",
"frame",
")",
"/",
"(",
"next_itr",
".",
"time",
"-",
"prev_itr",
".",
"time",
")",
")"
] | https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/ActivepointList.py#L89-L120 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/dataclasses.py | python | _is_dataclass_instance | (obj) | return hasattr(type(obj), _FIELDS) | Returns True if obj is an instance of a dataclass. | Returns True if obj is an instance of a dataclass. | [
"Returns",
"True",
"if",
"obj",
"is",
"an",
"instance",
"of",
"a",
"dataclass",
"."
] | def _is_dataclass_instance(obj):
"""Returns True if obj is an instance of a dataclass."""
return hasattr(type(obj), _FIELDS) | [
"def",
"_is_dataclass_instance",
"(",
"obj",
")",
":",
"return",
"hasattr",
"(",
"type",
"(",
"obj",
")",
",",
"_FIELDS",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/dataclasses.py#L1031-L1033 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/distutils/command/config.py | python | config.check_func | (self, func,
headers=None, include_dirs=None,
libraries=None, library_dirs=None,
decl=0, call=0) | return self.try_link(body, headers, include_dirs,
libraries, library_dirs) | Determine if function 'func' is available by constructing a
source file that refers to 'func', and compiles and links it.
If everything succeeds, returns true; otherwise returns false.
The constructed source file starts out by including the header
files listed in 'headers'. If 'decl' is true, it then declares
'func' (as "int func()"); you probably shouldn't supply 'headers'
and set 'decl' true in the same call, or you might get errors about
a conflicting declarations for 'func'. Finally, the constructed
'main()' function either references 'func' or (if 'call' is true)
calls it. 'libraries' and 'library_dirs' are used when
linking. | Determine if function 'func' is available by constructing a
source file that refers to 'func', and compiles and links it.
If everything succeeds, returns true; otherwise returns false. | [
"Determine",
"if",
"function",
"func",
"is",
"available",
"by",
"constructing",
"a",
"source",
"file",
"that",
"refers",
"to",
"func",
"and",
"compiles",
"and",
"links",
"it",
".",
"If",
"everything",
"succeeds",
"returns",
"true",
";",
"otherwise",
"returns",
"false",
"."
] | def check_func (self, func,
headers=None, include_dirs=None,
libraries=None, library_dirs=None,
decl=0, call=0):
"""Determine if function 'func' is available by constructing a
source file that refers to 'func', and compiles and links it.
If everything succeeds, returns true; otherwise returns false.
The constructed source file starts out by including the header
files listed in 'headers'. If 'decl' is true, it then declares
'func' (as "int func()"); you probably shouldn't supply 'headers'
and set 'decl' true in the same call, or you might get errors about
a conflicting declarations for 'func'. Finally, the constructed
'main()' function either references 'func' or (if 'call' is true)
calls it. 'libraries' and 'library_dirs' are used when
linking.
"""
self._check_compiler()
body = []
if decl:
body.append("int %s ();" % func)
body.append("int main () {")
if call:
body.append(" %s();" % func)
else:
body.append(" %s;" % func)
body.append("}")
body = string.join(body, "\n") + "\n"
return self.try_link(body, headers, include_dirs,
libraries, library_dirs) | [
"def",
"check_func",
"(",
"self",
",",
"func",
",",
"headers",
"=",
"None",
",",
"include_dirs",
"=",
"None",
",",
"libraries",
"=",
"None",
",",
"library_dirs",
"=",
"None",
",",
"decl",
"=",
"0",
",",
"call",
"=",
"0",
")",
":",
"self",
".",
"_check_compiler",
"(",
")",
"body",
"=",
"[",
"]",
"if",
"decl",
":",
"body",
".",
"append",
"(",
"\"int %s ();\"",
"%",
"func",
")",
"body",
".",
"append",
"(",
"\"int main () {\"",
")",
"if",
"call",
":",
"body",
".",
"append",
"(",
"\" %s();\"",
"%",
"func",
")",
"else",
":",
"body",
".",
"append",
"(",
"\" %s;\"",
"%",
"func",
")",
"body",
".",
"append",
"(",
"\"}\"",
")",
"body",
"=",
"string",
".",
"join",
"(",
"body",
",",
"\"\\n\"",
")",
"+",
"\"\\n\"",
"return",
"self",
".",
"try_link",
"(",
"body",
",",
"headers",
",",
"include_dirs",
",",
"libraries",
",",
"library_dirs",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/command/config.py#L296-L328 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/packages/ordered_dict.py | python | OrderedDict.update | (*args, **kwds) | od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v | od.update(E, **F) -> None. Update od from dict/iterable E and F. | [
"od",
".",
"update",
"(",
"E",
"**",
"F",
")",
"-",
">",
"None",
".",
"Update",
"od",
"from",
"dict",
"/",
"iterable",
"E",
"and",
"F",
"."
] | def update(*args, **kwds):
'''od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v
'''
if len(args) > 2:
raise TypeError('update() takes at most 2 positional '
'arguments (%d given)' % (len(args),))
elif not args:
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
# Make progressively weaker assumptions about "other"
other = ()
if len(args) == 2:
other = args[1]
if isinstance(other, dict):
for key in other:
self[key] = other[key]
elif hasattr(other, 'keys'):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value | [
"def",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"TypeError",
"(",
"'update() takes at most 2 positional '",
"'arguments (%d given)'",
"%",
"(",
"len",
"(",
"args",
")",
",",
")",
")",
"elif",
"not",
"args",
":",
"raise",
"TypeError",
"(",
"'update() takes at least 1 argument (0 given)'",
")",
"self",
"=",
"args",
"[",
"0",
"]",
"# Make progressively weaker assumptions about \"other\"",
"other",
"=",
"(",
")",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"other",
"=",
"args",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"other",
",",
"dict",
")",
":",
"for",
"key",
"in",
"other",
":",
"self",
"[",
"key",
"]",
"=",
"other",
"[",
"key",
"]",
"elif",
"hasattr",
"(",
"other",
",",
"'keys'",
")",
":",
"for",
"key",
"in",
"other",
".",
"keys",
"(",
")",
":",
"self",
"[",
"key",
"]",
"=",
"other",
"[",
"key",
"]",
"else",
":",
"for",
"key",
",",
"value",
"in",
"other",
":",
"self",
"[",
"key",
"]",
"=",
"value",
"for",
"key",
",",
"value",
"in",
"kwds",
".",
"items",
"(",
")",
":",
"self",
"[",
"key",
"]",
"=",
"value"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/packages/ordered_dict.py#L142-L171 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/tools/wrappers.py | python | ConvertTo32Bit.__getattr__ | (self, name) | return getattr(self._env, name) | Forward unimplemented attributes to the original environment.
Args:
name: Attribute that was accessed.
Returns:
Value behind the attribute name in the wrapped environment. | Forward unimplemented attributes to the original environment. | [
"Forward",
"unimplemented",
"attributes",
"to",
"the",
"original",
"environment",
"."
] | def __getattr__(self, name):
"""Forward unimplemented attributes to the original environment.
Args:
name: Attribute that was accessed.
Returns:
Value behind the attribute name in the wrapped environment.
"""
return getattr(self._env, name) | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"_env",
",",
"name",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/tools/wrappers.py#L486-L495 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/contrib/slim/quantization/imperative/ptq_registry.py | python | PTQRegistry.is_registered_layer | (cls, layer) | return layer in cls.registered_layers_map or \
isinstance(layer, tuple(cls.registered_layers_map.keys())) | Analyze whether the layer is register layer_info.
Args:
layer(Layer): The input layer can be a python class or an instance.
Returns:
flag(bool): Wether the layer is register layer_info. | Analyze whether the layer is register layer_info.
Args:
layer(Layer): The input layer can be a python class or an instance.
Returns:
flag(bool): Wether the layer is register layer_info. | [
"Analyze",
"whether",
"the",
"layer",
"is",
"register",
"layer_info",
".",
"Args",
":",
"layer",
"(",
"Layer",
")",
":",
"The",
"input",
"layer",
"can",
"be",
"a",
"python",
"class",
"or",
"an",
"instance",
".",
"Returns",
":",
"flag",
"(",
"bool",
")",
":",
"Wether",
"the",
"layer",
"is",
"register",
"layer_info",
"."
] | def is_registered_layer(cls, layer):
"""
Analyze whether the layer is register layer_info.
Args:
layer(Layer): The input layer can be a python class or an instance.
Returns:
flag(bool): Wether the layer is register layer_info.
"""
cls._init()
return layer in cls.registered_layers_map or \
isinstance(layer, tuple(cls.registered_layers_map.keys())) | [
"def",
"is_registered_layer",
"(",
"cls",
",",
"layer",
")",
":",
"cls",
".",
"_init",
"(",
")",
"return",
"layer",
"in",
"cls",
".",
"registered_layers_map",
"or",
"isinstance",
"(",
"layer",
",",
"tuple",
"(",
"cls",
".",
"registered_layers_map",
".",
"keys",
"(",
")",
")",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/slim/quantization/imperative/ptq_registry.py#L96-L106 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/pybind11/pybind11/setup_helpers.py | python | tmp_chdir | () | Prepare and enter a temporary directory, cleanup when done | Prepare and enter a temporary directory, cleanup when done | [
"Prepare",
"and",
"enter",
"a",
"temporary",
"directory",
"cleanup",
"when",
"done"
] | def tmp_chdir():
"Prepare and enter a temporary directory, cleanup when done"
# Threadsafe
with tmp_chdir_lock:
olddir = os.getcwd()
try:
tmpdir = tempfile.mkdtemp()
os.chdir(tmpdir)
yield tmpdir
finally:
os.chdir(olddir)
shutil.rmtree(tmpdir) | [
"def",
"tmp_chdir",
"(",
")",
":",
"# Threadsafe",
"with",
"tmp_chdir_lock",
":",
"olddir",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"os",
".",
"chdir",
"(",
"tmpdir",
")",
"yield",
"tmpdir",
"finally",
":",
"os",
".",
"chdir",
"(",
"olddir",
")",
"shutil",
".",
"rmtree",
"(",
"tmpdir",
")"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/pybind11/pybind11/setup_helpers.py#L216-L228 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/cpplint_1.4.5/cpplint.py | python | ProcessConfigOverrides | (filename) | return True | Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further. | Loads the configuration files and processes the config overrides. | [
"Loads",
"the",
"configuration",
"files",
"and",
"processes",
"the",
"config",
"overrides",
"."
] | def ProcessConfigOverrides(filename):
""" Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further.
"""
abs_filename = os.path.abspath(filename)
cfg_filters = []
keep_looking = True
while keep_looking:
abs_path, base_name = os.path.split(abs_filename)
if not base_name:
break # Reached the root directory.
cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
abs_filename = abs_path
if not os.path.isfile(cfg_file):
continue
try:
with open(cfg_file) as file_handle:
for line in file_handle:
line, _, _ = line.partition('#') # Remove comments.
if not line.strip():
continue
name, _, val = line.partition('=')
name = name.strip()
val = val.strip()
if name == 'set noparent':
keep_looking = False
elif name == 'filter':
cfg_filters.append(val)
elif name == 'exclude_files':
# When matching exclude_files pattern, use the base_name of
# the current file name or the directory name we are processing.
# For example, if we are checking for lint errors in /foo/bar/baz.cc
# and we found the .cfg file at /foo/CPPLINT.cfg, then the config
# file's "exclude_files" filter is meant to be checked against "bar"
# and not "baz" nor "bar/baz.cc".
if base_name:
pattern = re.compile(val)
if pattern.match(base_name):
if _cpplint_state.quiet:
# Suppress "Ignoring file" warning when using --quiet.
return False
_cpplint_state.PrintInfo('Ignoring "%s": file excluded by "%s". '
'File path component "%s" matches '
'pattern "%s"\n' %
(filename, cfg_file, base_name, val))
return False
elif name == 'linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
_cpplint_state.PrintError('Line length must be numeric.')
elif name == 'extensions':
ProcessExtensionsOption(val)
elif name == 'root':
global _root
# root directories are specified relative to CPPLINT.cfg dir.
_root = os.path.join(os.path.dirname(cfg_file), val)
elif name == 'headers':
ProcessHppHeadersOption(val)
else:
_cpplint_state.PrintError(
'Invalid configuration option (%s) in file %s\n' %
(name, cfg_file))
except IOError:
_cpplint_state.PrintError(
"Skipping config file '%s': Can't open for reading\n" % cfg_file)
keep_looking = False
# Apply all the accumulated filters in reverse order (top-level directory
# config options having the least priority).
for cfg_filter in reversed(cfg_filters):
_AddFilters(cfg_filter)
return True | [
"def",
"ProcessConfigOverrides",
"(",
"filename",
")",
":",
"abs_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"cfg_filters",
"=",
"[",
"]",
"keep_looking",
"=",
"True",
"while",
"keep_looking",
":",
"abs_path",
",",
"base_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"abs_filename",
")",
"if",
"not",
"base_name",
":",
"break",
"# Reached the root directory.",
"cfg_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"abs_path",
",",
"\"CPPLINT.cfg\"",
")",
"abs_filename",
"=",
"abs_path",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"cfg_file",
")",
":",
"continue",
"try",
":",
"with",
"open",
"(",
"cfg_file",
")",
"as",
"file_handle",
":",
"for",
"line",
"in",
"file_handle",
":",
"line",
",",
"_",
",",
"_",
"=",
"line",
".",
"partition",
"(",
"'#'",
")",
"# Remove comments.",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"continue",
"name",
",",
"_",
",",
"val",
"=",
"line",
".",
"partition",
"(",
"'='",
")",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"val",
"=",
"val",
".",
"strip",
"(",
")",
"if",
"name",
"==",
"'set noparent'",
":",
"keep_looking",
"=",
"False",
"elif",
"name",
"==",
"'filter'",
":",
"cfg_filters",
".",
"append",
"(",
"val",
")",
"elif",
"name",
"==",
"'exclude_files'",
":",
"# When matching exclude_files pattern, use the base_name of",
"# the current file name or the directory name we are processing.",
"# For example, if we are checking for lint errors in /foo/bar/baz.cc",
"# and we found the .cfg file at /foo/CPPLINT.cfg, then the config",
"# file's \"exclude_files\" filter is meant to be checked against \"bar\"",
"# and not \"baz\" nor \"bar/baz.cc\".",
"if",
"base_name",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"val",
")",
"if",
"pattern",
".",
"match",
"(",
"base_name",
")",
":",
"if",
"_cpplint_state",
".",
"quiet",
":",
"# Suppress \"Ignoring file\" warning when using --quiet.",
"return",
"False",
"_cpplint_state",
".",
"PrintInfo",
"(",
"'Ignoring \"%s\": file excluded by \"%s\". '",
"'File path component \"%s\" matches '",
"'pattern \"%s\"\\n'",
"%",
"(",
"filename",
",",
"cfg_file",
",",
"base_name",
",",
"val",
")",
")",
"return",
"False",
"elif",
"name",
"==",
"'linelength'",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"_cpplint_state",
".",
"PrintError",
"(",
"'Line length must be numeric.'",
")",
"elif",
"name",
"==",
"'extensions'",
":",
"ProcessExtensionsOption",
"(",
"val",
")",
"elif",
"name",
"==",
"'root'",
":",
"global",
"_root",
"# root directories are specified relative to CPPLINT.cfg dir.",
"_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"cfg_file",
")",
",",
"val",
")",
"elif",
"name",
"==",
"'headers'",
":",
"ProcessHppHeadersOption",
"(",
"val",
")",
"else",
":",
"_cpplint_state",
".",
"PrintError",
"(",
"'Invalid configuration option (%s) in file %s\\n'",
"%",
"(",
"name",
",",
"cfg_file",
")",
")",
"except",
"IOError",
":",
"_cpplint_state",
".",
"PrintError",
"(",
"\"Skipping config file '%s': Can't open for reading\\n\"",
"%",
"cfg_file",
")",
"keep_looking",
"=",
"False",
"# Apply all the accumulated filters in reverse order (top-level directory",
"# config options having the least priority).",
"for",
"cfg_filter",
"in",
"reversed",
"(",
"cfg_filters",
")",
":",
"_AddFilters",
"(",
"cfg_filter",
")",
"return",
"True"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/cpplint_1.4.5/cpplint.py#L6232-L6316 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Rect.GetHeight | (*args, **kwargs) | return _core_.Rect_GetHeight(*args, **kwargs) | GetHeight(self) -> int | GetHeight(self) -> int | [
"GetHeight",
"(",
"self",
")",
"-",
">",
"int"
] | def GetHeight(*args, **kwargs):
"""GetHeight(self) -> int"""
return _core_.Rect_GetHeight(*args, **kwargs) | [
"def",
"GetHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect_GetHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1293-L1295 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/mvctree.py | python | TextConverter.Convert | (node) | Should return a string. The node argument will be an
MVCTreeNode. | Should return a string. The node argument will be an
MVCTreeNode. | [
"Should",
"return",
"a",
"string",
".",
"The",
"node",
"argument",
"will",
"be",
"an",
"MVCTreeNode",
"."
] | def Convert(node):
"""
Should return a string. The node argument will be an
MVCTreeNode.
"""
raise NotImplementedError | [
"def",
"Convert",
"(",
"node",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/mvctree.py#L312-L317 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | PreListView | (*args, **kwargs) | return val | PreListView() -> ListView | PreListView() -> ListView | [
"PreListView",
"()",
"-",
">",
"ListView"
] | def PreListView(*args, **kwargs):
"""PreListView() -> ListView"""
val = _controls_.new_PreListView(*args, **kwargs)
return val | [
"def",
"PreListView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_controls_",
".",
"new_PreListView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4943-L4946 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/multiprocessing/connection.py | python | _ConnectionBase.recv | (self) | return _ForkingPickler.loads(buf.getbuffer()) | Receive a (picklable) object | Receive a (picklable) object | [
"Receive",
"a",
"(",
"picklable",
")",
"object"
] | def recv(self):
"""Receive a (picklable) object"""
self._check_closed()
self._check_readable()
buf = self._recv_bytes()
return _ForkingPickler.loads(buf.getbuffer()) | [
"def",
"recv",
"(",
"self",
")",
":",
"self",
".",
"_check_closed",
"(",
")",
"self",
".",
"_check_readable",
"(",
")",
"buf",
"=",
"self",
".",
"_recv_bytes",
"(",
")",
"return",
"_ForkingPickler",
".",
"loads",
"(",
"buf",
".",
"getbuffer",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/connection.py#L251-L256 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/upload.py | python | UploadNonSeekableInputManager._wrap_data | (self, data, callbacks, close_callbacks) | return self._osutil.open_file_chunk_reader_from_fileobj(
fileobj=fileobj, chunk_size=len(data), full_file_size=len(data),
callbacks=callbacks, close_callbacks=close_callbacks) | Wraps data with the interrupt reader and the file chunk reader.
:type data: bytes
:param data: The data to wrap.
:type callbacks: list
:param callbacks: The callbacks associated with the transfer future.
:type close_callbacks: list
:param close_callbacks: The callbacks to be called when closing the
wrapper for the data.
:return: Fully wrapped data. | Wraps data with the interrupt reader and the file chunk reader. | [
"Wraps",
"data",
"with",
"the",
"interrupt",
"reader",
"and",
"the",
"file",
"chunk",
"reader",
"."
] | def _wrap_data(self, data, callbacks, close_callbacks):
"""
Wraps data with the interrupt reader and the file chunk reader.
:type data: bytes
:param data: The data to wrap.
:type callbacks: list
:param callbacks: The callbacks associated with the transfer future.
:type close_callbacks: list
:param close_callbacks: The callbacks to be called when closing the
wrapper for the data.
:return: Fully wrapped data.
"""
fileobj = self._wrap_fileobj(six.BytesIO(data))
return self._osutil.open_file_chunk_reader_from_fileobj(
fileobj=fileobj, chunk_size=len(data), full_file_size=len(data),
callbacks=callbacks, close_callbacks=close_callbacks) | [
"def",
"_wrap_data",
"(",
"self",
",",
"data",
",",
"callbacks",
",",
"close_callbacks",
")",
":",
"fileobj",
"=",
"self",
".",
"_wrap_fileobj",
"(",
"six",
".",
"BytesIO",
"(",
"data",
")",
")",
"return",
"self",
".",
"_osutil",
".",
"open_file_chunk_reader_from_fileobj",
"(",
"fileobj",
"=",
"fileobj",
",",
"chunk_size",
"=",
"len",
"(",
"data",
")",
",",
"full_file_size",
"=",
"len",
"(",
"data",
")",
",",
"callbacks",
"=",
"callbacks",
",",
"close_callbacks",
"=",
"close_callbacks",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/upload.py#L463-L482 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/writer.py | python | encode_plain | (data, se) | PLAIN encoding; returns byte representation | PLAIN encoding; returns byte representation | [
"PLAIN",
"encoding",
";",
"returns",
"byte",
"representation"
] | def encode_plain(data, se):
"""PLAIN encoding; returns byte representation"""
out = convert(data, se)
if se.type == parquet_thrift.Type.BYTE_ARRAY:
return pack_byte_array(list(out))
else:
return out.tobytes() | [
"def",
"encode_plain",
"(",
"data",
",",
"se",
")",
":",
"out",
"=",
"convert",
"(",
"data",
",",
"se",
")",
"if",
"se",
".",
"type",
"==",
"parquet_thrift",
".",
"Type",
".",
"BYTE_ARRAY",
":",
"return",
"pack_byte_array",
"(",
"list",
"(",
"out",
")",
")",
"else",
":",
"return",
"out",
".",
"tobytes",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fastparquet/writer.py#L250-L256 | ||
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/json_format.py | python | _FieldToJsonObject | (
field, value, including_default_value_fields=False) | return value | Converts field value according to Proto3 JSON Specification. | Converts field value according to Proto3 JSON Specification. | [
"Converts",
"field",
"value",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | def _FieldToJsonObject(
field, value, including_default_value_fields=False):
"""Converts field value according to Proto3 JSON Specification."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return _MessageToJsonObject(value, including_default_value_fields)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
else:
raise SerializeToJsonError('Enum field contains an integer value '
'which can not mapped to an enum value.')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
# Use base64 Data encoding for bytes
return base64.b64encode(value).decode('utf-8')
else:
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return bool(value)
elif field.cpp_type in _INT64_TYPES:
return str(value)
elif field.cpp_type in _FLOAT_TYPES:
if math.isinf(value):
if value < 0.0:
return _NEG_INFINITY
else:
return _INFINITY
if math.isnan(value):
return _NAN
return value | [
"def",
"_FieldToJsonObject",
"(",
"field",
",",
"value",
",",
"including_default_value_fields",
"=",
"False",
")",
":",
"if",
"field",
".",
"cpp_type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"return",
"_MessageToJsonObject",
"(",
"value",
",",
"including_default_value_fields",
")",
"elif",
"field",
".",
"cpp_type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"CPPTYPE_ENUM",
":",
"enum_value",
"=",
"field",
".",
"enum_type",
".",
"values_by_number",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"enum_value",
"is",
"not",
"None",
":",
"return",
"enum_value",
".",
"name",
"else",
":",
"raise",
"SerializeToJsonError",
"(",
"'Enum field contains an integer value '",
"'which can not mapped to an enum value.'",
")",
"elif",
"field",
".",
"cpp_type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"CPPTYPE_STRING",
":",
"if",
"field",
".",
"type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"TYPE_BYTES",
":",
"# Use base64 Data encoding for bytes",
"return",
"base64",
".",
"b64encode",
"(",
"value",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"value",
"elif",
"field",
".",
"cpp_type",
"==",
"descriptor",
".",
"FieldDescriptor",
".",
"CPPTYPE_BOOL",
":",
"return",
"bool",
"(",
"value",
")",
"elif",
"field",
".",
"cpp_type",
"in",
"_INT64_TYPES",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"field",
".",
"cpp_type",
"in",
"_FLOAT_TYPES",
":",
"if",
"math",
".",
"isinf",
"(",
"value",
")",
":",
"if",
"value",
"<",
"0.0",
":",
"return",
"_NEG_INFINITY",
"else",
":",
"return",
"_INFINITY",
"if",
"math",
".",
"isnan",
"(",
"value",
")",
":",
"return",
"_NAN",
"return",
"value"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/json_format.py#L174-L204 | |
googleprojectzero/functionsimsearch | ec5d9e1224ff915b3dc9e7af19e21e110c25239c | pybindings/binary_ninja_plugin/modules/main.py | python | Plugin.save_all_functions | (self, bv, _) | Walk through all functions and save them into the index. | Walk through all functions and save them into the index. | [
"Walk",
"through",
"all",
"functions",
"and",
"save",
"them",
"into",
"the",
"index",
"."
] | def save_all_functions(self, bv, _):
"""
Walk through all functions and save them into the index.
"""
search_index = self.init_index(bv)
for function in bv.functions:
self.save_single_function_hash(bv, search_index, function, False)
self.metadata.__save__() | [
"def",
"save_all_functions",
"(",
"self",
",",
"bv",
",",
"_",
")",
":",
"search_index",
"=",
"self",
".",
"init_index",
"(",
"bv",
")",
"for",
"function",
"in",
"bv",
".",
"functions",
":",
"self",
".",
"save_single_function_hash",
"(",
"bv",
",",
"search_index",
",",
"function",
",",
"False",
")",
"self",
".",
"metadata",
".",
"__save__",
"(",
")"
] | https://github.com/googleprojectzero/functionsimsearch/blob/ec5d9e1224ff915b3dc9e7af19e21e110c25239c/pybindings/binary_ninja_plugin/modules/main.py#L159-L166 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.