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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/lite/python/tflite_keras_util.py | python | _create_pseudo_names | (tensors, prefix) | return names | Creates pseudo {input | output} names for subclassed Models.
Warning: this function should only be used to define default
names for `Metics` and `SavedModel`. No other use cases should
rely on a `Model`'s input or output names.
Example with dict:
`{'a': [x1, x2], 'b': x3}` becomes:
`['a_1', 'a_2', 'b']`
Example with list:
`[x, y]` becomes:
`['output_1', 'output_2']`
Args:
tensors: `Model`'s outputs or inputs.
prefix: 'output_' for outputs, 'input_' for inputs.
Returns:
Flattened list of pseudo names. | Creates pseudo {input | output} names for subclassed Models. | [
"Creates",
"pseudo",
"{",
"input",
"|",
"output",
"}",
"names",
"for",
"subclassed",
"Models",
"."
] | def _create_pseudo_names(tensors, prefix):
"""Creates pseudo {input | output} names for subclassed Models.
Warning: this function should only be used to define default
names for `Metics` and `SavedModel`. No other use cases should
rely on a `Model`'s input or output names.
Example with dict:
`{'a': [x1, x2], 'b': x3}` becomes:
`['a_1', 'a_2', 'b']`
Example with list:
`[x, y]` becomes:
`['output_1', 'output_2']`
Args:
tensors: `Model`'s outputs or inputs.
prefix: 'output_' for outputs, 'input_' for inputs.
Returns:
Flattened list of pseudo names.
"""
def one_index(ele):
# Start with "output_1" instead of "output_0".
if isinstance(ele, int):
return ele + 1
return ele
flat_paths = list(nest.yield_flat_paths(tensors))
flat_paths = nest.map_structure(one_index, flat_paths)
names = []
for path in flat_paths:
if not path:
name = prefix + '1' # Single output.
else:
name = '_'.join(str(p) for p in path)
if isinstance(path[0], int):
name = prefix + name
names.append(name)
return names | [
"def",
"_create_pseudo_names",
"(",
"tensors",
",",
"prefix",
")",
":",
"def",
"one_index",
"(",
"ele",
")",
":",
"# Start with \"output_1\" instead of \"output_0\".",
"if",
"isinstance",
"(",
"ele",
",",
"int",
")",
":",
"return",
"ele",
"+",
"1",
"return",
"ele",
"flat_paths",
"=",
"list",
"(",
"nest",
".",
"yield_flat_paths",
"(",
"tensors",
")",
")",
"flat_paths",
"=",
"nest",
".",
"map_structure",
"(",
"one_index",
",",
"flat_paths",
")",
"names",
"=",
"[",
"]",
"for",
"path",
"in",
"flat_paths",
":",
"if",
"not",
"path",
":",
"name",
"=",
"prefix",
"+",
"'1'",
"# Single output.",
"else",
":",
"name",
"=",
"'_'",
".",
"join",
"(",
"str",
"(",
"p",
")",
"for",
"p",
"in",
"path",
")",
"if",
"isinstance",
"(",
"path",
"[",
"0",
"]",
",",
"int",
")",
":",
"name",
"=",
"prefix",
"+",
"name",
"names",
".",
"append",
"(",
"name",
")",
"return",
"names"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/tflite_keras_util.py#L107-L149 | |
kiwix/kiwix-xulrunner | 38f4a10ae4b1585c16cb11730bb0dcc4924ae19f | android/gen-custom-android-build.py | python | step_move_apk_to_destination | (jsdata, **options) | place and rename built APKs to main output directory | place and rename built APKs to main output directory | [
"place",
"and",
"rename",
"built",
"APKs",
"to",
"main",
"output",
"directory"
] | def step_move_apk_to_destination(jsdata, **options):
""" place and rename built APKs to main output directory """
move_to_current_folder()
# ensure target directory exists (might not if kiwix was not built)
try:
os.makedirs(os.path.join(CURRENT_PATH, 'build', 'outputs', 'apk'))
except OSError:
pass
# move generated APK to satisfy other scripts
for variant in ('debug', 'debug-unaligned', 'release-unsigned'):
shutil.move(os.path.join(ANDROID_PATH, 'build', 'outputs', 'apk',
"{}-{}.apk"
.format(jsdata.get('package'), variant)),
os.path.join(CURRENT_PATH, 'build', 'outputs', 'apk',
"{}-{}.apk"
.format(jsdata.get('package'), variant))) | [
"def",
"step_move_apk_to_destination",
"(",
"jsdata",
",",
"*",
"*",
"options",
")",
":",
"move_to_current_folder",
"(",
")",
"# ensure target directory exists (might not if kiwix was not built)",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CURRENT_PATH",
",",
"'build'",
",",
"'outputs'",
",",
"'apk'",
")",
")",
"except",
"OSError",
":",
"pass",
"# move generated APK to satisfy other scripts",
"for",
"variant",
"in",
"(",
"'debug'",
",",
"'debug-unaligned'",
",",
"'release-unsigned'",
")",
":",
"shutil",
".",
"move",
"(",
"os",
".",
"path",
".",
"join",
"(",
"ANDROID_PATH",
",",
"'build'",
",",
"'outputs'",
",",
"'apk'",
",",
"\"{}-{}.apk\"",
".",
"format",
"(",
"jsdata",
".",
"get",
"(",
"'package'",
")",
",",
"variant",
")",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"CURRENT_PATH",
",",
"'build'",
",",
"'outputs'",
",",
"'apk'",
",",
"\"{}-{}.apk\"",
".",
"format",
"(",
"jsdata",
".",
"get",
"(",
"'package'",
")",
",",
"variant",
")",
")",
")"
] | https://github.com/kiwix/kiwix-xulrunner/blob/38f4a10ae4b1585c16cb11730bb0dcc4924ae19f/android/gen-custom-android-build.py#L528-L545 | ||
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/cpp_message.py | python | RepeatedScalarProperty | (cdescriptor) | return property(Getter, Setter, doc=doc) | Returns a Python property the given repeated scalar field. | Returns a Python property the given repeated scalar field. | [
"Returns",
"a",
"Python",
"property",
"the",
"given",
"repeated",
"scalar",
"field",
"."
] | def RepeatedScalarProperty(cdescriptor):
"""Returns a Python property the given repeated scalar field."""
def Getter(self):
container = self._composite_fields.get(cdescriptor.name, None)
if container is None:
container = RepeatedScalarContainer(self, cdescriptor)
self._composite_fields[cdescriptor.name] = container
return container
def Setter(self, new_value):
raise AttributeError('Assignment not allowed to repeated field '
'"%s" in protocol message object.' % cdescriptor.name)
doc = 'Magic attribute generated for "%s" proto field.' % cdescriptor.name
return property(Getter, Setter, doc=doc) | [
"def",
"RepeatedScalarProperty",
"(",
"cdescriptor",
")",
":",
"def",
"Getter",
"(",
"self",
")",
":",
"container",
"=",
"self",
".",
"_composite_fields",
".",
"get",
"(",
"cdescriptor",
".",
"name",
",",
"None",
")",
"if",
"container",
"is",
"None",
":",
"container",
"=",
"RepeatedScalarContainer",
"(",
"self",
",",
"cdescriptor",
")",
"self",
".",
"_composite_fields",
"[",
"cdescriptor",
".",
"name",
"]",
"=",
"container",
"return",
"container",
"def",
"Setter",
"(",
"self",
",",
"new_value",
")",
":",
"raise",
"AttributeError",
"(",
"'Assignment not allowed to repeated field '",
"'\"%s\" in protocol message object.'",
"%",
"cdescriptor",
".",
"name",
")",
"doc",
"=",
"'Magic attribute generated for \"%s\" proto field.'",
"%",
"cdescriptor",
".",
"name",
"return",
"property",
"(",
"Getter",
",",
"Setter",
",",
"doc",
"=",
"doc",
")"
] | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/cpp_message.py#L165-L180 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/WANDPowderReduction.py | python | WANDPowderReduction._expand_groups | (self) | return input_workspaces | expand workspace groups | expand workspace groups | [
"expand",
"workspace",
"groups"
] | def _expand_groups(self):
"""expand workspace groups"""
workspaces = self.getProperty("InputWorkspace").value
input_workspaces = []
for wsname in workspaces:
wks = AnalysisDataService.retrieve(wsname)
if isinstance(wks, WorkspaceGroup):
input_workspaces.extend(wks.getNames())
else:
input_workspaces.append(wsname)
return input_workspaces | [
"def",
"_expand_groups",
"(",
"self",
")",
":",
"workspaces",
"=",
"self",
".",
"getProperty",
"(",
"\"InputWorkspace\"",
")",
".",
"value",
"input_workspaces",
"=",
"[",
"]",
"for",
"wsname",
"in",
"workspaces",
":",
"wks",
"=",
"AnalysisDataService",
".",
"retrieve",
"(",
"wsname",
")",
"if",
"isinstance",
"(",
"wks",
",",
"WorkspaceGroup",
")",
":",
"input_workspaces",
".",
"extend",
"(",
"wks",
".",
"getNames",
"(",
")",
")",
"else",
":",
"input_workspaces",
".",
"append",
"(",
"wsname",
")",
"return",
"input_workspaces"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/WANDPowderReduction.py#L277-L288 | |
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | logdevice/ops/ldops/cluster.py | python | get_node_by_name | (client: AdminAPI, name: str) | return _get_node_by_node_config(resp.nodes[0]) | Returns Node by node name
Raises:
logdevice.admin.exceptions.types.NodeNotReady: if node client is
connected to is not ready yet to process request
thrift.py3.TransportError: if there's network error while
communicating with Thrift
ldops.exceptions.NodeNotFoundError: if there's no such node from
point of view of AdminAPI provider | Returns Node by node name | [
"Returns",
"Node",
"by",
"node",
"name"
] | async def get_node_by_name(client: AdminAPI, name: str) -> Node:
"""
Returns Node by node name
Raises:
logdevice.admin.exceptions.types.NodeNotReady: if node client is
connected to is not ready yet to process request
thrift.py3.TransportError: if there's network error while
communicating with Thrift
ldops.exceptions.NodeNotFoundError: if there's no such node from
point of view of AdminAPI provider
"""
resp: NodesConfigResponse = await admin_api.get_nodes_config(
client=client, req=NodesFilter(node=NodeID(name=name))
)
if not resp.nodes:
raise NodeNotFoundError(f"Node not found: name=`{name}'")
# There's guarantee from AdminAPI that there CANNOT be more than one
# node with the same name
return _get_node_by_node_config(resp.nodes[0]) | [
"async",
"def",
"get_node_by_name",
"(",
"client",
":",
"AdminAPI",
",",
"name",
":",
"str",
")",
"->",
"Node",
":",
"resp",
":",
"NodesConfigResponse",
"=",
"await",
"admin_api",
".",
"get_nodes_config",
"(",
"client",
"=",
"client",
",",
"req",
"=",
"NodesFilter",
"(",
"node",
"=",
"NodeID",
"(",
"name",
"=",
"name",
")",
")",
")",
"if",
"not",
"resp",
".",
"nodes",
":",
"raise",
"NodeNotFoundError",
"(",
"f\"Node not found: name=`{name}'\"",
")",
"# There's guarantee from AdminAPI that there CANNOT be more than one",
"# node with the same name",
"return",
"_get_node_by_node_config",
"(",
"resp",
".",
"nodes",
"[",
"0",
"]",
")"
] | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/logdevice/ops/ldops/cluster.py#L103-L123 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/debug/framework.py | python | OnSessionInitResponse.__init__ | (self, action) | Constructor.
Args:
action: (OnSessionInitAction) Debugger action to take on session init. | Constructor. | [
"Constructor",
"."
] | def __init__(self, action):
"""Constructor.
Args:
action: (OnSessionInitAction) Debugger action to take on session init.
"""
_check_type(action, str)
self.action = action | [
"def",
"__init__",
"(",
"self",
",",
"action",
")",
":",
"_check_type",
"(",
"action",
",",
"str",
")",
"self",
".",
"action",
"=",
"action"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/framework.py#L173-L180 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/algorithm_detail/calibration.py | python | has_calibration_already_been_applied | (workspace, full_file_path) | return has_calibration_applied | Checks if particular calibration, defined by the file path has been applied to a workspace.
:param workspace: The workspace which might have been calibrated
:param full_file_path: An absolute file path to the calibration file.
:return: True if the calibration has been applied else False | Checks if particular calibration, defined by the file path has been applied to a workspace. | [
"Checks",
"if",
"particular",
"calibration",
"defined",
"by",
"the",
"file",
"path",
"has",
"been",
"applied",
"to",
"a",
"workspace",
"."
] | def has_calibration_already_been_applied(workspace, full_file_path):
"""
Checks if particular calibration, defined by the file path has been applied to a workspace.
:param workspace: The workspace which might have been calibrated
:param full_file_path: An absolute file path to the calibration file.
:return: True if the calibration has been applied else False
"""
has_calibration_applied = False
if has_tag(CALIBRATION_WORKSPACE_TAG, workspace):
value = get_tag(CALIBRATION_WORKSPACE_TAG, workspace)
has_calibration_applied = value == full_file_path
return has_calibration_applied | [
"def",
"has_calibration_already_been_applied",
"(",
"workspace",
",",
"full_file_path",
")",
":",
"has_calibration_applied",
"=",
"False",
"if",
"has_tag",
"(",
"CALIBRATION_WORKSPACE_TAG",
",",
"workspace",
")",
":",
"value",
"=",
"get_tag",
"(",
"CALIBRATION_WORKSPACE_TAG",
",",
"workspace",
")",
"has_calibration_applied",
"=",
"value",
"==",
"full_file_path",
"return",
"has_calibration_applied"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/calibration.py#L136-L148 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/examples/python/bsd.py | python | Object.save | (self, path=None, overwrite=False) | Save the contents of the object to disk using 'path' argument as
the path, or save it to the current working directory using the
object name. | Save the contents of the object to disk using 'path' argument as
the path, or save it to the current working directory using the
object name. | [
"Save",
"the",
"contents",
"of",
"the",
"object",
"to",
"disk",
"using",
"path",
"argument",
"as",
"the",
"path",
"or",
"save",
"it",
"to",
"the",
"current",
"working",
"directory",
"using",
"the",
"object",
"name",
"."
] | def save(self, path=None, overwrite=False):
'''
Save the contents of the object to disk using 'path' argument as
the path, or save it to the current working directory using the
object name.
'''
if path is None:
path = self.name
if not overwrite and os.path.exists(path):
print('error: outfile "%s" already exists' % (path))
return
print('Saving "%s" to "%s"...' % (self.name, path))
with open(path, 'w') as f:
f.write(self.get_bytes()) | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"name",
"if",
"not",
"overwrite",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"print",
"(",
"'error: outfile \"%s\" already exists'",
"%",
"(",
"path",
")",
")",
"return",
"print",
"(",
"'Saving \"%s\" to \"%s\"...'",
"%",
"(",
"self",
".",
"name",
",",
"path",
")",
")",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"get_bytes",
"(",
")",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/examples/python/bsd.py#L81-L95 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | uCSIsVariationSelectorsSupplement | (code) | return ret | Check whether the character is part of
VariationSelectorsSupplement UCS Block | Check whether the character is part of
VariationSelectorsSupplement UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"VariationSelectorsSupplement",
"UCS",
"Block"
] | def uCSIsVariationSelectorsSupplement(code):
"""Check whether the character is part of
VariationSelectorsSupplement UCS Block """
ret = libxml2mod.xmlUCSIsVariationSelectorsSupplement(code)
return ret | [
"def",
"uCSIsVariationSelectorsSupplement",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsVariationSelectorsSupplement",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2973-L2977 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir_utils.py | python | convert_code_obj_to_function | (code_obj, caller_ir) | return _create_function_from_code_obj(fcode, func_env, func_arg, func_clo,
glbls) | Converts a code object from a `make_function.code` attr in the IR into a
python function, caller_ir is the FunctionIR of the caller and is used for
the resolution of freevars. | Converts a code object from a `make_function.code` attr in the IR into a
python function, caller_ir is the FunctionIR of the caller and is used for
the resolution of freevars. | [
"Converts",
"a",
"code",
"object",
"from",
"a",
"make_function",
".",
"code",
"attr",
"in",
"the",
"IR",
"into",
"a",
"python",
"function",
"caller_ir",
"is",
"the",
"FunctionIR",
"of",
"the",
"caller",
"and",
"is",
"used",
"for",
"the",
"resolution",
"of",
"freevars",
"."
] | def convert_code_obj_to_function(code_obj, caller_ir):
"""
Converts a code object from a `make_function.code` attr in the IR into a
python function, caller_ir is the FunctionIR of the caller and is used for
the resolution of freevars.
"""
fcode = code_obj.code
nfree = len(fcode.co_freevars)
# try and resolve freevars if they are consts in the caller's IR
# these can be baked into the new function
freevars = []
for x in fcode.co_freevars:
# not using guard here to differentiate between multiple definition and
# non-const variable
try:
freevar_def = caller_ir.get_definition(x)
except KeyError:
msg = ("Cannot capture a constant value for variable '%s' as there "
"are multiple definitions present." % x)
raise TypingError(msg, loc=code_obj.loc)
if isinstance(freevar_def, ir.Const):
freevars.append(freevar_def.value)
else:
msg = ("Cannot capture the non-constant value associated with "
"variable '%s' in a function that will escape." % x)
raise TypingError(msg, loc=code_obj.loc)
func_env = "\n".join([" c_%d = %s" % (i, x) for i, x in enumerate(freevars)])
func_clo = ",".join(["c_%d" % i for i in range(nfree)])
co_varnames = list(fcode.co_varnames)
# This is horrible. The code object knows about the number of args present
# it also knows the name of the args but these are bundled in with other
# vars in `co_varnames`. The make_function IR node knows what the defaults
# are, they are defined in the IR as consts. The following finds the total
# number of args (args + kwargs with defaults), finds the default values
# and infers the number of "kwargs with defaults" from this and then infers
# the number of actual arguments from that.
n_kwargs = 0
n_allargs = fcode.co_argcount
kwarg_defaults = caller_ir.get_definition(code_obj.defaults)
if kwarg_defaults is not None:
if isinstance(kwarg_defaults, tuple):
d = [caller_ir.get_definition(x).value for x in kwarg_defaults]
kwarg_defaults_tup = tuple(d)
else:
d = [caller_ir.get_definition(x).value
for x in kwarg_defaults.items]
kwarg_defaults_tup = tuple(d)
n_kwargs = len(kwarg_defaults_tup)
nargs = n_allargs - n_kwargs
func_arg = ",".join(["%s" % (co_varnames[i]) for i in range(nargs)])
if n_kwargs:
kw_const = ["%s = %s" % (co_varnames[i + nargs], kwarg_defaults_tup[i])
for i in range(n_kwargs)]
func_arg += ", "
func_arg += ", ".join(kw_const)
# globals are the same as those in the caller
glbls = caller_ir.func_id.func.__globals__
# create the function and return it
return _create_function_from_code_obj(fcode, func_env, func_arg, func_clo,
glbls) | [
"def",
"convert_code_obj_to_function",
"(",
"code_obj",
",",
"caller_ir",
")",
":",
"fcode",
"=",
"code_obj",
".",
"code",
"nfree",
"=",
"len",
"(",
"fcode",
".",
"co_freevars",
")",
"# try and resolve freevars if they are consts in the caller's IR",
"# these can be baked into the new function",
"freevars",
"=",
"[",
"]",
"for",
"x",
"in",
"fcode",
".",
"co_freevars",
":",
"# not using guard here to differentiate between multiple definition and",
"# non-const variable",
"try",
":",
"freevar_def",
"=",
"caller_ir",
".",
"get_definition",
"(",
"x",
")",
"except",
"KeyError",
":",
"msg",
"=",
"(",
"\"Cannot capture a constant value for variable '%s' as there \"",
"\"are multiple definitions present.\"",
"%",
"x",
")",
"raise",
"TypingError",
"(",
"msg",
",",
"loc",
"=",
"code_obj",
".",
"loc",
")",
"if",
"isinstance",
"(",
"freevar_def",
",",
"ir",
".",
"Const",
")",
":",
"freevars",
".",
"append",
"(",
"freevar_def",
".",
"value",
")",
"else",
":",
"msg",
"=",
"(",
"\"Cannot capture the non-constant value associated with \"",
"\"variable '%s' in a function that will escape.\"",
"%",
"x",
")",
"raise",
"TypingError",
"(",
"msg",
",",
"loc",
"=",
"code_obj",
".",
"loc",
")",
"func_env",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"\" c_%d = %s\"",
"%",
"(",
"i",
",",
"x",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"freevars",
")",
"]",
")",
"func_clo",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"c_%d\"",
"%",
"i",
"for",
"i",
"in",
"range",
"(",
"nfree",
")",
"]",
")",
"co_varnames",
"=",
"list",
"(",
"fcode",
".",
"co_varnames",
")",
"# This is horrible. The code object knows about the number of args present",
"# it also knows the name of the args but these are bundled in with other",
"# vars in `co_varnames`. The make_function IR node knows what the defaults",
"# are, they are defined in the IR as consts. The following finds the total",
"# number of args (args + kwargs with defaults), finds the default values",
"# and infers the number of \"kwargs with defaults\" from this and then infers",
"# the number of actual arguments from that.",
"n_kwargs",
"=",
"0",
"n_allargs",
"=",
"fcode",
".",
"co_argcount",
"kwarg_defaults",
"=",
"caller_ir",
".",
"get_definition",
"(",
"code_obj",
".",
"defaults",
")",
"if",
"kwarg_defaults",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"kwarg_defaults",
",",
"tuple",
")",
":",
"d",
"=",
"[",
"caller_ir",
".",
"get_definition",
"(",
"x",
")",
".",
"value",
"for",
"x",
"in",
"kwarg_defaults",
"]",
"kwarg_defaults_tup",
"=",
"tuple",
"(",
"d",
")",
"else",
":",
"d",
"=",
"[",
"caller_ir",
".",
"get_definition",
"(",
"x",
")",
".",
"value",
"for",
"x",
"in",
"kwarg_defaults",
".",
"items",
"]",
"kwarg_defaults_tup",
"=",
"tuple",
"(",
"d",
")",
"n_kwargs",
"=",
"len",
"(",
"kwarg_defaults_tup",
")",
"nargs",
"=",
"n_allargs",
"-",
"n_kwargs",
"func_arg",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"%s\"",
"%",
"(",
"co_varnames",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"nargs",
")",
"]",
")",
"if",
"n_kwargs",
":",
"kw_const",
"=",
"[",
"\"%s = %s\"",
"%",
"(",
"co_varnames",
"[",
"i",
"+",
"nargs",
"]",
",",
"kwarg_defaults_tup",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"n_kwargs",
")",
"]",
"func_arg",
"+=",
"\", \"",
"func_arg",
"+=",
"\", \"",
".",
"join",
"(",
"kw_const",
")",
"# globals are the same as those in the caller",
"glbls",
"=",
"caller_ir",
".",
"func_id",
".",
"func",
".",
"__globals__",
"# create the function and return it",
"return",
"_create_function_from_code_obj",
"(",
"fcode",
",",
"func_env",
",",
"func_arg",
",",
"func_clo",
",",
"glbls",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir_utils.py#L2096-L2161 | |
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vtr_flow/scripts/upgrade_arch.py | python | upgrade_device_layout | (arch) | return changed | Upgrades the legacy <gridlocation> specifications (on each pb_type) to the new format
placed under the <layout> tag. | Upgrades the legacy <gridlocation> specifications (on each pb_type) to the new format
placed under the <layout> tag. | [
"Upgrades",
"the",
"legacy",
"<gridlocation",
">",
"specifications",
"(",
"on",
"each",
"pb_type",
")",
"to",
"the",
"new",
"format",
"placed",
"under",
"the",
"<layout",
">",
"tag",
"."
] | def upgrade_device_layout(arch):
"""
Upgrades the legacy <gridlocation> specifications (on each pb_type) to the new format
placed under the <layout> tag.
"""
changed = False
# Get the layout tag
layout = arch.find("./layout")
# Find all the top level pb_types
top_pb_types = arch.findall("./complexblocklist/pb_type")
type_to_grid_specs = OrderedDict()
for top_pb_type in top_pb_types:
type_name = top_pb_type.attrib["name"]
assert type_name not in type_to_grid_specs
type_to_grid_specs[type_name] = []
gridlocations = top_pb_type.find("gridlocations")
if gridlocations == None:
continue
for child in gridlocations:
if child.tag is ET.Comment:
continue
assert child.tag == "loc"
type_to_grid_specs[type_name].append(child)
# Remove the legacy gridlocations from the <pb_type>
top_pb_type.remove(gridlocations)
changed = True
if not changed:
# No legacy specs to upgrade
return changed
device_auto = None
if "auto" in layout.attrib:
aspect_ratio = layout.attrib["auto"]
del layout.attrib["auto"]
change = True
device_auto = ET.SubElement(layout, "auto_layout")
device_auto.attrib["aspect_ratio"] = str(aspect_ratio)
elif "width" in layout.attrib and "height" in layout.attrib:
width = layout.attrib["width"]
height = layout.attrib["height"]
del layout.attrib["width"]
del layout.attrib["height"]
changed = True
device_auto = ET.SubElement(layout, "fixed_layout")
device_auto.attrib["name"] = "unnamed_device"
device_auto.attrib["width"] = width
device_auto.attrib["height"] = height
else:
assert False, "Unrecognized <layout> specification"
if 0:
for type, locs in type_to_grid_specs.items():
print("Type:", type)
for loc in locs:
print("\t", loc.tag, loc.attrib)
have_perimeter = False
for type_name, locs in type_to_grid_specs.items():
for loc in locs:
if loc.attrib["type"] == "perimeter":
have_perimeter = True
if changed:
layout.text = "\n" + INDENT
device_auto.text = "\n" + 2 * INDENT
device_auto.tail = "\n"
for type_name, locs in type_to_grid_specs.items():
for loc in locs:
assert loc.tag == "loc"
loc_type = loc.attrib["type"]
# Note that we scale the priority by a factor of 10 to allow us to 'tweak'
# the priorities without causing conflicts with user defined priorities
priority = 10 * int(loc.attrib["priority"])
if loc_type == "col":
start = loc.attrib["start"]
repeat = None
if "repeat" in loc.attrib:
repeat = loc.attrib["repeat"]
comment_str = (
"Column of '{}' with 'EMPTY' blocks wherever a '{}' does not fit.".format(
type_name, type_name
)
)
if have_perimeter:
comment_str += " Vertical offset by 1 for perimeter."
comment = ET.Comment(comment_str)
device_auto.append(comment)
comment.tail = "\n" + 2 * INDENT
col_spec = ET.SubElement(device_auto, "col")
col_spec.attrib["type"] = type_name
col_spec.attrib["startx"] = start
if have_perimeter:
col_spec.attrib["starty"] = "1"
if repeat:
col_spec.attrib["repeatx"] = repeat
col_spec.attrib["priority"] = str(priority)
col_spec.tail = "\n" + 2 * INDENT
# Classic VPR fills blank spaces (e.g. where a height > 1 block won't fit) with "EMPTY"
# instead of with the underlying type. To replicate that we create a col spec with the same
# location information, but of type 'EMPTY' and with slightly lower priority than the real type.
col_empty_spec = ET.SubElement(device_auto, "col")
col_empty_spec.attrib["type"] = "EMPTY"
col_empty_spec.attrib["startx"] = start
if repeat:
col_empty_spec.attrib["repeatx"] = repeat
if have_perimeter:
col_empty_spec.attrib["starty"] = "1"
col_empty_spec.attrib["priority"] = str(
priority - 1
) # -1 so it won't override the 'real' col
col_empty_spec.tail = "\n" + 2 * INDENT
elif loc_type == "rel":
pos = loc.attrib["pos"]
div_factor = 1.0 / float(pos)
int_div_factor = int(div_factor)
startx = "(W - 1) / {}".format(div_factor)
if float(int_div_factor) != div_factor:
print(
"Warning: Relative position factor conversion is not exact. Original pos factor: {}. New startx expression: {}".format(
pos, startx
)
)
comment_str = (
"Column of '{}' with 'EMPTY' blocks wherever a '{}' does not fit.".format(
type_name, type_name
)
)
if have_perimeter:
comment_str += " Vertical offset by 1 for perimeter."
comment = ET.Comment(comment_str)
device_auto.append(comment)
comment.tail = "\n" + 2 * INDENT
col_spec = ET.SubElement(device_auto, "col")
col_spec.attrib["type"] = type_name
col_spec.attrib["startx"] = startx
if have_perimeter:
col_spec.attrib["starty"] = "1"
col_spec.attrib["priority"] = str(priority)
col_spec.tail = "\n" + 2 * INDENT
# Classic VPR fills blank spaces (e.g. where a height > 1 block won't fit) with "EMPTY"
# instead of with the underlying type. To replicate that we create a col spec with the same
# location information, but of type 'EMPTY' and with slightly lower priority than the real type.
col_empty_spec = ET.SubElement(device_auto, "col")
col_empty_spec.attrib["type"] = "EMPTY"
col_empty_spec.attrib["startx"] = startx
if have_perimeter:
col_empty_spec.attrib["starty"] = "1"
col_empty_spec.attrib["priority"] = str(
priority - 1
) # -1 so it won't override the 'real' col
col_empty_spec.tail = "\n" + 2 * INDENT
elif loc_type == "fill":
comment = ET.Comment("Fill with '{}'".format(type_name))
device_auto.append(comment)
comment.tail = "\n" + 2 * INDENT
fill_spec = ET.SubElement(device_auto, "fill")
fill_spec.attrib["type"] = type_name
fill_spec.attrib["priority"] = str(priority)
fill_spec.tail = "\n" + 2 * INDENT
elif loc_type == "perimeter":
# The classic VPR perimeter specification did not include the corners (while the new version does)
# As a result we specify a full perimeter (including corners), and then apply an EMPTY type override
# at the corners
comment = ET.Comment(
"Perimeter of '{}' blocks with 'EMPTY' blocks at corners".format(type_name)
)
device_auto.append(comment)
comment.tail = "\n" + 2 * INDENT
perim_spec = ET.SubElement(device_auto, "perimeter")
perim_spec.attrib["type"] = type_name
perim_spec.attrib["priority"] = str(priority)
perim_spec.tail = "\n" + 2 * INDENT
corners_spec = ET.SubElement(device_auto, "corners")
corners_spec.attrib["type"] = "EMPTY"
corners_spec.attrib["priority"] = str(priority + 1) # +1 to ensure overrides
corners_spec.tail = "\n" + 2 * INDENT
else:
assert False, "Unrecognzied <loc> type tag {}".format(loc_type)
return changed | [
"def",
"upgrade_device_layout",
"(",
"arch",
")",
":",
"changed",
"=",
"False",
"# Get the layout tag",
"layout",
"=",
"arch",
".",
"find",
"(",
"\"./layout\"",
")",
"# Find all the top level pb_types",
"top_pb_types",
"=",
"arch",
".",
"findall",
"(",
"\"./complexblocklist/pb_type\"",
")",
"type_to_grid_specs",
"=",
"OrderedDict",
"(",
")",
"for",
"top_pb_type",
"in",
"top_pb_types",
":",
"type_name",
"=",
"top_pb_type",
".",
"attrib",
"[",
"\"name\"",
"]",
"assert",
"type_name",
"not",
"in",
"type_to_grid_specs",
"type_to_grid_specs",
"[",
"type_name",
"]",
"=",
"[",
"]",
"gridlocations",
"=",
"top_pb_type",
".",
"find",
"(",
"\"gridlocations\"",
")",
"if",
"gridlocations",
"==",
"None",
":",
"continue",
"for",
"child",
"in",
"gridlocations",
":",
"if",
"child",
".",
"tag",
"is",
"ET",
".",
"Comment",
":",
"continue",
"assert",
"child",
".",
"tag",
"==",
"\"loc\"",
"type_to_grid_specs",
"[",
"type_name",
"]",
".",
"append",
"(",
"child",
")",
"# Remove the legacy gridlocations from the <pb_type>",
"top_pb_type",
".",
"remove",
"(",
"gridlocations",
")",
"changed",
"=",
"True",
"if",
"not",
"changed",
":",
"# No legacy specs to upgrade",
"return",
"changed",
"device_auto",
"=",
"None",
"if",
"\"auto\"",
"in",
"layout",
".",
"attrib",
":",
"aspect_ratio",
"=",
"layout",
".",
"attrib",
"[",
"\"auto\"",
"]",
"del",
"layout",
".",
"attrib",
"[",
"\"auto\"",
"]",
"change",
"=",
"True",
"device_auto",
"=",
"ET",
".",
"SubElement",
"(",
"layout",
",",
"\"auto_layout\"",
")",
"device_auto",
".",
"attrib",
"[",
"\"aspect_ratio\"",
"]",
"=",
"str",
"(",
"aspect_ratio",
")",
"elif",
"\"width\"",
"in",
"layout",
".",
"attrib",
"and",
"\"height\"",
"in",
"layout",
".",
"attrib",
":",
"width",
"=",
"layout",
".",
"attrib",
"[",
"\"width\"",
"]",
"height",
"=",
"layout",
".",
"attrib",
"[",
"\"height\"",
"]",
"del",
"layout",
".",
"attrib",
"[",
"\"width\"",
"]",
"del",
"layout",
".",
"attrib",
"[",
"\"height\"",
"]",
"changed",
"=",
"True",
"device_auto",
"=",
"ET",
".",
"SubElement",
"(",
"layout",
",",
"\"fixed_layout\"",
")",
"device_auto",
".",
"attrib",
"[",
"\"name\"",
"]",
"=",
"\"unnamed_device\"",
"device_auto",
".",
"attrib",
"[",
"\"width\"",
"]",
"=",
"width",
"device_auto",
".",
"attrib",
"[",
"\"height\"",
"]",
"=",
"height",
"else",
":",
"assert",
"False",
",",
"\"Unrecognized <layout> specification\"",
"if",
"0",
":",
"for",
"type",
",",
"locs",
"in",
"type_to_grid_specs",
".",
"items",
"(",
")",
":",
"print",
"(",
"\"Type:\"",
",",
"type",
")",
"for",
"loc",
"in",
"locs",
":",
"print",
"(",
"\"\\t\"",
",",
"loc",
".",
"tag",
",",
"loc",
".",
"attrib",
")",
"have_perimeter",
"=",
"False",
"for",
"type_name",
",",
"locs",
"in",
"type_to_grid_specs",
".",
"items",
"(",
")",
":",
"for",
"loc",
"in",
"locs",
":",
"if",
"loc",
".",
"attrib",
"[",
"\"type\"",
"]",
"==",
"\"perimeter\"",
":",
"have_perimeter",
"=",
"True",
"if",
"changed",
":",
"layout",
".",
"text",
"=",
"\"\\n\"",
"+",
"INDENT",
"device_auto",
".",
"text",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"device_auto",
".",
"tail",
"=",
"\"\\n\"",
"for",
"type_name",
",",
"locs",
"in",
"type_to_grid_specs",
".",
"items",
"(",
")",
":",
"for",
"loc",
"in",
"locs",
":",
"assert",
"loc",
".",
"tag",
"==",
"\"loc\"",
"loc_type",
"=",
"loc",
".",
"attrib",
"[",
"\"type\"",
"]",
"# Note that we scale the priority by a factor of 10 to allow us to 'tweak'",
"# the priorities without causing conflicts with user defined priorities",
"priority",
"=",
"10",
"*",
"int",
"(",
"loc",
".",
"attrib",
"[",
"\"priority\"",
"]",
")",
"if",
"loc_type",
"==",
"\"col\"",
":",
"start",
"=",
"loc",
".",
"attrib",
"[",
"\"start\"",
"]",
"repeat",
"=",
"None",
"if",
"\"repeat\"",
"in",
"loc",
".",
"attrib",
":",
"repeat",
"=",
"loc",
".",
"attrib",
"[",
"\"repeat\"",
"]",
"comment_str",
"=",
"(",
"\"Column of '{}' with 'EMPTY' blocks wherever a '{}' does not fit.\"",
".",
"format",
"(",
"type_name",
",",
"type_name",
")",
")",
"if",
"have_perimeter",
":",
"comment_str",
"+=",
"\" Vertical offset by 1 for perimeter.\"",
"comment",
"=",
"ET",
".",
"Comment",
"(",
"comment_str",
")",
"device_auto",
".",
"append",
"(",
"comment",
")",
"comment",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"col_spec",
"=",
"ET",
".",
"SubElement",
"(",
"device_auto",
",",
"\"col\"",
")",
"col_spec",
".",
"attrib",
"[",
"\"type\"",
"]",
"=",
"type_name",
"col_spec",
".",
"attrib",
"[",
"\"startx\"",
"]",
"=",
"start",
"if",
"have_perimeter",
":",
"col_spec",
".",
"attrib",
"[",
"\"starty\"",
"]",
"=",
"\"1\"",
"if",
"repeat",
":",
"col_spec",
".",
"attrib",
"[",
"\"repeatx\"",
"]",
"=",
"repeat",
"col_spec",
".",
"attrib",
"[",
"\"priority\"",
"]",
"=",
"str",
"(",
"priority",
")",
"col_spec",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"# Classic VPR fills blank spaces (e.g. where a height > 1 block won't fit) with \"EMPTY\"",
"# instead of with the underlying type. To replicate that we create a col spec with the same",
"# location information, but of type 'EMPTY' and with slightly lower priority than the real type.",
"col_empty_spec",
"=",
"ET",
".",
"SubElement",
"(",
"device_auto",
",",
"\"col\"",
")",
"col_empty_spec",
".",
"attrib",
"[",
"\"type\"",
"]",
"=",
"\"EMPTY\"",
"col_empty_spec",
".",
"attrib",
"[",
"\"startx\"",
"]",
"=",
"start",
"if",
"repeat",
":",
"col_empty_spec",
".",
"attrib",
"[",
"\"repeatx\"",
"]",
"=",
"repeat",
"if",
"have_perimeter",
":",
"col_empty_spec",
".",
"attrib",
"[",
"\"starty\"",
"]",
"=",
"\"1\"",
"col_empty_spec",
".",
"attrib",
"[",
"\"priority\"",
"]",
"=",
"str",
"(",
"priority",
"-",
"1",
")",
"# -1 so it won't override the 'real' col",
"col_empty_spec",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"elif",
"loc_type",
"==",
"\"rel\"",
":",
"pos",
"=",
"loc",
".",
"attrib",
"[",
"\"pos\"",
"]",
"div_factor",
"=",
"1.0",
"/",
"float",
"(",
"pos",
")",
"int_div_factor",
"=",
"int",
"(",
"div_factor",
")",
"startx",
"=",
"\"(W - 1) / {}\"",
".",
"format",
"(",
"div_factor",
")",
"if",
"float",
"(",
"int_div_factor",
")",
"!=",
"div_factor",
":",
"print",
"(",
"\"Warning: Relative position factor conversion is not exact. Original pos factor: {}. New startx expression: {}\"",
".",
"format",
"(",
"pos",
",",
"startx",
")",
")",
"comment_str",
"=",
"(",
"\"Column of '{}' with 'EMPTY' blocks wherever a '{}' does not fit.\"",
".",
"format",
"(",
"type_name",
",",
"type_name",
")",
")",
"if",
"have_perimeter",
":",
"comment_str",
"+=",
"\" Vertical offset by 1 for perimeter.\"",
"comment",
"=",
"ET",
".",
"Comment",
"(",
"comment_str",
")",
"device_auto",
".",
"append",
"(",
"comment",
")",
"comment",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"col_spec",
"=",
"ET",
".",
"SubElement",
"(",
"device_auto",
",",
"\"col\"",
")",
"col_spec",
".",
"attrib",
"[",
"\"type\"",
"]",
"=",
"type_name",
"col_spec",
".",
"attrib",
"[",
"\"startx\"",
"]",
"=",
"startx",
"if",
"have_perimeter",
":",
"col_spec",
".",
"attrib",
"[",
"\"starty\"",
"]",
"=",
"\"1\"",
"col_spec",
".",
"attrib",
"[",
"\"priority\"",
"]",
"=",
"str",
"(",
"priority",
")",
"col_spec",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"# Classic VPR fills blank spaces (e.g. where a height > 1 block won't fit) with \"EMPTY\"",
"# instead of with the underlying type. To replicate that we create a col spec with the same",
"# location information, but of type 'EMPTY' and with slightly lower priority than the real type.",
"col_empty_spec",
"=",
"ET",
".",
"SubElement",
"(",
"device_auto",
",",
"\"col\"",
")",
"col_empty_spec",
".",
"attrib",
"[",
"\"type\"",
"]",
"=",
"\"EMPTY\"",
"col_empty_spec",
".",
"attrib",
"[",
"\"startx\"",
"]",
"=",
"startx",
"if",
"have_perimeter",
":",
"col_empty_spec",
".",
"attrib",
"[",
"\"starty\"",
"]",
"=",
"\"1\"",
"col_empty_spec",
".",
"attrib",
"[",
"\"priority\"",
"]",
"=",
"str",
"(",
"priority",
"-",
"1",
")",
"# -1 so it won't override the 'real' col",
"col_empty_spec",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"elif",
"loc_type",
"==",
"\"fill\"",
":",
"comment",
"=",
"ET",
".",
"Comment",
"(",
"\"Fill with '{}'\"",
".",
"format",
"(",
"type_name",
")",
")",
"device_auto",
".",
"append",
"(",
"comment",
")",
"comment",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"fill_spec",
"=",
"ET",
".",
"SubElement",
"(",
"device_auto",
",",
"\"fill\"",
")",
"fill_spec",
".",
"attrib",
"[",
"\"type\"",
"]",
"=",
"type_name",
"fill_spec",
".",
"attrib",
"[",
"\"priority\"",
"]",
"=",
"str",
"(",
"priority",
")",
"fill_spec",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"elif",
"loc_type",
"==",
"\"perimeter\"",
":",
"# The classic VPR perimeter specification did not include the corners (while the new version does)",
"# As a result we specify a full perimeter (including corners), and then apply an EMPTY type override",
"# at the corners",
"comment",
"=",
"ET",
".",
"Comment",
"(",
"\"Perimeter of '{}' blocks with 'EMPTY' blocks at corners\"",
".",
"format",
"(",
"type_name",
")",
")",
"device_auto",
".",
"append",
"(",
"comment",
")",
"comment",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"perim_spec",
"=",
"ET",
".",
"SubElement",
"(",
"device_auto",
",",
"\"perimeter\"",
")",
"perim_spec",
".",
"attrib",
"[",
"\"type\"",
"]",
"=",
"type_name",
"perim_spec",
".",
"attrib",
"[",
"\"priority\"",
"]",
"=",
"str",
"(",
"priority",
")",
"perim_spec",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"corners_spec",
"=",
"ET",
".",
"SubElement",
"(",
"device_auto",
",",
"\"corners\"",
")",
"corners_spec",
".",
"attrib",
"[",
"\"type\"",
"]",
"=",
"\"EMPTY\"",
"corners_spec",
".",
"attrib",
"[",
"\"priority\"",
"]",
"=",
"str",
"(",
"priority",
"+",
"1",
")",
"# +1 to ensure overrides",
"corners_spec",
".",
"tail",
"=",
"\"\\n\"",
"+",
"2",
"*",
"INDENT",
"else",
":",
"assert",
"False",
",",
"\"Unrecognzied <loc> type tag {}\"",
".",
"format",
"(",
"loc_type",
")",
"return",
"changed"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/upgrade_arch.py#L331-L553 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/html5parser.py | python | HTMLParser.parse | (self, stream, *args, **kwargs) | return self.tree.getDocument() | Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element).
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> | Parse a HTML document into a well-formed tree | [
"Parse",
"a",
"HTML",
"document",
"into",
"a",
"well",
"-",
"formed",
"tree"
] | def parse(self, stream, *args, **kwargs):
"""Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element).
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
"""
self._parse(stream, False, None, *args, **kwargs)
return self.tree.getDocument() | [
"def",
"parse",
"(",
"self",
",",
"stream",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_parse",
"(",
"stream",
",",
"False",
",",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"tree",
".",
"getDocument",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/html5lib/html5parser.py#L523-L569 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py | python | QueueBase._dequeue_return_value | (self, tensors) | Return the value to return from a dequeue op.
If the queue has names, return a dictionary with the
names as keys. Otherwise return either a single tensor
or a list of tensors depending on the length of `tensors`.
Args:
tensors: List of tensors from the dequeue op.
Returns:
A single tensor, a list of tensors, or a dictionary
of tensors. | Return the value to return from a dequeue op. | [
"Return",
"the",
"value",
"to",
"return",
"from",
"a",
"dequeue",
"op",
"."
] | def _dequeue_return_value(self, tensors):
"""Return the value to return from a dequeue op.
If the queue has names, return a dictionary with the
names as keys. Otherwise return either a single tensor
or a list of tensors depending on the length of `tensors`.
Args:
tensors: List of tensors from the dequeue op.
Returns:
A single tensor, a list of tensors, or a dictionary
of tensors.
"""
if self._names:
# The returned values in `tensors` are in the same order as
# the names in `self._names`.
return {n: tensors[i] for i, n in enumerate(self._names)}
elif len(tensors) == 1:
return tensors[0]
else:
return tensors | [
"def",
"_dequeue_return_value",
"(",
"self",
",",
"tensors",
")",
":",
"if",
"self",
".",
"_names",
":",
"# The returned values in `tensors` are in the same order as",
"# the names in `self._names`.",
"return",
"{",
"n",
":",
"tensors",
"[",
"i",
"]",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"self",
".",
"_names",
")",
"}",
"elif",
"len",
"(",
"tensors",
")",
"==",
"1",
":",
"return",
"tensors",
"[",
"0",
"]",
"else",
":",
"return",
"tensors"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py#L350-L371 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/inplace_ops.py | python | inplace_add | (x, i, v) | return alias_inplace_add(gen_array_ops.deep_copy(x), i, v) | Applies an inplace add on input x at index i with value v.
Note that this function is not actually inplace - it allocates
a copy of x. The utility is not avoiding memory copies but rather
specifying a sparse update.
If i is None, x and v must be the same shape. Computes
y = x; y += v;
If i is a scalar, x has a rank 1 higher than v's. Computes
y = x; y[i, :] += v;
Otherwise, x and v must have the same rank. Computes
y = x; y[i, :] += v;
Args:
x: A Tensor.
i: None, a scalar or a vector.
v: A Tensor.
Returns:
Returns y, which is guaranteed not to be an alias of x. | Applies an inplace add on input x at index i with value v. | [
"Applies",
"an",
"inplace",
"add",
"on",
"input",
"x",
"at",
"index",
"i",
"with",
"value",
"v",
"."
] | def inplace_add(x, i, v):
"""Applies an inplace add on input x at index i with value v.
Note that this function is not actually inplace - it allocates
a copy of x. The utility is not avoiding memory copies but rather
specifying a sparse update.
If i is None, x and v must be the same shape. Computes
y = x; y += v;
If i is a scalar, x has a rank 1 higher than v's. Computes
y = x; y[i, :] += v;
Otherwise, x and v must have the same rank. Computes
y = x; y[i, :] += v;
Args:
x: A Tensor.
i: None, a scalar or a vector.
v: A Tensor.
Returns:
Returns y, which is guaranteed not to be an alias of x.
"""
return alias_inplace_add(gen_array_ops.deep_copy(x), i, v) | [
"def",
"inplace_add",
"(",
"x",
",",
"i",
",",
"v",
")",
":",
"return",
"alias_inplace_add",
"(",
"gen_array_ops",
".",
"deep_copy",
"(",
"x",
")",
",",
"i",
",",
"v",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/inplace_ops.py#L198-L221 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/tools/build/win/resedit.py | python | _ResourceEditor.__init__ | (self, input_file, output_file) | Create a new editor.
Args:
input_file: path to the input file.
output_file: (optional) path to the output file. | Create a new editor. | [
"Create",
"a",
"new",
"editor",
"."
] | def __init__(self, input_file, output_file):
"""Create a new editor.
Args:
input_file: path to the input file.
output_file: (optional) path to the output file.
"""
self._input_file = input_file
self._output_file = output_file
self._modified = False
self._module = None
self._temp_dir = None
self._temp_file = None
self._update_handle = None | [
"def",
"__init__",
"(",
"self",
",",
"input_file",
",",
"output_file",
")",
":",
"self",
".",
"_input_file",
"=",
"input_file",
"self",
".",
"_output_file",
"=",
"output_file",
"self",
".",
"_modified",
"=",
"False",
"self",
".",
"_module",
"=",
"None",
"self",
".",
"_temp_dir",
"=",
"None",
"self",
".",
"_temp_file",
"=",
"None",
"self",
".",
"_update_handle",
"=",
"None"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/tools/build/win/resedit.py#L52-L65 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBModule.FindCompileUnits | (self, sb_file_spec) | return _lldb.SBModule_FindCompileUnits(self, sb_file_spec) | FindCompileUnits(SBModule self, SBFileSpec sb_file_spec) -> SBSymbolContextList
Find compile units related to *this module and passed source
file.
@param[in] sb_file_spec
A lldb::SBFileSpec object that contains source file
specification.
@return
A lldb::SBSymbolContextList that gets filled in with all of
the symbol contexts for all the matches. | FindCompileUnits(SBModule self, SBFileSpec sb_file_spec) -> SBSymbolContextList | [
"FindCompileUnits",
"(",
"SBModule",
"self",
"SBFileSpec",
"sb_file_spec",
")",
"-",
">",
"SBSymbolContextList"
] | def FindCompileUnits(self, sb_file_spec):
"""
FindCompileUnits(SBModule self, SBFileSpec sb_file_spec) -> SBSymbolContextList
Find compile units related to *this module and passed source
file.
@param[in] sb_file_spec
A lldb::SBFileSpec object that contains source file
specification.
@return
A lldb::SBSymbolContextList that gets filled in with all of
the symbol contexts for all the matches.
"""
return _lldb.SBModule_FindCompileUnits(self, sb_file_spec) | [
"def",
"FindCompileUnits",
"(",
"self",
",",
"sb_file_spec",
")",
":",
"return",
"_lldb",
".",
"SBModule_FindCompileUnits",
"(",
"self",
",",
"sb_file_spec",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L7283-L7299 | |
shogun-toolbox/shogun | 9b8d856971af5a295dd6ad70623ae45647a6334c | examples/meta/generator/parse.py | python | FastParser.p_objectType | (self, p) | objecttype : IDENTIFIER | objecttype : IDENTIFIER | [
"objecttype",
":",
"IDENTIFIER"
] | def p_objectType(self, p):
"objecttype : IDENTIFIER"
p[0] = {"ObjectType": p[1]} | [
"def",
"p_objectType",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"{",
"\"ObjectType\"",
":",
"p",
"[",
"1",
"]",
"}"
] | https://github.com/shogun-toolbox/shogun/blob/9b8d856971af5a295dd6ad70623ae45647a6334c/examples/meta/generator/parse.py#L186-L188 | ||
sfzhang15/FaceBoxes | b52cc92f9362d3adc08d54666aeb9ebb62fdb7da | scripts/cpp_lint.py | python | FileInfo.FullName | (self) | return os.path.abspath(self._filename).replace('\\', '/') | Make Windows paths like Unix. | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix",
"."
] | def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/') | [
"def",
"FullName",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/scripts/cpp_lint.py#L881-L883 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/util/android_chrome_version.py | python | GenerateVersionCodes | (version_values, arch, is_next_build) | return version_codes | Build dict of version codes for the specified build architecture. Eg:
{
'CHROME_VERSION_CODE': '378100010',
'MONOCHROME_VERSION_CODE': '378100013',
...
}
versionCode values are built like this:
{full BUILD int}{3 digits: PATCH}{1 digit: package}{1 digit: ABIs}.
MAJOR and MINOR values are not used for generating versionCode.
- MINOR is always 0. It was used for something long ago in Chrome's history
but has not been used since, and has never been nonzero on Android.
- MAJOR is cosmetic and controlled by the release managers. MAJOR and BUILD
always have reasonable sort ordering: for two version codes A and B, it's
always the case that (A.MAJOR < B.MAJOR) implies (A.BUILD < B.BUILD), and
that (A.MAJOR > B.MAJOR) implies (A.BUILD > B.BUILD). This property is just
maintained by the humans who set MAJOR.
Thus, this method is responsible for the final two digits of versionCode. | Build dict of version codes for the specified build architecture. Eg: | [
"Build",
"dict",
"of",
"version",
"codes",
"for",
"the",
"specified",
"build",
"architecture",
".",
"Eg",
":"
] | def GenerateVersionCodes(version_values, arch, is_next_build):
"""Build dict of version codes for the specified build architecture. Eg:
{
'CHROME_VERSION_CODE': '378100010',
'MONOCHROME_VERSION_CODE': '378100013',
...
}
versionCode values are built like this:
{full BUILD int}{3 digits: PATCH}{1 digit: package}{1 digit: ABIs}.
MAJOR and MINOR values are not used for generating versionCode.
- MINOR is always 0. It was used for something long ago in Chrome's history
but has not been used since, and has never been nonzero on Android.
- MAJOR is cosmetic and controlled by the release managers. MAJOR and BUILD
always have reasonable sort ordering: for two version codes A and B, it's
always the case that (A.MAJOR < B.MAJOR) implies (A.BUILD < B.BUILD), and
that (A.MAJOR > B.MAJOR) implies (A.BUILD > B.BUILD). This property is just
maintained by the humans who set MAJOR.
Thus, this method is responsible for the final two digits of versionCode.
"""
base_version_code = int(
'%s%03d00' % (version_values['BUILD'], int(version_values['PATCH'])))
if is_next_build:
base_version_code += _NEXT_BUILD_VERSION_CODE_DIFF
mfg, bitness = _ARCH_TO_MFG_AND_BITNESS[arch]
version_codes = {}
for apk, package, abis in _APKS[bitness]:
abi_bits = _ABIS_TO_BIT_MASK[mfg][abis]
package_bits = _PACKAGE_NAMES[package]
version_code_name = apk + '_VERSION_CODE'
version_code_val = base_version_code + abi_bits + package_bits
version_codes[version_code_name] = str(version_code_val)
return version_codes | [
"def",
"GenerateVersionCodes",
"(",
"version_values",
",",
"arch",
",",
"is_next_build",
")",
":",
"base_version_code",
"=",
"int",
"(",
"'%s%03d00'",
"%",
"(",
"version_values",
"[",
"'BUILD'",
"]",
",",
"int",
"(",
"version_values",
"[",
"'PATCH'",
"]",
")",
")",
")",
"if",
"is_next_build",
":",
"base_version_code",
"+=",
"_NEXT_BUILD_VERSION_CODE_DIFF",
"mfg",
",",
"bitness",
"=",
"_ARCH_TO_MFG_AND_BITNESS",
"[",
"arch",
"]",
"version_codes",
"=",
"{",
"}",
"for",
"apk",
",",
"package",
",",
"abis",
"in",
"_APKS",
"[",
"bitness",
"]",
":",
"abi_bits",
"=",
"_ABIS_TO_BIT_MASK",
"[",
"mfg",
"]",
"[",
"abis",
"]",
"package_bits",
"=",
"_PACKAGE_NAMES",
"[",
"package",
"]",
"version_code_name",
"=",
"apk",
"+",
"'_VERSION_CODE'",
"version_code_val",
"=",
"base_version_code",
"+",
"abi_bits",
"+",
"package_bits",
"version_codes",
"[",
"version_code_name",
"]",
"=",
"str",
"(",
"version_code_val",
")",
"return",
"version_codes"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/util/android_chrome_version.py#L172-L214 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | PrintData.__init__ | (self, *args) | __init__(self) -> PrintData
__init__(self, PrintData data) -> PrintData | __init__(self) -> PrintData
__init__(self, PrintData data) -> PrintData | [
"__init__",
"(",
"self",
")",
"-",
">",
"PrintData",
"__init__",
"(",
"self",
"PrintData",
"data",
")",
"-",
">",
"PrintData"
] | def __init__(self, *args):
"""
__init__(self) -> PrintData
__init__(self, PrintData data) -> PrintData
"""
_windows_.PrintData_swiginit(self,_windows_.new_PrintData(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_windows_",
".",
"PrintData_swiginit",
"(",
"self",
",",
"_windows_",
".",
"new_PrintData",
"(",
"*",
"args",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L4702-L4707 | ||
facebookresearch/ELF | 1f790173095cd910976d9f651b80beb872ec5d12 | vendor/pybind11/tools/clang/cindex.py | python | CursorKind.is_translation_unit | (self) | return conf.lib.clang_isTranslationUnit(self) | Test if this is a translation unit kind. | Test if this is a translation unit kind. | [
"Test",
"if",
"this",
"is",
"a",
"translation",
"unit",
"kind",
"."
] | def is_translation_unit(self):
"""Test if this is a translation unit kind."""
return conf.lib.clang_isTranslationUnit(self) | [
"def",
"is_translation_unit",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isTranslationUnit",
"(",
"self",
")"
] | https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L600-L602 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | iOHTTPMatch | (filename) | return ret | check if the URI matches an HTTP one | check if the URI matches an HTTP one | [
"check",
"if",
"the",
"URI",
"matches",
"an",
"HTTP",
"one"
] | def iOHTTPMatch(filename):
"""check if the URI matches an HTTP one """
ret = libxml2mod.xmlIOHTTPMatch(filename)
return ret | [
"def",
"iOHTTPMatch",
"(",
"filename",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlIOHTTPMatch",
"(",
"filename",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L1893-L1896 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/more-itertools/py3/more_itertools/recipes.py | python | first_true | (iterable, default=None, pred=None) | return next(filter(pred, iterable), default) | Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item for which
``pred(item) == True`` .
>>> first_true(range(10))
1
>>> first_true(range(10), pred=lambda x: x > 5)
6
>>> first_true(range(10), default='missing', pred=lambda x: x > 9)
'missing' | Returns the first true value in the iterable. | [
"Returns",
"the",
"first",
"true",
"value",
"in",
"the",
"iterable",
"."
] | def first_true(iterable, default=None, pred=None):
"""
Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item for which
``pred(item) == True`` .
>>> first_true(range(10))
1
>>> first_true(range(10), pred=lambda x: x > 5)
6
>>> first_true(range(10), default='missing', pred=lambda x: x > 9)
'missing'
"""
return next(filter(pred, iterable), default) | [
"def",
"first_true",
"(",
"iterable",
",",
"default",
"=",
"None",
",",
"pred",
"=",
"None",
")",
":",
"return",
"next",
"(",
"filter",
"(",
"pred",
",",
"iterable",
")",
",",
"default",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py3/more_itertools/recipes.py#L468-L485 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.SetPrintColourMode | (*args, **kwargs) | return _stc.StyledTextCtrl_SetPrintColourMode(*args, **kwargs) | SetPrintColourMode(self, int mode)
Modify colours when printing for clearer printed text. | SetPrintColourMode(self, int mode) | [
"SetPrintColourMode",
"(",
"self",
"int",
"mode",
")"
] | def SetPrintColourMode(*args, **kwargs):
"""
SetPrintColourMode(self, int mode)
Modify colours when printing for clearer printed text.
"""
return _stc.StyledTextCtrl_SetPrintColourMode(*args, **kwargs) | [
"def",
"SetPrintColourMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetPrintColourMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3480-L3486 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/xml/sax/handler.py | python | ContentHandler.startPrefixMapping | (self, prefix, uri) | Begin the scope of a prefix-URI Namespace mapping.
The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the
default).
There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the
start/endPrefixMapping event supplies the information to the
application to expand prefixes in those contexts itself, if
necessary.
Note that start/endPrefixMapping events are not guaranteed to
be properly nested relative to each-other: all
startPrefixMapping events will occur before the corresponding
startElement event, and all endPrefixMapping events will occur
after the corresponding endElement event, but their order is
not guaranteed. | Begin the scope of a prefix-URI Namespace mapping. | [
"Begin",
"the",
"scope",
"of",
"a",
"prefix",
"-",
"URI",
"Namespace",
"mapping",
"."
] | def startPrefixMapping(self, prefix, uri):
"""Begin the scope of a prefix-URI Namespace mapping.
The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the
default).
There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the
start/endPrefixMapping event supplies the information to the
application to expand prefixes in those contexts itself, if
necessary.
Note that start/endPrefixMapping events are not guaranteed to
be properly nested relative to each-other: all
startPrefixMapping events will occur before the corresponding
startElement event, and all endPrefixMapping events will occur
after the corresponding endElement event, but their order is
not guaranteed.""" | [
"def",
"startPrefixMapping",
"(",
"self",
",",
"prefix",
",",
"uri",
")",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/sax/handler.py#L96-L117 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/base_widget.py | python | BaseWidget.data_save_dialog | (self, data_type=None, title=None) | return QFileInfo(fname).filePath() | Pop up a save file dialog box.
@param data_type: string used to filter the files
@param title: string to use as title | Pop up a save file dialog box. | [
"Pop",
"up",
"a",
"save",
"file",
"dialog",
"box",
"."
] | def data_save_dialog(self, data_type=None, title=None):
"""
Pop up a save file dialog box.
@param data_type: string used to filter the files
@param title: string to use as title
"""
if data_type is None:
data_type = self._data_type
if title is None:
title = "Save file - Set a location and name"
fname = QFileDialog.getSaveFileName(self, title,
self._settings.data_path,
data_type)
if isinstance(fname, tuple):
fname = fname[0]
return QFileInfo(fname).filePath() | [
"def",
"data_save_dialog",
"(",
"self",
",",
"data_type",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"if",
"data_type",
"is",
"None",
":",
"data_type",
"=",
"self",
".",
"_data_type",
"if",
"title",
"is",
"None",
":",
"title",
"=",
"\"Save file - Set a location and name\"",
"fname",
"=",
"QFileDialog",
".",
"getSaveFileName",
"(",
"self",
",",
"title",
",",
"self",
".",
"_settings",
".",
"data_path",
",",
"data_type",
")",
"if",
"isinstance",
"(",
"fname",
",",
"tuple",
")",
":",
"fname",
"=",
"fname",
"[",
"0",
"]",
"return",
"QFileInfo",
"(",
"fname",
")",
".",
"filePath",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/base_widget.py#L160-L175 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Scripting.py | python | Dist.get_arch_name | (self) | return self.arch_name | Returns the archive file name.
Set the attribute *arch_name* to change the default value::
def dist(ctx):
ctx.arch_name = 'ctx.tar.bz2'
:rtype: string | Returns the archive file name.
Set the attribute *arch_name* to change the default value:: | [
"Returns",
"the",
"archive",
"file",
"name",
".",
"Set",
"the",
"attribute",
"*",
"arch_name",
"*",
"to",
"change",
"the",
"default",
"value",
"::"
] | def get_arch_name(self):
"""
Returns the archive file name.
Set the attribute *arch_name* to change the default value::
def dist(ctx):
ctx.arch_name = 'ctx.tar.bz2'
:rtype: string
"""
try:
self.arch_name
except AttributeError:
self.arch_name = self.get_base_name() + '.' + self.ext_algo.get(self.algo, self.algo)
return self.arch_name | [
"def",
"get_arch_name",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"arch_name",
"except",
"AttributeError",
":",
"self",
".",
"arch_name",
"=",
"self",
".",
"get_base_name",
"(",
")",
"+",
"'.'",
"+",
"self",
".",
"ext_algo",
".",
"get",
"(",
"self",
".",
"algo",
",",
"self",
".",
"algo",
")",
"return",
"self",
".",
"arch_name"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Scripting.py#L438-L452 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/minpack.py | python | curve_fit | (f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False,
check_finite=True, bounds=(-np.inf, np.inf), method=None,
jac=None, **kwargs) | Use non-linear least squares to fit a function, f, to data.
Assumes ``ydata = f(xdata, *params) + eps``
Parameters
----------
f : callable
The model function, f(x, ...). It must take the independent
variable as the first argument and the parameters to fit as
separate remaining arguments.
xdata : An M-length sequence or an (k,M)-shaped array for functions with k predictors
The independent variable where the data is measured.
ydata : M-length sequence
The dependent data --- nominally f(xdata, ...)
p0 : None, scalar, or N-length sequence, optional
Initial guess for the parameters. If None, then the initial
values will all be 1 (if the number of parameters for the function
can be determined using introspection, otherwise a ValueError
is raised).
sigma : None or M-length sequence or MxM array, optional
Determines the uncertainty in `ydata`. If we define residuals as
``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma`
depends on its number of dimensions:
- A 1-d `sigma` should contain values of standard deviations of
errors in `ydata`. In this case, the optimized function is
``chisq = sum((r / sigma) ** 2)``.
- A 2-d `sigma` should contain the covariance matrix of
errors in `ydata`. In this case, the optimized function is
``chisq = r.T @ inv(sigma) @ r``.
.. versionadded:: 0.19
None (default) is equivalent of 1-d `sigma` filled with ones.
absolute_sigma : bool, optional
If True, `sigma` is used in an absolute sense and the estimated parameter
covariance `pcov` reflects these absolute values.
If False, only the relative magnitudes of the `sigma` values matter.
The returned parameter covariance matrix `pcov` is based on scaling
`sigma` by a constant factor. This constant is set by demanding that the
reduced `chisq` for the optimal parameters `popt` when using the
*scaled* `sigma` equals unity. In other words, `sigma` is scaled to
match the sample variance of the residuals after the fit.
Mathematically,
``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)``
check_finite : bool, optional
If True, check that the input arrays do not contain nans of infs,
and raise a ValueError if they do. Setting this parameter to
False may silently produce nonsensical results if the input arrays
do contain nans. Default is True.
bounds : 2-tuple of array_like, optional
Lower and upper bounds on parameters. Defaults to no bounds.
Each element of the tuple must be either an array with the length equal
to the number of parameters, or a scalar (in which case the bound is
taken to be the same for all parameters.) Use ``np.inf`` with an
appropriate sign to disable bounds on all or some parameters.
.. versionadded:: 0.17
method : {'lm', 'trf', 'dogbox'}, optional
Method to use for optimization. See `least_squares` for more details.
Default is 'lm' for unconstrained problems and 'trf' if `bounds` are
provided. The method 'lm' won't work when the number of observations
is less than the number of variables, use 'trf' or 'dogbox' in this
case.
.. versionadded:: 0.17
jac : callable, string or None, optional
Function with signature ``jac(x, ...)`` which computes the Jacobian
matrix of the model function with respect to parameters as a dense
array_like structure. It will be scaled according to provided `sigma`.
If None (default), the Jacobian will be estimated numerically.
String keywords for 'trf' and 'dogbox' methods can be used to select
a finite difference scheme, see `least_squares`.
.. versionadded:: 0.18
kwargs
Keyword arguments passed to `leastsq` for ``method='lm'`` or
`least_squares` otherwise.
Returns
-------
popt : array
Optimal values for the parameters so that the sum of the squared
residuals of ``f(xdata, *popt) - ydata`` is minimized
pcov : 2d array
The estimated covariance of popt. The diagonals provide the variance
of the parameter estimate. To compute one standard deviation errors
on the parameters use ``perr = np.sqrt(np.diag(pcov))``.
How the `sigma` parameter affects the estimated covariance
depends on `absolute_sigma` argument, as described above.
If the Jacobian matrix at the solution doesn't have a full rank, then
'lm' method returns a matrix filled with ``np.inf``, on the other hand
'trf' and 'dogbox' methods use Moore-Penrose pseudoinverse to compute
the covariance matrix.
Raises
------
ValueError
if either `ydata` or `xdata` contain NaNs, or if incompatible options
are used.
RuntimeError
if the least-squares minimization fails.
OptimizeWarning
if covariance of the parameters can not be estimated.
See Also
--------
least_squares : Minimize the sum of squares of nonlinear functions.
scipy.stats.linregress : Calculate a linear least squares regression for
two sets of measurements.
Notes
-----
With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm
through `leastsq`. Note that this algorithm can only deal with
unconstrained problems.
Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to
the docstring of `least_squares` for more information.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.optimize import curve_fit
>>> def func(x, a, b, c):
... return a * np.exp(-b * x) + c
Define the data to be fit with some noise:
>>> xdata = np.linspace(0, 4, 50)
>>> y = func(xdata, 2.5, 1.3, 0.5)
>>> np.random.seed(1729)
>>> y_noise = 0.2 * np.random.normal(size=xdata.size)
>>> ydata = y + y_noise
>>> plt.plot(xdata, ydata, 'b-', label='data')
Fit for the parameters a, b, c of the function `func`:
>>> popt, pcov = curve_fit(func, xdata, ydata)
>>> popt
array([ 2.55423706, 1.35190947, 0.47450618])
>>> plt.plot(xdata, func(xdata, *popt), 'r-',
... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
Constrain the optimization to the region of ``0 <= a <= 3``,
``0 <= b <= 1`` and ``0 <= c <= 0.5``:
>>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
>>> popt
array([ 2.43708906, 1. , 0.35015434])
>>> plt.plot(xdata, func(xdata, *popt), 'g--',
... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
>>> plt.xlabel('x')
>>> plt.ylabel('y')
>>> plt.legend()
>>> plt.show() | Use non-linear least squares to fit a function, f, to data. | [
"Use",
"non",
"-",
"linear",
"least",
"squares",
"to",
"fit",
"a",
"function",
"f",
"to",
"data",
"."
] | def curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False,
check_finite=True, bounds=(-np.inf, np.inf), method=None,
jac=None, **kwargs):
"""
Use non-linear least squares to fit a function, f, to data.
Assumes ``ydata = f(xdata, *params) + eps``
Parameters
----------
f : callable
The model function, f(x, ...). It must take the independent
variable as the first argument and the parameters to fit as
separate remaining arguments.
xdata : An M-length sequence or an (k,M)-shaped array for functions with k predictors
The independent variable where the data is measured.
ydata : M-length sequence
The dependent data --- nominally f(xdata, ...)
p0 : None, scalar, or N-length sequence, optional
Initial guess for the parameters. If None, then the initial
values will all be 1 (if the number of parameters for the function
can be determined using introspection, otherwise a ValueError
is raised).
sigma : None or M-length sequence or MxM array, optional
Determines the uncertainty in `ydata`. If we define residuals as
``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma`
depends on its number of dimensions:
- A 1-d `sigma` should contain values of standard deviations of
errors in `ydata`. In this case, the optimized function is
``chisq = sum((r / sigma) ** 2)``.
- A 2-d `sigma` should contain the covariance matrix of
errors in `ydata`. In this case, the optimized function is
``chisq = r.T @ inv(sigma) @ r``.
.. versionadded:: 0.19
None (default) is equivalent of 1-d `sigma` filled with ones.
absolute_sigma : bool, optional
If True, `sigma` is used in an absolute sense and the estimated parameter
covariance `pcov` reflects these absolute values.
If False, only the relative magnitudes of the `sigma` values matter.
The returned parameter covariance matrix `pcov` is based on scaling
`sigma` by a constant factor. This constant is set by demanding that the
reduced `chisq` for the optimal parameters `popt` when using the
*scaled* `sigma` equals unity. In other words, `sigma` is scaled to
match the sample variance of the residuals after the fit.
Mathematically,
``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)``
check_finite : bool, optional
If True, check that the input arrays do not contain nans of infs,
and raise a ValueError if they do. Setting this parameter to
False may silently produce nonsensical results if the input arrays
do contain nans. Default is True.
bounds : 2-tuple of array_like, optional
Lower and upper bounds on parameters. Defaults to no bounds.
Each element of the tuple must be either an array with the length equal
to the number of parameters, or a scalar (in which case the bound is
taken to be the same for all parameters.) Use ``np.inf`` with an
appropriate sign to disable bounds on all or some parameters.
.. versionadded:: 0.17
method : {'lm', 'trf', 'dogbox'}, optional
Method to use for optimization. See `least_squares` for more details.
Default is 'lm' for unconstrained problems and 'trf' if `bounds` are
provided. The method 'lm' won't work when the number of observations
is less than the number of variables, use 'trf' or 'dogbox' in this
case.
.. versionadded:: 0.17
jac : callable, string or None, optional
Function with signature ``jac(x, ...)`` which computes the Jacobian
matrix of the model function with respect to parameters as a dense
array_like structure. It will be scaled according to provided `sigma`.
If None (default), the Jacobian will be estimated numerically.
String keywords for 'trf' and 'dogbox' methods can be used to select
a finite difference scheme, see `least_squares`.
.. versionadded:: 0.18
kwargs
Keyword arguments passed to `leastsq` for ``method='lm'`` or
`least_squares` otherwise.
Returns
-------
popt : array
Optimal values for the parameters so that the sum of the squared
residuals of ``f(xdata, *popt) - ydata`` is minimized
pcov : 2d array
The estimated covariance of popt. The diagonals provide the variance
of the parameter estimate. To compute one standard deviation errors
on the parameters use ``perr = np.sqrt(np.diag(pcov))``.
How the `sigma` parameter affects the estimated covariance
depends on `absolute_sigma` argument, as described above.
If the Jacobian matrix at the solution doesn't have a full rank, then
'lm' method returns a matrix filled with ``np.inf``, on the other hand
'trf' and 'dogbox' methods use Moore-Penrose pseudoinverse to compute
the covariance matrix.
Raises
------
ValueError
if either `ydata` or `xdata` contain NaNs, or if incompatible options
are used.
RuntimeError
if the least-squares minimization fails.
OptimizeWarning
if covariance of the parameters can not be estimated.
See Also
--------
least_squares : Minimize the sum of squares of nonlinear functions.
scipy.stats.linregress : Calculate a linear least squares regression for
two sets of measurements.
Notes
-----
With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm
through `leastsq`. Note that this algorithm can only deal with
unconstrained problems.
Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to
the docstring of `least_squares` for more information.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.optimize import curve_fit
>>> def func(x, a, b, c):
... return a * np.exp(-b * x) + c
Define the data to be fit with some noise:
>>> xdata = np.linspace(0, 4, 50)
>>> y = func(xdata, 2.5, 1.3, 0.5)
>>> np.random.seed(1729)
>>> y_noise = 0.2 * np.random.normal(size=xdata.size)
>>> ydata = y + y_noise
>>> plt.plot(xdata, ydata, 'b-', label='data')
Fit for the parameters a, b, c of the function `func`:
>>> popt, pcov = curve_fit(func, xdata, ydata)
>>> popt
array([ 2.55423706, 1.35190947, 0.47450618])
>>> plt.plot(xdata, func(xdata, *popt), 'r-',
... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
Constrain the optimization to the region of ``0 <= a <= 3``,
``0 <= b <= 1`` and ``0 <= c <= 0.5``:
>>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
>>> popt
array([ 2.43708906, 1. , 0.35015434])
>>> plt.plot(xdata, func(xdata, *popt), 'g--',
... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
>>> plt.xlabel('x')
>>> plt.ylabel('y')
>>> plt.legend()
>>> plt.show()
"""
if p0 is None:
# determine number of parameters by inspecting the function
from scipy._lib._util import getargspec_no_self as _getargspec
args, varargs, varkw, defaults = _getargspec(f)
if len(args) < 2:
raise ValueError("Unable to determine number of fit parameters.")
n = len(args) - 1
else:
p0 = np.atleast_1d(p0)
n = p0.size
lb, ub = prepare_bounds(bounds, n)
if p0 is None:
p0 = _initialize_feasible(lb, ub)
bounded_problem = np.any((lb > -np.inf) | (ub < np.inf))
if method is None:
if bounded_problem:
method = 'trf'
else:
method = 'lm'
if method == 'lm' and bounded_problem:
raise ValueError("Method 'lm' only works for unconstrained problems. "
"Use 'trf' or 'dogbox' instead.")
# NaNs can not be handled
if check_finite:
ydata = np.asarray_chkfinite(ydata)
else:
ydata = np.asarray(ydata)
if isinstance(xdata, (list, tuple, np.ndarray)):
# `xdata` is passed straight to the user-defined `f`, so allow
# non-array_like `xdata`.
if check_finite:
xdata = np.asarray_chkfinite(xdata)
else:
xdata = np.asarray(xdata)
# optimization may produce garbage for float32 inputs, cast them to float64
xdata = xdata.astype(float)
ydata = ydata.astype(float)
# Determine type of sigma
if sigma is not None:
sigma = np.asarray(sigma)
# if 1-d, sigma are errors, define transform = 1/sigma
if sigma.shape == (ydata.size, ):
transform = 1.0 / sigma
# if 2-d, sigma is the covariance matrix,
# define transform = L such that L L^T = C
elif sigma.shape == (ydata.size, ydata.size):
try:
# scipy.linalg.cholesky requires lower=True to return L L^T = A
transform = cholesky(sigma, lower=True)
except LinAlgError:
raise ValueError("`sigma` must be positive definite.")
else:
raise ValueError("`sigma` has incorrect shape.")
else:
transform = None
func = _wrap_func(f, xdata, ydata, transform)
if callable(jac):
jac = _wrap_jac(jac, xdata, transform)
elif jac is None and method != 'lm':
jac = '2-point'
if method == 'lm':
# Remove full_output from kwargs, otherwise we're passing it in twice.
return_full = kwargs.pop('full_output', False)
res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
popt, pcov, infodict, errmsg, ier = res
cost = np.sum(infodict['fvec'] ** 2)
if ier not in [1, 2, 3, 4]:
raise RuntimeError("Optimal parameters not found: " + errmsg)
else:
# Rename maxfev (leastsq) to max_nfev (least_squares), if specified.
if 'max_nfev' not in kwargs:
kwargs['max_nfev'] = kwargs.pop('maxfev', None)
res = least_squares(func, p0, jac=jac, bounds=bounds, method=method,
**kwargs)
if not res.success:
raise RuntimeError("Optimal parameters not found: " + res.message)
cost = 2 * res.cost # res.cost is half sum of squares!
popt = res.x
# Do Moore-Penrose inverse discarding zero singular values.
_, s, VT = svd(res.jac, full_matrices=False)
threshold = np.finfo(float).eps * max(res.jac.shape) * s[0]
s = s[s > threshold]
VT = VT[:s.size]
pcov = np.dot(VT.T / s**2, VT)
return_full = False
warn_cov = False
if pcov is None:
# indeterminate covariance
pcov = zeros((len(popt), len(popt)), dtype=float)
pcov.fill(inf)
warn_cov = True
elif not absolute_sigma:
if ydata.size > p0.size:
s_sq = cost / (ydata.size - p0.size)
pcov = pcov * s_sq
else:
pcov.fill(inf)
warn_cov = True
if warn_cov:
warnings.warn('Covariance of the parameters could not be estimated',
category=OptimizeWarning)
if return_full:
return popt, pcov, infodict, errmsg, ier
else:
return popt, pcov | [
"def",
"curve_fit",
"(",
"f",
",",
"xdata",
",",
"ydata",
",",
"p0",
"=",
"None",
",",
"sigma",
"=",
"None",
",",
"absolute_sigma",
"=",
"False",
",",
"check_finite",
"=",
"True",
",",
"bounds",
"=",
"(",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
")",
",",
"method",
"=",
"None",
",",
"jac",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"p0",
"is",
"None",
":",
"# determine number of parameters by inspecting the function",
"from",
"scipy",
".",
"_lib",
".",
"_util",
"import",
"getargspec_no_self",
"as",
"_getargspec",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
"=",
"_getargspec",
"(",
"f",
")",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Unable to determine number of fit parameters.\"",
")",
"n",
"=",
"len",
"(",
"args",
")",
"-",
"1",
"else",
":",
"p0",
"=",
"np",
".",
"atleast_1d",
"(",
"p0",
")",
"n",
"=",
"p0",
".",
"size",
"lb",
",",
"ub",
"=",
"prepare_bounds",
"(",
"bounds",
",",
"n",
")",
"if",
"p0",
"is",
"None",
":",
"p0",
"=",
"_initialize_feasible",
"(",
"lb",
",",
"ub",
")",
"bounded_problem",
"=",
"np",
".",
"any",
"(",
"(",
"lb",
">",
"-",
"np",
".",
"inf",
")",
"|",
"(",
"ub",
"<",
"np",
".",
"inf",
")",
")",
"if",
"method",
"is",
"None",
":",
"if",
"bounded_problem",
":",
"method",
"=",
"'trf'",
"else",
":",
"method",
"=",
"'lm'",
"if",
"method",
"==",
"'lm'",
"and",
"bounded_problem",
":",
"raise",
"ValueError",
"(",
"\"Method 'lm' only works for unconstrained problems. \"",
"\"Use 'trf' or 'dogbox' instead.\"",
")",
"# NaNs can not be handled",
"if",
"check_finite",
":",
"ydata",
"=",
"np",
".",
"asarray_chkfinite",
"(",
"ydata",
")",
"else",
":",
"ydata",
"=",
"np",
".",
"asarray",
"(",
"ydata",
")",
"if",
"isinstance",
"(",
"xdata",
",",
"(",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"# `xdata` is passed straight to the user-defined `f`, so allow",
"# non-array_like `xdata`.",
"if",
"check_finite",
":",
"xdata",
"=",
"np",
".",
"asarray_chkfinite",
"(",
"xdata",
")",
"else",
":",
"xdata",
"=",
"np",
".",
"asarray",
"(",
"xdata",
")",
"# optimization may produce garbage for float32 inputs, cast them to float64",
"xdata",
"=",
"xdata",
".",
"astype",
"(",
"float",
")",
"ydata",
"=",
"ydata",
".",
"astype",
"(",
"float",
")",
"# Determine type of sigma",
"if",
"sigma",
"is",
"not",
"None",
":",
"sigma",
"=",
"np",
".",
"asarray",
"(",
"sigma",
")",
"# if 1-d, sigma are errors, define transform = 1/sigma",
"if",
"sigma",
".",
"shape",
"==",
"(",
"ydata",
".",
"size",
",",
")",
":",
"transform",
"=",
"1.0",
"/",
"sigma",
"# if 2-d, sigma is the covariance matrix,",
"# define transform = L such that L L^T = C",
"elif",
"sigma",
".",
"shape",
"==",
"(",
"ydata",
".",
"size",
",",
"ydata",
".",
"size",
")",
":",
"try",
":",
"# scipy.linalg.cholesky requires lower=True to return L L^T = A",
"transform",
"=",
"cholesky",
"(",
"sigma",
",",
"lower",
"=",
"True",
")",
"except",
"LinAlgError",
":",
"raise",
"ValueError",
"(",
"\"`sigma` must be positive definite.\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"`sigma` has incorrect shape.\"",
")",
"else",
":",
"transform",
"=",
"None",
"func",
"=",
"_wrap_func",
"(",
"f",
",",
"xdata",
",",
"ydata",
",",
"transform",
")",
"if",
"callable",
"(",
"jac",
")",
":",
"jac",
"=",
"_wrap_jac",
"(",
"jac",
",",
"xdata",
",",
"transform",
")",
"elif",
"jac",
"is",
"None",
"and",
"method",
"!=",
"'lm'",
":",
"jac",
"=",
"'2-point'",
"if",
"method",
"==",
"'lm'",
":",
"# Remove full_output from kwargs, otherwise we're passing it in twice.",
"return_full",
"=",
"kwargs",
".",
"pop",
"(",
"'full_output'",
",",
"False",
")",
"res",
"=",
"leastsq",
"(",
"func",
",",
"p0",
",",
"Dfun",
"=",
"jac",
",",
"full_output",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
"popt",
",",
"pcov",
",",
"infodict",
",",
"errmsg",
",",
"ier",
"=",
"res",
"cost",
"=",
"np",
".",
"sum",
"(",
"infodict",
"[",
"'fvec'",
"]",
"**",
"2",
")",
"if",
"ier",
"not",
"in",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
"]",
":",
"raise",
"RuntimeError",
"(",
"\"Optimal parameters not found: \"",
"+",
"errmsg",
")",
"else",
":",
"# Rename maxfev (leastsq) to max_nfev (least_squares), if specified.",
"if",
"'max_nfev'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'max_nfev'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'maxfev'",
",",
"None",
")",
"res",
"=",
"least_squares",
"(",
"func",
",",
"p0",
",",
"jac",
"=",
"jac",
",",
"bounds",
"=",
"bounds",
",",
"method",
"=",
"method",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"res",
".",
"success",
":",
"raise",
"RuntimeError",
"(",
"\"Optimal parameters not found: \"",
"+",
"res",
".",
"message",
")",
"cost",
"=",
"2",
"*",
"res",
".",
"cost",
"# res.cost is half sum of squares!",
"popt",
"=",
"res",
".",
"x",
"# Do Moore-Penrose inverse discarding zero singular values.",
"_",
",",
"s",
",",
"VT",
"=",
"svd",
"(",
"res",
".",
"jac",
",",
"full_matrices",
"=",
"False",
")",
"threshold",
"=",
"np",
".",
"finfo",
"(",
"float",
")",
".",
"eps",
"*",
"max",
"(",
"res",
".",
"jac",
".",
"shape",
")",
"*",
"s",
"[",
"0",
"]",
"s",
"=",
"s",
"[",
"s",
">",
"threshold",
"]",
"VT",
"=",
"VT",
"[",
":",
"s",
".",
"size",
"]",
"pcov",
"=",
"np",
".",
"dot",
"(",
"VT",
".",
"T",
"/",
"s",
"**",
"2",
",",
"VT",
")",
"return_full",
"=",
"False",
"warn_cov",
"=",
"False",
"if",
"pcov",
"is",
"None",
":",
"# indeterminate covariance",
"pcov",
"=",
"zeros",
"(",
"(",
"len",
"(",
"popt",
")",
",",
"len",
"(",
"popt",
")",
")",
",",
"dtype",
"=",
"float",
")",
"pcov",
".",
"fill",
"(",
"inf",
")",
"warn_cov",
"=",
"True",
"elif",
"not",
"absolute_sigma",
":",
"if",
"ydata",
".",
"size",
">",
"p0",
".",
"size",
":",
"s_sq",
"=",
"cost",
"/",
"(",
"ydata",
".",
"size",
"-",
"p0",
".",
"size",
")",
"pcov",
"=",
"pcov",
"*",
"s_sq",
"else",
":",
"pcov",
".",
"fill",
"(",
"inf",
")",
"warn_cov",
"=",
"True",
"if",
"warn_cov",
":",
"warnings",
".",
"warn",
"(",
"'Covariance of the parameters could not be estimated'",
",",
"category",
"=",
"OptimizeWarning",
")",
"if",
"return_full",
":",
"return",
"popt",
",",
"pcov",
",",
"infodict",
",",
"errmsg",
",",
"ier",
"else",
":",
"return",
"popt",
",",
"pcov"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/minpack.py#L504-L796 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/base/renderers.py | python | LatexRenderer.addPreamble | (self, node) | Add a string to the preamble (see pdf.py). | Add a string to the preamble (see pdf.py). | [
"Add",
"a",
"string",
"to",
"the",
"preamble",
"(",
"see",
"pdf",
".",
"py",
")",
"."
] | def addPreamble(self, node):
"""
Add a string to the preamble (see pdf.py).
"""
self._preamble.append(node) | [
"def",
"addPreamble",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"_preamble",
".",
"append",
"(",
"node",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/base/renderers.py#L421-L425 | ||
rbgirshick/caffe-fast-rcnn | 28a579eaf0668850705598b3075b8969f22226d9 | scripts/cpp_lint.py | python | FindStartOfExpressionInLine | (line, endpos, depth, startchar, endchar) | return (-1, depth) | Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line) | Find position at the matching startchar. | [
"Find",
"position",
"at",
"the",
"matching",
"startchar",
"."
] | def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
"""Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line)
"""
for i in xrange(endpos, -1, -1):
if line[i] == endchar:
depth += 1
elif line[i] == startchar:
depth -= 1
if depth == 0:
return (i, 0)
return (-1, depth) | [
"def",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"endpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"endpos",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"endchar",
":",
"depth",
"+=",
"1",
"elif",
"line",
"[",
"i",
"]",
"==",
"startchar",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"return",
"(",
"i",
",",
"0",
")",
"return",
"(",
"-",
"1",
",",
"depth",
")"
] | https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L1300-L1324 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/common_util.py | python | GetCommandLineForLogging | (cmd, env_diff=None) | return cmd_str + subprocess.list2cmdline(cmd) | Get command line string.
Args:
cmd: Command line argument
env_diff: Environment modification for the command line.
Returns:
Command line string. | Get command line string. | [
"Get",
"command",
"line",
"string",
"."
] | def GetCommandLineForLogging(cmd, env_diff=None):
"""Get command line string.
Args:
cmd: Command line argument
env_diff: Environment modification for the command line.
Returns:
Command line string.
"""
cmd_str = ''
if env_diff:
for key, value in env_diff.iteritems():
cmd_str += '{}={} '.format(key, value)
return cmd_str + subprocess.list2cmdline(cmd) | [
"def",
"GetCommandLineForLogging",
"(",
"cmd",
",",
"env_diff",
"=",
"None",
")",
":",
"cmd_str",
"=",
"''",
"if",
"env_diff",
":",
"for",
"key",
",",
"value",
"in",
"env_diff",
".",
"iteritems",
"(",
")",
":",
"cmd_str",
"+=",
"'{}={} '",
".",
"format",
"(",
"key",
",",
"value",
")",
"return",
"cmd_str",
"+",
"subprocess",
".",
"list2cmdline",
"(",
"cmd",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/common_util.py#L103-L117 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.AutoCompStops | (*args, **kwargs) | return _stc.StyledTextCtrl_AutoCompStops(*args, **kwargs) | AutoCompStops(self, String characterSet)
Define a set of character that when typed cancel the auto-completion list. | AutoCompStops(self, String characterSet) | [
"AutoCompStops",
"(",
"self",
"String",
"characterSet",
")"
] | def AutoCompStops(*args, **kwargs):
"""
AutoCompStops(self, String characterSet)
Define a set of character that when typed cancel the auto-completion list.
"""
return _stc.StyledTextCtrl_AutoCompStops(*args, **kwargs) | [
"def",
"AutoCompStops",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_AutoCompStops",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L3070-L3076 | |
NREL/EnergyPlus | fadc5973b85c70e8cc923efb69c144e808a26078 | src/EnergyPlus/api/func.py | python | Functional.callback_error | (self, state, f: FunctionType) | This function allows a client to register a function to be called back by EnergyPlus when an error message
is added to the error file. The user can then detect specific error messages or whatever.
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:param f: A python function which takes an integer severity and a string (bytes) argument and returns nothing
:return: Nothing | This function allows a client to register a function to be called back by EnergyPlus when an error message
is added to the error file. The user can then detect specific error messages or whatever. | [
"This",
"function",
"allows",
"a",
"client",
"to",
"register",
"a",
"function",
"to",
"be",
"called",
"back",
"by",
"EnergyPlus",
"when",
"an",
"error",
"message",
"is",
"added",
"to",
"the",
"error",
"file",
".",
"The",
"user",
"can",
"then",
"detect",
"specific",
"error",
"messages",
"or",
"whatever",
"."
] | def callback_error(self, state, f: FunctionType) -> None:
"""
This function allows a client to register a function to be called back by EnergyPlus when an error message
is added to the error file. The user can then detect specific error messages or whatever.
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:param f: A python function which takes an integer severity and a string (bytes) argument and returns nothing
:return: Nothing
"""
cb_ptr = self.py_error_callback_type(f)
error_callbacks.append(cb_ptr)
self.api.registerErrorCallback(state, cb_ptr) | [
"def",
"callback_error",
"(",
"self",
",",
"state",
",",
"f",
":",
"FunctionType",
")",
"->",
"None",
":",
"cb_ptr",
"=",
"self",
".",
"py_error_callback_type",
"(",
"f",
")",
"error_callbacks",
".",
"append",
"(",
"cb_ptr",
")",
"self",
".",
"api",
".",
"registerErrorCallback",
"(",
"state",
",",
"cb_ptr",
")"
] | https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/src/EnergyPlus/api/func.py#L644-L655 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/pipeline/sync/skip/portal.py | python | Portal.copy | (self, prev_stream: AbstractStream, next_stream: AbstractStream, phony: Tensor,) | return PortalCopy.apply(self, prev_stream, next_stream, phony) | Copies the hidden tensor by a :class:`PortalCopy`.
Give a phony and use the returning phony to keep backpropagation::
+-- PortalCopy --+
| |
-- Fork ---------- Join -- | Copies the hidden tensor by a :class:`PortalCopy`. | [
"Copies",
"the",
"hidden",
"tensor",
"by",
"a",
":",
"class",
":",
"PortalCopy",
"."
] | def copy(self, prev_stream: AbstractStream, next_stream: AbstractStream, phony: Tensor,) -> Tensor:
"""Copies the hidden tensor by a :class:`PortalCopy`.
Give a phony and use the returning phony to keep backpropagation::
+-- PortalCopy --+
| |
-- Fork ---------- Join --
"""
if self.tensor is None:
return get_phony(torch.device("cpu"), requires_grad=False)
return PortalCopy.apply(self, prev_stream, next_stream, phony) | [
"def",
"copy",
"(",
"self",
",",
"prev_stream",
":",
"AbstractStream",
",",
"next_stream",
":",
"AbstractStream",
",",
"phony",
":",
"Tensor",
",",
")",
"->",
"Tensor",
":",
"if",
"self",
".",
"tensor",
"is",
"None",
":",
"return",
"get_phony",
"(",
"torch",
".",
"device",
"(",
"\"cpu\"",
")",
",",
"requires_grad",
"=",
"False",
")",
"return",
"PortalCopy",
".",
"apply",
"(",
"self",
",",
"prev_stream",
",",
"next_stream",
",",
"phony",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/pipeline/sync/skip/portal.py#L73-L86 | |
google/flatbuffers | b3006913369e0a7550795e477011ac5bebb93497 | python/flatbuffers/flexbuffers.py | python | Builder.IndirectUInt | (self, value, byte_width=0) | Encodes unsigned integer value indirectly.
Args:
value: An unsigned integer value.
byte_width: Number of bytes to use: 1, 2, 4, or 8. | Encodes unsigned integer value indirectly. | [
"Encodes",
"unsigned",
"integer",
"value",
"indirectly",
"."
] | def IndirectUInt(self, value, byte_width=0):
"""Encodes unsigned integer value indirectly.
Args:
value: An unsigned integer value.
byte_width: Number of bytes to use: 1, 2, 4, or 8.
"""
bit_width = BitWidth.U(value) if byte_width == 0 else BitWidth.B(byte_width)
self._PushIndirect(value, Type.INDIRECT_UINT, bit_width) | [
"def",
"IndirectUInt",
"(",
"self",
",",
"value",
",",
"byte_width",
"=",
"0",
")",
":",
"bit_width",
"=",
"BitWidth",
".",
"U",
"(",
"value",
")",
"if",
"byte_width",
"==",
"0",
"else",
"BitWidth",
".",
"B",
"(",
"byte_width",
")",
"self",
".",
"_PushIndirect",
"(",
"value",
",",
"Type",
".",
"INDIRECT_UINT",
",",
"bit_width",
")"
] | https://github.com/google/flatbuffers/blob/b3006913369e0a7550795e477011ac5bebb93497/python/flatbuffers/flexbuffers.py#L1264-L1272 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/filter_design.py | python | _zpklp2lp | (z, p, k, wo=1.0) | return z_lp, p_lp, k_lp | r"""
Transform a lowpass filter prototype to a different frequency.
Return an analog low-pass filter with cutoff frequency `wo`
from an analog low-pass filter prototype with unity cutoff frequency,
using zeros, poles, and gain ('zpk') representation.
Parameters
----------
z : array_like
Zeros of the analog IIR filter transfer function.
p : array_like
Poles of the analog IIR filter transfer function.
k : float
System gain of the analog IIR filter transfer function.
wo : float
Desired cutoff, as angular frequency (e.g. rad/s).
Defaults to no change.
Returns
-------
z : ndarray
Zeros of the transformed low-pass filter transfer function.
p : ndarray
Poles of the transformed low-pass filter transfer function.
k : float
System gain of the transformed low-pass filter.
Notes
-----
This is derived from the s-plane substitution
.. math:: s \rightarrow \frac{s}{\omega_0} | r"""
Transform a lowpass filter prototype to a different frequency. | [
"r",
"Transform",
"a",
"lowpass",
"filter",
"prototype",
"to",
"a",
"different",
"frequency",
"."
] | def _zpklp2lp(z, p, k, wo=1.0):
r"""
Transform a lowpass filter prototype to a different frequency.
Return an analog low-pass filter with cutoff frequency `wo`
from an analog low-pass filter prototype with unity cutoff frequency,
using zeros, poles, and gain ('zpk') representation.
Parameters
----------
z : array_like
Zeros of the analog IIR filter transfer function.
p : array_like
Poles of the analog IIR filter transfer function.
k : float
System gain of the analog IIR filter transfer function.
wo : float
Desired cutoff, as angular frequency (e.g. rad/s).
Defaults to no change.
Returns
-------
z : ndarray
Zeros of the transformed low-pass filter transfer function.
p : ndarray
Poles of the transformed low-pass filter transfer function.
k : float
System gain of the transformed low-pass filter.
Notes
-----
This is derived from the s-plane substitution
.. math:: s \rightarrow \frac{s}{\omega_0}
"""
z = atleast_1d(z)
p = atleast_1d(p)
wo = float(wo) # Avoid int wraparound
degree = _relative_degree(z, p)
# Scale all points radially from origin to shift cutoff frequency
z_lp = wo * z
p_lp = wo * p
# Each shifted pole decreases gain by wo, each shifted zero increases it.
# Cancel out the net change to keep overall gain the same
k_lp = k * wo**degree
return z_lp, p_lp, k_lp | [
"def",
"_zpklp2lp",
"(",
"z",
",",
"p",
",",
"k",
",",
"wo",
"=",
"1.0",
")",
":",
"z",
"=",
"atleast_1d",
"(",
"z",
")",
"p",
"=",
"atleast_1d",
"(",
"p",
")",
"wo",
"=",
"float",
"(",
"wo",
")",
"# Avoid int wraparound",
"degree",
"=",
"_relative_degree",
"(",
"z",
",",
"p",
")",
"# Scale all points radially from origin to shift cutoff frequency",
"z_lp",
"=",
"wo",
"*",
"z",
"p_lp",
"=",
"wo",
"*",
"p",
"# Each shifted pole decreases gain by wo, each shifted zero increases it.",
"# Cancel out the net change to keep overall gain the same",
"k_lp",
"=",
"k",
"*",
"wo",
"**",
"degree",
"return",
"z_lp",
",",
"p_lp",
",",
"k_lp"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/filter_design.py#L1786-L1836 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/backends/android_app_backend.py | python | AndroidAppBackend.Start | (self) | Start an Android app and wait for it to finish launching.
If the app has webviews, the app is launched with the suitable
command line arguments.
AppStory derivations can customize the wait-for-ready-state to wait
for a more specific event if needed. | Start an Android app and wait for it to finish launching. | [
"Start",
"an",
"Android",
"app",
"and",
"wait",
"for",
"it",
"to",
"finish",
"launching",
"."
] | def Start(self):
"""Start an Android app and wait for it to finish launching.
If the app has webviews, the app is launched with the suitable
command line arguments.
AppStory derivations can customize the wait-for-ready-state to wait
for a more specific event if needed.
"""
if self._app_has_webviews:
webview_startup_args = self.GetWebviewStartupArgs()
backend_settings = (
android_browser_backend_settings.WebviewBackendSettings(
'android-webview'))
with android_command_line_backend.SetUpCommandLineFlags(
self.device, backend_settings, webview_startup_args):
self._LaunchAndWaitForApplication()
else:
self._LaunchAndWaitForApplication()
self._is_running = True | [
"def",
"Start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_app_has_webviews",
":",
"webview_startup_args",
"=",
"self",
".",
"GetWebviewStartupArgs",
"(",
")",
"backend_settings",
"=",
"(",
"android_browser_backend_settings",
".",
"WebviewBackendSettings",
"(",
"'android-webview'",
")",
")",
"with",
"android_command_line_backend",
".",
"SetUpCommandLineFlags",
"(",
"self",
".",
"device",
",",
"backend_settings",
",",
"webview_startup_args",
")",
":",
"self",
".",
"_LaunchAndWaitForApplication",
"(",
")",
"else",
":",
"self",
".",
"_LaunchAndWaitForApplication",
"(",
")",
"self",
".",
"_is_running",
"=",
"True"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/android_app_backend.py#L58-L77 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TextCtrl.IsMultiLine | (*args, **kwargs) | return _controls_.TextCtrl_IsMultiLine(*args, **kwargs) | IsMultiLine(self) -> bool | IsMultiLine(self) -> bool | [
"IsMultiLine",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsMultiLine(*args, **kwargs):
"""IsMultiLine(self) -> bool"""
return _controls_.TextCtrl_IsMultiLine(*args, **kwargs) | [
"def",
"IsMultiLine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextCtrl_IsMultiLine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2035-L2037 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/training/momentum.py | python | MomentumOptimizer.__init__ | (self, learning_rate, momentum,
use_locking=False, name="Momentum", use_nesterov=False) | Construct a new Momentum optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
momentum: A `Tensor` or a floating point value. The momentum.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "Momentum". | Construct a new Momentum optimizer. | [
"Construct",
"a",
"new",
"Momentum",
"optimizer",
"."
] | def __init__(self, learning_rate, momentum,
use_locking=False, name="Momentum", use_nesterov=False):
"""Construct a new Momentum optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
momentum: A `Tensor` or a floating point value. The momentum.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "Momentum".
"""
super(MomentumOptimizer, self).__init__(use_locking, name)
self._learning_rate = learning_rate
self._momentum = momentum
self._use_nesterov = use_nesterov | [
"def",
"__init__",
"(",
"self",
",",
"learning_rate",
",",
"momentum",
",",
"use_locking",
"=",
"False",
",",
"name",
"=",
"\"Momentum\"",
",",
"use_nesterov",
"=",
"False",
")",
":",
"super",
"(",
"MomentumOptimizer",
",",
"self",
")",
".",
"__init__",
"(",
"use_locking",
",",
"name",
")",
"self",
".",
"_learning_rate",
"=",
"learning_rate",
"self",
".",
"_momentum",
"=",
"momentum",
"self",
".",
"_use_nesterov",
"=",
"use_nesterov"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/momentum.py#L33-L47 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Distribution.load_entry_point | (self, group, name) | return ep.load() | Return the `name` entry point of `group` or raise ImportError | Return the `name` entry point of `group` or raise ImportError | [
"Return",
"the",
"name",
"entry",
"point",
"of",
"group",
"or",
"raise",
"ImportError"
] | def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
return ep.load() | [
"def",
"load_entry_point",
"(",
"self",
",",
"group",
",",
"name",
")",
":",
"ep",
"=",
"self",
".",
"get_entry_info",
"(",
"group",
",",
"name",
")",
"if",
"ep",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"Entry point %r not found\"",
"%",
"(",
"(",
"group",
",",
"name",
")",
",",
")",
")",
"return",
"ep",
".",
"load",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L5693-L5703 | |
chanyn/3Dpose_ssl | 585696676279683a279b1ecca136c0e0d02aef2a | tensorflow/m_refine_v2.py | python | kaiming | (shape, dtype, partition_info=None) | return(tf.truncated_normal(shape, dtype=dtype)*tf.sqrt(2/float(shape[0]))) | Kaiming initialization as described in https://arxiv.org/pdf/1502.01852.pdf
Args
shape: dimensions of the tf array to initialize
dtype: data type of the array
partition_info: (Optional) info about how the variable is partitioned.
See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/init_ops.py#L26
Needed to be used as an initializer.
Returns
Tensorflow array with initial weights | Kaiming initialization as described in https://arxiv.org/pdf/1502.01852.pdf | [
"Kaiming",
"initialization",
"as",
"described",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1502",
".",
"01852",
".",
"pdf"
] | def kaiming(shape, dtype, partition_info=None):
"""Kaiming initialization as described in https://arxiv.org/pdf/1502.01852.pdf
Args
shape: dimensions of the tf array to initialize
dtype: data type of the array
partition_info: (Optional) info about how the variable is partitioned.
See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/init_ops.py#L26
Needed to be used as an initializer.
Returns
Tensorflow array with initial weights
"""
return(tf.truncated_normal(shape, dtype=dtype)*tf.sqrt(2/float(shape[0]))) | [
"def",
"kaiming",
"(",
"shape",
",",
"dtype",
",",
"partition_info",
"=",
"None",
")",
":",
"return",
"(",
"tf",
".",
"truncated_normal",
"(",
"shape",
",",
"dtype",
"=",
"dtype",
")",
"*",
"tf",
".",
"sqrt",
"(",
"2",
"/",
"float",
"(",
"shape",
"[",
"0",
"]",
")",
")",
")"
] | https://github.com/chanyn/3Dpose_ssl/blob/585696676279683a279b1ecca136c0e0d02aef2a/tensorflow/m_refine_v2.py#L16-L28 | |
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | protobuf/python/google/protobuf/internal/_parameterized.py | python | NamedParameters | (*testcases) | return _ParameterDecorator(_FIRST_ARG, testcases) | A decorator for creating parameterized tests.
See the module docstring for a usage example. The first element of
each parameter tuple should be a string and will be appended to the
name of the test method.
Args:
*testcases: Parameters for the decorated method, either a single
iterable, or a list of tuples.
Returns:
A test generator to be handled by TestGeneratorMetaclass. | A decorator for creating parameterized tests. | [
"A",
"decorator",
"for",
"creating",
"parameterized",
"tests",
"."
] | def NamedParameters(*testcases):
"""A decorator for creating parameterized tests.
See the module docstring for a usage example. The first element of
each parameter tuple should be a string and will be appended to the
name of the test method.
Args:
*testcases: Parameters for the decorated method, either a single
iterable, or a list of tuples.
Returns:
A test generator to be handled by TestGeneratorMetaclass.
"""
return _ParameterDecorator(_FIRST_ARG, testcases) | [
"def",
"NamedParameters",
"(",
"*",
"testcases",
")",
":",
"return",
"_ParameterDecorator",
"(",
"_FIRST_ARG",
",",
"testcases",
")"
] | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/internal/_parameterized.py#L317-L331 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/subprocess_main.py | python | check_python_version | () | Checks python version to be greater or equal than 3.4
:return: exit code (1 - error, None - successful) | Checks python version to be greater or equal than 3.4
:return: exit code (1 - error, None - successful) | [
"Checks",
"python",
"version",
"to",
"be",
"greater",
"or",
"equal",
"than",
"3",
".",
"4",
":",
"return",
":",
"exit",
"code",
"(",
"1",
"-",
"error",
"None",
"-",
"successful",
")"
] | def check_python_version():
"""
Checks python version to be greater or equal than 3.4
:return: exit code (1 - error, None - successful)
"""
if sys.version_info < (3, 4):
print('Python version should be of version 3.4 or newer')
return 1 | [
"def",
"check_python_version",
"(",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"4",
")",
":",
"print",
"(",
"'Python version should be of version 3.4 or newer'",
")",
"return",
"1"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/subprocess_main.py#L10-L17 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/boosted_trees/estimator_batch/custom_loss_head.py | python | CustomLossHead.__init__ | (self,
loss_fn,
link_fn,
logit_dimension,
head_name=None,
weight_column_name=None,
metrics_fn=None) | `Head` for specifying arbitrary loss function.
Args:
loss_fn: Loss function.
link_fn: Function that converts logits to prediction.
logit_dimension: Number of dimensions for the logits.
head_name: name of the head. Predictions, summary, metrics keys are
suffixed by `"/" + head_name` and the default variable scope is
`head_name`.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
metrics_fn: a function that takes predictions dict, labels and weights and
returns a dictionary of metrics to be calculated. | `Head` for specifying arbitrary loss function. | [
"Head",
"for",
"specifying",
"arbitrary",
"loss",
"function",
"."
] | def __init__(self,
loss_fn,
link_fn,
logit_dimension,
head_name=None,
weight_column_name=None,
metrics_fn=None):
"""`Head` for specifying arbitrary loss function.
Args:
loss_fn: Loss function.
link_fn: Function that converts logits to prediction.
logit_dimension: Number of dimensions for the logits.
head_name: name of the head. Predictions, summary, metrics keys are
suffixed by `"/" + head_name` and the default variable scope is
`head_name`.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
metrics_fn: a function that takes predictions dict, labels and weights and
returns a dictionary of metrics to be calculated.
"""
def loss_wrapper(labels, logits, weight_tensor):
if weight_tensor is None:
weight_tensor = array_ops.ones(
shape=[array_ops.shape(labels)[0], 1], dtype=dtypes.float32)
weighted_loss, _ = loss_fn(labels, weight_tensor, logits)
average_loss = math_ops.reduce_mean(weighted_loss)
return average_loss, average_loss / math_ops.reduce_mean(weight_tensor)
super(CustomLossHead, self).__init__(
loss_fn=loss_wrapper,
link_fn=link_fn,
head_name=head_name,
weight_column_name=weight_column_name,
enable_centered_bias=False,
label_dimension=logit_dimension)
self._metrics_fn = metrics_fn | [
"def",
"__init__",
"(",
"self",
",",
"loss_fn",
",",
"link_fn",
",",
"logit_dimension",
",",
"head_name",
"=",
"None",
",",
"weight_column_name",
"=",
"None",
",",
"metrics_fn",
"=",
"None",
")",
":",
"def",
"loss_wrapper",
"(",
"labels",
",",
"logits",
",",
"weight_tensor",
")",
":",
"if",
"weight_tensor",
"is",
"None",
":",
"weight_tensor",
"=",
"array_ops",
".",
"ones",
"(",
"shape",
"=",
"[",
"array_ops",
".",
"shape",
"(",
"labels",
")",
"[",
"0",
"]",
",",
"1",
"]",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
"weighted_loss",
",",
"_",
"=",
"loss_fn",
"(",
"labels",
",",
"weight_tensor",
",",
"logits",
")",
"average_loss",
"=",
"math_ops",
".",
"reduce_mean",
"(",
"weighted_loss",
")",
"return",
"average_loss",
",",
"average_loss",
"/",
"math_ops",
".",
"reduce_mean",
"(",
"weight_tensor",
")",
"super",
"(",
"CustomLossHead",
",",
"self",
")",
".",
"__init__",
"(",
"loss_fn",
"=",
"loss_wrapper",
",",
"link_fn",
"=",
"link_fn",
",",
"head_name",
"=",
"head_name",
",",
"weight_column_name",
"=",
"weight_column_name",
",",
"enable_centered_bias",
"=",
"False",
",",
"label_dimension",
"=",
"logit_dimension",
")",
"self",
".",
"_metrics_fn",
"=",
"metrics_fn"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/boosted_trees/estimator_batch/custom_loss_head.py#L30-L69 | ||
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecAsmWrapper | (self, arch, *args) | return popen.returncode | Filter logo banner from invocations of asm.exe. | Filter logo banner from invocations of asm.exe. | [
"Filter",
"logo",
"banner",
"from",
"invocations",
"of",
"asm",
".",
"exe",
"."
] | def ExecAsmWrapper(self, arch, *args):
"""Filter logo banner from invocations of asm.exe."""
env = self._GetEnv(arch)
# MSVS doesn't assemble x64 asm files.
if arch == 'environment.x64':
return 0
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = popen.communicate()
for line in out.splitlines():
if (not line.startswith('Copyright (C) Microsoft Corporation') and
not line.startswith('Microsoft (R) Macro Assembler') and
not line.startswith(' Assembling: ') and
line):
print line
return popen.returncode | [
"def",
"ExecAsmWrapper",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"# MSVS doesn't assemble x64 asm files.",
"if",
"arch",
"==",
"'environment.x64'",
":",
"return",
"0",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"out",
",",
"_",
"=",
"popen",
".",
"communicate",
"(",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"'Copyright (C) Microsoft Corporation'",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"'Microsoft (R) Macro Assembler'",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"' Assembling: '",
")",
"and",
"line",
")",
":",
"print",
"line",
"return",
"popen",
".",
"returncode"
] | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/win_tool.py#L247-L262 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/__init__.py | python | convert_directive_function | (directive_fn) | return FunctionalDirective | Define & return a directive class generated from `directive_fn`.
`directive_fn` uses the old-style, functional interface. | Define & return a directive class generated from `directive_fn`. | [
"Define",
"&",
"return",
"a",
"directive",
"class",
"generated",
"from",
"directive_fn",
"."
] | def convert_directive_function(directive_fn):
"""
Define & return a directive class generated from `directive_fn`.
`directive_fn` uses the old-style, functional interface.
"""
class FunctionalDirective(Directive):
option_spec = getattr(directive_fn, 'options', None)
has_content = getattr(directive_fn, 'content', False)
_argument_spec = getattr(directive_fn, 'arguments', (0, 0, False))
required_arguments, optional_arguments, final_argument_whitespace \
= _argument_spec
def run(self):
return directive_fn(
self.name, self.arguments, self.options, self.content,
self.lineno, self.content_offset, self.block_text,
self.state, self.state_machine)
# Return new-style directive.
return FunctionalDirective | [
"def",
"convert_directive_function",
"(",
"directive_fn",
")",
":",
"class",
"FunctionalDirective",
"(",
"Directive",
")",
":",
"option_spec",
"=",
"getattr",
"(",
"directive_fn",
",",
"'options'",
",",
"None",
")",
"has_content",
"=",
"getattr",
"(",
"directive_fn",
",",
"'content'",
",",
"False",
")",
"_argument_spec",
"=",
"getattr",
"(",
"directive_fn",
",",
"'arguments'",
",",
"(",
"0",
",",
"0",
",",
"False",
")",
")",
"required_arguments",
",",
"optional_arguments",
",",
"final_argument_whitespace",
"=",
"_argument_spec",
"def",
"run",
"(",
"self",
")",
":",
"return",
"directive_fn",
"(",
"self",
".",
"name",
",",
"self",
".",
"arguments",
",",
"self",
".",
"options",
",",
"self",
".",
"content",
",",
"self",
".",
"lineno",
",",
"self",
".",
"content_offset",
",",
"self",
".",
"block_text",
",",
"self",
".",
"state",
",",
"self",
".",
"state_machine",
")",
"# Return new-style directive.",
"return",
"FunctionalDirective"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/__init__.py#L391-L413 | |
facebookresearch/faiss | eb8781557f556505ca93f6f21fff932e17f0d9e0 | contrib/evaluation.py | python | test_ref_knn_with_draws | (Dref, Iref, Dnew, Inew) | test that knn search results are identical, raise if not | test that knn search results are identical, raise if not | [
"test",
"that",
"knn",
"search",
"results",
"are",
"identical",
"raise",
"if",
"not"
] | def test_ref_knn_with_draws(Dref, Iref, Dnew, Inew):
""" test that knn search results are identical, raise if not """
np.testing.assert_array_almost_equal(Dref, Dnew, decimal=5)
# here we have to be careful because of draws
testcase = unittest.TestCase() # because it makes nice error messages
for i in range(len(Iref)):
if np.all(Iref[i] == Inew[i]): # easy case
continue
# we can deduce nothing about the latest line
skip_dis = Dref[i, -1]
for dis in np.unique(Dref):
if dis == skip_dis:
continue
mask = Dref[i, :] == dis
testcase.assertEqual(set(Iref[i, mask]), set(Inew[i, mask])) | [
"def",
"test_ref_knn_with_draws",
"(",
"Dref",
",",
"Iref",
",",
"Dnew",
",",
"Inew",
")",
":",
"np",
".",
"testing",
".",
"assert_array_almost_equal",
"(",
"Dref",
",",
"Dnew",
",",
"decimal",
"=",
"5",
")",
"# here we have to be careful because of draws",
"testcase",
"=",
"unittest",
".",
"TestCase",
"(",
")",
"# because it makes nice error messages",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"Iref",
")",
")",
":",
"if",
"np",
".",
"all",
"(",
"Iref",
"[",
"i",
"]",
"==",
"Inew",
"[",
"i",
"]",
")",
":",
"# easy case",
"continue",
"# we can deduce nothing about the latest line",
"skip_dis",
"=",
"Dref",
"[",
"i",
",",
"-",
"1",
"]",
"for",
"dis",
"in",
"np",
".",
"unique",
"(",
"Dref",
")",
":",
"if",
"dis",
"==",
"skip_dis",
":",
"continue",
"mask",
"=",
"Dref",
"[",
"i",
",",
":",
"]",
"==",
"dis",
"testcase",
".",
"assertEqual",
"(",
"set",
"(",
"Iref",
"[",
"i",
",",
"mask",
"]",
")",
",",
"set",
"(",
"Inew",
"[",
"i",
",",
"mask",
"]",
")",
")"
] | https://github.com/facebookresearch/faiss/blob/eb8781557f556505ca93f6f21fff932e17f0d9e0/contrib/evaluation.py#L227-L241 | ||
tensorflow/minigo | 6d89c202cdceaf449aefc3149ab2110d44f1a6a4 | ml_perf/utils.py | python | copy_tree | (src, dst, verbose=False) | Copies everything under src to dst. | Copies everything under src to dst. | [
"Copies",
"everything",
"under",
"src",
"to",
"dst",
"."
] | def copy_tree(src, dst, verbose=False):
"""Copies everything under src to dst."""
print('Copying {} to {}'.format(src, dst))
for src_dir, sub_dirs, basenames in tf.io.gfile.walk(src):
rel_dir = os.path.relpath(src_dir, src)
dst_dir = os.path.join(dst, rel_dir)
for sub_dir in sorted(sub_dirs):
path = os.path.join(dst, rel_dir, sub_dir)
print('Make dir {}'.format(path))
tf.io.gfile.makedirs(path)
if basenames:
print('Copying {} files from {} to {}'.format(
len(basenames), src_dir, dst_dir))
for basename in basenames:
src_path = os.path.join(src_dir, basename)
dst_path = os.path.join(dst_dir, basename)
if verbose:
print('Copying {} to {}'.format(src_path, dst_path))
tf.io.gfile.copy(src_path, dst_path) | [
"def",
"copy_tree",
"(",
"src",
",",
"dst",
",",
"verbose",
"=",
"False",
")",
":",
"print",
"(",
"'Copying {} to {}'",
".",
"format",
"(",
"src",
",",
"dst",
")",
")",
"for",
"src_dir",
",",
"sub_dirs",
",",
"basenames",
"in",
"tf",
".",
"io",
".",
"gfile",
".",
"walk",
"(",
"src",
")",
":",
"rel_dir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"src_dir",
",",
"src",
")",
"dst_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"rel_dir",
")",
"for",
"sub_dir",
"in",
"sorted",
"(",
"sub_dirs",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"rel_dir",
",",
"sub_dir",
")",
"print",
"(",
"'Make dir {}'",
".",
"format",
"(",
"path",
")",
")",
"tf",
".",
"io",
".",
"gfile",
".",
"makedirs",
"(",
"path",
")",
"if",
"basenames",
":",
"print",
"(",
"'Copying {} files from {} to {}'",
".",
"format",
"(",
"len",
"(",
"basenames",
")",
",",
"src_dir",
",",
"dst_dir",
")",
")",
"for",
"basename",
"in",
"basenames",
":",
"src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src_dir",
",",
"basename",
")",
"dst_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst_dir",
",",
"basename",
")",
"if",
"verbose",
":",
"print",
"(",
"'Copying {} to {}'",
".",
"format",
"(",
"src_path",
",",
"dst_path",
")",
")",
"tf",
".",
"io",
".",
"gfile",
".",
"copy",
"(",
"src_path",
",",
"dst_path",
")"
] | https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/ml_perf/utils.py#L112-L131 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/tools/saved_model_cli.py | python | get_meta_graph_def | (saved_model_dir, tag_set) | return saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) | DEPRECATED: Use saved_model_utils.get_meta_graph_def instead.
Gets MetaGraphDef from SavedModel. Returns the MetaGraphDef for the given
tag-set and SavedModel directory.
Args:
saved_model_dir: Directory containing the SavedModel to inspect or execute.
tag_set: Group of tag(s) of the MetaGraphDef to load, in string format,
separated by ','. For tag-set contains multiple tags, all tags must be
passed in.
Raises:
RuntimeError: An error when the given tag-set does not exist in the
SavedModel.
Returns:
A MetaGraphDef corresponding to the tag-set. | DEPRECATED: Use saved_model_utils.get_meta_graph_def instead. | [
"DEPRECATED",
":",
"Use",
"saved_model_utils",
".",
"get_meta_graph_def",
"instead",
"."
] | def get_meta_graph_def(saved_model_dir, tag_set):
"""DEPRECATED: Use saved_model_utils.get_meta_graph_def instead.
Gets MetaGraphDef from SavedModel. Returns the MetaGraphDef for the given
tag-set and SavedModel directory.
Args:
saved_model_dir: Directory containing the SavedModel to inspect or execute.
tag_set: Group of tag(s) of the MetaGraphDef to load, in string format,
separated by ','. For tag-set contains multiple tags, all tags must be
passed in.
Raises:
RuntimeError: An error when the given tag-set does not exist in the
SavedModel.
Returns:
A MetaGraphDef corresponding to the tag-set.
"""
return saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) | [
"def",
"get_meta_graph_def",
"(",
"saved_model_dir",
",",
"tag_set",
")",
":",
"return",
"saved_model_utils",
".",
"get_meta_graph_def",
"(",
"saved_model_dir",
",",
"tag_set",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/tools/saved_model_cli.py#L188-L207 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.IsSelectionBold | (*args, **kwargs) | return _richtext.RichTextCtrl_IsSelectionBold(*args, **kwargs) | IsSelectionBold(self) -> bool
Is all of the selection bold? | IsSelectionBold(self) -> bool | [
"IsSelectionBold",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsSelectionBold(*args, **kwargs):
"""
IsSelectionBold(self) -> bool
Is all of the selection bold?
"""
return _richtext.RichTextCtrl_IsSelectionBold(*args, **kwargs) | [
"def",
"IsSelectionBold",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_IsSelectionBold",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3919-L3925 | |
Ford/AVData | 2fdb17f236966a560c8c5c4f3976886d2dc3cab5 | ford_demo/scripts/extrinsics_broadcaster.py | python | main | () | Main function.
Reading transform info from a yaml file and publish to tf2 | Main function.
Reading transform info from a yaml file and publish to tf2 | [
"Main",
"function",
".",
"Reading",
"transform",
"info",
"from",
"a",
"yaml",
"file",
"and",
"publish",
"to",
"tf2"
] | def main():
"""Main function.
Reading transform info from a yaml file and publish to tf2
"""
if len(sys.argv) == 1:
print("error: no extrinsics yaml file given")
print("usage: python extrinsics_broadcaster.py extrinsic_example.yaml")
return
file_path = open(sys.argv[1])
print(file_path)
transform_stamped = yaml.safe_load(file_path)
command = 'rosrun tf2_ros static_transform_publisher '\
'%f %f %f %f %f %f %f %s %s' % (transform_stamped['transform']['translation']['x'],
transform_stamped['transform']['translation']['y'],
transform_stamped['transform']['translation']['z'],
transform_stamped['transform']['rotation']['x'],
transform_stamped['transform']['rotation']['y'],
transform_stamped['transform']['rotation']['z'],
transform_stamped['transform']['rotation']['w'],
transform_stamped['header']['frame_id'],
transform_stamped['child_frame_id'])
print(command)
ret = os.system(command)
print(ret) | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"1",
":",
"print",
"(",
"\"error: no extrinsics yaml file given\"",
")",
"print",
"(",
"\"usage: python extrinsics_broadcaster.py extrinsic_example.yaml\"",
")",
"return",
"file_path",
"=",
"open",
"(",
"sys",
".",
"argv",
"[",
"1",
"]",
")",
"print",
"(",
"file_path",
")",
"transform_stamped",
"=",
"yaml",
".",
"safe_load",
"(",
"file_path",
")",
"command",
"=",
"'rosrun tf2_ros static_transform_publisher '",
"'%f %f %f %f %f %f %f %s %s'",
"%",
"(",
"transform_stamped",
"[",
"'transform'",
"]",
"[",
"'translation'",
"]",
"[",
"'x'",
"]",
",",
"transform_stamped",
"[",
"'transform'",
"]",
"[",
"'translation'",
"]",
"[",
"'y'",
"]",
",",
"transform_stamped",
"[",
"'transform'",
"]",
"[",
"'translation'",
"]",
"[",
"'z'",
"]",
",",
"transform_stamped",
"[",
"'transform'",
"]",
"[",
"'rotation'",
"]",
"[",
"'x'",
"]",
",",
"transform_stamped",
"[",
"'transform'",
"]",
"[",
"'rotation'",
"]",
"[",
"'y'",
"]",
",",
"transform_stamped",
"[",
"'transform'",
"]",
"[",
"'rotation'",
"]",
"[",
"'z'",
"]",
",",
"transform_stamped",
"[",
"'transform'",
"]",
"[",
"'rotation'",
"]",
"[",
"'w'",
"]",
",",
"transform_stamped",
"[",
"'header'",
"]",
"[",
"'frame_id'",
"]",
",",
"transform_stamped",
"[",
"'child_frame_id'",
"]",
")",
"print",
"(",
"command",
")",
"ret",
"=",
"os",
".",
"system",
"(",
"command",
")",
"print",
"(",
"ret",
")"
] | https://github.com/Ford/AVData/blob/2fdb17f236966a560c8c5c4f3976886d2dc3cab5/ford_demo/scripts/extrinsics_broadcaster.py#L11-L36 | ||
Ubpa/RenderLab | 71db49aa03de4fb258f9171691c8d570216e5e05 | bin/NN_Trainer/NN_Trainer.py | python | TrainModel | (trainX, trainY, batchSize, patience) | return model | 用提供的数据,训练模型
@param
trainX: 输入数据
trainY: 输出数据
batchSize: 批大小
patience: 用于 EarlyStopping
@return
model: 模型 | 用提供的数据,训练模型 | [
"用提供的数据,训练模型"
] | def TrainModel(trainX, trainY, batchSize, patience):
"""
用提供的数据,训练模型
@param
trainX: 输入数据
trainY: 输出数据
batchSize: 批大小
patience: 用于 EarlyStopping
@return
model: 模型
"""
print("training model ...")
model = keras.Sequential([
layers.Dense(hiddenUnit0, activation=tf.nn.tanh, input_shape=(inputDim,), name='dense0'),
layers.Dense(hiddenUnit1, activation=tf.nn.tanh, name='dense1'),
layers.Dense(outputDim, name='dense2')
])
#model.summary()
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss ='mse',
metrics=['mae', 'mse'])
# The patience parameter is the amount of epochs to check for improvement
early_stop = keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = patience)
model.fit(trainX, trainY, epochs = epoch, batch_size = batchSize,
validation_split = 0.2, callbacks=[early_stop], verbose = 0)
print("training model complete")
return model | [
"def",
"TrainModel",
"(",
"trainX",
",",
"trainY",
",",
"batchSize",
",",
"patience",
")",
":",
"print",
"(",
"\"training model ...\"",
")",
"model",
"=",
"keras",
".",
"Sequential",
"(",
"[",
"layers",
".",
"Dense",
"(",
"hiddenUnit0",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"tanh",
",",
"input_shape",
"=",
"(",
"inputDim",
",",
")",
",",
"name",
"=",
"'dense0'",
")",
",",
"layers",
".",
"Dense",
"(",
"hiddenUnit1",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"tanh",
",",
"name",
"=",
"'dense1'",
")",
",",
"layers",
".",
"Dense",
"(",
"outputDim",
",",
"name",
"=",
"'dense2'",
")",
"]",
")",
"#model.summary()",
"model",
".",
"compile",
"(",
"optimizer",
"=",
"tf",
".",
"keras",
".",
"optimizers",
".",
"Adam",
"(",
")",
",",
"loss",
"=",
"'mse'",
",",
"metrics",
"=",
"[",
"'mae'",
",",
"'mse'",
"]",
")",
"# The patience parameter is the amount of epochs to check for improvement",
"early_stop",
"=",
"keras",
".",
"callbacks",
".",
"EarlyStopping",
"(",
"monitor",
"=",
"'val_loss'",
",",
"patience",
"=",
"patience",
")",
"model",
".",
"fit",
"(",
"trainX",
",",
"trainY",
",",
"epochs",
"=",
"epoch",
",",
"batch_size",
"=",
"batchSize",
",",
"validation_split",
"=",
"0.2",
",",
"callbacks",
"=",
"[",
"early_stop",
"]",
",",
"verbose",
"=",
"0",
")",
"print",
"(",
"\"training model complete\"",
")",
"return",
"model"
] | https://github.com/Ubpa/RenderLab/blob/71db49aa03de4fb258f9171691c8d570216e5e05/bin/NN_Trainer/NN_Trainer.py#L208-L244 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PGProperty.SetValueInEvent | (*args, **kwargs) | return _propgrid.PGProperty_SetValueInEvent(*args, **kwargs) | SetValueInEvent(self, wxVariant value) | SetValueInEvent(self, wxVariant value) | [
"SetValueInEvent",
"(",
"self",
"wxVariant",
"value",
")"
] | def SetValueInEvent(*args, **kwargs):
"""SetValueInEvent(self, wxVariant value)"""
return _propgrid.PGProperty_SetValueInEvent(*args, **kwargs) | [
"def",
"SetValueInEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_SetValueInEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L719-L721 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/_lobpcg.py | python | lobpcg | (A: Tensor,
k: Optional[int] = None,
B: Optional[Tensor] = None,
X: Optional[Tensor] = None,
n: Optional[int] = None,
iK: Optional[Tensor] = None,
niter: Optional[int] = None,
tol: Optional[float] = None,
largest: Optional[bool] = None,
method: Optional[str] = None,
tracker: None = None,
ortho_iparams: Optional[Dict[str, int]] = None,
ortho_fparams: Optional[Dict[str, float]] = None,
ortho_bparams: Optional[Dict[str, bool]] = None
) | return _lobpcg(
A, k, B, X,
n, iK, niter, tol, largest, method, tracker,
ortho_iparams, ortho_fparams, ortho_bparams
) | Find the k largest (or smallest) eigenvalues and the corresponding
eigenvectors of a symmetric positive definite generalized
eigenvalue problem using matrix-free LOBPCG methods.
This function is a front-end to the following LOBPCG algorithms
selectable via `method` argument:
`method="basic"` - the LOBPCG method introduced by Andrew
Knyazev, see [Knyazev2001]. A less robust method, may fail when
Cholesky is applied to singular input.
`method="ortho"` - the LOBPCG method with orthogonal basis
selection [StathopoulosEtal2002]. A robust method.
Supported inputs are dense, sparse, and batches of dense matrices.
.. note:: In general, the basic method spends least time per
iteration. However, the robust methods converge much faster and
are more stable. So, the usage of the basic method is generally
not recommended but there exist cases where the usage of the
basic method may be preferred.
.. warning:: The backward method does not support sparse and complex inputs.
It works only when `B` is not provided (i.e. `B == None`).
We are actively working on extensions, and the details of
the algorithms are going to be published promptly.
.. warning:: While it is assumed that `A` is symmetric, `A.grad` is not.
To make sure that `A.grad` is symmetric, so that `A - t * A.grad` is symmetric
in first-order optimization routines, prior to running `lobpcg`
we do the following symmetrization map: `A -> (A + A.t()) / 2`.
The map is performed only when the `A` requires gradients.
Args:
A (Tensor): the input tensor of size :math:`(*, m, m)`
B (Tensor, optional): the input tensor of size :math:`(*, m,
m)`. When not specified, `B` is interpereted as
identity matrix.
X (tensor, optional): the input tensor of size :math:`(*, m, n)`
where `k <= n <= m`. When specified, it is used as
initial approximation of eigenvectors. X must be a
dense tensor.
iK (tensor, optional): the input tensor of size :math:`(*, m,
m)`. When specified, it will be used as preconditioner.
k (integer, optional): the number of requested
eigenpairs. Default is the number of :math:`X`
columns (when specified) or `1`.
n (integer, optional): if :math:`X` is not specified then `n`
specifies the size of the generated random
approximation of eigenvectors. Default value for `n`
is `k`. If :math:`X` is specified, the value of `n`
(when specified) must be the number of :math:`X`
columns.
tol (float, optional): residual tolerance for stopping
criterion. Default is `feps ** 0.5` where `feps` is
smallest non-zero floating-point number of the given
input tensor `A` data type.
largest (bool, optional): when True, solve the eigenproblem for
the largest eigenvalues. Otherwise, solve the
eigenproblem for smallest eigenvalues. Default is
`True`.
method (str, optional): select LOBPCG method. See the
description of the function above. Default is
"ortho".
niter (int, optional): maximum number of iterations. When
reached, the iteration process is hard-stopped and
the current approximation of eigenpairs is returned.
For infinite iteration but until convergence criteria
is met, use `-1`.
tracker (callable, optional) : a function for tracing the
iteration process. When specified, it is called at
each iteration step with LOBPCG instance as an
argument. The LOBPCG instance holds the full state of
the iteration process in the following attributes:
`iparams`, `fparams`, `bparams` - dictionaries of
integer, float, and boolean valued input
parameters, respectively
`ivars`, `fvars`, `bvars`, `tvars` - dictionaries
of integer, float, boolean, and Tensor valued
iteration variables, respectively.
`A`, `B`, `iK` - input Tensor arguments.
`E`, `X`, `S`, `R` - iteration Tensor variables.
For instance:
`ivars["istep"]` - the current iteration step
`X` - the current approximation of eigenvectors
`E` - the current approximation of eigenvalues
`R` - the current residual
`ivars["converged_count"]` - the current number of converged eigenpairs
`tvars["rerr"]` - the current state of convergence criteria
Note that when `tracker` stores Tensor objects from
the LOBPCG instance, it must make copies of these.
If `tracker` sets `bvars["force_stop"] = True`, the
iteration process will be hard-stopped.
ortho_iparams, ortho_fparams, ortho_bparams (dict, optional):
various parameters to LOBPCG algorithm when using
`method="ortho"`.
Returns:
E (Tensor): tensor of eigenvalues of size :math:`(*, k)`
X (Tensor): tensor of eigenvectors of size :math:`(*, m, k)`
References:
[Knyazev2001] Andrew V. Knyazev. (2001) Toward the Optimal
Preconditioned Eigensolver: Locally Optimal Block Preconditioned
Conjugate Gradient Method. SIAM J. Sci. Comput., 23(2),
517-541. (25 pages)
https://epubs.siam.org/doi/abs/10.1137/S1064827500366124
[StathopoulosEtal2002] Andreas Stathopoulos and Kesheng
Wu. (2002) A Block Orthogonalization Procedure with Constant
Synchronization Requirements. SIAM J. Sci. Comput., 23(6),
2165-2182. (18 pages)
https://epubs.siam.org/doi/10.1137/S1064827500370883
[DuerschEtal2018] Jed A. Duersch, Meiyue Shao, Chao Yang, Ming
Gu. (2018) A Robust and Efficient Implementation of LOBPCG.
SIAM J. Sci. Comput., 40(5), C655-C676. (22 pages)
https://epubs.siam.org/doi/abs/10.1137/17M1129830 | Find the k largest (or smallest) eigenvalues and the corresponding
eigenvectors of a symmetric positive definite generalized
eigenvalue problem using matrix-free LOBPCG methods. | [
"Find",
"the",
"k",
"largest",
"(",
"or",
"smallest",
")",
"eigenvalues",
"and",
"the",
"corresponding",
"eigenvectors",
"of",
"a",
"symmetric",
"positive",
"definite",
"generalized",
"eigenvalue",
"problem",
"using",
"matrix",
"-",
"free",
"LOBPCG",
"methods",
"."
] | def lobpcg(A: Tensor,
k: Optional[int] = None,
B: Optional[Tensor] = None,
X: Optional[Tensor] = None,
n: Optional[int] = None,
iK: Optional[Tensor] = None,
niter: Optional[int] = None,
tol: Optional[float] = None,
largest: Optional[bool] = None,
method: Optional[str] = None,
tracker: None = None,
ortho_iparams: Optional[Dict[str, int]] = None,
ortho_fparams: Optional[Dict[str, float]] = None,
ortho_bparams: Optional[Dict[str, bool]] = None
) -> Tuple[Tensor, Tensor]:
"""Find the k largest (or smallest) eigenvalues and the corresponding
eigenvectors of a symmetric positive definite generalized
eigenvalue problem using matrix-free LOBPCG methods.
This function is a front-end to the following LOBPCG algorithms
selectable via `method` argument:
`method="basic"` - the LOBPCG method introduced by Andrew
Knyazev, see [Knyazev2001]. A less robust method, may fail when
Cholesky is applied to singular input.
`method="ortho"` - the LOBPCG method with orthogonal basis
selection [StathopoulosEtal2002]. A robust method.
Supported inputs are dense, sparse, and batches of dense matrices.
.. note:: In general, the basic method spends least time per
iteration. However, the robust methods converge much faster and
are more stable. So, the usage of the basic method is generally
not recommended but there exist cases where the usage of the
basic method may be preferred.
.. warning:: The backward method does not support sparse and complex inputs.
It works only when `B` is not provided (i.e. `B == None`).
We are actively working on extensions, and the details of
the algorithms are going to be published promptly.
.. warning:: While it is assumed that `A` is symmetric, `A.grad` is not.
To make sure that `A.grad` is symmetric, so that `A - t * A.grad` is symmetric
in first-order optimization routines, prior to running `lobpcg`
we do the following symmetrization map: `A -> (A + A.t()) / 2`.
The map is performed only when the `A` requires gradients.
Args:
A (Tensor): the input tensor of size :math:`(*, m, m)`
B (Tensor, optional): the input tensor of size :math:`(*, m,
m)`. When not specified, `B` is interpereted as
identity matrix.
X (tensor, optional): the input tensor of size :math:`(*, m, n)`
where `k <= n <= m`. When specified, it is used as
initial approximation of eigenvectors. X must be a
dense tensor.
iK (tensor, optional): the input tensor of size :math:`(*, m,
m)`. When specified, it will be used as preconditioner.
k (integer, optional): the number of requested
eigenpairs. Default is the number of :math:`X`
columns (when specified) or `1`.
n (integer, optional): if :math:`X` is not specified then `n`
specifies the size of the generated random
approximation of eigenvectors. Default value for `n`
is `k`. If :math:`X` is specified, the value of `n`
(when specified) must be the number of :math:`X`
columns.
tol (float, optional): residual tolerance for stopping
criterion. Default is `feps ** 0.5` where `feps` is
smallest non-zero floating-point number of the given
input tensor `A` data type.
largest (bool, optional): when True, solve the eigenproblem for
the largest eigenvalues. Otherwise, solve the
eigenproblem for smallest eigenvalues. Default is
`True`.
method (str, optional): select LOBPCG method. See the
description of the function above. Default is
"ortho".
niter (int, optional): maximum number of iterations. When
reached, the iteration process is hard-stopped and
the current approximation of eigenpairs is returned.
For infinite iteration but until convergence criteria
is met, use `-1`.
tracker (callable, optional) : a function for tracing the
iteration process. When specified, it is called at
each iteration step with LOBPCG instance as an
argument. The LOBPCG instance holds the full state of
the iteration process in the following attributes:
`iparams`, `fparams`, `bparams` - dictionaries of
integer, float, and boolean valued input
parameters, respectively
`ivars`, `fvars`, `bvars`, `tvars` - dictionaries
of integer, float, boolean, and Tensor valued
iteration variables, respectively.
`A`, `B`, `iK` - input Tensor arguments.
`E`, `X`, `S`, `R` - iteration Tensor variables.
For instance:
`ivars["istep"]` - the current iteration step
`X` - the current approximation of eigenvectors
`E` - the current approximation of eigenvalues
`R` - the current residual
`ivars["converged_count"]` - the current number of converged eigenpairs
`tvars["rerr"]` - the current state of convergence criteria
Note that when `tracker` stores Tensor objects from
the LOBPCG instance, it must make copies of these.
If `tracker` sets `bvars["force_stop"] = True`, the
iteration process will be hard-stopped.
ortho_iparams, ortho_fparams, ortho_bparams (dict, optional):
various parameters to LOBPCG algorithm when using
`method="ortho"`.
Returns:
E (Tensor): tensor of eigenvalues of size :math:`(*, k)`
X (Tensor): tensor of eigenvectors of size :math:`(*, m, k)`
References:
[Knyazev2001] Andrew V. Knyazev. (2001) Toward the Optimal
Preconditioned Eigensolver: Locally Optimal Block Preconditioned
Conjugate Gradient Method. SIAM J. Sci. Comput., 23(2),
517-541. (25 pages)
https://epubs.siam.org/doi/abs/10.1137/S1064827500366124
[StathopoulosEtal2002] Andreas Stathopoulos and Kesheng
Wu. (2002) A Block Orthogonalization Procedure with Constant
Synchronization Requirements. SIAM J. Sci. Comput., 23(6),
2165-2182. (18 pages)
https://epubs.siam.org/doi/10.1137/S1064827500370883
[DuerschEtal2018] Jed A. Duersch, Meiyue Shao, Chao Yang, Ming
Gu. (2018) A Robust and Efficient Implementation of LOBPCG.
SIAM J. Sci. Comput., 40(5), C655-C676. (22 pages)
https://epubs.siam.org/doi/abs/10.1137/17M1129830
"""
if not torch.jit.is_scripting():
tensor_ops = (A, B, X, iK)
if (not set(map(type, tensor_ops)).issubset((torch.Tensor, type(None))) and has_torch_function(tensor_ops)):
return handle_torch_function(
lobpcg, tensor_ops, A, k=k,
B=B, X=X, n=n, iK=iK, niter=niter, tol=tol,
largest=largest, method=method, tracker=tracker,
ortho_iparams=ortho_iparams,
ortho_fparams=ortho_fparams,
ortho_bparams=ortho_bparams)
if not torch._jit_internal.is_scripting():
if A.requires_grad or (B is not None and B.requires_grad):
# While it is expected that `A` is symmetric,
# the `A_grad` might be not. Therefore we perform the trick below,
# so that `A_grad` becomes symmetric.
# The symmetrization is important for first-order optimization methods,
# so that (A - alpha * A_grad) is still a symmetric matrix.
# Same holds for `B`.
A_sym = (A + A.mT) / 2
B_sym = (B + B.mT) / 2 if (B is not None) else None
return LOBPCGAutogradFunction.apply(
A_sym, k, B_sym, X, n, iK, niter, tol, largest,
method, tracker, ortho_iparams, ortho_fparams, ortho_bparams
)
else:
if A.requires_grad or (B is not None and B.requires_grad):
raise RuntimeError(
'Script and require grads is not supported atm.'
'If you just want to do the forward, use .detach()'
'on A and B before calling into lobpcg'
)
return _lobpcg(
A, k, B, X,
n, iK, niter, tol, largest, method, tracker,
ortho_iparams, ortho_fparams, ortho_bparams
) | [
"def",
"lobpcg",
"(",
"A",
":",
"Tensor",
",",
"k",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"B",
":",
"Optional",
"[",
"Tensor",
"]",
"=",
"None",
",",
"X",
":",
"Optional",
"[",
"Tensor",
"]",
"=",
"None",
",",
"n",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"iK",
":",
"Optional",
"[",
"Tensor",
"]",
"=",
"None",
",",
"niter",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"tol",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"largest",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"method",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"tracker",
":",
"None",
"=",
"None",
",",
"ortho_iparams",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
"=",
"None",
",",
"ortho_fparams",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"float",
"]",
"]",
"=",
"None",
",",
"ortho_bparams",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"bool",
"]",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"Tensor",
",",
"Tensor",
"]",
":",
"if",
"not",
"torch",
".",
"jit",
".",
"is_scripting",
"(",
")",
":",
"tensor_ops",
"=",
"(",
"A",
",",
"B",
",",
"X",
",",
"iK",
")",
"if",
"(",
"not",
"set",
"(",
"map",
"(",
"type",
",",
"tensor_ops",
")",
")",
".",
"issubset",
"(",
"(",
"torch",
".",
"Tensor",
",",
"type",
"(",
"None",
")",
")",
")",
"and",
"has_torch_function",
"(",
"tensor_ops",
")",
")",
":",
"return",
"handle_torch_function",
"(",
"lobpcg",
",",
"tensor_ops",
",",
"A",
",",
"k",
"=",
"k",
",",
"B",
"=",
"B",
",",
"X",
"=",
"X",
",",
"n",
"=",
"n",
",",
"iK",
"=",
"iK",
",",
"niter",
"=",
"niter",
",",
"tol",
"=",
"tol",
",",
"largest",
"=",
"largest",
",",
"method",
"=",
"method",
",",
"tracker",
"=",
"tracker",
",",
"ortho_iparams",
"=",
"ortho_iparams",
",",
"ortho_fparams",
"=",
"ortho_fparams",
",",
"ortho_bparams",
"=",
"ortho_bparams",
")",
"if",
"not",
"torch",
".",
"_jit_internal",
".",
"is_scripting",
"(",
")",
":",
"if",
"A",
".",
"requires_grad",
"or",
"(",
"B",
"is",
"not",
"None",
"and",
"B",
".",
"requires_grad",
")",
":",
"# While it is expected that `A` is symmetric,",
"# the `A_grad` might be not. Therefore we perform the trick below,",
"# so that `A_grad` becomes symmetric.",
"# The symmetrization is important for first-order optimization methods,",
"# so that (A - alpha * A_grad) is still a symmetric matrix.",
"# Same holds for `B`.",
"A_sym",
"=",
"(",
"A",
"+",
"A",
".",
"mT",
")",
"/",
"2",
"B_sym",
"=",
"(",
"B",
"+",
"B",
".",
"mT",
")",
"/",
"2",
"if",
"(",
"B",
"is",
"not",
"None",
")",
"else",
"None",
"return",
"LOBPCGAutogradFunction",
".",
"apply",
"(",
"A_sym",
",",
"k",
",",
"B_sym",
",",
"X",
",",
"n",
",",
"iK",
",",
"niter",
",",
"tol",
",",
"largest",
",",
"method",
",",
"tracker",
",",
"ortho_iparams",
",",
"ortho_fparams",
",",
"ortho_bparams",
")",
"else",
":",
"if",
"A",
".",
"requires_grad",
"or",
"(",
"B",
"is",
"not",
"None",
"and",
"B",
".",
"requires_grad",
")",
":",
"raise",
"RuntimeError",
"(",
"'Script and require grads is not supported atm.'",
"'If you just want to do the forward, use .detach()'",
"'on A and B before calling into lobpcg'",
")",
"return",
"_lobpcg",
"(",
"A",
",",
"k",
",",
"B",
",",
"X",
",",
"n",
",",
"iK",
",",
"niter",
",",
"tol",
",",
"largest",
",",
"method",
",",
"tracker",
",",
"ortho_iparams",
",",
"ortho_fparams",
",",
"ortho_bparams",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/_lobpcg.py#L340-L538 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/grsnWallImagerDisplayS.py | python | grsnWallImagerDisplayS.__init__ | (self) | construction | construction | [
"construction"
] | def __init__(self):
"construction"
PtDebugPrint("grsnWallImagerDisplayS::init begin")
ptResponder.__init__(self)
self.id = 52397
self.version = 1
PtDebugPrint("grsnWallImagerDisplayS::init end") | [
"def",
"__init__",
"(",
"self",
")",
":",
"PtDebugPrint",
"(",
"\"grsnWallImagerDisplayS::init begin\"",
")",
"ptResponder",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"id",
"=",
"52397",
"self",
".",
"version",
"=",
"1",
"PtDebugPrint",
"(",
"\"grsnWallImagerDisplayS::init end\"",
")"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/grsnWallImagerDisplayS.py#L85-L91 | ||
ros-perception/vision_opencv | c791220cefd0abf02c6719e2ce0fea465857a88e | image_geometry/src/image_geometry/cameramodels.py | python | StereoCameraModel.project3dToPixel | (self, point) | return (l, r) | :param point: 3D point
:type point: (x, y, z)
Returns the rectified pixel coordinates (u, v) of the 3D point, for each camera, as ((u_left, v_left), (u_right, v_right))
using the cameras' :math:`P` matrices.
This is the inverse of :meth:`projectPixelTo3d`. | :param point: 3D point
:type point: (x, y, z) | [
":",
"param",
"point",
":",
"3D",
"point",
":",
"type",
"point",
":",
"(",
"x",
"y",
"z",
")"
] | def project3dToPixel(self, point):
"""
:param point: 3D point
:type point: (x, y, z)
Returns the rectified pixel coordinates (u, v) of the 3D point, for each camera, as ((u_left, v_left), (u_right, v_right))
using the cameras' :math:`P` matrices.
This is the inverse of :meth:`projectPixelTo3d`.
"""
l = self.left.project3dToPixel(point)
r = self.right.project3dToPixel(point)
return (l, r) | [
"def",
"project3dToPixel",
"(",
"self",
",",
"point",
")",
":",
"l",
"=",
"self",
".",
"left",
".",
"project3dToPixel",
"(",
"point",
")",
"r",
"=",
"self",
".",
"right",
".",
"project3dToPixel",
"(",
"point",
")",
"return",
"(",
"l",
",",
"r",
")"
] | https://github.com/ros-perception/vision_opencv/blob/c791220cefd0abf02c6719e2ce0fea465857a88e/image_geometry/src/image_geometry/cameramodels.py#L310-L321 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py | python | VarTrace.attach | (self) | Attach callback to all vars that are not traced. | Attach callback to all vars that are not traced. | [
"Attach",
"callback",
"to",
"all",
"vars",
"that",
"are",
"not",
"traced",
"."
] | def attach(self):
"Attach callback to all vars that are not traced."
while self.untraced:
var, callback = self.untraced.pop()
var.trace_add('write', callback)
self.traced.append((var, callback)) | [
"def",
"attach",
"(",
"self",
")",
":",
"while",
"self",
".",
"untraced",
":",
"var",
",",
"callback",
"=",
"self",
".",
"untraced",
".",
"pop",
"(",
")",
"var",
".",
"trace_add",
"(",
"'write'",
",",
"callback",
")",
"self",
".",
"traced",
".",
"append",
"(",
"(",
"var",
",",
"callback",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L2243-L2248 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/CallTipWindow.py | python | CallTip.position_window | (self) | Check if needs to reposition the window, and if so - do it. | Check if needs to reposition the window, and if so - do it. | [
"Check",
"if",
"needs",
"to",
"reposition",
"the",
"window",
"and",
"if",
"so",
"-",
"do",
"it",
"."
] | def position_window(self):
"""Check if needs to reposition the window, and if so - do it."""
curline = int(self.widget.index("insert").split('.')[0])
if curline == self.lastline:
return
self.lastline = curline
self.widget.see("insert")
if curline == self.parenline:
box = self.widget.bbox("%d.%d" % (self.parenline,
self.parencol))
else:
box = self.widget.bbox("%d.0" % curline)
if not box:
box = list(self.widget.bbox("insert"))
# align to left of window
box[0] = 0
box[2] = 0
x = box[0] + self.widget.winfo_rootx() + 2
y = box[1] + box[3] + self.widget.winfo_rooty()
self.tipwindow.wm_geometry("+%d+%d" % (x, y)) | [
"def",
"position_window",
"(",
"self",
")",
":",
"curline",
"=",
"int",
"(",
"self",
".",
"widget",
".",
"index",
"(",
"\"insert\"",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"if",
"curline",
"==",
"self",
".",
"lastline",
":",
"return",
"self",
".",
"lastline",
"=",
"curline",
"self",
".",
"widget",
".",
"see",
"(",
"\"insert\"",
")",
"if",
"curline",
"==",
"self",
".",
"parenline",
":",
"box",
"=",
"self",
".",
"widget",
".",
"bbox",
"(",
"\"%d.%d\"",
"%",
"(",
"self",
".",
"parenline",
",",
"self",
".",
"parencol",
")",
")",
"else",
":",
"box",
"=",
"self",
".",
"widget",
".",
"bbox",
"(",
"\"%d.0\"",
"%",
"curline",
")",
"if",
"not",
"box",
":",
"box",
"=",
"list",
"(",
"self",
".",
"widget",
".",
"bbox",
"(",
"\"insert\"",
")",
")",
"# align to left of window",
"box",
"[",
"0",
"]",
"=",
"0",
"box",
"[",
"2",
"]",
"=",
"0",
"x",
"=",
"box",
"[",
"0",
"]",
"+",
"self",
".",
"widget",
".",
"winfo_rootx",
"(",
")",
"+",
"2",
"y",
"=",
"box",
"[",
"1",
"]",
"+",
"box",
"[",
"3",
"]",
"+",
"self",
".",
"widget",
".",
"winfo_rooty",
"(",
")",
"self",
".",
"tipwindow",
".",
"wm_geometry",
"(",
"\"+%d+%d\"",
"%",
"(",
"x",
",",
"y",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/CallTipWindow.py#L27-L46 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/legendre.py | python | legmul | (c1, c2) | return legadd(c0, legmulx(c1)) | Multiply one Legendre series by another.
Returns the product of two Legendre series `c1` * `c2`. The arguments
are sequences of coefficients, from lowest order "term" to highest,
e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Legendre series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Of Legendre series coefficients representing their product.
See Also
--------
legadd, legsub, legmulx, legdiv, legpow
Notes
-----
In general, the (polynomial) product of two C-series results in terms
that are not in the Legendre polynomial basis set. Thus, to express
the product as a Legendre series, it is necessary to "reproject" the
product onto said basis set, which may produce "unintuitive" (but
correct) results; see Examples section below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> c1 = (1,2,3)
>>> c2 = (3,2)
>>> L.legmul(c1,c2) # multiplication requires "reprojection"
array([ 4.33333333, 10.4 , 11.66666667, 3.6 ]) # may vary | Multiply one Legendre series by another. | [
"Multiply",
"one",
"Legendre",
"series",
"by",
"another",
"."
] | def legmul(c1, c2):
"""
Multiply one Legendre series by another.
Returns the product of two Legendre series `c1` * `c2`. The arguments
are sequences of coefficients, from lowest order "term" to highest,
e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Legendre series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Of Legendre series coefficients representing their product.
See Also
--------
legadd, legsub, legmulx, legdiv, legpow
Notes
-----
In general, the (polynomial) product of two C-series results in terms
that are not in the Legendre polynomial basis set. Thus, to express
the product as a Legendre series, it is necessary to "reproject" the
product onto said basis set, which may produce "unintuitive" (but
correct) results; see Examples section below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> c1 = (1,2,3)
>>> c2 = (3,2)
>>> L.legmul(c1,c2) # multiplication requires "reprojection"
array([ 4.33333333, 10.4 , 11.66666667, 3.6 ]) # may vary
"""
# s1, s2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if len(c1) > len(c2):
c = c2
xs = c1
else:
c = c1
xs = c2
if len(c) == 1:
c0 = c[0]*xs
c1 = 0
elif len(c) == 2:
c0 = c[0]*xs
c1 = c[1]*xs
else:
nd = len(c)
c0 = c[-2]*xs
c1 = c[-1]*xs
for i in range(3, len(c) + 1):
tmp = c0
nd = nd - 1
c0 = legsub(c[-i]*xs, (c1*(nd - 1))/nd)
c1 = legadd(tmp, (legmulx(c1)*(2*nd - 1))/nd)
return legadd(c0, legmulx(c1)) | [
"def",
"legmul",
"(",
"c1",
",",
"c2",
")",
":",
"# s1, s2 are trimmed copies",
"[",
"c1",
",",
"c2",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"c1",
",",
"c2",
"]",
")",
"if",
"len",
"(",
"c1",
")",
">",
"len",
"(",
"c2",
")",
":",
"c",
"=",
"c2",
"xs",
"=",
"c1",
"else",
":",
"c",
"=",
"c1",
"xs",
"=",
"c2",
"if",
"len",
"(",
"c",
")",
"==",
"1",
":",
"c0",
"=",
"c",
"[",
"0",
"]",
"*",
"xs",
"c1",
"=",
"0",
"elif",
"len",
"(",
"c",
")",
"==",
"2",
":",
"c0",
"=",
"c",
"[",
"0",
"]",
"*",
"xs",
"c1",
"=",
"c",
"[",
"1",
"]",
"*",
"xs",
"else",
":",
"nd",
"=",
"len",
"(",
"c",
")",
"c0",
"=",
"c",
"[",
"-",
"2",
"]",
"*",
"xs",
"c1",
"=",
"c",
"[",
"-",
"1",
"]",
"*",
"xs",
"for",
"i",
"in",
"range",
"(",
"3",
",",
"len",
"(",
"c",
")",
"+",
"1",
")",
":",
"tmp",
"=",
"c0",
"nd",
"=",
"nd",
"-",
"1",
"c0",
"=",
"legsub",
"(",
"c",
"[",
"-",
"i",
"]",
"*",
"xs",
",",
"(",
"c1",
"*",
"(",
"nd",
"-",
"1",
")",
")",
"/",
"nd",
")",
"c1",
"=",
"legadd",
"(",
"tmp",
",",
"(",
"legmulx",
"(",
"c1",
")",
"*",
"(",
"2",
"*",
"nd",
"-",
"1",
")",
")",
"/",
"nd",
")",
"return",
"legadd",
"(",
"c0",
",",
"legmulx",
"(",
"c1",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/legendre.py#L464-L529 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py | python | _find_adapter | (registry, ob) | Return an adapter factory for `ob` from `registry` | Return an adapter factory for `ob` from `registry` | [
"Return",
"an",
"adapter",
"factory",
"for",
"ob",
"from",
"registry"
] | def _find_adapter(registry, ob):
"""Return an adapter factory for `ob` from `registry`"""
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
for t in types:
if t in registry:
return registry[t] | [
"def",
"_find_adapter",
"(",
"registry",
",",
"ob",
")",
":",
"types",
"=",
"_always_object",
"(",
"inspect",
".",
"getmro",
"(",
"getattr",
"(",
"ob",
",",
"'__class__'",
",",
"type",
"(",
"ob",
")",
")",
")",
")",
"for",
"t",
"in",
"types",
":",
"if",
"t",
"in",
"registry",
":",
"return",
"registry",
"[",
"t",
"]"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py#L3037-L3042 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/strings.py | python | cat_core | (list_of_columns: List, sep: str) | return np.sum(arr_with_sep, axis=0) | Auxiliary function for :meth:`str.cat`
Parameters
----------
list_of_columns : list of numpy arrays
List of arrays to be concatenated with sep;
these arrays may not contain NaNs!
sep : string
The separator string for concatenating the columns.
Returns
-------
nd.array
The concatenation of list_of_columns with sep. | Auxiliary function for :meth:`str.cat` | [
"Auxiliary",
"function",
"for",
":",
"meth",
":",
"str",
".",
"cat"
] | def cat_core(list_of_columns: List, sep: str):
"""
Auxiliary function for :meth:`str.cat`
Parameters
----------
list_of_columns : list of numpy arrays
List of arrays to be concatenated with sep;
these arrays may not contain NaNs!
sep : string
The separator string for concatenating the columns.
Returns
-------
nd.array
The concatenation of list_of_columns with sep.
"""
if sep == "":
# no need to interleave sep if it is empty
arr_of_cols = np.asarray(list_of_columns, dtype=object)
return np.sum(arr_of_cols, axis=0)
list_with_sep = [sep] * (2 * len(list_of_columns) - 1)
list_with_sep[::2] = list_of_columns
arr_with_sep = np.asarray(list_with_sep, dtype=object)
return np.sum(arr_with_sep, axis=0) | [
"def",
"cat_core",
"(",
"list_of_columns",
":",
"List",
",",
"sep",
":",
"str",
")",
":",
"if",
"sep",
"==",
"\"\"",
":",
"# no need to interleave sep if it is empty",
"arr_of_cols",
"=",
"np",
".",
"asarray",
"(",
"list_of_columns",
",",
"dtype",
"=",
"object",
")",
"return",
"np",
".",
"sum",
"(",
"arr_of_cols",
",",
"axis",
"=",
"0",
")",
"list_with_sep",
"=",
"[",
"sep",
"]",
"*",
"(",
"2",
"*",
"len",
"(",
"list_of_columns",
")",
"-",
"1",
")",
"list_with_sep",
"[",
":",
":",
"2",
"]",
"=",
"list_of_columns",
"arr_with_sep",
"=",
"np",
".",
"asarray",
"(",
"list_with_sep",
",",
"dtype",
"=",
"object",
")",
"return",
"np",
".",
"sum",
"(",
"arr_with_sep",
",",
"axis",
"=",
"0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/strings.py#L59-L83 | |
cvmfs/cvmfs | 4637bdb5153178eadf885c1acf37bdc5c685bf8a | cpplint.py | python | _CppLintState.SetCountingStyle | (self, counting_style) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style | [
"def",
"SetCountingStyle",
"(",
"self",
",",
"counting_style",
")",
":",
"self",
".",
"counting",
"=",
"counting_style"
] | https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L785-L787 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/MSVS/MSVSVersion.py | python | VisualStudioVersion.ToolPath | (self, tool) | return os.path.normpath(os.path.join(self.path, "VC", "bin", tool)) | Returns the path to a given compiler tool. | Returns the path to a given compiler tool. | [
"Returns",
"the",
"path",
"to",
"a",
"given",
"compiler",
"tool",
"."
] | def ToolPath(self, tool):
"""Returns the path to a given compiler tool. """
return os.path.normpath(os.path.join(self.path, "VC", "bin", tool)) | [
"def",
"ToolPath",
"(",
"self",
",",
"tool",
")",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"\"VC\"",
",",
"\"bin\"",
",",
"tool",
")",
")"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/MSVS/MSVSVersion.py#L65-L67 | |
lmb-freiburg/ogn | 974f72ef4bf840d6f6693d22d1843a79223e77ce | scripts/cpp_lint.py | python | CheckSpacing | (filename, clean_lines, linenum, nesting_state, error) | Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks for the correctness of various spacing issues in the code. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"issues",
"in",
"the",
"code",
"."
] | def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
if IsBlankLine(line) and not nesting_state.InNamespaceBody():
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, we complain if there's a comment too near the text
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if (line.count('"', 0, commentpos) -
line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
# Allow one space for new scopes, two spaces otherwise:
if (not Match(r'^\s*{ //', line) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# There should always be a space between the // and the comment
commentend = commentpos + 2
if commentend < len(line) and not line[commentend] == ' ':
# but some lines are exceptions -- e.g. if they're big
# comment delimiters like:
# //----------------------------------------------------------
# or are an empty C++ style Doxygen comment, like:
# ///
# or C++ style Doxygen comments placed after the variable:
# ///< Header comment
# //!< Header comment
# or they begin with multiple slashes followed by a space:
# //////// Header comment
match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
Search(r'^/$', line[commentend:]) or
Search(r'^!< ', line[commentend:]) or
Search(r'^/< ', line[commentend:]) or
Search(r'^/+ ', line[commentend:]))
if not match:
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
CheckComment(line[commentpos:], filename, linenum, error)
line = clean_lines.elided[linenum] # get rid of comments and strings
# Don't try to do spacing checks for operator methods
line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
# Also ignore using ns::operator<<;
match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
if (match and
not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
elif not Match(r'#.*include', line):
# Avoid false positives on ->
reduced_line = line.replace('->', '')
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
if (match and
not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
if (match and
not FindPreviousMatchingAngleBracket(clean_lines, linenum,
match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
# A pet peeve of mine: no spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
# Next we will look for issues with function calls.
CheckSpacingForFunctionCall(filename, line, linenum, error)
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces. And since you should never have braces at the beginning of a line,
# this is an easy test.
match = Match(r'^(.*[^ ({]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<]".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in xrange(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'new char * []'.
if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search('for *\(.*[^:]:[^: ]', line) or
Search('for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop') | [
"def",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want to check inside C++11",
"# raw strings,",
"raw",
"=",
"clean_lines",
".",
"lines_without_raw_strings",
"line",
"=",
"raw",
"[",
"linenum",
"]",
"# Before nixing comments, check if the line is blank for no good",
"# reason. This includes the first line after a block is opened, and",
"# blank lines at the end of a function (ie, right before a line like '}'",
"#",
"# Skip all the blank line checks if we are immediately inside a",
"# namespace body. In other words, don't issue blank line warnings",
"# for this block:",
"# namespace {",
"#",
"# }",
"#",
"# A warning about missing end of namespace comments will be issued instead.",
"if",
"IsBlankLine",
"(",
"line",
")",
"and",
"not",
"nesting_state",
".",
"InNamespaceBody",
"(",
")",
":",
"elided",
"=",
"clean_lines",
".",
"elided",
"prev_line",
"=",
"elided",
"[",
"linenum",
"-",
"1",
"]",
"prevbrace",
"=",
"prev_line",
".",
"rfind",
"(",
"'{'",
")",
"# TODO(unknown): Don't complain if line before blank line, and line after,",
"# both start with alnums and are indented the same amount.",
"# This ignores whitespace at the start of a namespace block",
"# because those are not usually indented.",
"if",
"prevbrace",
"!=",
"-",
"1",
"and",
"prev_line",
"[",
"prevbrace",
":",
"]",
".",
"find",
"(",
"'}'",
")",
"==",
"-",
"1",
":",
"# OK, we have a blank line at the start of a code block. Before we",
"# complain, we check if it is an exception to the rule: The previous",
"# non-empty line has the parameters of a function header that are indented",
"# 4 spaces (because they did not fit in a 80 column line when placed on",
"# the same line as the function name). We also check for the case where",
"# the previous line is indented 6 spaces, which may happen when the",
"# initializers of a constructor do not fit into a 80 column line.",
"exception",
"=",
"False",
"if",
"Match",
"(",
"r' {6}\\w'",
",",
"prev_line",
")",
":",
"# Initializer list?",
"# We are looking for the opening column of initializer list, which",
"# should be indented 4 spaces to cause 6 space indentation afterwards.",
"search_position",
"=",
"linenum",
"-",
"2",
"while",
"(",
"search_position",
">=",
"0",
"and",
"Match",
"(",
"r' {6}\\w'",
",",
"elided",
"[",
"search_position",
"]",
")",
")",
":",
"search_position",
"-=",
"1",
"exception",
"=",
"(",
"search_position",
">=",
"0",
"and",
"elided",
"[",
"search_position",
"]",
"[",
":",
"5",
"]",
"==",
"' :'",
")",
"else",
":",
"# Search for the function arguments or an initializer list. We use a",
"# simple heuristic here: If the line is indented 4 spaces; and we have a",
"# closing paren, without the opening paren, followed by an opening brace",
"# or colon (for initializer lists) we assume that it is the last line of",
"# a function header. If we have a colon indented 4 spaces, it is an",
"# initializer list.",
"exception",
"=",
"(",
"Match",
"(",
"r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)'",
",",
"prev_line",
")",
"or",
"Match",
"(",
"r' {4}:'",
",",
"prev_line",
")",
")",
"if",
"not",
"exception",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/blank_line'",
",",
"2",
",",
"'Redundant blank line at the start of a code block '",
"'should be deleted.'",
")",
"# Ignore blank lines at the end of a block in a long if-else",
"# chain, like this:",
"# if (condition1) {",
"# // Something followed by a blank line",
"#",
"# } else if (condition2) {",
"# // Something else",
"# }",
"if",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"next_line",
"=",
"raw",
"[",
"linenum",
"+",
"1",
"]",
"if",
"(",
"next_line",
"and",
"Match",
"(",
"r'\\s*}'",
",",
"next_line",
")",
"and",
"next_line",
".",
"find",
"(",
"'} else '",
")",
"==",
"-",
"1",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/blank_line'",
",",
"3",
",",
"'Redundant blank line at the end of a code block '",
"'should be deleted.'",
")",
"matched",
"=",
"Match",
"(",
"r'\\s*(public|protected|private):'",
",",
"prev_line",
")",
"if",
"matched",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/blank_line'",
",",
"3",
",",
"'Do not leave a blank line after \"%s:\"'",
"%",
"matched",
".",
"group",
"(",
"1",
")",
")",
"# Next, we complain if there's a comment too near the text",
"commentpos",
"=",
"line",
".",
"find",
"(",
"'//'",
")",
"if",
"commentpos",
"!=",
"-",
"1",
":",
"# Check if the // may be in quotes. If so, ignore it",
"# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison",
"if",
"(",
"line",
".",
"count",
"(",
"'\"'",
",",
"0",
",",
"commentpos",
")",
"-",
"line",
".",
"count",
"(",
"'\\\\\"'",
",",
"0",
",",
"commentpos",
")",
")",
"%",
"2",
"==",
"0",
":",
"# not in quotes",
"# Allow one space for new scopes, two spaces otherwise:",
"if",
"(",
"not",
"Match",
"(",
"r'^\\s*{ //'",
",",
"line",
")",
"and",
"(",
"(",
"commentpos",
">=",
"1",
"and",
"line",
"[",
"commentpos",
"-",
"1",
"]",
"not",
"in",
"string",
".",
"whitespace",
")",
"or",
"(",
"commentpos",
">=",
"2",
"and",
"line",
"[",
"commentpos",
"-",
"2",
"]",
"not",
"in",
"string",
".",
"whitespace",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/comments'",
",",
"2",
",",
"'At least two spaces is best between code and comments'",
")",
"# There should always be a space between the // and the comment",
"commentend",
"=",
"commentpos",
"+",
"2",
"if",
"commentend",
"<",
"len",
"(",
"line",
")",
"and",
"not",
"line",
"[",
"commentend",
"]",
"==",
"' '",
":",
"# but some lines are exceptions -- e.g. if they're big",
"# comment delimiters like:",
"# //----------------------------------------------------------",
"# or are an empty C++ style Doxygen comment, like:",
"# ///",
"# or C++ style Doxygen comments placed after the variable:",
"# ///< Header comment",
"# //!< Header comment",
"# or they begin with multiple slashes followed by a space:",
"# //////// Header comment",
"match",
"=",
"(",
"Search",
"(",
"r'[=/-]{4,}\\s*$'",
",",
"line",
"[",
"commentend",
":",
"]",
")",
"or",
"Search",
"(",
"r'^/$'",
",",
"line",
"[",
"commentend",
":",
"]",
")",
"or",
"Search",
"(",
"r'^!< '",
",",
"line",
"[",
"commentend",
":",
"]",
")",
"or",
"Search",
"(",
"r'^/< '",
",",
"line",
"[",
"commentend",
":",
"]",
")",
"or",
"Search",
"(",
"r'^/+ '",
",",
"line",
"[",
"commentend",
":",
"]",
")",
")",
"if",
"not",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/comments'",
",",
"4",
",",
"'Should have a space between // and comment'",
")",
"CheckComment",
"(",
"line",
"[",
"commentpos",
":",
"]",
",",
"filename",
",",
"linenum",
",",
"error",
")",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# get rid of comments and strings",
"# Don't try to do spacing checks for operator methods",
"line",
"=",
"re",
".",
"sub",
"(",
"r'operator(==|!=|<|<<|<=|>=|>>|>)\\('",
",",
"'operator\\('",
",",
"line",
")",
"# We allow no-spaces around = within an if: \"if ( (a=Foo()) == 0 )\".",
"# Otherwise not. Note we only check for non-spaces on *both* sides;",
"# sometimes people put non-spaces on one side when aligning ='s among",
"# many lines (not that this is behavior that I approve of...)",
"if",
"Search",
"(",
"r'[\\w.]=[\\w.]'",
",",
"line",
")",
"and",
"not",
"Search",
"(",
"r'\\b(if|while) '",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/operators'",
",",
"4",
",",
"'Missing spaces around ='",
")",
"# It's ok not to have spaces around binary operators like + - * /, but if",
"# there's too little whitespace, we get concerned. It's hard to tell,",
"# though, so we punt on this one for now. TODO.",
"# You should always have whitespace around binary operators.",
"#",
"# Check <= and >= first to avoid false positives with < and >, then",
"# check non-include lines for spacing around < and >.",
"match",
"=",
"Search",
"(",
"r'[^<>=!\\s](==|!=|<=|>=)[^<>=!\\s]'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/operators'",
",",
"3",
",",
"'Missing spaces around %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# We allow no-spaces around << when used like this: 10<<20, but",
"# not otherwise (particularly, not when used as streams)",
"# Also ignore using ns::operator<<;",
"match",
"=",
"Search",
"(",
"r'(operator|\\S)(?:L|UL|ULL|l|ul|ull)?<<(\\S)'",
",",
"line",
")",
"if",
"(",
"match",
"and",
"not",
"(",
"match",
".",
"group",
"(",
"1",
")",
".",
"isdigit",
"(",
")",
"and",
"match",
".",
"group",
"(",
"2",
")",
".",
"isdigit",
"(",
")",
")",
"and",
"not",
"(",
"match",
".",
"group",
"(",
"1",
")",
"==",
"'operator'",
"and",
"match",
".",
"group",
"(",
"2",
")",
"==",
"';'",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/operators'",
",",
"3",
",",
"'Missing spaces around <<'",
")",
"elif",
"not",
"Match",
"(",
"r'#.*include'",
",",
"line",
")",
":",
"# Avoid false positives on ->",
"reduced_line",
"=",
"line",
".",
"replace",
"(",
"'->'",
",",
"''",
")",
"# Look for < that is not surrounded by spaces. This is only",
"# triggered if both sides are missing spaces, even though",
"# technically should should flag if at least one side is missing a",
"# space. This is done to avoid some false positives with shifts.",
"match",
"=",
"Search",
"(",
"r'[^\\s<]<([^\\s=<].*)'",
",",
"reduced_line",
")",
"if",
"(",
"match",
"and",
"not",
"FindNextMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/operators'",
",",
"3",
",",
"'Missing spaces around <'",
")",
"# Look for > that is not surrounded by spaces. Similar to the",
"# above, we only trigger if both sides are missing spaces to avoid",
"# false positives with shifts.",
"match",
"=",
"Search",
"(",
"r'^(.*[^\\s>])>[^\\s=>]'",
",",
"reduced_line",
")",
"if",
"(",
"match",
"and",
"not",
"FindPreviousMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/operators'",
",",
"3",
",",
"'Missing spaces around >'",
")",
"# We allow no-spaces around >> for almost anything. This is because",
"# C++11 allows \">>\" to close nested templates, which accounts for",
"# most cases when \">>\" is not followed by a space.",
"#",
"# We still warn on \">>\" followed by alpha character, because that is",
"# likely due to \">>\" being used for right shifts, e.g.:",
"# value >> alpha",
"#",
"# When \">>\" is used to close templates, the alphanumeric letter that",
"# follows would be part of an identifier, and there should still be",
"# a space separating the template type and the identifier.",
"# type<type<type>> alpha",
"match",
"=",
"Search",
"(",
"r'>>[a-zA-Z_]'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/operators'",
",",
"3",
",",
"'Missing spaces around >>'",
")",
"# There shouldn't be space around unary operators",
"match",
"=",
"Search",
"(",
"r'(!\\s|~\\s|[\\s]--[\\s;]|[\\s]\\+\\+[\\s;])'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/operators'",
",",
"4",
",",
"'Extra space for operator %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# A pet peeve of mine: no spaces after an if, while, switch, or for",
"match",
"=",
"Search",
"(",
"r' (if\\(|for\\(|while\\(|switch\\()'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"5",
",",
"'Missing space before ( in %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# For if/for/while/switch, the left and right parens should be",
"# consistent about how many spaces are inside the parens, and",
"# there should either be zero or one spaces inside the parens.",
"# We don't want: \"if ( foo)\" or \"if ( foo )\".",
"# Exception: \"for ( ; foo; bar)\" and \"for (foo; bar; )\" are allowed.",
"match",
"=",
"Search",
"(",
"r'\\b(if|for|while|switch)\\s*'",
"r'\\(([ ]*)(.).*[^ ]+([ ]*)\\)\\s*{\\s*$'",
",",
"line",
")",
"if",
"match",
":",
"if",
"len",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"!=",
"len",
"(",
"match",
".",
"group",
"(",
"4",
")",
")",
":",
"if",
"not",
"(",
"match",
".",
"group",
"(",
"3",
")",
"==",
"';'",
"and",
"len",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"==",
"1",
"+",
"len",
"(",
"match",
".",
"group",
"(",
"4",
")",
")",
"or",
"not",
"match",
".",
"group",
"(",
"2",
")",
"and",
"Search",
"(",
"r'\\bfor\\s*\\(.*; \\)'",
",",
"line",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"5",
",",
"'Mismatching spaces inside () in %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"if",
"len",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"not",
"in",
"[",
"0",
",",
"1",
"]",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"5",
",",
"'Should have zero or one spaces inside ( and ) in %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# You should always have a space after a comma (either as fn arg or operator)",
"#",
"# This does not apply when the non-space character following the",
"# comma is another comma, since the only time when that happens is",
"# for empty macro arguments.",
"#",
"# We run this check in two passes: first pass on elided lines to",
"# verify that lines contain missing whitespaces, second pass on raw",
"# lines to confirm that those missing whitespaces are not due to",
"# elided comments.",
"if",
"Search",
"(",
"r',[^,\\s]'",
",",
"line",
")",
"and",
"Search",
"(",
"r',[^,\\s]'",
",",
"raw",
"[",
"linenum",
"]",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/comma'",
",",
"3",
",",
"'Missing space after ,'",
")",
"# You should always have a space after a semicolon",
"# except for few corner cases",
"# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more",
"# space after ;",
"if",
"Search",
"(",
"r';[^\\s};\\\\)/]'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/semicolon'",
",",
"3",
",",
"'Missing space after ;'",
")",
"# Next we will look for issues with function calls.",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"line",
",",
"linenum",
",",
"error",
")",
"# Except after an opening paren, or after another opening brace (in case of",
"# an initializer list, for instance), you should have spaces before your",
"# braces. And since you should never have braces at the beginning of a line,",
"# this is an easy test.",
"match",
"=",
"Match",
"(",
"r'^(.*[^ ({]){'",
",",
"line",
")",
"if",
"match",
":",
"# Try a bit harder to check for brace initialization. This",
"# happens in one of the following forms:",
"# Constructor() : initializer_list_{} { ... }",
"# Constructor{}.MemberFunction()",
"# Type variable{};",
"# FunctionCall(type{}, ...);",
"# LastArgument(..., type{});",
"# LOG(INFO) << type{} << \" ...\";",
"# map_of_type[{...}] = ...;",
"#",
"# We check for the character following the closing brace, and",
"# silence the warning if it's one of those listed above, i.e.",
"# \"{.;,)<]\".",
"#",
"# To account for nested initializer list, we allow any number of",
"# closing braces up to \"{;,)<\". We can't simply silence the",
"# warning on first sight of closing brace, because that would",
"# cause false negatives for things that are not initializer lists.",
"# Silence this: But not this:",
"# Outer{ if (...) {",
"# Inner{...} if (...){ // Missing space before {",
"# }; }",
"#",
"# There is a false negative with this approach if people inserted",
"# spurious semicolons, e.g. \"if (cond){};\", but we will catch the",
"# spurious semicolon with a separate check.",
"(",
"endline",
",",
"endlinenum",
",",
"endpos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"len",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"trailing_text",
"=",
"''",
"if",
"endpos",
">",
"-",
"1",
":",
"trailing_text",
"=",
"endline",
"[",
"endpos",
":",
"]",
"for",
"offset",
"in",
"xrange",
"(",
"endlinenum",
"+",
"1",
",",
"min",
"(",
"endlinenum",
"+",
"3",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
"-",
"1",
")",
")",
":",
"trailing_text",
"+=",
"clean_lines",
".",
"elided",
"[",
"offset",
"]",
"if",
"not",
"Match",
"(",
"r'^[\\s}]*[{.;,)<\\]]'",
",",
"trailing_text",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"5",
",",
"'Missing space before {'",
")",
"# Make sure '} else {' has spaces.",
"if",
"Search",
"(",
"r'}else'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"5",
",",
"'Missing space before else'",
")",
"# You shouldn't have spaces before your brackets, except maybe after",
"# 'delete []' or 'new char * []'.",
"if",
"Search",
"(",
"r'\\w\\s+\\['",
",",
"line",
")",
"and",
"not",
"Search",
"(",
"r'delete\\s+\\['",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"5",
",",
"'Extra space before ['",
")",
"# You shouldn't have a space before a semicolon at the end of the line.",
"# There's a special case for \"for\" since the style guide allows space before",
"# the semicolon there.",
"if",
"Search",
"(",
"r':\\s*;\\s*$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/semicolon'",
",",
"5",
",",
"'Semicolon defining empty statement. Use {} instead.'",
")",
"elif",
"Search",
"(",
"r'^\\s*;\\s*$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/semicolon'",
",",
"5",
",",
"'Line contains only semicolon. If this should be an empty statement, '",
"'use {} instead.'",
")",
"elif",
"(",
"Search",
"(",
"r'\\s+;\\s*$'",
",",
"line",
")",
"and",
"not",
"Search",
"(",
"r'\\bfor\\b'",
",",
"line",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/semicolon'",
",",
"5",
",",
"'Extra space before last semicolon. If this should be an empty '",
"'statement, use {} instead.'",
")",
"# In range-based for, we wanted spaces before and after the colon, but",
"# not around \"::\" tokens that might appear.",
"if",
"(",
"Search",
"(",
"'for *\\(.*[^:]:[^: ]'",
",",
"line",
")",
"or",
"Search",
"(",
"'for *\\(.*[^: ]:[^:]'",
",",
"line",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/forcolon'",
",",
"2",
",",
"'Missing space around colon in range-based for loop'",
")"
] | https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L2643-L2988 | ||
tum-vision/fusenet | a1451be2971b348a01b0f525c2a3a7a0e215a591 | scripts/cpp_lint.py | python | CheckForNewlineAtEOF | (filename, lines, error) | Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error if there is no newline char at the end of the file. | [
"Logs",
"an",
"error",
"if",
"there",
"is",
"no",
"newline",
"char",
"at",
"the",
"end",
"of",
"the",
"file",
"."
] | def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.') | [
"def",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# The array lines() was created by adding two newlines to the",
"# original file (go figure), then splitting on \\n.",
"# To verify that the file ends in \\n, we just have to make sure the",
"# last-but-two element of lines() exists and is empty.",
"if",
"len",
"(",
"lines",
")",
"<",
"3",
"or",
"lines",
"[",
"-",
"2",
"]",
":",
"error",
"(",
"filename",
",",
"len",
"(",
"lines",
")",
"-",
"2",
",",
"'whitespace/ending_newline'",
",",
"5",
",",
"'Could not find a newline character at the end of the file.'",
")"
] | https://github.com/tum-vision/fusenet/blob/a1451be2971b348a01b0f525c2a3a7a0e215a591/scripts/cpp_lint.py#L1508-L1523 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Environment.py | python | SubstitutionEnvironment.subst_path | (self, path, target=None, source=None) | return r | Substitute a path list, turning EntryProxies into Nodes
and leaving Nodes (and other objects) as-is. | Substitute a path list, turning EntryProxies into Nodes
and leaving Nodes (and other objects) as-is. | [
"Substitute",
"a",
"path",
"list",
"turning",
"EntryProxies",
"into",
"Nodes",
"and",
"leaving",
"Nodes",
"(",
"and",
"other",
"objects",
")",
"as",
"-",
"is",
"."
] | def subst_path(self, path, target=None, source=None):
"""Substitute a path list, turning EntryProxies into Nodes
and leaving Nodes (and other objects) as-is."""
if not is_List(path):
path = [path]
def s(obj):
"""This is the "string conversion" routine that we have our
substitutions use to return Nodes, not strings. This relies
on the fact that an EntryProxy object has a get() method that
returns the underlying Node that it wraps, which is a bit of
architectural dependence that we might need to break or modify
in the future in response to additional requirements."""
try:
get = obj.get
except AttributeError:
obj = to_String_for_subst(obj)
else:
obj = get()
return obj
r = []
for p in path:
if is_String(p):
p = self.subst(p, target=target, source=source, conv=s)
if is_List(p):
if len(p) == 1:
p = p[0]
else:
# We have an object plus a string, or multiple
# objects that we need to smush together. No choice
# but to make them into a string.
p = ''.join(map(to_String_for_subst, p))
else:
p = s(p)
r.append(p)
return r | [
"def",
"subst_path",
"(",
"self",
",",
"path",
",",
"target",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"if",
"not",
"is_List",
"(",
"path",
")",
":",
"path",
"=",
"[",
"path",
"]",
"def",
"s",
"(",
"obj",
")",
":",
"\"\"\"This is the \"string conversion\" routine that we have our\n substitutions use to return Nodes, not strings. This relies\n on the fact that an EntryProxy object has a get() method that\n returns the underlying Node that it wraps, which is a bit of\n architectural dependence that we might need to break or modify\n in the future in response to additional requirements.\"\"\"",
"try",
":",
"get",
"=",
"obj",
".",
"get",
"except",
"AttributeError",
":",
"obj",
"=",
"to_String_for_subst",
"(",
"obj",
")",
"else",
":",
"obj",
"=",
"get",
"(",
")",
"return",
"obj",
"r",
"=",
"[",
"]",
"for",
"p",
"in",
"path",
":",
"if",
"is_String",
"(",
"p",
")",
":",
"p",
"=",
"self",
".",
"subst",
"(",
"p",
",",
"target",
"=",
"target",
",",
"source",
"=",
"source",
",",
"conv",
"=",
"s",
")",
"if",
"is_List",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"1",
":",
"p",
"=",
"p",
"[",
"0",
"]",
"else",
":",
"# We have an object plus a string, or multiple",
"# objects that we need to smush together. No choice",
"# but to make them into a string.",
"p",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"to_String_for_subst",
",",
"p",
")",
")",
"else",
":",
"p",
"=",
"s",
"(",
"p",
")",
"r",
".",
"append",
"(",
"p",
")",
"return",
"r"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Environment.py#L526-L563 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | benchmark/python/sparse/dot.py | python | measure_cost | (repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs) | return diff / repeat | Measure time cost of running a function | Measure time cost of running a function | [
"Measure",
"time",
"cost",
"of",
"running",
"a",
"function"
] | def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs):
"""Measure time cost of running a function
"""
mx.nd.waitall()
args_list = []
for arg in args:
args_list.append(arg)
start = time.time()
if scipy_trans_lhs:
args_list[0] = np.transpose(args_list[0]) if scipy_dns_lhs else sp.spmatrix.transpose(args_list[0])
for _ in range(repeat):
func_name(*args_list, **kwargs)
mx.nd.waitall()
end = time.time()
diff = end - start
return diff / repeat | [
"def",
"measure_cost",
"(",
"repeat",
",",
"scipy_trans_lhs",
",",
"scipy_dns_lhs",
",",
"func_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mx",
".",
"nd",
".",
"waitall",
"(",
")",
"args_list",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"args_list",
".",
"append",
"(",
"arg",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"if",
"scipy_trans_lhs",
":",
"args_list",
"[",
"0",
"]",
"=",
"np",
".",
"transpose",
"(",
"args_list",
"[",
"0",
"]",
")",
"if",
"scipy_dns_lhs",
"else",
"sp",
".",
"spmatrix",
".",
"transpose",
"(",
"args_list",
"[",
"0",
"]",
")",
"for",
"_",
"in",
"range",
"(",
"repeat",
")",
":",
"func_name",
"(",
"*",
"args_list",
",",
"*",
"*",
"kwargs",
")",
"mx",
".",
"nd",
".",
"waitall",
"(",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"diff",
"=",
"end",
"-",
"start",
"return",
"diff",
"/",
"repeat"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/benchmark/python/sparse/dot.py#L110-L125 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/gui/Application.py | python | Application.__init__ | (self, file_paths, platform) | Application constructor.
Create the main window, setup the message handler, import the preferences,
and connect all of the action handlers. Finally, enter the gtk main loop and block.
Args:
file_paths: a list of flow graph file passed from command line
platform: platform module | Application constructor.
Create the main window, setup the message handler, import the preferences,
and connect all of the action handlers. Finally, enter the gtk main loop and block. | [
"Application",
"constructor",
".",
"Create",
"the",
"main",
"window",
"setup",
"the",
"message",
"handler",
"import",
"the",
"preferences",
"and",
"connect",
"all",
"of",
"the",
"action",
"handlers",
".",
"Finally",
"enter",
"the",
"gtk",
"main",
"loop",
"and",
"block",
"."
] | def __init__(self, file_paths, platform):
Gtk.Application.__init__(self)
"""
Application constructor.
Create the main window, setup the message handler, import the preferences,
and connect all of the action handlers. Finally, enter the gtk main loop and block.
Args:
file_paths: a list of flow graph file passed from command line
platform: platform module
"""
self.clipboard = None
self.dialog = None
# Setup the main window
self.platform = platform
self.config = platform.config
log.debug("Application()")
# Connect all actions to _handle_action
for x in Actions.get_actions():
Actions.connect(x, handler=self._handle_action)
Actions.actions[x].enable()
if x.startswith("app."):
self.add_action(Actions.actions[x])
# Setup the shortcut keys
# These are the globally defined shortcuts
keypress = Actions.actions[x].keypresses
if keypress:
self.set_accels_for_action(x, keypress)
# Initialize
self.init_file_paths = [os.path.abspath(
file_path) for file_path in file_paths]
self.init = False | [
"def",
"__init__",
"(",
"self",
",",
"file_paths",
",",
"platform",
")",
":",
"Gtk",
".",
"Application",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"clipboard",
"=",
"None",
"self",
".",
"dialog",
"=",
"None",
"# Setup the main window",
"self",
".",
"platform",
"=",
"platform",
"self",
".",
"config",
"=",
"platform",
".",
"config",
"log",
".",
"debug",
"(",
"\"Application()\"",
")",
"# Connect all actions to _handle_action",
"for",
"x",
"in",
"Actions",
".",
"get_actions",
"(",
")",
":",
"Actions",
".",
"connect",
"(",
"x",
",",
"handler",
"=",
"self",
".",
"_handle_action",
")",
"Actions",
".",
"actions",
"[",
"x",
"]",
".",
"enable",
"(",
")",
"if",
"x",
".",
"startswith",
"(",
"\"app.\"",
")",
":",
"self",
".",
"add_action",
"(",
"Actions",
".",
"actions",
"[",
"x",
"]",
")",
"# Setup the shortcut keys",
"# These are the globally defined shortcuts",
"keypress",
"=",
"Actions",
".",
"actions",
"[",
"x",
"]",
".",
"keypresses",
"if",
"keypress",
":",
"self",
".",
"set_accels_for_action",
"(",
"x",
",",
"keypress",
")",
"# Initialize",
"self",
".",
"init_file_paths",
"=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"file_path",
")",
"for",
"file_path",
"in",
"file_paths",
"]",
"self",
".",
"init",
"=",
"False"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/Application.py#L35-L69 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/pkg_resources/__init__.py | python | _ReqExtras.markers_pass | (self, req, extras=None) | return not req.marker or any(extra_evals) | Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True. | Evaluate markers for req against each extra that
demanded it. | [
"Evaluate",
"markers",
"for",
"req",
"against",
"each",
"extra",
"that",
"demanded",
"it",
"."
] | def markers_pass(self, req, extras=None):
"""
Evaluate markers for req against each extra that
demanded it.
Return False if the req has a marker and fails
evaluation. Otherwise, return True.
"""
extra_evals = (
req.marker.evaluate({'extra': extra})
for extra in self.get(req, ()) + (extras or (None,))
)
return not req.marker or any(extra_evals) | [
"def",
"markers_pass",
"(",
"self",
",",
"req",
",",
"extras",
"=",
"None",
")",
":",
"extra_evals",
"=",
"(",
"req",
".",
"marker",
".",
"evaluate",
"(",
"{",
"'extra'",
":",
"extra",
"}",
")",
"for",
"extra",
"in",
"self",
".",
"get",
"(",
"req",
",",
"(",
")",
")",
"+",
"(",
"extras",
"or",
"(",
"None",
",",
")",
")",
")",
"return",
"not",
"req",
".",
"marker",
"or",
"any",
"(",
"extra_evals",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L944-L956 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/posixpath.py | python | normcase | (s) | return s | Normalize case of pathname. Has no effect under Posix | Normalize case of pathname. Has no effect under Posix | [
"Normalize",
"case",
"of",
"pathname",
".",
"Has",
"no",
"effect",
"under",
"Posix"
] | def normcase(s):
"""Normalize case of pathname. Has no effect under Posix"""
return s | [
"def",
"normcase",
"(",
"s",
")",
":",
"return",
"s"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/posixpath.py#L51-L53 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_wx/objpanel.py | python | ScalarPanel.restore | (self) | Object values are copied into widgets. | Object values are copied into widgets. | [
"Object",
"values",
"are",
"copied",
"into",
"widgets",
"."
] | def restore(self):
"""
Object values are copied into widgets.
"""
for widgetcontainer in self.widgetcontainers:
widgetcontainer.apply_obj_to_valuewidget() | [
"def",
"restore",
"(",
"self",
")",
":",
"for",
"widgetcontainer",
"in",
"self",
".",
"widgetcontainers",
":",
"widgetcontainer",
".",
"apply_obj_to_valuewidget",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L1847-L1852 | ||
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/input.py | python | ValidateRulesInTarget | (target, target_dict, extra_sources_for_rules) | Ensures that the rules sections in target_dict are valid and consistent,
and determines which sources they apply to.
Arguments:
target: string, name of target.
target_dict: dict, target spec containing "rules" and "sources" lists.
extra_sources_for_rules: a list of keys to scan for rule matches in
addition to 'sources'. | Ensures that the rules sections in target_dict are valid and consistent,
and determines which sources they apply to. | [
"Ensures",
"that",
"the",
"rules",
"sections",
"in",
"target_dict",
"are",
"valid",
"and",
"consistent",
"and",
"determines",
"which",
"sources",
"they",
"apply",
"to",
"."
] | def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
"""Ensures that the rules sections in target_dict are valid and consistent,
and determines which sources they apply to.
Arguments:
target: string, name of target.
target_dict: dict, target spec containing "rules" and "sources" lists.
extra_sources_for_rules: a list of keys to scan for rule matches in
addition to 'sources'.
"""
# Dicts to map between values found in rules' 'rule_name' and 'extension'
# keys and the rule dicts themselves.
rule_names = {}
rule_extensions = {}
rules = target_dict.get('rules', [])
for rule in rules:
# Make sure that there's no conflict among rule names and extensions.
rule_name = rule['rule_name']
if rule_name in rule_names:
raise KeyError, 'rule %s exists in duplicate, target %s' % \
(rule_name, target)
rule_names[rule_name] = rule
rule_extension = rule['extension']
if rule_extension in rule_extensions:
raise KeyError, ('extension %s associated with multiple rules, ' +
'target %s rules %s and %s') % \
(rule_extension, target,
rule_extensions[rule_extension]['rule_name'],
rule_name)
rule_extensions[rule_extension] = rule
# Make sure rule_sources isn't already there. It's going to be
# created below if needed.
if 'rule_sources' in rule:
raise KeyError, \
'rule_sources must not exist in input, target %s rule %s' % \
(target, rule_name)
extension = rule['extension']
rule_sources = []
source_keys = ['sources']
source_keys.extend(extra_sources_for_rules)
for source_key in source_keys:
for source in target_dict.get(source_key, []):
(source_root, source_extension) = os.path.splitext(source)
if source_extension.startswith('.'):
source_extension = source_extension[1:]
if source_extension == extension:
rule_sources.append(source)
if len(rule_sources) > 0:
rule['rule_sources'] = rule_sources | [
"def",
"ValidateRulesInTarget",
"(",
"target",
",",
"target_dict",
",",
"extra_sources_for_rules",
")",
":",
"# Dicts to map between values found in rules' 'rule_name' and 'extension'",
"# keys and the rule dicts themselves.",
"rule_names",
"=",
"{",
"}",
"rule_extensions",
"=",
"{",
"}",
"rules",
"=",
"target_dict",
".",
"get",
"(",
"'rules'",
",",
"[",
"]",
")",
"for",
"rule",
"in",
"rules",
":",
"# Make sure that there's no conflict among rule names and extensions.",
"rule_name",
"=",
"rule",
"[",
"'rule_name'",
"]",
"if",
"rule_name",
"in",
"rule_names",
":",
"raise",
"KeyError",
",",
"'rule %s exists in duplicate, target %s'",
"%",
"(",
"rule_name",
",",
"target",
")",
"rule_names",
"[",
"rule_name",
"]",
"=",
"rule",
"rule_extension",
"=",
"rule",
"[",
"'extension'",
"]",
"if",
"rule_extension",
"in",
"rule_extensions",
":",
"raise",
"KeyError",
",",
"(",
"'extension %s associated with multiple rules, '",
"+",
"'target %s rules %s and %s'",
")",
"%",
"(",
"rule_extension",
",",
"target",
",",
"rule_extensions",
"[",
"rule_extension",
"]",
"[",
"'rule_name'",
"]",
",",
"rule_name",
")",
"rule_extensions",
"[",
"rule_extension",
"]",
"=",
"rule",
"# Make sure rule_sources isn't already there. It's going to be",
"# created below if needed.",
"if",
"'rule_sources'",
"in",
"rule",
":",
"raise",
"KeyError",
",",
"'rule_sources must not exist in input, target %s rule %s'",
"%",
"(",
"target",
",",
"rule_name",
")",
"extension",
"=",
"rule",
"[",
"'extension'",
"]",
"rule_sources",
"=",
"[",
"]",
"source_keys",
"=",
"[",
"'sources'",
"]",
"source_keys",
".",
"extend",
"(",
"extra_sources_for_rules",
")",
"for",
"source_key",
"in",
"source_keys",
":",
"for",
"source",
"in",
"target_dict",
".",
"get",
"(",
"source_key",
",",
"[",
"]",
")",
":",
"(",
"source_root",
",",
"source_extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"source",
")",
"if",
"source_extension",
".",
"startswith",
"(",
"'.'",
")",
":",
"source_extension",
"=",
"source_extension",
"[",
"1",
":",
"]",
"if",
"source_extension",
"==",
"extension",
":",
"rule_sources",
".",
"append",
"(",
"source",
")",
"if",
"len",
"(",
"rule_sources",
")",
">",
"0",
":",
"rule",
"[",
"'rule_sources'",
"]",
"=",
"rule_sources"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/input.py#L2171-L2225 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/blocks/block.py | python | Block.import_data | (self, name, states, parameters, **_) | Import this block's params from nested data.
Any param keys that do not exist will be ignored.
Since params can be dynamically created based another param,
call rewrite, and repeat the load until the params stick. | Import this block's params from nested data.
Any param keys that do not exist will be ignored.
Since params can be dynamically created based another param,
call rewrite, and repeat the load until the params stick. | [
"Import",
"this",
"block",
"s",
"params",
"from",
"nested",
"data",
".",
"Any",
"param",
"keys",
"that",
"do",
"not",
"exist",
"will",
"be",
"ignored",
".",
"Since",
"params",
"can",
"be",
"dynamically",
"created",
"based",
"another",
"param",
"call",
"rewrite",
"and",
"repeat",
"the",
"load",
"until",
"the",
"params",
"stick",
"."
] | def import_data(self, name, states, parameters, **_):
"""
Import this block's params from nested data.
Any param keys that do not exist will be ignored.
Since params can be dynamically created based another param,
call rewrite, and repeat the load until the params stick.
"""
self.params['id'].value = name
self.states.update(states)
def get_hash():
return hash(tuple(hash(v) for v in self.params.values()))
pre_rewrite_hash = -1
while pre_rewrite_hash != get_hash():
for key, value in parameters.items():
try:
self.params[key].set_value(value)
except KeyError:
continue
# Store hash and call rewrite
pre_rewrite_hash = get_hash()
self.rewrite() | [
"def",
"import_data",
"(",
"self",
",",
"name",
",",
"states",
",",
"parameters",
",",
"*",
"*",
"_",
")",
":",
"self",
".",
"params",
"[",
"'id'",
"]",
".",
"value",
"=",
"name",
"self",
".",
"states",
".",
"update",
"(",
"states",
")",
"def",
"get_hash",
"(",
")",
":",
"return",
"hash",
"(",
"tuple",
"(",
"hash",
"(",
"v",
")",
"for",
"v",
"in",
"self",
".",
"params",
".",
"values",
"(",
")",
")",
")",
"pre_rewrite_hash",
"=",
"-",
"1",
"while",
"pre_rewrite_hash",
"!=",
"get_hash",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"parameters",
".",
"items",
"(",
")",
":",
"try",
":",
"self",
".",
"params",
"[",
"key",
"]",
".",
"set_value",
"(",
"value",
")",
"except",
"KeyError",
":",
"continue",
"# Store hash and call rewrite",
"pre_rewrite_hash",
"=",
"get_hash",
"(",
")",
"self",
".",
"rewrite",
"(",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/blocks/block.py#L668-L690 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py | python | Connection.set_session | (self, session) | Set the session to be used when the TLS/SSL connection is established.
:param session: A Session instance representing the session to use.
:returns: None
.. versionadded:: 0.14 | Set the session to be used when the TLS/SSL connection is established. | [
"Set",
"the",
"session",
"to",
"be",
"used",
"when",
"the",
"TLS",
"/",
"SSL",
"connection",
"is",
"established",
"."
] | def set_session(self, session):
"""
Set the session to be used when the TLS/SSL connection is established.
:param session: A Session instance representing the session to use.
:returns: None
.. versionadded:: 0.14
"""
if not isinstance(session, Session):
raise TypeError("session must be a Session instance")
result = _lib.SSL_set_session(self._ssl, session._session)
if not result:
_raise_current_error() | [
"def",
"set_session",
"(",
"self",
",",
"session",
")",
":",
"if",
"not",
"isinstance",
"(",
"session",
",",
"Session",
")",
":",
"raise",
"TypeError",
"(",
"\"session must be a Session instance\"",
")",
"result",
"=",
"_lib",
".",
"SSL_set_session",
"(",
"self",
".",
"_ssl",
",",
"session",
".",
"_session",
")",
"if",
"not",
"result",
":",
"_raise_current_error",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py#L2301-L2315 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/tools/in_graph_env.py | python | InGraphEnv.done | (self) | return self._done | Access the variable indicating whether the episode is done. | Access the variable indicating whether the episode is done. | [
"Access",
"the",
"variable",
"indicating",
"whether",
"the",
"episode",
"is",
"done",
"."
] | def done(self):
"""Access the variable indicating whether the episode is done."""
return self._done | [
"def",
"done",
"(",
"self",
")",
":",
"return",
"self",
".",
"_done"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/tools/in_graph_env.py#L123-L125 | |
p4lang/behavioral-model | 81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9 | tools/runtime_CLI.py | python | RuntimeAPI.do_meter_set_rates | (self, line) | Configure rates for a meter: meter_set_rates <name> <index> <rate_1>:<burst_1> <rate_2>:<burst_2> ...\nRate uses units/microsecond and burst uses units where units is bytes or packets | Configure rates for a meter: meter_set_rates <name> <index> <rate_1>:<burst_1> <rate_2>:<burst_2> ...\nRate uses units/microsecond and burst uses units where units is bytes or packets | [
"Configure",
"rates",
"for",
"a",
"meter",
":",
"meter_set_rates",
"<name",
">",
"<index",
">",
"<rate_1",
">",
":",
"<burst_1",
">",
"<rate_2",
">",
":",
"<burst_2",
">",
"...",
"\\",
"nRate",
"uses",
"units",
"/",
"microsecond",
"and",
"burst",
"uses",
"units",
"where",
"units",
"is",
"bytes",
"or",
"packets"
] | def do_meter_set_rates(self, line):
"Configure rates for a meter: meter_set_rates <name> <index> <rate_1>:<burst_1> <rate_2>:<burst_2> ...\nRate uses units/microsecond and burst uses units where units is bytes or packets"
args = line.split()
self.at_least_n_args(args, 2)
meter_name = args[0]
meter = self.get_res("meter", meter_name, ResType.meter_array)
try:
index = int(args[1])
except:
raise UIn_Error("Bad format for index")
rates = args[2:]
if len(rates) != meter.rate_count:
raise UIn_Error(
"Invalid number of rates, expected %d but got %d"
% (meter.rate_count, len(rates))
)
new_rates = []
for rate in rates:
try:
r, b = rate.split(':')
r = float(r)
b = int(b)
new_rates.append(BmMeterRateConfig(r, b))
except:
raise UIn_Error("Error while parsing rates")
if meter.is_direct:
table_name = meter.binding
self.client.bm_mt_set_meter_rates(0, table_name, index, new_rates)
else:
self.client.bm_meter_set_rates(0, meter.name, index, new_rates) | [
"def",
"do_meter_set_rates",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"line",
".",
"split",
"(",
")",
"self",
".",
"at_least_n_args",
"(",
"args",
",",
"2",
")",
"meter_name",
"=",
"args",
"[",
"0",
"]",
"meter",
"=",
"self",
".",
"get_res",
"(",
"\"meter\"",
",",
"meter_name",
",",
"ResType",
".",
"meter_array",
")",
"try",
":",
"index",
"=",
"int",
"(",
"args",
"[",
"1",
"]",
")",
"except",
":",
"raise",
"UIn_Error",
"(",
"\"Bad format for index\"",
")",
"rates",
"=",
"args",
"[",
"2",
":",
"]",
"if",
"len",
"(",
"rates",
")",
"!=",
"meter",
".",
"rate_count",
":",
"raise",
"UIn_Error",
"(",
"\"Invalid number of rates, expected %d but got %d\"",
"%",
"(",
"meter",
".",
"rate_count",
",",
"len",
"(",
"rates",
")",
")",
")",
"new_rates",
"=",
"[",
"]",
"for",
"rate",
"in",
"rates",
":",
"try",
":",
"r",
",",
"b",
"=",
"rate",
".",
"split",
"(",
"':'",
")",
"r",
"=",
"float",
"(",
"r",
")",
"b",
"=",
"int",
"(",
"b",
")",
"new_rates",
".",
"append",
"(",
"BmMeterRateConfig",
"(",
"r",
",",
"b",
")",
")",
"except",
":",
"raise",
"UIn_Error",
"(",
"\"Error while parsing rates\"",
")",
"if",
"meter",
".",
"is_direct",
":",
"table_name",
"=",
"meter",
".",
"binding",
"self",
".",
"client",
".",
"bm_mt_set_meter_rates",
"(",
"0",
",",
"table_name",
",",
"index",
",",
"new_rates",
")",
"else",
":",
"self",
".",
"client",
".",
"bm_meter_set_rates",
"(",
"0",
",",
"meter",
".",
"name",
",",
"index",
",",
"new_rates",
")"
] | https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/runtime_CLI.py#L1956-L1985 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py | python | makeHTMLTags | (tagStr) | return _makeTags( tagStr, False ) | Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches
tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values.
Example::
text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
# makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple
a,a_end = makeHTMLTags("A")
link_expr = a + SkipTo(a_end)("link_text") + a_end
for link in link_expr.searchString(text):
# attributes in the <A> tag (like "href" shown here) are also accessible as named results
print(link.link_text, '->', link.href)
prints::
pyparsing -> http://pyparsing.wikispaces.com | Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches
tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. | [
"Helper",
"to",
"construct",
"opening",
"and",
"closing",
"tag",
"expressions",
"for",
"HTML",
"given",
"a",
"tag",
"name",
".",
"Matches",
"tags",
"in",
"either",
"upper",
"or",
"lower",
"case",
"attributes",
"with",
"namespaces",
"and",
"with",
"quoted",
"or",
"unquoted",
"values",
"."
] | def makeHTMLTags(tagStr):
"""
Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches
tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values.
Example::
text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
# makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple
a,a_end = makeHTMLTags("A")
link_expr = a + SkipTo(a_end)("link_text") + a_end
for link in link_expr.searchString(text):
# attributes in the <A> tag (like "href" shown here) are also accessible as named results
print(link.link_text, '->', link.href)
prints::
pyparsing -> http://pyparsing.wikispaces.com
"""
return _makeTags( tagStr, False ) | [
"def",
"makeHTMLTags",
"(",
"tagStr",
")",
":",
"return",
"_makeTags",
"(",
"tagStr",
",",
"False",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L4904-L4921 | |
moai/moai-dev | 0ba7c678311d1fa9dbc091f60665e95e54169fdf | 3rdparty/libwebp-0.4.1/swig/libwebp.py | python | WebPEncodeBGRA | (rgb, width, height, stride, quality_factor) | return webp[0] | WebPEncodeBGRA(uint8_t rgb, int width, int height, int stride, float quality_factor) -> lossy_webp | WebPEncodeBGRA(uint8_t rgb, int width, int height, int stride, float quality_factor) -> lossy_webp | [
"WebPEncodeBGRA",
"(",
"uint8_t",
"rgb",
"int",
"width",
"int",
"height",
"int",
"stride",
"float",
"quality_factor",
")",
"-",
">",
"lossy_webp"
] | def WebPEncodeBGRA(rgb, width, height, stride, quality_factor):
"""WebPEncodeBGRA(uint8_t rgb, int width, int height, int stride, float quality_factor) -> lossy_webp"""
webp = wrap_WebPEncodeBGRA(
rgb, _UNUSED, _UNUSED, width, height, stride, quality_factor)
if len(webp[0]) == 0:
return None
return webp[0] | [
"def",
"WebPEncodeBGRA",
"(",
"rgb",
",",
"width",
",",
"height",
",",
"stride",
",",
"quality_factor",
")",
":",
"webp",
"=",
"wrap_WebPEncodeBGRA",
"(",
"rgb",
",",
"_UNUSED",
",",
"_UNUSED",
",",
"width",
",",
"height",
",",
"stride",
",",
"quality_factor",
")",
"if",
"len",
"(",
"webp",
"[",
"0",
"]",
")",
"==",
"0",
":",
"return",
"None",
"return",
"webp",
"[",
"0",
"]"
] | https://github.com/moai/moai-dev/blob/0ba7c678311d1fa9dbc091f60665e95e54169fdf/3rdparty/libwebp-0.4.1/swig/libwebp.py#L160-L166 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/processing/modeler/ModelerGraphicItem.py | python | ModelerInputGraphicItem.create_widget_context | (self) | return widget_context | Returns a new widget context for use in the model editor | Returns a new widget context for use in the model editor | [
"Returns",
"a",
"new",
"widget",
"context",
"for",
"use",
"in",
"the",
"model",
"editor"
] | def create_widget_context(self):
"""
Returns a new widget context for use in the model editor
"""
widget_context = QgsProcessingParameterWidgetContext()
widget_context.setProject(QgsProject.instance())
if iface is not None:
widget_context.setMapCanvas(iface.mapCanvas())
widget_context.setActiveLayer(iface.activeLayer())
widget_context.setModel(self.model())
return widget_context | [
"def",
"create_widget_context",
"(",
"self",
")",
":",
"widget_context",
"=",
"QgsProcessingParameterWidgetContext",
"(",
")",
"widget_context",
".",
"setProject",
"(",
"QgsProject",
".",
"instance",
"(",
")",
")",
"if",
"iface",
"is",
"not",
"None",
":",
"widget_context",
".",
"setMapCanvas",
"(",
"iface",
".",
"mapCanvas",
"(",
")",
")",
"widget_context",
".",
"setActiveLayer",
"(",
"iface",
".",
"activeLayer",
"(",
")",
")",
"widget_context",
".",
"setModel",
"(",
"self",
".",
"model",
"(",
")",
")",
"return",
"widget_context"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/processing/modeler/ModelerGraphicItem.py#L68-L79 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py | python | ScriptWriter.get_args | (cls, dist, header=None) | Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points. | Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points. | [
"Yield",
"write_script",
"()",
"argument",
"tuples",
"for",
"a",
"distribution",
"s",
"console_scripts",
"and",
"gui_scripts",
"entry",
"points",
"."
] | def get_args(cls, dist, header=None):
"""
Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points.
"""
if header is None:
header = cls.get_header()
spec = str(dist.as_requirement())
for type_ in 'console', 'gui':
group = type_ + '_scripts'
for name, ep in dist.get_entry_map(group).items():
cls._ensure_safe_name(name)
script_text = cls.template % locals()
args = cls._get_script_args(type_, name, header, script_text)
for res in args:
yield res | [
"def",
"get_args",
"(",
"cls",
",",
"dist",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
"=",
"cls",
".",
"get_header",
"(",
")",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"for",
"type_",
"in",
"'console'",
",",
"'gui'",
":",
"group",
"=",
"type_",
"+",
"'_scripts'",
"for",
"name",
",",
"ep",
"in",
"dist",
".",
"get_entry_map",
"(",
"group",
")",
".",
"items",
"(",
")",
":",
"cls",
".",
"_ensure_safe_name",
"(",
"name",
")",
"script_text",
"=",
"cls",
".",
"template",
"%",
"locals",
"(",
")",
"args",
"=",
"cls",
".",
"_get_script_args",
"(",
"type_",
",",
"name",
",",
"header",
",",
"script_text",
")",
"for",
"res",
"in",
"args",
":",
"yield",
"res"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py#L2107-L2122 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/saving/saveable_object.py | python | SaveableObject.device | (self) | return self.specs[0].device | The device for SaveSpec Tensors. | The device for SaveSpec Tensors. | [
"The",
"device",
"for",
"SaveSpec",
"Tensors",
"."
] | def device(self):
"""The device for SaveSpec Tensors."""
return self.specs[0].device | [
"def",
"device",
"(",
"self",
")",
":",
"return",
"self",
".",
"specs",
"[",
"0",
"]",
".",
"device"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/saving/saveable_object.py#L73-L75 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npdatetime.py | python | get_datetime_timedelta_conversion | (datetime_unit, timedelta_unit) | Compute a possible conversion for combining *datetime_unit* and
*timedelta_unit* (presumably for adding or subtracting).
Return (result unit, integer datetime multiplier, integer timedelta
multiplier). RuntimeError is raised if the combination is impossible. | Compute a possible conversion for combining *datetime_unit* and
*timedelta_unit* (presumably for adding or subtracting).
Return (result unit, integer datetime multiplier, integer timedelta
multiplier). RuntimeError is raised if the combination is impossible. | [
"Compute",
"a",
"possible",
"conversion",
"for",
"combining",
"*",
"datetime_unit",
"*",
"and",
"*",
"timedelta_unit",
"*",
"(",
"presumably",
"for",
"adding",
"or",
"subtracting",
")",
".",
"Return",
"(",
"result",
"unit",
"integer",
"datetime",
"multiplier",
"integer",
"timedelta",
"multiplier",
")",
".",
"RuntimeError",
"is",
"raised",
"if",
"the",
"combination",
"is",
"impossible",
"."
] | def get_datetime_timedelta_conversion(datetime_unit, timedelta_unit):
"""
Compute a possible conversion for combining *datetime_unit* and
*timedelta_unit* (presumably for adding or subtracting).
Return (result unit, integer datetime multiplier, integer timedelta
multiplier). RuntimeError is raised if the combination is impossible.
"""
# XXX now unused (I don't know where / how Numpy uses this)
dt_unit_code = DATETIME_UNITS[datetime_unit]
td_unit_code = DATETIME_UNITS[timedelta_unit]
if td_unit_code == 14 or dt_unit_code == 14:
return datetime_unit, 1, 1
if td_unit_code < 2 and dt_unit_code >= 2:
# Cannot combine Y or M timedelta64 with a finer-grained datetime64
raise RuntimeError("cannot combine datetime64(%r) and timedelta64(%r)"
% (datetime_unit, timedelta_unit))
dt_factor, td_factor = 1, 1
# If years or months, the datetime unit is first scaled to weeks or days,
# then conversion continues below. This is the same algorithm as used
# in Numpy's get_datetime_conversion_factor() (src/multiarray/datetime.c):
# """Conversions between years/months and other units use
# the factor averaged over the 400 year leap year cycle."""
if dt_unit_code == 0:
if td_unit_code >= 4:
dt_factor = 97 + 400 * 365
td_factor = 400
dt_unit_code = 4
elif td_unit_code == 2:
dt_factor = 97 + 400 * 365
td_factor = 400 * 7
dt_unit_code = 2
elif dt_unit_code == 1:
if td_unit_code >= 4:
dt_factor = 97 + 400 * 365
td_factor = 400 * 12
dt_unit_code = 4
elif td_unit_code == 2:
dt_factor = 97 + 400 * 365
td_factor = 400 * 12 * 7
dt_unit_code = 2
if td_unit_code >= dt_unit_code:
factor = _get_conversion_multiplier(dt_unit_code, td_unit_code)
assert factor is not None, (dt_unit_code, td_unit_code)
return timedelta_unit, dt_factor * factor, td_factor
else:
factor = _get_conversion_multiplier(td_unit_code, dt_unit_code)
assert factor is not None, (dt_unit_code, td_unit_code)
return datetime_unit, dt_factor, td_factor * factor | [
"def",
"get_datetime_timedelta_conversion",
"(",
"datetime_unit",
",",
"timedelta_unit",
")",
":",
"# XXX now unused (I don't know where / how Numpy uses this)",
"dt_unit_code",
"=",
"DATETIME_UNITS",
"[",
"datetime_unit",
"]",
"td_unit_code",
"=",
"DATETIME_UNITS",
"[",
"timedelta_unit",
"]",
"if",
"td_unit_code",
"==",
"14",
"or",
"dt_unit_code",
"==",
"14",
":",
"return",
"datetime_unit",
",",
"1",
",",
"1",
"if",
"td_unit_code",
"<",
"2",
"and",
"dt_unit_code",
">=",
"2",
":",
"# Cannot combine Y or M timedelta64 with a finer-grained datetime64",
"raise",
"RuntimeError",
"(",
"\"cannot combine datetime64(%r) and timedelta64(%r)\"",
"%",
"(",
"datetime_unit",
",",
"timedelta_unit",
")",
")",
"dt_factor",
",",
"td_factor",
"=",
"1",
",",
"1",
"# If years or months, the datetime unit is first scaled to weeks or days,",
"# then conversion continues below. This is the same algorithm as used",
"# in Numpy's get_datetime_conversion_factor() (src/multiarray/datetime.c):",
"# \"\"\"Conversions between years/months and other units use",
"# the factor averaged over the 400 year leap year cycle.\"\"\"",
"if",
"dt_unit_code",
"==",
"0",
":",
"if",
"td_unit_code",
">=",
"4",
":",
"dt_factor",
"=",
"97",
"+",
"400",
"*",
"365",
"td_factor",
"=",
"400",
"dt_unit_code",
"=",
"4",
"elif",
"td_unit_code",
"==",
"2",
":",
"dt_factor",
"=",
"97",
"+",
"400",
"*",
"365",
"td_factor",
"=",
"400",
"*",
"7",
"dt_unit_code",
"=",
"2",
"elif",
"dt_unit_code",
"==",
"1",
":",
"if",
"td_unit_code",
">=",
"4",
":",
"dt_factor",
"=",
"97",
"+",
"400",
"*",
"365",
"td_factor",
"=",
"400",
"*",
"12",
"dt_unit_code",
"=",
"4",
"elif",
"td_unit_code",
"==",
"2",
":",
"dt_factor",
"=",
"97",
"+",
"400",
"*",
"365",
"td_factor",
"=",
"400",
"*",
"12",
"*",
"7",
"dt_unit_code",
"=",
"2",
"if",
"td_unit_code",
">=",
"dt_unit_code",
":",
"factor",
"=",
"_get_conversion_multiplier",
"(",
"dt_unit_code",
",",
"td_unit_code",
")",
"assert",
"factor",
"is",
"not",
"None",
",",
"(",
"dt_unit_code",
",",
"td_unit_code",
")",
"return",
"timedelta_unit",
",",
"dt_factor",
"*",
"factor",
",",
"td_factor",
"else",
":",
"factor",
"=",
"_get_conversion_multiplier",
"(",
"td_unit_code",
",",
"dt_unit_code",
")",
"assert",
"factor",
"is",
"not",
"None",
",",
"(",
"dt_unit_code",
",",
"td_unit_code",
")",
"return",
"datetime_unit",
",",
"dt_factor",
",",
"td_factor",
"*",
"factor"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npdatetime.py#L120-L169 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py | python | stripid | (text) | return _re_stripid.sub(r'\1', text) | Remove the hexadecimal id from a Python object representation. | Remove the hexadecimal id from a Python object representation. | [
"Remove",
"the",
"hexadecimal",
"id",
"from",
"a",
"Python",
"object",
"representation",
"."
] | def stripid(text):
"""Remove the hexadecimal id from a Python object representation."""
# The behaviour of %p is implementation-dependent in terms of case.
return _re_stripid.sub(r'\1', text) | [
"def",
"stripid",
"(",
"text",
")",
":",
"# The behaviour of %p is implementation-dependent in terms of case.",
"return",
"_re_stripid",
".",
"sub",
"(",
"r'\\1'",
",",
"text",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py#L124-L127 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pydoc.py | python | HTMLDoc.docother | (self, object, name=None, mod=None, *ignored) | return lhs + self.repr(object) | Produce HTML documentation for a data object. | Produce HTML documentation for a data object. | [
"Produce",
"HTML",
"documentation",
"for",
"a",
"data",
"object",
"."
] | def docother(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a data object."""
lhs = name and '<strong>%s</strong> = ' % name or ''
return lhs + self.repr(object) | [
"def",
"docother",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
",",
"*",
"ignored",
")",
":",
"lhs",
"=",
"name",
"and",
"'<strong>%s</strong> = '",
"%",
"name",
"or",
"''",
"return",
"lhs",
"+",
"self",
".",
"repr",
"(",
"object",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pydoc.py#L1013-L1016 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Display.GetCount | (*args, **kwargs) | return _misc_.Display_GetCount(*args, **kwargs) | GetCount() -> unsigned int
Return the number of available displays. | GetCount() -> unsigned int | [
"GetCount",
"()",
"-",
">",
"unsigned",
"int"
] | def GetCount(*args, **kwargs):
"""
GetCount() -> unsigned int
Return the number of available displays.
"""
return _misc_.Display_GetCount(*args, **kwargs) | [
"def",
"GetCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Display_GetCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L6092-L6098 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.CallTipPosAtStart | (*args, **kwargs) | return _stc.StyledTextCtrl_CallTipPosAtStart(*args, **kwargs) | CallTipPosAtStart(self) -> int
Retrieve the position where the caret was before displaying the call tip. | CallTipPosAtStart(self) -> int | [
"CallTipPosAtStart",
"(",
"self",
")",
"-",
">",
"int"
] | def CallTipPosAtStart(*args, **kwargs):
"""
CallTipPosAtStart(self) -> int
Retrieve the position where the caret was before displaying the call tip.
"""
return _stc.StyledTextCtrl_CallTipPosAtStart(*args, **kwargs) | [
"def",
"CallTipPosAtStart",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_CallTipPosAtStart",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3820-L3826 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | GridTableBase.SetView | (*args, **kwargs) | return _grid.GridTableBase_SetView(*args, **kwargs) | SetView(self, Grid grid) | SetView(self, Grid grid) | [
"SetView",
"(",
"self",
"Grid",
"grid",
")"
] | def SetView(*args, **kwargs):
"""SetView(self, Grid grid)"""
return _grid.GridTableBase_SetView(*args, **kwargs) | [
"def",
"SetView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_SetView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L782-L784 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py | python | have_gui | () | return int(vim.eval("has('gui_running')")) == 1 | Returns True if vim is in a gui (Gvim/MacVim), False otherwise. | Returns True if vim is in a gui (Gvim/MacVim), False otherwise. | [
"Returns",
"True",
"if",
"vim",
"is",
"in",
"a",
"gui",
"(",
"Gvim",
"/",
"MacVim",
")",
"False",
"otherwise",
"."
] | def have_gui():
""" Returns True if vim is in a gui (Gvim/MacVim), False otherwise. """
return int(vim.eval("has('gui_running')")) == 1 | [
"def",
"have_gui",
"(",
")",
":",
"return",
"int",
"(",
"vim",
".",
"eval",
"(",
"\"has('gui_running')\"",
")",
")",
"==",
"1"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L140-L142 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewCtrl_GetClassDefaultAttributes | (*args, **kwargs) | return _dataview.DataViewCtrl_GetClassDefaultAttributes(*args, **kwargs) | DataViewCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this. | DataViewCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes | [
"DataViewCtrl_GetClassDefaultAttributes",
"(",
"int",
"variant",
"=",
"WINDOW_VARIANT_NORMAL",
")",
"-",
">",
"VisualAttributes"
] | def DataViewCtrl_GetClassDefaultAttributes(*args, **kwargs):
"""
DataViewCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _dataview.DataViewCtrl_GetClassDefaultAttributes(*args, **kwargs) | [
"def",
"DataViewCtrl_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewCtrl_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1875-L1890 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py | python | TimeSeriesReader.read_full | (self) | Return the full dataset.
Largely for interactive use/plotting (or evaluation on small
datasets). Generally not very efficient. Not recommended for training.
Returns:
Same return type as `read`, but with the full dataset rather than an
arbitrary chunk of it. A dictionary mapping feature names to `Tensor`
values, where the size of the first dimension of each `Tensor` is the
number of samples in the entire dataset. These `Tensor`s should be
constant across graph invocations, assuming that the underlying data
remains constant. Current implementations re-read data on each graph
invocation, although this may change in the future. | Return the full dataset. | [
"Return",
"the",
"full",
"dataset",
"."
] | def read_full(self):
"""Return the full dataset.
Largely for interactive use/plotting (or evaluation on small
datasets). Generally not very efficient. Not recommended for training.
Returns:
Same return type as `read`, but with the full dataset rather than an
arbitrary chunk of it. A dictionary mapping feature names to `Tensor`
values, where the size of the first dimension of each `Tensor` is the
number of samples in the entire dataset. These `Tensor`s should be
constant across graph invocations, assuming that the underlying data
remains constant. Current implementations re-read data on each graph
invocation, although this may change in the future.
"""
pass | [
"def",
"read_full",
"(",
"self",
")",
":",
"pass"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py#L200-L215 | ||
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/streaming_aead/_encrypting_stream.py | python | RawEncryptingStream.__init__ | (self, stream_aead: tink_bindings.StreamingAead,
ciphertext_destination: BinaryIO, associated_data: bytes) | Create a new RawEncryptingStream.
Args:
stream_aead: C++ StreamingAead primitive from which a C++ EncryptingStream
will be obtained.
ciphertext_destination: A writable file-like object to which ciphertext
bytes will be written.
associated_data: The associated data to use for encryption. This must
match the associated_data used for decryption. | Create a new RawEncryptingStream. | [
"Create",
"a",
"new",
"RawEncryptingStream",
"."
] | def __init__(self, stream_aead: tink_bindings.StreamingAead,
ciphertext_destination: BinaryIO, associated_data: bytes):
"""Create a new RawEncryptingStream.
Args:
stream_aead: C++ StreamingAead primitive from which a C++ EncryptingStream
will be obtained.
ciphertext_destination: A writable file-like object to which ciphertext
bytes will be written.
associated_data: The associated data to use for encryption. This must
match the associated_data used for decryption.
"""
super().__init__()
if not ciphertext_destination.writable():
raise ValueError('ciphertext_destination must be writable')
cc_ciphertext_destination = _file_object_adapter.FileObjectAdapter(
ciphertext_destination)
self._cc_encrypting_stream = _new_cc_encrypting_stream(
stream_aead, associated_data, cc_ciphertext_destination) | [
"def",
"__init__",
"(",
"self",
",",
"stream_aead",
":",
"tink_bindings",
".",
"StreamingAead",
",",
"ciphertext_destination",
":",
"BinaryIO",
",",
"associated_data",
":",
"bytes",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"if",
"not",
"ciphertext_destination",
".",
"writable",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'ciphertext_destination must be writable'",
")",
"cc_ciphertext_destination",
"=",
"_file_object_adapter",
".",
"FileObjectAdapter",
"(",
"ciphertext_destination",
")",
"self",
".",
"_cc_encrypting_stream",
"=",
"_new_cc_encrypting_stream",
"(",
"stream_aead",
",",
"associated_data",
",",
"cc_ciphertext_destination",
")"
] | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/streaming_aead/_encrypting_stream.py#L45-L63 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/cli/profile_analyzer_cli.py | python | ProfileAnalyzer._render_normalized_cost_bar | (self, cost, max_cost, length) | return output | Render a text bar representing a normalized cost.
Args:
cost: the absolute value of the cost.
max_cost: the maximum cost value to normalize the absolute cost with.
length: (int) length of the cost bar, in number of characters, excluding
the brackets on the two ends.
Returns:
An instance of debugger_cli_common.RichTextLine. | Render a text bar representing a normalized cost. | [
"Render",
"a",
"text",
"bar",
"representing",
"a",
"normalized",
"cost",
"."
] | def _render_normalized_cost_bar(self, cost, max_cost, length):
"""Render a text bar representing a normalized cost.
Args:
cost: the absolute value of the cost.
max_cost: the maximum cost value to normalize the absolute cost with.
length: (int) length of the cost bar, in number of characters, excluding
the brackets on the two ends.
Returns:
An instance of debugger_cli_common.RichTextLine.
"""
num_ticks = int(np.ceil(float(cost) / max_cost * length))
num_ticks = num_ticks or 1 # Minimum is 1 tick.
output = RL("[", font_attr=self._LINE_COST_ATTR)
output += RL("|" * num_ticks + " " * (length - num_ticks),
font_attr=["bold", self._LINE_COST_ATTR])
output += RL("]", font_attr=self._LINE_COST_ATTR)
return output | [
"def",
"_render_normalized_cost_bar",
"(",
"self",
",",
"cost",
",",
"max_cost",
",",
"length",
")",
":",
"num_ticks",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"float",
"(",
"cost",
")",
"/",
"max_cost",
"*",
"length",
")",
")",
"num_ticks",
"=",
"num_ticks",
"or",
"1",
"# Minimum is 1 tick.",
"output",
"=",
"RL",
"(",
"\"[\"",
",",
"font_attr",
"=",
"self",
".",
"_LINE_COST_ATTR",
")",
"output",
"+=",
"RL",
"(",
"\"|\"",
"*",
"num_ticks",
"+",
"\" \"",
"*",
"(",
"length",
"-",
"num_ticks",
")",
",",
"font_attr",
"=",
"[",
"\"bold\"",
",",
"self",
".",
"_LINE_COST_ATTR",
"]",
")",
"output",
"+=",
"RL",
"(",
"\"]\"",
",",
"font_attr",
"=",
"self",
".",
"_LINE_COST_ATTR",
")",
"return",
"output"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/profile_analyzer_cli.py#L740-L758 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xmlNode.getBase | (self, doc) | return ret | Searches for the BASE URL. The code should work on both XML
and HTML document even if base mechanisms are completely
different. It returns the base as defined in RFC 2396
sections 5.1.1. Base URI within Document Content and 5.1.2.
Base URI from the Encapsulating Entity However it does not
return the document base (5.1.3), use doc->URL in this case | Searches for the BASE URL. The code should work on both XML
and HTML document even if base mechanisms are completely
different. It returns the base as defined in RFC 2396
sections 5.1.1. Base URI within Document Content and 5.1.2.
Base URI from the Encapsulating Entity However it does not
return the document base (5.1.3), use doc->URL in this case | [
"Searches",
"for",
"the",
"BASE",
"URL",
".",
"The",
"code",
"should",
"work",
"on",
"both",
"XML",
"and",
"HTML",
"document",
"even",
"if",
"base",
"mechanisms",
"are",
"completely",
"different",
".",
"It",
"returns",
"the",
"base",
"as",
"defined",
"in",
"RFC",
"2396",
"sections",
"5",
".",
"1",
".",
"1",
".",
"Base",
"URI",
"within",
"Document",
"Content",
"and",
"5",
".",
"1",
".",
"2",
".",
"Base",
"URI",
"from",
"the",
"Encapsulating",
"Entity",
"However",
"it",
"does",
"not",
"return",
"the",
"document",
"base",
"(",
"5",
".",
"1",
".",
"3",
")",
"use",
"doc",
"-",
">",
"URL",
"in",
"this",
"case"
] | def getBase(self, doc):
"""Searches for the BASE URL. The code should work on both XML
and HTML document even if base mechanisms are completely
different. It returns the base as defined in RFC 2396
sections 5.1.1. Base URI within Document Content and 5.1.2.
Base URI from the Encapsulating Entity However it does not
return the document base (5.1.3), use doc->URL in this case """
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlNodeGetBase(doc__o, self._o)
return ret | [
"def",
"getBase",
"(",
"self",
",",
"doc",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlNodeGetBase",
"(",
"doc__o",
",",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L3236-L3246 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/gromacstopfile.py | python | GromacsTopFile._processDihedralType | (self, line) | Process a line in the [ dihedraltypes ] category. | Process a line in the [ dihedraltypes ] category. | [
"Process",
"a",
"line",
"in",
"the",
"[",
"dihedraltypes",
"]",
"category",
"."
] | def _processDihedralType(self, line):
"""Process a line in the [ dihedraltypes ] category."""
fields = line.split()
if len(fields) < 7:
raise ValueError('Too few fields in [ dihedraltypes ] line: '+line)
if fields[4] not in ('1', '2', '3', '4', '5', '9'):
raise ValueError('Unsupported function type in [ dihedraltypes ] line: '+line)
key = tuple(fields[:5])
if fields[4] == '9' and key in self._dihedralTypes:
# There are multiple dihedrals defined for these atom types.
self._dihedralTypes[key].append(fields)
else:
self._dihedralTypes[key] = [fields] | [
"def",
"_processDihedralType",
"(",
"self",
",",
"line",
")",
":",
"fields",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"fields",
")",
"<",
"7",
":",
"raise",
"ValueError",
"(",
"'Too few fields in [ dihedraltypes ] line: '",
"+",
"line",
")",
"if",
"fields",
"[",
"4",
"]",
"not",
"in",
"(",
"'1'",
",",
"'2'",
",",
"'3'",
",",
"'4'",
",",
"'5'",
",",
"'9'",
")",
":",
"raise",
"ValueError",
"(",
"'Unsupported function type in [ dihedraltypes ] line: '",
"+",
"line",
")",
"key",
"=",
"tuple",
"(",
"fields",
"[",
":",
"5",
"]",
")",
"if",
"fields",
"[",
"4",
"]",
"==",
"'9'",
"and",
"key",
"in",
"self",
".",
"_dihedralTypes",
":",
"# There are multiple dihedrals defined for these atom types.",
"self",
".",
"_dihedralTypes",
"[",
"key",
"]",
".",
"append",
"(",
"fields",
")",
"else",
":",
"self",
".",
"_dihedralTypes",
"[",
"key",
"]",
"=",
"[",
"fields",
"]"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/gromacstopfile.py#L418-L430 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py | python | split_by_sparsity | (values) | return dense_values, dense_indices, sparse_values, sparse_indices | Split values into dense and sparse values.
Args:
values: a list of tensors or `PerReplica`s.
Returns:
Four lists:
a list of dense values, a list of their indices in `values` and
a list of sparse values, a list of their indices in `values`. | Split values into dense and sparse values. | [
"Split",
"values",
"into",
"dense",
"and",
"sparse",
"values",
"."
] | def split_by_sparsity(values):
"""Split values into dense and sparse values.
Args:
values: a list of tensors or `PerReplica`s.
Returns:
Four lists:
a list of dense values, a list of their indices in `values` and
a list of sparse values, a list of their indices in `values`.
"""
dense_values = []
dense_indices = []
sparse_values = []
sparse_indices = []
for i, v in enumerate(values):
if is_indexed_slices(v):
sparse_values.append(v)
sparse_indices.append(i)
else:
dense_values.append(v)
dense_indices.append(i)
return dense_values, dense_indices, sparse_values, sparse_indices | [
"def",
"split_by_sparsity",
"(",
"values",
")",
":",
"dense_values",
"=",
"[",
"]",
"dense_indices",
"=",
"[",
"]",
"sparse_values",
"=",
"[",
"]",
"sparse_indices",
"=",
"[",
"]",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"if",
"is_indexed_slices",
"(",
"v",
")",
":",
"sparse_values",
".",
"append",
"(",
"v",
")",
"sparse_indices",
".",
"append",
"(",
"i",
")",
"else",
":",
"dense_values",
".",
"append",
"(",
"v",
")",
"dense_indices",
".",
"append",
"(",
"i",
")",
"return",
"dense_values",
",",
"dense_indices",
",",
"sparse_values",
",",
"sparse_indices"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py#L725-L747 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/generic.py | python | NDFrame._AXIS_NUMBERS | (self) | return {"index": 0} | .. deprecated:: 1.1.0 | .. deprecated:: 1.1.0 | [
"..",
"deprecated",
"::",
"1",
".",
"1",
".",
"0"
] | def _AXIS_NUMBERS(self) -> dict[str, int]:
""".. deprecated:: 1.1.0"""
level = self.ndim + 1
warnings.warn(
"_AXIS_NUMBERS has been deprecated.", FutureWarning, stacklevel=level
)
return {"index": 0} | [
"def",
"_AXIS_NUMBERS",
"(",
"self",
")",
"->",
"dict",
"[",
"str",
",",
"int",
"]",
":",
"level",
"=",
"self",
".",
"ndim",
"+",
"1",
"warnings",
".",
"warn",
"(",
"\"_AXIS_NUMBERS has been deprecated.\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"level",
")",
"return",
"{",
"\"index\"",
":",
"0",
"}"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L486-L492 | |
Smorodov/Multitarget-tracker | bee300e8bfd660c86cbeb6892c65a5b7195c9381 | thirdparty/pybind11/tools/clang/cindex.py | python | SourceLocation.from_offset | (tu, file, offset) | return conf.lib.clang_getLocationForOffset(tu, file, offset) | Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file | Retrieve a SourceLocation from a given character offset. | [
"Retrieve",
"a",
"SourceLocation",
"from",
"a",
"given",
"character",
"offset",
"."
] | def from_offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(tu, file, offset) | [
"def",
"from_offset",
"(",
"tu",
",",
"file",
",",
"offset",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getLocationForOffset",
"(",
"tu",
",",
"file",
",",
"offset",
")"
] | https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L188-L195 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FMRendererMSOffice2007.DrawMenuBarBackground | (self, dc, rect) | Draws the menu bar background according to the active theme.
:param `dc`: an instance of :class:`DC`;
:param `rect`: an instance of :class:`Rect`, representing the menubar client rectangle. | Draws the menu bar background according to the active theme. | [
"Draws",
"the",
"menu",
"bar",
"background",
"according",
"to",
"the",
"active",
"theme",
"."
] | def DrawMenuBarBackground(self, dc, rect):
"""
Draws the menu bar background according to the active theme.
:param `dc`: an instance of :class:`DC`;
:param `rect`: an instance of :class:`Rect`, representing the menubar client rectangle.
"""
# Keep old pen and brush
dcsaver = DCSaver(dc)
artMgr = ArtManager.Get()
baseColour = self.menuBarFaceColour
dc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
dc.DrawRectangleRect(rect)
# Define the rounded rectangle base on the given rect
# we need an array of 9 points for it
regPts = [wx.Point() for ii in xrange(9)]
radius = 2
regPts[0] = wx.Point(rect.x, rect.y + radius)
regPts[1] = wx.Point(rect.x+radius, rect.y)
regPts[2] = wx.Point(rect.x+rect.width-radius-1, rect.y)
regPts[3] = wx.Point(rect.x+rect.width-1, rect.y + radius)
regPts[4] = wx.Point(rect.x+rect.width-1, rect.y + rect.height - radius - 1)
regPts[5] = wx.Point(rect.x+rect.width-radius-1, rect.y + rect.height-1)
regPts[6] = wx.Point(rect.x+radius, rect.y + rect.height-1)
regPts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)
regPts[8] = regPts[0]
# Define the middle points
factor = artMgr.GetMenuBgFactor()
leftPt1 = wx.Point(rect.x, rect.y + (rect.height / factor))
leftPt2 = wx.Point(rect.x, rect.y + (rect.height / factor)*(factor-1))
rightPt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))
rightPt2 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor)*(factor-1))
# Define the top region
topReg = [wx.Point() for ii in xrange(7)]
topReg[0] = regPts[0]
topReg[1] = regPts[1]
topReg[2] = wx.Point(regPts[2].x+1, regPts[2].y)
topReg[3] = wx.Point(regPts[3].x + 1, regPts[3].y)
topReg[4] = wx.Point(rightPt1.x, rightPt1.y+1)
topReg[5] = wx.Point(leftPt1.x, leftPt1.y+1)
topReg[6] = topReg[0]
# Define the middle region
middle = wx.RectPP(leftPt1, wx.Point(rightPt2.x - 2, rightPt2.y))
# Define the bottom region
bottom = wx.RectPP(leftPt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))
topStartColour = artMgr.LightColour(baseColour, 90)
topEndColour = artMgr.LightColour(baseColour, 60)
bottomStartColour = artMgr.LightColour(baseColour, 40)
bottomEndColour = artMgr.LightColour(baseColour, 20)
topRegion = wx.RegionFromPoints(topReg)
artMgr.PaintGradientRegion(dc, topRegion, topStartColour, topEndColour)
artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)
artMgr.PaintStraightGradientBox(dc, middle, topEndColour, bottomStartColour) | [
"def",
"DrawMenuBarBackground",
"(",
"self",
",",
"dc",
",",
"rect",
")",
":",
"# Keep old pen and brush",
"dcsaver",
"=",
"DCSaver",
"(",
"dc",
")",
"artMgr",
"=",
"ArtManager",
".",
"Get",
"(",
")",
"baseColour",
"=",
"self",
".",
"menuBarFaceColour",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_3DFACE",
")",
")",
")",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_3DFACE",
")",
")",
")",
"dc",
".",
"DrawRectangleRect",
"(",
"rect",
")",
"# Define the rounded rectangle base on the given rect",
"# we need an array of 9 points for it",
"regPts",
"=",
"[",
"wx",
".",
"Point",
"(",
")",
"for",
"ii",
"in",
"xrange",
"(",
"9",
")",
"]",
"radius",
"=",
"2",
"regPts",
"[",
"0",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
"+",
"radius",
")",
"regPts",
"[",
"1",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"radius",
",",
"rect",
".",
"y",
")",
"regPts",
"[",
"2",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"rect",
".",
"width",
"-",
"radius",
"-",
"1",
",",
"rect",
".",
"y",
")",
"regPts",
"[",
"3",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"rect",
".",
"width",
"-",
"1",
",",
"rect",
".",
"y",
"+",
"radius",
")",
"regPts",
"[",
"4",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"rect",
".",
"width",
"-",
"1",
",",
"rect",
".",
"y",
"+",
"rect",
".",
"height",
"-",
"radius",
"-",
"1",
")",
"regPts",
"[",
"5",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"rect",
".",
"width",
"-",
"radius",
"-",
"1",
",",
"rect",
".",
"y",
"+",
"rect",
".",
"height",
"-",
"1",
")",
"regPts",
"[",
"6",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"radius",
",",
"rect",
".",
"y",
"+",
"rect",
".",
"height",
"-",
"1",
")",
"regPts",
"[",
"7",
"]",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
"+",
"rect",
".",
"height",
"-",
"radius",
"-",
"1",
")",
"regPts",
"[",
"8",
"]",
"=",
"regPts",
"[",
"0",
"]",
"# Define the middle points",
"factor",
"=",
"artMgr",
".",
"GetMenuBgFactor",
"(",
")",
"leftPt1",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
"+",
"(",
"rect",
".",
"height",
"/",
"factor",
")",
")",
"leftPt2",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
"+",
"(",
"rect",
".",
"height",
"/",
"factor",
")",
"*",
"(",
"factor",
"-",
"1",
")",
")",
"rightPt1",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"rect",
".",
"width",
",",
"rect",
".",
"y",
"+",
"(",
"rect",
".",
"height",
"/",
"factor",
")",
")",
"rightPt2",
"=",
"wx",
".",
"Point",
"(",
"rect",
".",
"x",
"+",
"rect",
".",
"width",
",",
"rect",
".",
"y",
"+",
"(",
"rect",
".",
"height",
"/",
"factor",
")",
"*",
"(",
"factor",
"-",
"1",
")",
")",
"# Define the top region",
"topReg",
"=",
"[",
"wx",
".",
"Point",
"(",
")",
"for",
"ii",
"in",
"xrange",
"(",
"7",
")",
"]",
"topReg",
"[",
"0",
"]",
"=",
"regPts",
"[",
"0",
"]",
"topReg",
"[",
"1",
"]",
"=",
"regPts",
"[",
"1",
"]",
"topReg",
"[",
"2",
"]",
"=",
"wx",
".",
"Point",
"(",
"regPts",
"[",
"2",
"]",
".",
"x",
"+",
"1",
",",
"regPts",
"[",
"2",
"]",
".",
"y",
")",
"topReg",
"[",
"3",
"]",
"=",
"wx",
".",
"Point",
"(",
"regPts",
"[",
"3",
"]",
".",
"x",
"+",
"1",
",",
"regPts",
"[",
"3",
"]",
".",
"y",
")",
"topReg",
"[",
"4",
"]",
"=",
"wx",
".",
"Point",
"(",
"rightPt1",
".",
"x",
",",
"rightPt1",
".",
"y",
"+",
"1",
")",
"topReg",
"[",
"5",
"]",
"=",
"wx",
".",
"Point",
"(",
"leftPt1",
".",
"x",
",",
"leftPt1",
".",
"y",
"+",
"1",
")",
"topReg",
"[",
"6",
"]",
"=",
"topReg",
"[",
"0",
"]",
"# Define the middle region",
"middle",
"=",
"wx",
".",
"RectPP",
"(",
"leftPt1",
",",
"wx",
".",
"Point",
"(",
"rightPt2",
".",
"x",
"-",
"2",
",",
"rightPt2",
".",
"y",
")",
")",
"# Define the bottom region",
"bottom",
"=",
"wx",
".",
"RectPP",
"(",
"leftPt2",
",",
"wx",
".",
"Point",
"(",
"rect",
".",
"GetRight",
"(",
")",
"-",
"1",
",",
"rect",
".",
"GetBottom",
"(",
")",
")",
")",
"topStartColour",
"=",
"artMgr",
".",
"LightColour",
"(",
"baseColour",
",",
"90",
")",
"topEndColour",
"=",
"artMgr",
".",
"LightColour",
"(",
"baseColour",
",",
"60",
")",
"bottomStartColour",
"=",
"artMgr",
".",
"LightColour",
"(",
"baseColour",
",",
"40",
")",
"bottomEndColour",
"=",
"artMgr",
".",
"LightColour",
"(",
"baseColour",
",",
"20",
")",
"topRegion",
"=",
"wx",
".",
"RegionFromPoints",
"(",
"topReg",
")",
"artMgr",
".",
"PaintGradientRegion",
"(",
"dc",
",",
"topRegion",
",",
"topStartColour",
",",
"topEndColour",
")",
"artMgr",
".",
"PaintStraightGradientBox",
"(",
"dc",
",",
"bottom",
",",
"bottomStartColour",
",",
"bottomEndColour",
")",
"artMgr",
".",
"PaintStraightGradientBox",
"(",
"dc",
",",
"middle",
",",
"topEndColour",
",",
"bottomStartColour",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L1533-L1600 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/webapp2/webapp2_extras/appengine/auth/models.py | python | User.validate_token | (cls, user_id, subject, token) | return cls.token_model.get(user=user_id, subject=subject,
token=token) is not None | Checks for existence of a token, given user_id, subject and token.
:param user_id:
User unique ID.
:param subject:
The subject of the key. Examples:
- 'auth'
- 'signup'
:param token:
The token string to be validated.
:returns:
A :class:`UserToken` or None if the token does not exist. | Checks for existence of a token, given user_id, subject and token. | [
"Checks",
"for",
"existence",
"of",
"a",
"token",
"given",
"user_id",
"subject",
"and",
"token",
"."
] | def validate_token(cls, user_id, subject, token):
"""Checks for existence of a token, given user_id, subject and token.
:param user_id:
User unique ID.
:param subject:
The subject of the key. Examples:
- 'auth'
- 'signup'
:param token:
The token string to be validated.
:returns:
A :class:`UserToken` or None if the token does not exist.
"""
return cls.token_model.get(user=user_id, subject=subject,
token=token) is not None | [
"def",
"validate_token",
"(",
"cls",
",",
"user_id",
",",
"subject",
",",
"token",
")",
":",
"return",
"cls",
".",
"token_model",
".",
"get",
"(",
"user",
"=",
"user_id",
",",
"subject",
"=",
"subject",
",",
"token",
"=",
"token",
")",
"is",
"not",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2_extras/appengine/auth/models.py#L306-L322 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/saving/saveable_hook.py | python | SaveableHook.__init__ | (self, name) | Creates a `SaveableHook` object.
Args:
name: the name to save the object under. | Creates a `SaveableHook` object. | [
"Creates",
"a",
"SaveableHook",
"object",
"."
] | def __init__(self, name):
"""Creates a `SaveableHook` object.
Args:
name: the name to save the object under.
"""
super(SaveableHook, self).__init__(
tensor=constant_op.constant(0),
name=name,
) | [
"def",
"__init__",
"(",
"self",
",",
"name",
")",
":",
"super",
"(",
"SaveableHook",
",",
"self",
")",
".",
"__init__",
"(",
"tensor",
"=",
"constant_op",
".",
"constant",
"(",
"0",
")",
",",
"name",
"=",
"name",
",",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/saving/saveable_hook.py#L34-L43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.