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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/print-in-order.py | python | Foo.first | (self, printFirst) | :type printFirst: method
:rtype: void | :type printFirst: method
:rtype: void | [
":",
"type",
"printFirst",
":",
"method",
":",
"rtype",
":",
"void"
] | def first(self, printFirst):
"""
:type printFirst: method
:rtype: void
"""
with self.__cv:
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
self.__has_first = True
self.__cv.notifyAll() | [
"def",
"first",
"(",
"self",
",",
"printFirst",
")",
":",
"with",
"self",
".",
"__cv",
":",
"# printFirst() outputs \"first\". Do not change or remove this line.",
"printFirst",
"(",
")",
"self",
".",
"__has_first",
"=",
"True",
"self",
".",
"__cv",
".",
"notifyAll",
"(",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/print-in-order.py#L13-L22 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | register_loader_type | (loader_type, provider_factory) | Register `provider_factory` to make providers for `loader_type`
`loader_type` is the type or class of a PEP 302 ``module.__loader__``,
and `provider_factory` is a function that, passed a *module* object,
returns an ``IResourceProvider`` for that module. | Register `provider_factory` to make providers for `loader_type` | [
"Register",
"provider_factory",
"to",
"make",
"providers",
"for",
"loader_type"
] | def register_loader_type(loader_type, provider_factory):
"""Register `provider_factory` to make providers for `loader_type`
`loader_type` is the type or class of a PEP 302 ``module.__loader__``,
and `provider_factory` is a function that, passed a *module* object,
returns an ``IResourceProvider`` for that module.
"""
_provider_factories[loader_type] = provider_factory | [
"def",
"register_loader_type",
"(",
"loader_type",
",",
"provider_factory",
")",
":",
"_provider_factories",
"[",
"loader_type",
"]",
"=",
"provider_factory"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L423-L430 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Bell | (*args) | return _misc_.Bell(*args) | Bell() | Bell() | [
"Bell",
"()"
] | def Bell(*args):
"""Bell()"""
return _misc_.Bell(*args) | [
"def",
"Bell",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"Bell",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L316-L318 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/pyreadline/modes/notemacs.py | python | NotEmacsMode.abort | (self, e) | Abort the current editing command and ring the terminals bell
(subject to the setting of bell-style). | Abort the current editing command and ring the terminals bell
(subject to the setting of bell-style). | [
"Abort",
"the",
"current",
"editing",
"command",
"and",
"ring",
"the",
"terminals",
"bell",
"(",
"subject",
"to",
"the",
"setting",
"of",
"bell",
"-",
"style",
")",
"."
] | def abort(self, e): # (C-g)
'''Abort the current editing command and ring the terminals bell
(subject to the setting of bell-style).'''
self._bell() | [
"def",
"abort",
"(",
"self",
",",
"e",
")",
":",
"# (C-g)",
"self",
".",
"_bell",
"(",
")"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/notemacs.py#L482-L485 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | GETnHandler.WriteServiceImplementation | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteServiceImplementation(self, func, file):
"""Overrriden from TypeHandler."""
file.Write(
"error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
file.Write(
" uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
func.name)
last_arg = func.GetLastOriginalArg()
all_but_last_args = func.GetOriginalArgs()[:-1]
for arg in all_but_last_args:
arg.WriteGetCode(file)
code = """ typedef cmds::%(func_name)s::Result Result;
GLsizei num_values = 0;
GetNumValuesReturnedForGLGet(pname, &num_values);
Result* result = GetSharedMemoryAs<Result*>(
c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
%(last_arg_type)s params = result ? result->GetData() : NULL;
"""
file.Write(code % {
'last_arg_type': last_arg.type,
'func_name': func.name,
})
func.WriteHandlerValidation(file)
code = """ // Check that the client initialized the result.
if (result->size != 0) {
return error::kInvalidArguments;
}
"""
shadowed = func.GetInfo('shadowed')
if not shadowed:
file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
file.Write(code)
func.WriteHandlerImplementation(file)
if shadowed:
code = """ result->SetNumResults(num_values);
return error::kNoError;
}
"""
else:
code = """ GLenum error = glGetError();
if (error == GL_NO_ERROR) {
result->SetNumResults(num_values);
} else {
LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
}
return error::kNoError;
}
"""
file.Write(code % {'func_name': func.name}) | [
"def",
"WriteServiceImplementation",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"file",
".",
"Write",
"(",
"\"error::Error GLES2DecoderImpl::Handle%s(\\n\"",
"%",
"func",
".",
"name",
")",
"file",
".",
"Write",
"(",
"\" uint32 immediate_data_size, const gles2::cmds::%s& c) {\\n\"",
"%",
"func",
".",
"name",
")",
"last_arg",
"=",
"func",
".",
"GetLastOriginalArg",
"(",
")",
"all_but_last_args",
"=",
"func",
".",
"GetOriginalArgs",
"(",
")",
"[",
":",
"-",
"1",
"]",
"for",
"arg",
"in",
"all_but_last_args",
":",
"arg",
".",
"WriteGetCode",
"(",
"file",
")",
"code",
"=",
"\"\"\" typedef cmds::%(func_name)s::Result Result;\n GLsizei num_values = 0;\n GetNumValuesReturnedForGLGet(pname, &num_values);\n Result* result = GetSharedMemoryAs<Result*>(\n c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));\n %(last_arg_type)s params = result ? result->GetData() : NULL;\n\"\"\"",
"file",
".",
"Write",
"(",
"code",
"%",
"{",
"'last_arg_type'",
":",
"last_arg",
".",
"type",
",",
"'func_name'",
":",
"func",
".",
"name",
",",
"}",
")",
"func",
".",
"WriteHandlerValidation",
"(",
"file",
")",
"code",
"=",
"\"\"\" // Check that the client initialized the result.\n if (result->size != 0) {\n return error::kInvalidArguments;\n }\n\"\"\"",
"shadowed",
"=",
"func",
".",
"GetInfo",
"(",
"'shadowed'",
")",
"if",
"not",
"shadowed",
":",
"file",
".",
"Write",
"(",
"' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER(\"%s\");\\n'",
"%",
"func",
".",
"name",
")",
"file",
".",
"Write",
"(",
"code",
")",
"func",
".",
"WriteHandlerImplementation",
"(",
"file",
")",
"if",
"shadowed",
":",
"code",
"=",
"\"\"\" result->SetNumResults(num_values);\n return error::kNoError;\n}\n\"\"\"",
"else",
":",
"code",
"=",
"\"\"\" GLenum error = glGetError();\n if (error == GL_NO_ERROR) {\n result->SetNumResults(num_values);\n } else {\n LOCAL_SET_GL_ERROR(error, \"%(func_name)s\", \"\");\n }\n return error::kNoError;\n}\n\n\"\"\"",
"file",
".",
"Write",
"(",
"code",
"%",
"{",
"'func_name'",
":",
"func",
".",
"name",
"}",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L4504-L4555 | ||
google/omaha | 61e8c2833fd69c9a13978400108e5b9ebff24a09 | omaha/installers/tag_meta_installers.py | python | TagBinary | (apps, file, applytag_exe_name) | Creates a number of application specific binaries for the
passed in binary.
Args:
apps: Dictionary of key=lang, value=[Application].
file: The input file to be stamped.
applytag_exe_name: The full path to applytag_exe_name. | Creates a number of application specific binaries for the
passed in binary.
Args:
apps: Dictionary of key=lang, value=[Application].
file: The input file to be stamped.
applytag_exe_name: The full path to applytag_exe_name. | [
"Creates",
"a",
"number",
"of",
"application",
"specific",
"binaries",
"for",
"the",
"passed",
"in",
"binary",
".",
"Args",
":",
"apps",
":",
"Dictionary",
"of",
"key",
"=",
"lang",
"value",
"=",
"[",
"Application",
"]",
".",
"file",
":",
"The",
"input",
"file",
"to",
"be",
"stamped",
".",
"applytag_exe_name",
":",
"The",
"full",
"path",
"to",
"applytag_exe_name",
"."
] | def TagBinary(apps, file, applytag_exe_name):
"""Creates a number of application specific binaries for the
passed in binary.
Args:
apps: Dictionary of key=lang, value=[Application].
file: The input file to be stamped.
applytag_exe_name: The full path to applytag_exe_name.
"""
if not apps:
return
for apps_lang in apps:
for app in apps[apps_lang]:
TagOneFile(file, app, applytag_exe_name) | [
"def",
"TagBinary",
"(",
"apps",
",",
"file",
",",
"applytag_exe_name",
")",
":",
"if",
"not",
"apps",
":",
"return",
"for",
"apps_lang",
"in",
"apps",
":",
"for",
"app",
"in",
"apps",
"[",
"apps_lang",
"]",
":",
"TagOneFile",
"(",
"file",
",",
"app",
",",
"applytag_exe_name",
")"
] | https://github.com/google/omaha/blob/61e8c2833fd69c9a13978400108e5b9ebff24a09/omaha/installers/tag_meta_installers.py#L218-L230 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/udf/typing.py | python | MaskedScalarNullOp.generic | (self, args, kws) | Typing for `Masked` + `NA`
Handles situations like `x + cudf.NA` | Typing for `Masked` + `NA`
Handles situations like `x + cudf.NA` | [
"Typing",
"for",
"Masked",
"+",
"NA",
"Handles",
"situations",
"like",
"x",
"+",
"cudf",
".",
"NA"
] | def generic(self, args, kws):
"""
Typing for `Masked` + `NA`
Handles situations like `x + cudf.NA`
"""
if isinstance(args[0], MaskedType) and isinstance(args[1], NAType):
# In the case of op(Masked, NA), the result has the same
# dtype as the original regardless of what it is
return nb_signature(args[0], args[0], na_type,)
elif isinstance(args[0], NAType) and isinstance(args[1], MaskedType):
return nb_signature(args[1], na_type, args[1]) | [
"def",
"generic",
"(",
"self",
",",
"args",
",",
"kws",
")",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"MaskedType",
")",
"and",
"isinstance",
"(",
"args",
"[",
"1",
"]",
",",
"NAType",
")",
":",
"# In the case of op(Masked, NA), the result has the same",
"# dtype as the original regardless of what it is",
"return",
"nb_signature",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"0",
"]",
",",
"na_type",
",",
")",
"elif",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"NAType",
")",
"and",
"isinstance",
"(",
"args",
"[",
"1",
"]",
",",
"MaskedType",
")",
":",
"return",
"nb_signature",
"(",
"args",
"[",
"1",
"]",
",",
"na_type",
",",
"args",
"[",
"1",
"]",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/udf/typing.py#L266-L276 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py | python | DependencyList.set_output | (self, output_file) | Set the output file and clear the list of already added
dependencies.
`output_file` must be a string. The specified file is
immediately overwritten.
If output_file is '-', the output will be written to stdout.
If it is None, no file output is done when calling add(). | Set the output file and clear the list of already added
dependencies. | [
"Set",
"the",
"output",
"file",
"and",
"clear",
"the",
"list",
"of",
"already",
"added",
"dependencies",
"."
] | def set_output(self, output_file):
"""
Set the output file and clear the list of already added
dependencies.
`output_file` must be a string. The specified file is
immediately overwritten.
If output_file is '-', the output will be written to stdout.
If it is None, no file output is done when calling add().
"""
self.list = []
if output_file:
if output_file == '-':
of = None
else:
of = output_file
self.file = docutils.io.FileOutput(destination_path=of,
encoding='utf8', autoclose=False)
else:
self.file = None | [
"def",
"set_output",
"(",
"self",
",",
"output_file",
")",
":",
"self",
".",
"list",
"=",
"[",
"]",
"if",
"output_file",
":",
"if",
"output_file",
"==",
"'-'",
":",
"of",
"=",
"None",
"else",
":",
"of",
"=",
"output_file",
"self",
".",
"file",
"=",
"docutils",
".",
"io",
".",
"FileOutput",
"(",
"destination_path",
"=",
"of",
",",
"encoding",
"=",
"'utf8'",
",",
"autoclose",
"=",
"False",
")",
"else",
":",
"self",
".",
"file",
"=",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py#L722-L742 | ||
fifengine/fifengine | 4b62c42e85bec19893cef8e63e6855927cff2c47 | engine/python/fife/extensions/serializers/xmlobject.py | python | XMLObjectSaver.save_animation | (self, animation_id, object) | save animation definitions for the given id
@type animation_id: str
@param animation_id: id of the animation data structure
@type object: fife.Object
@param object: the object which should be saved | save animation definitions for the given id | [
"save",
"animation",
"definitions",
"for",
"the",
"given",
"id"
] | def save_animation(self, animation_id, object):
""" save animation definitions for the given id
@type animation_id: str
@param animation_id: id of the animation data structure
@type object: fife.Object
@param object: the object which should be saved
"""
pass | [
"def",
"save_animation",
"(",
"self",
",",
"animation_id",
",",
"object",
")",
":",
"pass"
] | https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/serializers/xmlobject.py#L202-L210 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/ecdsa/numbertheory.py | python | lcm2 | (a,b) | return (a*b)//gcd(a,b) | Least common multiple of two integers. | Least common multiple of two integers. | [
"Least",
"common",
"multiple",
"of",
"two",
"integers",
"."
] | def lcm2(a,b):
"""Least common multiple of two integers."""
return (a*b)//gcd(a,b) | [
"def",
"lcm2",
"(",
"a",
",",
"b",
")",
":",
"return",
"(",
"a",
"*",
"b",
")",
"//",
"gcd",
"(",
"a",
",",
"b",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/ecdsa/numbertheory.py#L225-L228 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/windows/windows.py | python | _len_guards | (M) | return M <= 1 | Handle small or incorrect window lengths | Handle small or incorrect window lengths | [
"Handle",
"small",
"or",
"incorrect",
"window",
"lengths"
] | def _len_guards(M):
"""Handle small or incorrect window lengths"""
if int(M) != M or M < 0:
raise ValueError('Window length M must be a non-negative integer')
return M <= 1 | [
"def",
"_len_guards",
"(",
"M",
")",
":",
"if",
"int",
"(",
"M",
")",
"!=",
"M",
"or",
"M",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Window length M must be a non-negative integer'",
")",
"return",
"M",
"<=",
"1"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/windows/windows.py#L19-L23 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/Codegen.py | python | ForwardDeclarationBuilder.addInMozillaDom | (self, name, isStruct=False) | Add a forward declaration to the mozilla::dom:: namespace. |name| should not
contain any other namespaces. | Add a forward declaration to the mozilla::dom:: namespace. |name| should not
contain any other namespaces. | [
"Add",
"a",
"forward",
"declaration",
"to",
"the",
"mozilla",
"::",
"dom",
"::",
"namespace",
".",
"|name|",
"should",
"not",
"contain",
"any",
"other",
"namespaces",
"."
] | def addInMozillaDom(self, name, isStruct=False):
"""
Add a forward declaration to the mozilla::dom:: namespace. |name| should not
contain any other namespaces.
"""
self._listAdd(["mozilla", "dom"], name, isStruct) | [
"def",
"addInMozillaDom",
"(",
"self",
",",
"name",
",",
"isStruct",
"=",
"False",
")",
":",
"self",
".",
"_listAdd",
"(",
"[",
"\"mozilla\"",
",",
"\"dom\"",
"]",
",",
"name",
",",
"isStruct",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/Codegen.py#L11825-L11830 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | MessageDialog.SetHelpLabel | (*args, **kwargs) | return _windows_.MessageDialog_SetHelpLabel(*args, **kwargs) | SetHelpLabel(self, String help) -> bool | SetHelpLabel(self, String help) -> bool | [
"SetHelpLabel",
"(",
"self",
"String",
"help",
")",
"-",
">",
"bool"
] | def SetHelpLabel(*args, **kwargs):
"""SetHelpLabel(self, String help) -> bool"""
return _windows_.MessageDialog_SetHelpLabel(*args, **kwargs) | [
"def",
"SetHelpLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"MessageDialog_SetHelpLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L3650-L3652 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | cmake/developer_package/cpplint/cpplint.py | python | CheckCheck | (filename, clean_lines, linenum, error) | Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks the use of CHECK and EXPECT macros. | [
"Checks",
"the",
"use",
"of",
"CHECK",
"and",
"EXPECT",
"macros",
"."
] | def CheckCheck(filename, clean_lines, linenum, error):
"""Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Decide the set of replacement macros that should be suggested
lines = clean_lines.elided
(check_macro, start_pos) = FindCheckMacro(lines[linenum])
if not check_macro:
return
# Find end of the boolean expression by matching parentheses
(last_line, end_line, end_pos) = CloseExpression(
clean_lines, linenum, start_pos)
if end_pos < 0:
return
# If the check macro is followed by something other than a
# semicolon, assume users will log their own custom error messages
# and don't suggest any replacements.
if not Match(r'\s*;', last_line[end_pos:]):
return
if linenum == end_line:
expression = lines[linenum][start_pos + 1:end_pos - 1]
else:
expression = lines[linenum][start_pos + 1:]
for i in xrange(linenum + 1, end_line):
expression += lines[i]
expression += last_line[0:end_pos - 1]
# Parse expression so that we can take parentheses into account.
# This avoids false positives for inputs like "CHECK((a < 4) == b)",
# which is not replaceable by CHECK_LE.
lhs = ''
rhs = ''
operator = None
while expression:
matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
r'==|!=|>=|>|<=|<|\()(.*)$', expression)
if matched:
token = matched.group(1)
if token == '(':
# Parenthesized operand
expression = matched.group(2)
(end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
if end < 0:
return # Unmatched parenthesis
lhs += '(' + expression[0:end]
expression = expression[end:]
elif token in ('&&', '||'):
# Logical and/or operators. This means the expression
# contains more than one term, for example:
# CHECK(42 < a && a < b);
#
# These are not replaceable with CHECK_LE, so bail out early.
return
elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
# Non-relational operator
lhs += token
expression = matched.group(2)
else:
# Relational operator
operator = token
rhs = matched.group(2)
break
else:
# Unparenthesized operand. Instead of appending to lhs one character
# at a time, we do another regular expression match to consume several
# characters at once if possible. Trivial benchmark shows that this
# is more efficient when the operands are longer than a single
# character, which is generally the case.
matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
if not matched:
matched = Match(r'^(\s*\S)(.*)$', expression)
if not matched:
break
lhs += matched.group(1)
expression = matched.group(2)
# Only apply checks if we got all parts of the boolean expression
if not (lhs and operator and rhs):
return
# Check that rhs do not contain logical operators. We already know
# that lhs is fine since the loop above parses out && and ||.
if rhs.find('&&') > -1 or rhs.find('||') > -1:
return
# At least one of the operands must be a constant literal. This is
# to avoid suggesting replacements for unprintable things like
# CHECK(variable != iterator)
#
# The following pattern matches decimal, hex integers, strings, and
# characters (in that order).
lhs = lhs.strip()
rhs = rhs.strip()
match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
if Match(match_constant, lhs) or Match(match_constant, rhs):
# Note: since we know both lhs and rhs, we can provide a more
# descriptive error message like:
# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
# Instead of:
# Consider using CHECK_EQ instead of CHECK(a == b)
#
# We are still keeping the less descriptive message because if lhs
# or rhs gets long, the error message might become unreadable.
error(filename, linenum, 'readability/check', 2,
'Consider using %s instead of %s(a %s b)' % (
_CHECK_REPLACEMENT[check_macro][operator],
check_macro, operator)) | [
"def",
"CheckCheck",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Decide the set of replacement macros that should be suggested",
"lines",
"=",
"clean_lines",
".",
"elided",
"(",
"check_macro",
",",
"start_pos",
")",
"=",
"FindCheckMacro",
"(",
"lines",
"[",
"linenum",
"]",
")",
"if",
"not",
"check_macro",
":",
"return",
"# Find end of the boolean expression by matching parentheses",
"(",
"last_line",
",",
"end_line",
",",
"end_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"start_pos",
")",
"if",
"end_pos",
"<",
"0",
":",
"return",
"# If the check macro is followed by something other than a",
"# semicolon, assume users will log their own custom error messages",
"# and don't suggest any replacements.",
"if",
"not",
"Match",
"(",
"r'\\s*;'",
",",
"last_line",
"[",
"end_pos",
":",
"]",
")",
":",
"return",
"if",
"linenum",
"==",
"end_line",
":",
"expression",
"=",
"lines",
"[",
"linenum",
"]",
"[",
"start_pos",
"+",
"1",
":",
"end_pos",
"-",
"1",
"]",
"else",
":",
"expression",
"=",
"lines",
"[",
"linenum",
"]",
"[",
"start_pos",
"+",
"1",
":",
"]",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
"+",
"1",
",",
"end_line",
")",
":",
"expression",
"+=",
"lines",
"[",
"i",
"]",
"expression",
"+=",
"last_line",
"[",
"0",
":",
"end_pos",
"-",
"1",
"]",
"# Parse expression so that we can take parentheses into account.",
"# This avoids false positives for inputs like \"CHECK((a < 4) == b)\",",
"# which is not replaceable by CHECK_LE.",
"lhs",
"=",
"''",
"rhs",
"=",
"''",
"operator",
"=",
"None",
"while",
"expression",
":",
"matched",
"=",
"Match",
"(",
"r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'",
"r'==|!=|>=|>|<=|<|\\()(.*)$'",
",",
"expression",
")",
"if",
"matched",
":",
"token",
"=",
"matched",
".",
"group",
"(",
"1",
")",
"if",
"token",
"==",
"'('",
":",
"# Parenthesized operand",
"expression",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"(",
"end",
",",
"_",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"expression",
",",
"0",
",",
"[",
"'('",
"]",
")",
"if",
"end",
"<",
"0",
":",
"return",
"# Unmatched parenthesis",
"lhs",
"+=",
"'('",
"+",
"expression",
"[",
"0",
":",
"end",
"]",
"expression",
"=",
"expression",
"[",
"end",
":",
"]",
"elif",
"token",
"in",
"(",
"'&&'",
",",
"'||'",
")",
":",
"# Logical and/or operators. This means the expression",
"# contains more than one term, for example:",
"# CHECK(42 < a && a < b);",
"#",
"# These are not replaceable with CHECK_LE, so bail out early.",
"return",
"elif",
"token",
"in",
"(",
"'<<'",
",",
"'<<='",
",",
"'>>'",
",",
"'>>='",
",",
"'->*'",
",",
"'->'",
")",
":",
"# Non-relational operator",
"lhs",
"+=",
"token",
"expression",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"else",
":",
"# Relational operator",
"operator",
"=",
"token",
"rhs",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"break",
"else",
":",
"# Unparenthesized operand. Instead of appending to lhs one character",
"# at a time, we do another regular expression match to consume several",
"# characters at once if possible. Trivial benchmark shows that this",
"# is more efficient when the operands are longer than a single",
"# character, which is generally the case.",
"matched",
"=",
"Match",
"(",
"r'^([^-=!<>()&|]+)(.*)$'",
",",
"expression",
")",
"if",
"not",
"matched",
":",
"matched",
"=",
"Match",
"(",
"r'^(\\s*\\S)(.*)$'",
",",
"expression",
")",
"if",
"not",
"matched",
":",
"break",
"lhs",
"+=",
"matched",
".",
"group",
"(",
"1",
")",
"expression",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"# Only apply checks if we got all parts of the boolean expression",
"if",
"not",
"(",
"lhs",
"and",
"operator",
"and",
"rhs",
")",
":",
"return",
"# Check that rhs do not contain logical operators. We already know",
"# that lhs is fine since the loop above parses out && and ||.",
"if",
"rhs",
".",
"find",
"(",
"'&&'",
")",
">",
"-",
"1",
"or",
"rhs",
".",
"find",
"(",
"'||'",
")",
">",
"-",
"1",
":",
"return",
"# At least one of the operands must be a constant literal. This is",
"# to avoid suggesting replacements for unprintable things like",
"# CHECK(variable != iterator)",
"#",
"# The following pattern matches decimal, hex integers, strings, and",
"# characters (in that order).",
"lhs",
"=",
"lhs",
".",
"strip",
"(",
")",
"rhs",
"=",
"rhs",
".",
"strip",
"(",
")",
"match_constant",
"=",
"r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'",
"if",
"Match",
"(",
"match_constant",
",",
"lhs",
")",
"or",
"Match",
"(",
"match_constant",
",",
"rhs",
")",
":",
"# Note: since we know both lhs and rhs, we can provide a more",
"# descriptive error message like:",
"# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)",
"# Instead of:",
"# Consider using CHECK_EQ instead of CHECK(a == b)",
"#",
"# We are still keeping the less descriptive message because if lhs",
"# or rhs gets long, the error message might become unreadable.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/check'",
",",
"2",
",",
"'Consider using %s instead of %s(a %s b)'",
"%",
"(",
"_CHECK_REPLACEMENT",
"[",
"check_macro",
"]",
"[",
"operator",
"]",
",",
"check_macro",
",",
"operator",
")",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/cmake/developer_package/cpplint/cpplint.py#L4365-L4480 | ||
facebookresearch/habitat-sim | 63b6c71d9ca8adaefb140b198196f5d0ca1f1e34 | examples/viewer.py | python | HabitatSimInteractiveViewer.mouse_scroll_event | (self, event: Application.MouseScrollEvent) | Handles `Application.MouseScrollEvent`. When in LOOK mode, enables camera
zooming (fine-grained zoom using shift) When in GRAB mode, adjusts the depth
of the grabber's object. (larger depth change rate using shift) | Handles `Application.MouseScrollEvent`. When in LOOK mode, enables camera
zooming (fine-grained zoom using shift) When in GRAB mode, adjusts the depth
of the grabber's object. (larger depth change rate using shift) | [
"Handles",
"Application",
".",
"MouseScrollEvent",
".",
"When",
"in",
"LOOK",
"mode",
"enables",
"camera",
"zooming",
"(",
"fine",
"-",
"grained",
"zoom",
"using",
"shift",
")",
"When",
"in",
"GRAB",
"mode",
"adjusts",
"the",
"depth",
"of",
"the",
"grabber",
"s",
"object",
".",
"(",
"larger",
"depth",
"change",
"rate",
"using",
"shift",
")"
] | def mouse_scroll_event(self, event: Application.MouseScrollEvent) -> None:
"""
Handles `Application.MouseScrollEvent`. When in LOOK mode, enables camera
zooming (fine-grained zoom using shift) When in GRAB mode, adjusts the depth
of the grabber's object. (larger depth change rate using shift)
"""
scroll_mod_val = (
event.offset.y
if abs(event.offset.y) > abs(event.offset.x)
else event.offset.x
)
if not scroll_mod_val:
return
# use shift to scale action response
shift_pressed = bool(event.modifiers & Application.InputEvent.Modifier.SHIFT)
alt_pressed = bool(event.modifiers & Application.InputEvent.Modifier.ALT)
ctrl_pressed = bool(event.modifiers & Application.InputEvent.Modifier.CTRL)
# if interactive mode is False -> LOOK MODE
if self.mouse_interaction == MouseMode.LOOK:
# use shift for fine-grained zooming
mod_val = 1.01 if shift_pressed else 1.1
mod = mod_val if scroll_mod_val > 0 else 1.0 / mod_val
cam = self.render_camera
cam.zoom(mod)
self.redraw()
elif self.mouse_interaction == MouseMode.GRAB and self.mouse_grabber:
# adjust the depth
mod_val = 0.1 if shift_pressed else 0.01
scroll_delta = scroll_mod_val * mod_val
if alt_pressed or ctrl_pressed:
# rotate the object's local constraint frame
agent_t = self.agent_body_node.transformation_matrix()
# ALT - yaw
rotation_axis = agent_t.transform_vector(mn.Vector3(0, 1, 0))
if alt_pressed and ctrl_pressed:
# ALT+CTRL - roll
rotation_axis = agent_t.transform_vector(mn.Vector3(0, 0, -1))
elif ctrl_pressed:
# CTRL - pitch
rotation_axis = agent_t.transform_vector(mn.Vector3(1, 0, 0))
self.mouse_grabber.rotate_local_frame_by_global_angle_axis(
rotation_axis, mn.Rad(scroll_delta)
)
else:
# update location of grabbed object
self.mouse_grabber.grip_depth += scroll_delta
self.update_grab_position(self.get_mouse_position(event.position))
self.redraw()
event.accepted = True | [
"def",
"mouse_scroll_event",
"(",
"self",
",",
"event",
":",
"Application",
".",
"MouseScrollEvent",
")",
"->",
"None",
":",
"scroll_mod_val",
"=",
"(",
"event",
".",
"offset",
".",
"y",
"if",
"abs",
"(",
"event",
".",
"offset",
".",
"y",
")",
">",
"abs",
"(",
"event",
".",
"offset",
".",
"x",
")",
"else",
"event",
".",
"offset",
".",
"x",
")",
"if",
"not",
"scroll_mod_val",
":",
"return",
"# use shift to scale action response",
"shift_pressed",
"=",
"bool",
"(",
"event",
".",
"modifiers",
"&",
"Application",
".",
"InputEvent",
".",
"Modifier",
".",
"SHIFT",
")",
"alt_pressed",
"=",
"bool",
"(",
"event",
".",
"modifiers",
"&",
"Application",
".",
"InputEvent",
".",
"Modifier",
".",
"ALT",
")",
"ctrl_pressed",
"=",
"bool",
"(",
"event",
".",
"modifiers",
"&",
"Application",
".",
"InputEvent",
".",
"Modifier",
".",
"CTRL",
")",
"# if interactive mode is False -> LOOK MODE",
"if",
"self",
".",
"mouse_interaction",
"==",
"MouseMode",
".",
"LOOK",
":",
"# use shift for fine-grained zooming",
"mod_val",
"=",
"1.01",
"if",
"shift_pressed",
"else",
"1.1",
"mod",
"=",
"mod_val",
"if",
"scroll_mod_val",
">",
"0",
"else",
"1.0",
"/",
"mod_val",
"cam",
"=",
"self",
".",
"render_camera",
"cam",
".",
"zoom",
"(",
"mod",
")",
"self",
".",
"redraw",
"(",
")",
"elif",
"self",
".",
"mouse_interaction",
"==",
"MouseMode",
".",
"GRAB",
"and",
"self",
".",
"mouse_grabber",
":",
"# adjust the depth",
"mod_val",
"=",
"0.1",
"if",
"shift_pressed",
"else",
"0.01",
"scroll_delta",
"=",
"scroll_mod_val",
"*",
"mod_val",
"if",
"alt_pressed",
"or",
"ctrl_pressed",
":",
"# rotate the object's local constraint frame",
"agent_t",
"=",
"self",
".",
"agent_body_node",
".",
"transformation_matrix",
"(",
")",
"# ALT - yaw",
"rotation_axis",
"=",
"agent_t",
".",
"transform_vector",
"(",
"mn",
".",
"Vector3",
"(",
"0",
",",
"1",
",",
"0",
")",
")",
"if",
"alt_pressed",
"and",
"ctrl_pressed",
":",
"# ALT+CTRL - roll",
"rotation_axis",
"=",
"agent_t",
".",
"transform_vector",
"(",
"mn",
".",
"Vector3",
"(",
"0",
",",
"0",
",",
"-",
"1",
")",
")",
"elif",
"ctrl_pressed",
":",
"# CTRL - pitch",
"rotation_axis",
"=",
"agent_t",
".",
"transform_vector",
"(",
"mn",
".",
"Vector3",
"(",
"1",
",",
"0",
",",
"0",
")",
")",
"self",
".",
"mouse_grabber",
".",
"rotate_local_frame_by_global_angle_axis",
"(",
"rotation_axis",
",",
"mn",
".",
"Rad",
"(",
"scroll_delta",
")",
")",
"else",
":",
"# update location of grabbed object",
"self",
".",
"mouse_grabber",
".",
"grip_depth",
"+=",
"scroll_delta",
"self",
".",
"update_grab_position",
"(",
"self",
".",
"get_mouse_position",
"(",
"event",
".",
"position",
")",
")",
"self",
".",
"redraw",
"(",
")",
"event",
".",
"accepted",
"=",
"True"
] | https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/examples/viewer.py#L528-L579 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py | python | ScrolledCanvas.reset | (self, canvwidth=None, canvheight=None, bg = None) | Adjust canvas and scrollbars according to given canvas size. | Adjust canvas and scrollbars according to given canvas size. | [
"Adjust",
"canvas",
"and",
"scrollbars",
"according",
"to",
"given",
"canvas",
"size",
"."
] | def reset(self, canvwidth=None, canvheight=None, bg = None):
"""Adjust canvas and scrollbars according to given canvas size."""
if canvwidth:
self.canvwidth = canvwidth
if canvheight:
self.canvheight = canvheight
if bg:
self.bg = bg
self._canvas.config(bg=bg,
scrollregion=(-self.canvwidth//2, -self.canvheight//2,
self.canvwidth//2, self.canvheight//2))
self._canvas.xview_moveto(0.5*(self.canvwidth - self.width + 30) /
self.canvwidth)
self._canvas.yview_moveto(0.5*(self.canvheight- self.height + 30) /
self.canvheight)
self.adjustScrolls() | [
"def",
"reset",
"(",
"self",
",",
"canvwidth",
"=",
"None",
",",
"canvheight",
"=",
"None",
",",
"bg",
"=",
"None",
")",
":",
"if",
"canvwidth",
":",
"self",
".",
"canvwidth",
"=",
"canvwidth",
"if",
"canvheight",
":",
"self",
".",
"canvheight",
"=",
"canvheight",
"if",
"bg",
":",
"self",
".",
"bg",
"=",
"bg",
"self",
".",
"_canvas",
".",
"config",
"(",
"bg",
"=",
"bg",
",",
"scrollregion",
"=",
"(",
"-",
"self",
".",
"canvwidth",
"//",
"2",
",",
"-",
"self",
".",
"canvheight",
"//",
"2",
",",
"self",
".",
"canvwidth",
"//",
"2",
",",
"self",
".",
"canvheight",
"//",
"2",
")",
")",
"self",
".",
"_canvas",
".",
"xview_moveto",
"(",
"0.5",
"*",
"(",
"self",
".",
"canvwidth",
"-",
"self",
".",
"width",
"+",
"30",
")",
"/",
"self",
".",
"canvwidth",
")",
"self",
".",
"_canvas",
".",
"yview_moveto",
"(",
"0.5",
"*",
"(",
"self",
".",
"canvheight",
"-",
"self",
".",
"height",
"+",
"30",
")",
"/",
"self",
".",
"canvheight",
")",
"self",
".",
"adjustScrolls",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py#L360-L375 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py | python | HTTPConnectionPool.close | (self) | Close all pooled connections and disable the pool. | Close all pooled connections and disable the pool. | [
"Close",
"all",
"pooled",
"connections",
"and",
"disable",
"the",
"pool",
"."
] | def close(self):
"""
Close all pooled connections and disable the pool.
"""
# Disable access to the pool
old_pool, self.pool = self.pool, None
try:
while True:
conn = old_pool.get(block=False)
if conn:
conn.close()
except Empty:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"# Disable access to the pool",
"old_pool",
",",
"self",
".",
"pool",
"=",
"self",
".",
"pool",
",",
"None",
"try",
":",
"while",
"True",
":",
"conn",
"=",
"old_pool",
".",
"get",
"(",
"block",
"=",
"False",
")",
"if",
"conn",
":",
"conn",
".",
"close",
"(",
")",
"except",
"Empty",
":",
"pass"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py#L386-L400 | ||
OpenXRay/xray-15 | 1390dfb08ed20997d7e8c95147ea8e8cb71f5e86 | cs/sdk/3d_sdk/maya/ver-8.5/devkit/plug-ins/scripted/polyModifier.py | python | polyModifierCmd._initModifierNode | (self, modifierNode) | Derived classes should override this method if they wish to initialize
input attributes on the modifierNode | Derived classes should override this method if they wish to initialize
input attributes on the modifierNode | [
"Derived",
"classes",
"should",
"override",
"this",
"method",
"if",
"they",
"wish",
"to",
"initialize",
"input",
"attributes",
"on",
"the",
"modifierNode"
] | def _initModifierNode(self, modifierNode):
"""
Derived classes should override this method if they wish to initialize
input attributes on the modifierNode
"""
pass | [
"def",
"_initModifierNode",
"(",
"self",
",",
"modifierNode",
")",
":",
"pass"
] | https://github.com/OpenXRay/xray-15/blob/1390dfb08ed20997d7e8c95147ea8e8cb71f5e86/cs/sdk/3d_sdk/maya/ver-8.5/devkit/plug-ins/scripted/polyModifier.py#L484-L489 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/datastore_hooks.py | python | IsUnalteredQueryPermitted | () | return _IsServicingPrivilegedRequest() | Checks if the current user is internal, or the request is privileged.
"Internal users" are users whose email address belongs to a certain
privileged domain; but some privileged requests, such as task queue tasks,
are also considered privileged.
Returns:
True for users with google.com emails and privileged requests. | Checks if the current user is internal, or the request is privileged. | [
"Checks",
"if",
"the",
"current",
"user",
"is",
"internal",
"or",
"the",
"request",
"is",
"privileged",
"."
] | def IsUnalteredQueryPermitted():
"""Checks if the current user is internal, or the request is privileged.
"Internal users" are users whose email address belongs to a certain
privileged domain; but some privileged requests, such as task queue tasks,
are also considered privileged.
Returns:
True for users with google.com emails and privileged requests.
"""
if utils.IsInternalUser():
return True
if users.is_current_user_admin():
# It's possible to be an admin with a non-internal account; For example,
# the default login for dev appserver instances is test@example.com.
return True
return _IsServicingPrivilegedRequest() | [
"def",
"IsUnalteredQueryPermitted",
"(",
")",
":",
"if",
"utils",
".",
"IsInternalUser",
"(",
")",
":",
"return",
"True",
"if",
"users",
".",
"is_current_user_admin",
"(",
")",
":",
"# It's possible to be an admin with a non-internal account; For example,",
"# the default login for dev appserver instances is test@example.com.",
"return",
"True",
"return",
"_IsServicingPrivilegedRequest",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/datastore_hooks.py#L101-L117 | |
google/mediapipe | e6c19885c6d3c6f410c730952aeed2852790d306 | mediapipe/examples/desktop/media_sequence/kinetics_dataset.py | python | Kinetics.generate_examples | (self, path_to_mediapipe_binary,
path_to_graph_directory,
only_generate_metadata=False,
splits_to_process="train,val,test",
video_path_format_string=None,
download_labels_for_map=True) | Downloads data and generates sharded TFRecords.
Downloads the data files, generates metadata, and processes the metadata
with MediaPipe to produce tf.SequenceExamples for training. The resulting
files can be read with as_dataset(). After running this function the
original data files can be deleted.
Args:
path_to_mediapipe_binary: Path to the compiled binary for the BUILD target
mediapipe/examples/desktop/demo:media_sequence_demo.
path_to_graph_directory: Path to the directory with MediaPipe graphs in
mediapipe/graphs/media_sequence/.
only_generate_metadata: If true, do not run mediapipe and write the
metadata to disk instead.
splits_to_process: csv string of which splits to process. Allows providing
a custom CSV with the CSV flag. The original data is still downloaded
to generate the label_map.
video_path_format_string: The format string for the path to local files.
download_labels_for_map: If true, download the annotations to create the
label map. | Downloads data and generates sharded TFRecords. | [
"Downloads",
"data",
"and",
"generates",
"sharded",
"TFRecords",
"."
] | def generate_examples(self, path_to_mediapipe_binary,
path_to_graph_directory,
only_generate_metadata=False,
splits_to_process="train,val,test",
video_path_format_string=None,
download_labels_for_map=True):
"""Downloads data and generates sharded TFRecords.
Downloads the data files, generates metadata, and processes the metadata
with MediaPipe to produce tf.SequenceExamples for training. The resulting
files can be read with as_dataset(). After running this function the
original data files can be deleted.
Args:
path_to_mediapipe_binary: Path to the compiled binary for the BUILD target
mediapipe/examples/desktop/demo:media_sequence_demo.
path_to_graph_directory: Path to the directory with MediaPipe graphs in
mediapipe/graphs/media_sequence/.
only_generate_metadata: If true, do not run mediapipe and write the
metadata to disk instead.
splits_to_process: csv string of which splits to process. Allows providing
a custom CSV with the CSV flag. The original data is still downloaded
to generate the label_map.
video_path_format_string: The format string for the path to local files.
download_labels_for_map: If true, download the annotations to create the
label map.
"""
if not path_to_mediapipe_binary:
raise ValueError(
"You must supply the path to the MediaPipe binary for "
"mediapipe/examples/desktop/demo:media_sequence_demo.")
if not path_to_graph_directory:
raise ValueError(
"You must supply the path to the directory with MediaPipe graphs in "
"mediapipe/graphs/media_sequence/.")
logging.info("Downloading data.")
download_output = self._download_data(download_labels_for_map)
for key in splits_to_process.split(","):
logging.info("Generating metadata for split: %s", key)
all_metadata = list(self._generate_metadata(
key, download_output, video_path_format_string))
logging.info("An example of the metadata: ")
logging.info(all_metadata[0])
random.seed(47)
random.shuffle(all_metadata)
shards = SPLITS[key]["shards"]
shard_names = [os.path.join(
self.path_to_data, FILEPATTERN % key + "-%05d-of-%05d" % (
i, shards)) for i in range(shards)]
writers = [tf.io.TFRecordWriter(shard_name) for shard_name in shard_names]
with _close_on_exit(writers) as writers:
for i, seq_ex in enumerate(all_metadata):
if not only_generate_metadata:
print("Processing example %d of %d (%d%%) \r" % (
i, len(all_metadata), i * 100 / len(all_metadata)), end="")
for graph in GRAPHS:
graph_path = os.path.join(path_to_graph_directory, graph)
seq_ex = self._run_mediapipe(
path_to_mediapipe_binary, seq_ex, graph_path)
writers[i % len(writers)].write(seq_ex.SerializeToString())
logging.info("Data extraction complete.") | [
"def",
"generate_examples",
"(",
"self",
",",
"path_to_mediapipe_binary",
",",
"path_to_graph_directory",
",",
"only_generate_metadata",
"=",
"False",
",",
"splits_to_process",
"=",
"\"train,val,test\"",
",",
"video_path_format_string",
"=",
"None",
",",
"download_labels_for_map",
"=",
"True",
")",
":",
"if",
"not",
"path_to_mediapipe_binary",
":",
"raise",
"ValueError",
"(",
"\"You must supply the path to the MediaPipe binary for \"",
"\"mediapipe/examples/desktop/demo:media_sequence_demo.\"",
")",
"if",
"not",
"path_to_graph_directory",
":",
"raise",
"ValueError",
"(",
"\"You must supply the path to the directory with MediaPipe graphs in \"",
"\"mediapipe/graphs/media_sequence/.\"",
")",
"logging",
".",
"info",
"(",
"\"Downloading data.\"",
")",
"download_output",
"=",
"self",
".",
"_download_data",
"(",
"download_labels_for_map",
")",
"for",
"key",
"in",
"splits_to_process",
".",
"split",
"(",
"\",\"",
")",
":",
"logging",
".",
"info",
"(",
"\"Generating metadata for split: %s\"",
",",
"key",
")",
"all_metadata",
"=",
"list",
"(",
"self",
".",
"_generate_metadata",
"(",
"key",
",",
"download_output",
",",
"video_path_format_string",
")",
")",
"logging",
".",
"info",
"(",
"\"An example of the metadata: \"",
")",
"logging",
".",
"info",
"(",
"all_metadata",
"[",
"0",
"]",
")",
"random",
".",
"seed",
"(",
"47",
")",
"random",
".",
"shuffle",
"(",
"all_metadata",
")",
"shards",
"=",
"SPLITS",
"[",
"key",
"]",
"[",
"\"shards\"",
"]",
"shard_names",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path_to_data",
",",
"FILEPATTERN",
"%",
"key",
"+",
"\"-%05d-of-%05d\"",
"%",
"(",
"i",
",",
"shards",
")",
")",
"for",
"i",
"in",
"range",
"(",
"shards",
")",
"]",
"writers",
"=",
"[",
"tf",
".",
"io",
".",
"TFRecordWriter",
"(",
"shard_name",
")",
"for",
"shard_name",
"in",
"shard_names",
"]",
"with",
"_close_on_exit",
"(",
"writers",
")",
"as",
"writers",
":",
"for",
"i",
",",
"seq_ex",
"in",
"enumerate",
"(",
"all_metadata",
")",
":",
"if",
"not",
"only_generate_metadata",
":",
"print",
"(",
"\"Processing example %d of %d (%d%%) \\r\"",
"%",
"(",
"i",
",",
"len",
"(",
"all_metadata",
")",
",",
"i",
"*",
"100",
"/",
"len",
"(",
"all_metadata",
")",
")",
",",
"end",
"=",
"\"\"",
")",
"for",
"graph",
"in",
"GRAPHS",
":",
"graph_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_to_graph_directory",
",",
"graph",
")",
"seq_ex",
"=",
"self",
".",
"_run_mediapipe",
"(",
"path_to_mediapipe_binary",
",",
"seq_ex",
",",
"graph_path",
")",
"writers",
"[",
"i",
"%",
"len",
"(",
"writers",
")",
"]",
".",
"write",
"(",
"seq_ex",
".",
"SerializeToString",
"(",
")",
")",
"logging",
".",
"info",
"(",
"\"Data extraction complete.\"",
")"
] | https://github.com/google/mediapipe/blob/e6c19885c6d3c6f410c730952aeed2852790d306/mediapipe/examples/desktop/media_sequence/kinetics_dataset.py#L224-L284 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/manifold/t_sne.py | python | _kl_divergence_error | (params, P, neighbors, degrees_of_freedom, n_samples,
n_components) | return kl_divergence | t-SNE objective function: the absolute error of the
KL divergence of p_ijs and q_ijs.
Parameters
----------
params : array, shape (n_params,)
Unraveled embedding.
P : array, shape (n_samples * (n_samples-1) / 2,)
Condensed joint probability matrix.
neighbors : array (n_samples, K)
The neighbors is not actually required to calculate the
divergence, but is here to match the signature of the
gradient function
degrees_of_freedom : float
Degrees of freedom of the Student's-t distribution.
n_samples : int
Number of samples.
n_components : int
Dimension of the embedded space.
Returns
-------
kl_divergence : float
Kullback-Leibler divergence of p_ij and q_ij.
grad : array, shape (n_params,)
Unraveled gradient of the Kullback-Leibler divergence with respect to
the embedding. | t-SNE objective function: the absolute error of the
KL divergence of p_ijs and q_ijs. | [
"t",
"-",
"SNE",
"objective",
"function",
":",
"the",
"absolute",
"error",
"of",
"the",
"KL",
"divergence",
"of",
"p_ijs",
"and",
"q_ijs",
"."
] | def _kl_divergence_error(params, P, neighbors, degrees_of_freedom, n_samples,
n_components):
"""t-SNE objective function: the absolute error of the
KL divergence of p_ijs and q_ijs.
Parameters
----------
params : array, shape (n_params,)
Unraveled embedding.
P : array, shape (n_samples * (n_samples-1) / 2,)
Condensed joint probability matrix.
neighbors : array (n_samples, K)
The neighbors is not actually required to calculate the
divergence, but is here to match the signature of the
gradient function
degrees_of_freedom : float
Degrees of freedom of the Student's-t distribution.
n_samples : int
Number of samples.
n_components : int
Dimension of the embedded space.
Returns
-------
kl_divergence : float
Kullback-Leibler divergence of p_ij and q_ij.
grad : array, shape (n_params,)
Unraveled gradient of the Kullback-Leibler divergence with respect to
the embedding.
"""
X_embedded = params.reshape(n_samples, n_components)
# Q is a heavy-tailed distribution: Student's t-distribution
n = pdist(X_embedded, "sqeuclidean")
n += 1.
n /= degrees_of_freedom
n **= (degrees_of_freedom + 1.0) / -2.0
Q = np.maximum(n / (2.0 * np.sum(n)), MACHINE_EPSILON)
# Optimization trick below: np.dot(x, y) is faster than
# np.sum(x * y) because it calls BLAS
# Objective: C (Kullback-Leibler divergence of P and Q)
if len(P.shape) == 2:
P = squareform(P)
kl_divergence = 2.0 * np.dot(P, np.log(P / Q))
return kl_divergence | [
"def",
"_kl_divergence_error",
"(",
"params",
",",
"P",
",",
"neighbors",
",",
"degrees_of_freedom",
",",
"n_samples",
",",
"n_components",
")",
":",
"X_embedded",
"=",
"params",
".",
"reshape",
"(",
"n_samples",
",",
"n_components",
")",
"# Q is a heavy-tailed distribution: Student's t-distribution",
"n",
"=",
"pdist",
"(",
"X_embedded",
",",
"\"sqeuclidean\"",
")",
"n",
"+=",
"1.",
"n",
"/=",
"degrees_of_freedom",
"n",
"**=",
"(",
"degrees_of_freedom",
"+",
"1.0",
")",
"/",
"-",
"2.0",
"Q",
"=",
"np",
".",
"maximum",
"(",
"n",
"/",
"(",
"2.0",
"*",
"np",
".",
"sum",
"(",
"n",
")",
")",
",",
"MACHINE_EPSILON",
")",
"# Optimization trick below: np.dot(x, y) is faster than",
"# np.sum(x * y) because it calls BLAS",
"# Objective: C (Kullback-Leibler divergence of P and Q)",
"if",
"len",
"(",
"P",
".",
"shape",
")",
"==",
"2",
":",
"P",
"=",
"squareform",
"(",
"P",
")",
"kl_divergence",
"=",
"2.0",
"*",
"np",
".",
"dot",
"(",
"P",
",",
"np",
".",
"log",
"(",
"P",
"/",
"Q",
")",
")",
"return",
"kl_divergence"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/manifold/t_sne.py#L168-L221 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py | python | MSVSSolution.Write | (self, writer=gyp.common.WriteOnDiff) | Writes the solution file to disk.
Raises:
IndexError: An entry appears multiple times. | Writes the solution file to disk. | [
"Writes",
"the",
"solution",
"file",
"to",
"disk",
"."
] | def Write(self, writer=gyp.common.WriteOnDiff):
"""Writes the solution file to disk.
Raises:
IndexError: An entry appears multiple times.
"""
# Walk the entry tree and collect all the folders and projects.
all_entries = set()
entries_to_check = self.entries[:]
while entries_to_check:
e = entries_to_check.pop(0)
# If this entry has been visited, nothing to do.
if e in all_entries:
continue
all_entries.add(e)
# If this is a folder, check its entries too.
if isinstance(e, MSVSFolder):
entries_to_check += e.entries
all_entries = sorted(all_entries)
# Open file and print header
f = writer(self.path)
f.write('Microsoft Visual Studio Solution File, '
'Format Version %s\r\n' % self.version.SolutionVersion())
f.write('# %s\r\n' % self.version.Description())
# Project entries
sln_root = os.path.split(self.path)[0]
for e in all_entries:
relative_path = gyp.common.RelativePath(e.path, sln_root)
# msbuild does not accept an empty folder_name.
# use '.' in case relative_path is empty.
folder_name = relative_path.replace('/', '\\') or '.'
f.write('Project("%s") = "%s", "%s", "%s"\r\n' % (
e.entry_type_guid, # Entry type GUID
e.name, # Folder name
folder_name, # Folder name (again)
e.get_guid(), # Entry GUID
))
# TODO(rspangler): Need a way to configure this stuff
if self.websiteProperties:
f.write('\tProjectSection(WebsiteProperties) = preProject\r\n'
'\t\tDebug.AspNetCompiler.Debug = "True"\r\n'
'\t\tRelease.AspNetCompiler.Debug = "False"\r\n'
'\tEndProjectSection\r\n')
if isinstance(e, MSVSFolder):
if e.items:
f.write('\tProjectSection(SolutionItems) = preProject\r\n')
for i in e.items:
f.write('\t\t%s = %s\r\n' % (i, i))
f.write('\tEndProjectSection\r\n')
if isinstance(e, MSVSProject):
if e.dependencies:
f.write('\tProjectSection(ProjectDependencies) = postProject\r\n')
for d in e.dependencies:
f.write('\t\t%s = %s\r\n' % (d.get_guid(), d.get_guid()))
f.write('\tEndProjectSection\r\n')
f.write('EndProject\r\n')
# Global section
f.write('Global\r\n')
# Configurations (variants)
f.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n')
for v in self.variants:
f.write('\t\t%s = %s\r\n' % (v, v))
f.write('\tEndGlobalSection\r\n')
# Sort config guids for easier diffing of solution changes.
config_guids = []
config_guids_overrides = {}
for e in all_entries:
if isinstance(e, MSVSProject):
config_guids.append(e.get_guid())
config_guids_overrides[e.get_guid()] = e.config_platform_overrides
config_guids.sort()
f.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n')
for g in config_guids:
for v in self.variants:
nv = config_guids_overrides[g].get(v, v)
# Pick which project configuration to build for this solution
# configuration.
f.write('\t\t%s.%s.ActiveCfg = %s\r\n' % (
g, # Project GUID
v, # Solution build configuration
nv, # Project build config for that solution config
))
# Enable project in this solution configuration.
f.write('\t\t%s.%s.Build.0 = %s\r\n' % (
g, # Project GUID
v, # Solution build configuration
nv, # Project build config for that solution config
))
f.write('\tEndGlobalSection\r\n')
# TODO(rspangler): Should be able to configure this stuff too (though I've
# never seen this be any different)
f.write('\tGlobalSection(SolutionProperties) = preSolution\r\n')
f.write('\t\tHideSolutionNode = FALSE\r\n')
f.write('\tEndGlobalSection\r\n')
# Folder mappings
# Omit this section if there are no folders
if any([e.entries for e in all_entries if isinstance(e, MSVSFolder)]):
f.write('\tGlobalSection(NestedProjects) = preSolution\r\n')
for e in all_entries:
if not isinstance(e, MSVSFolder):
continue # Does not apply to projects, only folders
for subentry in e.entries:
f.write('\t\t%s = %s\r\n' % (subentry.get_guid(), e.get_guid()))
f.write('\tEndGlobalSection\r\n')
f.write('EndGlobal\r\n')
f.close() | [
"def",
"Write",
"(",
"self",
",",
"writer",
"=",
"gyp",
".",
"common",
".",
"WriteOnDiff",
")",
":",
"# Walk the entry tree and collect all the folders and projects.",
"all_entries",
"=",
"set",
"(",
")",
"entries_to_check",
"=",
"self",
".",
"entries",
"[",
":",
"]",
"while",
"entries_to_check",
":",
"e",
"=",
"entries_to_check",
".",
"pop",
"(",
"0",
")",
"# If this entry has been visited, nothing to do.",
"if",
"e",
"in",
"all_entries",
":",
"continue",
"all_entries",
".",
"add",
"(",
"e",
")",
"# If this is a folder, check its entries too.",
"if",
"isinstance",
"(",
"e",
",",
"MSVSFolder",
")",
":",
"entries_to_check",
"+=",
"e",
".",
"entries",
"all_entries",
"=",
"sorted",
"(",
"all_entries",
")",
"# Open file and print header",
"f",
"=",
"writer",
"(",
"self",
".",
"path",
")",
"f",
".",
"write",
"(",
"'Microsoft Visual Studio Solution File, '",
"'Format Version %s\\r\\n'",
"%",
"self",
".",
"version",
".",
"SolutionVersion",
"(",
")",
")",
"f",
".",
"write",
"(",
"'# %s\\r\\n'",
"%",
"self",
".",
"version",
".",
"Description",
"(",
")",
")",
"# Project entries",
"sln_root",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"path",
")",
"[",
"0",
"]",
"for",
"e",
"in",
"all_entries",
":",
"relative_path",
"=",
"gyp",
".",
"common",
".",
"RelativePath",
"(",
"e",
".",
"path",
",",
"sln_root",
")",
"# msbuild does not accept an empty folder_name.",
"# use '.' in case relative_path is empty.",
"folder_name",
"=",
"relative_path",
".",
"replace",
"(",
"'/'",
",",
"'\\\\'",
")",
"or",
"'.'",
"f",
".",
"write",
"(",
"'Project(\"%s\") = \"%s\", \"%s\", \"%s\"\\r\\n'",
"%",
"(",
"e",
".",
"entry_type_guid",
",",
"# Entry type GUID",
"e",
".",
"name",
",",
"# Folder name",
"folder_name",
",",
"# Folder name (again)",
"e",
".",
"get_guid",
"(",
")",
",",
"# Entry GUID",
")",
")",
"# TODO(rspangler): Need a way to configure this stuff",
"if",
"self",
".",
"websiteProperties",
":",
"f",
".",
"write",
"(",
"'\\tProjectSection(WebsiteProperties) = preProject\\r\\n'",
"'\\t\\tDebug.AspNetCompiler.Debug = \"True\"\\r\\n'",
"'\\t\\tRelease.AspNetCompiler.Debug = \"False\"\\r\\n'",
"'\\tEndProjectSection\\r\\n'",
")",
"if",
"isinstance",
"(",
"e",
",",
"MSVSFolder",
")",
":",
"if",
"e",
".",
"items",
":",
"f",
".",
"write",
"(",
"'\\tProjectSection(SolutionItems) = preProject\\r\\n'",
")",
"for",
"i",
"in",
"e",
".",
"items",
":",
"f",
".",
"write",
"(",
"'\\t\\t%s = %s\\r\\n'",
"%",
"(",
"i",
",",
"i",
")",
")",
"f",
".",
"write",
"(",
"'\\tEndProjectSection\\r\\n'",
")",
"if",
"isinstance",
"(",
"e",
",",
"MSVSProject",
")",
":",
"if",
"e",
".",
"dependencies",
":",
"f",
".",
"write",
"(",
"'\\tProjectSection(ProjectDependencies) = postProject\\r\\n'",
")",
"for",
"d",
"in",
"e",
".",
"dependencies",
":",
"f",
".",
"write",
"(",
"'\\t\\t%s = %s\\r\\n'",
"%",
"(",
"d",
".",
"get_guid",
"(",
")",
",",
"d",
".",
"get_guid",
"(",
")",
")",
")",
"f",
".",
"write",
"(",
"'\\tEndProjectSection\\r\\n'",
")",
"f",
".",
"write",
"(",
"'EndProject\\r\\n'",
")",
"# Global section",
"f",
".",
"write",
"(",
"'Global\\r\\n'",
")",
"# Configurations (variants)",
"f",
".",
"write",
"(",
"'\\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\\r\\n'",
")",
"for",
"v",
"in",
"self",
".",
"variants",
":",
"f",
".",
"write",
"(",
"'\\t\\t%s = %s\\r\\n'",
"%",
"(",
"v",
",",
"v",
")",
")",
"f",
".",
"write",
"(",
"'\\tEndGlobalSection\\r\\n'",
")",
"# Sort config guids for easier diffing of solution changes.",
"config_guids",
"=",
"[",
"]",
"config_guids_overrides",
"=",
"{",
"}",
"for",
"e",
"in",
"all_entries",
":",
"if",
"isinstance",
"(",
"e",
",",
"MSVSProject",
")",
":",
"config_guids",
".",
"append",
"(",
"e",
".",
"get_guid",
"(",
")",
")",
"config_guids_overrides",
"[",
"e",
".",
"get_guid",
"(",
")",
"]",
"=",
"e",
".",
"config_platform_overrides",
"config_guids",
".",
"sort",
"(",
")",
"f",
".",
"write",
"(",
"'\\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\\r\\n'",
")",
"for",
"g",
"in",
"config_guids",
":",
"for",
"v",
"in",
"self",
".",
"variants",
":",
"nv",
"=",
"config_guids_overrides",
"[",
"g",
"]",
".",
"get",
"(",
"v",
",",
"v",
")",
"# Pick which project configuration to build for this solution",
"# configuration.",
"f",
".",
"write",
"(",
"'\\t\\t%s.%s.ActiveCfg = %s\\r\\n'",
"%",
"(",
"g",
",",
"# Project GUID",
"v",
",",
"# Solution build configuration",
"nv",
",",
"# Project build config for that solution config",
")",
")",
"# Enable project in this solution configuration.",
"f",
".",
"write",
"(",
"'\\t\\t%s.%s.Build.0 = %s\\r\\n'",
"%",
"(",
"g",
",",
"# Project GUID",
"v",
",",
"# Solution build configuration",
"nv",
",",
"# Project build config for that solution config",
")",
")",
"f",
".",
"write",
"(",
"'\\tEndGlobalSection\\r\\n'",
")",
"# TODO(rspangler): Should be able to configure this stuff too (though I've",
"# never seen this be any different)",
"f",
".",
"write",
"(",
"'\\tGlobalSection(SolutionProperties) = preSolution\\r\\n'",
")",
"f",
".",
"write",
"(",
"'\\t\\tHideSolutionNode = FALSE\\r\\n'",
")",
"f",
".",
"write",
"(",
"'\\tEndGlobalSection\\r\\n'",
")",
"# Folder mappings",
"# Omit this section if there are no folders",
"if",
"any",
"(",
"[",
"e",
".",
"entries",
"for",
"e",
"in",
"all_entries",
"if",
"isinstance",
"(",
"e",
",",
"MSVSFolder",
")",
"]",
")",
":",
"f",
".",
"write",
"(",
"'\\tGlobalSection(NestedProjects) = preSolution\\r\\n'",
")",
"for",
"e",
"in",
"all_entries",
":",
"if",
"not",
"isinstance",
"(",
"e",
",",
"MSVSFolder",
")",
":",
"continue",
"# Does not apply to projects, only folders",
"for",
"subentry",
"in",
"e",
".",
"entries",
":",
"f",
".",
"write",
"(",
"'\\t\\t%s = %s\\r\\n'",
"%",
"(",
"subentry",
".",
"get_guid",
"(",
")",
",",
"e",
".",
"get_guid",
"(",
")",
")",
")",
"f",
".",
"write",
"(",
"'\\tEndGlobalSection\\r\\n'",
")",
"f",
".",
"write",
"(",
"'EndGlobal\\r\\n'",
")",
"f",
".",
"close",
"(",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py#L214-L338 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributions/kl.py | python | _batch_trace_XXT | (bmat) | return flat_trace.reshape(bmat.shape[:-2]) | Utility function for calculating the trace of XX^{T} with X having arbitrary trailing batch dimensions | Utility function for calculating the trace of XX^{T} with X having arbitrary trailing batch dimensions | [
"Utility",
"function",
"for",
"calculating",
"the",
"trace",
"of",
"XX^",
"{",
"T",
"}",
"with",
"X",
"having",
"arbitrary",
"trailing",
"batch",
"dimensions"
] | def _batch_trace_XXT(bmat):
"""
Utility function for calculating the trace of XX^{T} with X having arbitrary trailing batch dimensions
"""
n = bmat.size(-1)
m = bmat.size(-2)
flat_trace = bmat.reshape(-1, m * n).pow(2).sum(-1)
return flat_trace.reshape(bmat.shape[:-2]) | [
"def",
"_batch_trace_XXT",
"(",
"bmat",
")",
":",
"n",
"=",
"bmat",
".",
"size",
"(",
"-",
"1",
")",
"m",
"=",
"bmat",
".",
"size",
"(",
"-",
"2",
")",
"flat_trace",
"=",
"bmat",
".",
"reshape",
"(",
"-",
"1",
",",
"m",
"*",
"n",
")",
".",
"pow",
"(",
"2",
")",
".",
"sum",
"(",
"-",
"1",
")",
"return",
"flat_trace",
".",
"reshape",
"(",
"bmat",
".",
"shape",
"[",
":",
"-",
"2",
"]",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributions/kl.py#L134-L141 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/docs/tools/dump_ast_matchers.py | python | act_on_decl | (declaration, comment, allowed_types) | Parse the matcher out of the given declaration and comment.
If 'allowed_types' is set, it contains a list of node types the matcher
can match on, as extracted from the static type asserts in the matcher
definition. | Parse the matcher out of the given declaration and comment. | [
"Parse",
"the",
"matcher",
"out",
"of",
"the",
"given",
"declaration",
"and",
"comment",
"."
] | def act_on_decl(declaration, comment, allowed_types):
"""Parse the matcher out of the given declaration and comment.
If 'allowed_types' is set, it contains a list of node types the matcher
can match on, as extracted from the static type asserts in the matcher
definition.
"""
if declaration.strip():
# Node matchers are defined by writing:
# VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;
m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*<
\s*([^\s,]+)\s*(?:,
\s*([^\s>]+)\s*)?>
\s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
if m:
result, inner, name = m.groups()
if not inner:
inner = result
add_matcher(result, name, 'Matcher<%s>...' % inner,
comment, is_dyncast=True)
return
# Special case of type matchers:
# AstTypeMatcher<ArgumentType> name
m = re.match(r""".*AstTypeMatcher\s*<
\s*([^\s>]+)\s*>
\s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
if m:
inner, name = m.groups()
add_matcher('Type', name, 'Matcher<%s>...' % inner,
comment, is_dyncast=True)
# FIXME: re-enable once we have implemented casting on the TypeLoc
# hierarchy.
# add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,
# comment, is_dyncast=True)
return
# Parse the various matcher definition macros.
m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER(?:_DECL)?\(
\s*([^\s,]+\s*),
\s*(?:[^\s,]+\s*),
\s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
\)\s*;\s*$""", declaration, flags=re.X)
if m:
loc, name, results = m.groups()[0:3]
result_types = [r.strip() for r in results.split(',')]
comment_result_types = extract_result_types(comment)
if (comment_result_types and
sorted(result_types) != sorted(comment_result_types)):
raise Exception('Inconsistent documentation for: %s' % name)
for result_type in result_types:
add_matcher(result_type, name, 'Matcher<Type>', comment)
# if loc:
# add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>',
# comment)
return
m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
\s*([^\s,]+)\s*,
\s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*\d+\s*)?
\)\s*{\s*$""", declaration, flags=re.X)
if m:
p, n, name, results = m.groups()[0:4]
args = m.groups()[4:]
result_types = [r.strip() for r in results.split(',')]
if allowed_types and allowed_types != result_types:
raise Exception('Inconsistent documentation for: %s' % name)
if n not in ['', '2']:
raise Exception('Cannot parse "%s"' % declaration)
args = ', '.join('%s %s' % (args[i], args[i+1])
for i in range(0, len(args), 2) if args[i])
for result_type in result_types:
add_matcher(result_type, name, args, comment)
return
m = re.match(r"""^\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\(
(?:\s*([^\s,]+)\s*,)?
\s*([^\s,]+)\s*
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*\d+\s*)?
\)\s*{\s*$""", declaration, flags=re.X)
if m:
p, n, result, name = m.groups()[0:4]
args = m.groups()[4:]
if n not in ['', '2']:
raise Exception('Cannot parse "%s"' % declaration)
args = ', '.join('%s %s' % (args[i], args[i+1])
for i in range(0, len(args), 2) if args[i])
add_matcher(result, name, args, comment)
return
m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
(?:\s*([^\s,]+)\s*,)?
\s*([^\s,]+)\s*
(?:,\s*([^,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*\d+\s*)?
\)\s*{""", declaration, flags=re.X)
if m:
p, n, result, name = m.groups()[0:4]
args = m.groups()[4:]
if not result:
if not allowed_types:
raise Exception('Did not find allowed result types for: %s' % name)
result_types = allowed_types
else:
result_types = [result]
if n not in ['', '2']:
raise Exception('Cannot parse "%s"' % declaration)
args = ', '.join('%s %s' % (args[i], args[i+1])
for i in range(0, len(args), 2) if args[i])
for result_type in result_types:
add_matcher(result_type, name, args, comment)
return
# Parse ArgumentAdapting matchers.
m = re.match(
r"""^.*ArgumentAdaptingMatcherFunc<.*>\s*
([a-zA-Z]*);$""",
declaration, flags=re.X)
if m:
name = m.groups()[0]
add_matcher('*', name, 'Matcher<*>', comment)
return
# Parse Variadic functions.
m = re.match(
r"""^.*internal::VariadicFunction\s*<\s*([^,]+),\s*([^,]+),\s*[^>]+>\s*
([a-zA-Z]*);$""",
declaration, flags=re.X)
if m:
result, arg, name = m.groups()[:3]
add_matcher(result, name, '%s, ..., %s' % (arg, arg), comment)
return
# Parse Variadic operator matchers.
m = re.match(
r"""^.*VariadicOperatorMatcherFunc\s*<\s*([^,]+),\s*([^\s]+)\s*>\s*
([a-zA-Z]*);$""",
declaration, flags=re.X)
if m:
min_args, max_args, name = m.groups()[:3]
if max_args == '1':
add_matcher('*', name, 'Matcher<*>', comment)
return
elif max_args == 'std::numeric_limits<unsigned>::max()':
add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment)
return
# Parse free standing matcher functions, like:
# Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {
m = re.match(r"""^\s*(.*)\s+
([^\s\(]+)\s*\(
(.*)
\)\s*{""", declaration, re.X)
if m:
result, name, args = m.groups()
args = ', '.join(p.strip() for p in args.split(','))
m = re.match(r'.*\s+internal::(Bindable)?Matcher<([^>]+)>$', result)
if m:
result_types = [m.group(2)]
else:
result_types = extract_result_types(comment)
if not result_types:
if not comment:
# Only overloads don't have their own doxygen comments; ignore those.
print('Ignoring "%s"' % name)
else:
print('Cannot determine result type for "%s"' % name)
else:
for result_type in result_types:
add_matcher(result_type, name, args, comment)
else:
print('*** Unparsable: "' + declaration + '" ***') | [
"def",
"act_on_decl",
"(",
"declaration",
",",
"comment",
",",
"allowed_types",
")",
":",
"if",
"declaration",
".",
"strip",
"(",
")",
":",
"# Node matchers are defined by writing:",
"# VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\".*Variadic(?:DynCast)?AllOfMatcher\\s*<\n \\s*([^\\s,]+)\\s*(?:,\n \\s*([^\\s>]+)\\s*)?>\n \\s*([^\\s;]+)\\s*;\\s*$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"result",
",",
"inner",
",",
"name",
"=",
"m",
".",
"groups",
"(",
")",
"if",
"not",
"inner",
":",
"inner",
"=",
"result",
"add_matcher",
"(",
"result",
",",
"name",
",",
"'Matcher<%s>...'",
"%",
"inner",
",",
"comment",
",",
"is_dyncast",
"=",
"True",
")",
"return",
"# Special case of type matchers:",
"# AstTypeMatcher<ArgumentType> name",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\".*AstTypeMatcher\\s*<\n \\s*([^\\s>]+)\\s*>\n \\s*([^\\s;]+)\\s*;\\s*$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"inner",
",",
"name",
"=",
"m",
".",
"groups",
"(",
")",
"add_matcher",
"(",
"'Type'",
",",
"name",
",",
"'Matcher<%s>...'",
"%",
"inner",
",",
"comment",
",",
"is_dyncast",
"=",
"True",
")",
"# FIXME: re-enable once we have implemented casting on the TypeLoc",
"# hierarchy.",
"# add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,",
"# comment, is_dyncast=True)",
"return",
"# Parse the various matcher definition macros.",
"m",
"=",
"re",
".",
"match",
"(",
"\"\"\".*AST_TYPE(LOC)?_TRAVERSE_MATCHER(?:_DECL)?\\(\n \\s*([^\\s,]+\\s*),\n \\s*(?:[^\\s,]+\\s*),\n \\s*AST_POLYMORPHIC_SUPPORTED_TYPES\\(([^)]*)\\)\n \\)\\s*;\\s*$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"loc",
",",
"name",
",",
"results",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
":",
"3",
"]",
"result_types",
"=",
"[",
"r",
".",
"strip",
"(",
")",
"for",
"r",
"in",
"results",
".",
"split",
"(",
"','",
")",
"]",
"comment_result_types",
"=",
"extract_result_types",
"(",
"comment",
")",
"if",
"(",
"comment_result_types",
"and",
"sorted",
"(",
"result_types",
")",
"!=",
"sorted",
"(",
"comment_result_types",
")",
")",
":",
"raise",
"Exception",
"(",
"'Inconsistent documentation for: %s'",
"%",
"name",
")",
"for",
"result_type",
"in",
"result_types",
":",
"add_matcher",
"(",
"result_type",
",",
"name",
",",
"'Matcher<Type>'",
",",
"comment",
")",
"# if loc:",
"# add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>',",
"# comment)",
"return",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\"^\\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\\(\n \\s*([^\\s,]+)\\s*,\n \\s*AST_POLYMORPHIC_SUPPORTED_TYPES\\(([^)]*)\\)\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*\\d+\\s*)?\n \\)\\s*{\\s*$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"p",
",",
"n",
",",
"name",
",",
"results",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
":",
"4",
"]",
"args",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"4",
":",
"]",
"result_types",
"=",
"[",
"r",
".",
"strip",
"(",
")",
"for",
"r",
"in",
"results",
".",
"split",
"(",
"','",
")",
"]",
"if",
"allowed_types",
"and",
"allowed_types",
"!=",
"result_types",
":",
"raise",
"Exception",
"(",
"'Inconsistent documentation for: %s'",
"%",
"name",
")",
"if",
"n",
"not",
"in",
"[",
"''",
",",
"'2'",
"]",
":",
"raise",
"Exception",
"(",
"'Cannot parse \"%s\"'",
"%",
"declaration",
")",
"args",
"=",
"', '",
".",
"join",
"(",
"'%s %s'",
"%",
"(",
"args",
"[",
"i",
"]",
",",
"args",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"args",
")",
",",
"2",
")",
"if",
"args",
"[",
"i",
"]",
")",
"for",
"result_type",
"in",
"result_types",
":",
"add_matcher",
"(",
"result_type",
",",
"name",
",",
"args",
",",
"comment",
")",
"return",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\"^\\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\\(\n (?:\\s*([^\\s,]+)\\s*,)?\n \\s*([^\\s,]+)\\s*\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*\\d+\\s*)?\n \\)\\s*{\\s*$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"p",
",",
"n",
",",
"result",
",",
"name",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
":",
"4",
"]",
"args",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"4",
":",
"]",
"if",
"n",
"not",
"in",
"[",
"''",
",",
"'2'",
"]",
":",
"raise",
"Exception",
"(",
"'Cannot parse \"%s\"'",
"%",
"declaration",
")",
"args",
"=",
"', '",
".",
"join",
"(",
"'%s %s'",
"%",
"(",
"args",
"[",
"i",
"]",
",",
"args",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"args",
")",
",",
"2",
")",
"if",
"args",
"[",
"i",
"]",
")",
"add_matcher",
"(",
"result",
",",
"name",
",",
"args",
",",
"comment",
")",
"return",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\"^\\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\\(\n (?:\\s*([^\\s,]+)\\s*,)?\n \\s*([^\\s,]+)\\s*\n (?:,\\s*([^,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*([^\\s,]+)\\s*\n ,\\s*([^\\s,]+)\\s*)?\n (?:,\\s*\\d+\\s*)?\n \\)\\s*{\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"p",
",",
"n",
",",
"result",
",",
"name",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
":",
"4",
"]",
"args",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"4",
":",
"]",
"if",
"not",
"result",
":",
"if",
"not",
"allowed_types",
":",
"raise",
"Exception",
"(",
"'Did not find allowed result types for: %s'",
"%",
"name",
")",
"result_types",
"=",
"allowed_types",
"else",
":",
"result_types",
"=",
"[",
"result",
"]",
"if",
"n",
"not",
"in",
"[",
"''",
",",
"'2'",
"]",
":",
"raise",
"Exception",
"(",
"'Cannot parse \"%s\"'",
"%",
"declaration",
")",
"args",
"=",
"', '",
".",
"join",
"(",
"'%s %s'",
"%",
"(",
"args",
"[",
"i",
"]",
",",
"args",
"[",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"args",
")",
",",
"2",
")",
"if",
"args",
"[",
"i",
"]",
")",
"for",
"result_type",
"in",
"result_types",
":",
"add_matcher",
"(",
"result_type",
",",
"name",
",",
"args",
",",
"comment",
")",
"return",
"# Parse ArgumentAdapting matchers.",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\"^.*ArgumentAdaptingMatcherFunc<.*>\\s*\n ([a-zA-Z]*);$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"name",
"=",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"add_matcher",
"(",
"'*'",
",",
"name",
",",
"'Matcher<*>'",
",",
"comment",
")",
"return",
"# Parse Variadic functions.",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\"^.*internal::VariadicFunction\\s*<\\s*([^,]+),\\s*([^,]+),\\s*[^>]+>\\s*\n ([a-zA-Z]*);$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"result",
",",
"arg",
",",
"name",
"=",
"m",
".",
"groups",
"(",
")",
"[",
":",
"3",
"]",
"add_matcher",
"(",
"result",
",",
"name",
",",
"'%s, ..., %s'",
"%",
"(",
"arg",
",",
"arg",
")",
",",
"comment",
")",
"return",
"# Parse Variadic operator matchers.",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\"^.*VariadicOperatorMatcherFunc\\s*<\\s*([^,]+),\\s*([^\\s]+)\\s*>\\s*\n ([a-zA-Z]*);$\"\"\"",
",",
"declaration",
",",
"flags",
"=",
"re",
".",
"X",
")",
"if",
"m",
":",
"min_args",
",",
"max_args",
",",
"name",
"=",
"m",
".",
"groups",
"(",
")",
"[",
":",
"3",
"]",
"if",
"max_args",
"==",
"'1'",
":",
"add_matcher",
"(",
"'*'",
",",
"name",
",",
"'Matcher<*>'",
",",
"comment",
")",
"return",
"elif",
"max_args",
"==",
"'std::numeric_limits<unsigned>::max()'",
":",
"add_matcher",
"(",
"'*'",
",",
"name",
",",
"'Matcher<*>, ..., Matcher<*>'",
",",
"comment",
")",
"return",
"# Parse free standing matcher functions, like:",
"# Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\"\"^\\s*(.*)\\s+\n ([^\\s\\(]+)\\s*\\(\n (.*)\n \\)\\s*{\"\"\"",
",",
"declaration",
",",
"re",
".",
"X",
")",
"if",
"m",
":",
"result",
",",
"name",
",",
"args",
"=",
"m",
".",
"groups",
"(",
")",
"args",
"=",
"', '",
".",
"join",
"(",
"p",
".",
"strip",
"(",
")",
"for",
"p",
"in",
"args",
".",
"split",
"(",
"','",
")",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r'.*\\s+internal::(Bindable)?Matcher<([^>]+)>$'",
",",
"result",
")",
"if",
"m",
":",
"result_types",
"=",
"[",
"m",
".",
"group",
"(",
"2",
")",
"]",
"else",
":",
"result_types",
"=",
"extract_result_types",
"(",
"comment",
")",
"if",
"not",
"result_types",
":",
"if",
"not",
"comment",
":",
"# Only overloads don't have their own doxygen comments; ignore those.",
"print",
"(",
"'Ignoring \"%s\"'",
"%",
"name",
")",
"else",
":",
"print",
"(",
"'Cannot determine result type for \"%s\"'",
"%",
"name",
")",
"else",
":",
"for",
"result_type",
"in",
"result_types",
":",
"add_matcher",
"(",
"result_type",
",",
"name",
",",
"args",
",",
"comment",
")",
"else",
":",
"print",
"(",
"'*** Unparsable: \"'",
"+",
"declaration",
"+",
"'\" ***'",
")"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/docs/tools/dump_ast_matchers.py#L134-L320 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/date_converters.py | python | parse_date_fields | (year_col, month_col, day_col) | return parsing.try_parse_year_month_day(year_col, month_col, day_col) | Parse columns with years, months and days into a single date column.
.. deprecated:: 1.2 | Parse columns with years, months and days into a single date column. | [
"Parse",
"columns",
"with",
"years",
"months",
"and",
"days",
"into",
"a",
"single",
"date",
"column",
"."
] | def parse_date_fields(year_col, month_col, day_col):
"""
Parse columns with years, months and days into a single date column.
.. deprecated:: 1.2
"""
warnings.warn(
"""
Use pd.to_datetime({"year": year_col, "month": month_col, "day": day_col}) instead to get a Pandas Series.
Use ser = pd.to_datetime({"year": year_col, "month": month_col, "day": day_col}) and
np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array.
""", # noqa: E501
FutureWarning,
stacklevel=2,
)
year_col = _maybe_cast(year_col)
month_col = _maybe_cast(month_col)
day_col = _maybe_cast(day_col)
return parsing.try_parse_year_month_day(year_col, month_col, day_col) | [
"def",
"parse_date_fields",
"(",
"year_col",
",",
"month_col",
",",
"day_col",
")",
":",
"warnings",
".",
"warn",
"(",
"\"\"\"\n Use pd.to_datetime({\"year\": year_col, \"month\": month_col, \"day\": day_col}) instead to get a Pandas Series.\n Use ser = pd.to_datetime({\"year\": year_col, \"month\": month_col, \"day\": day_col}) and\n np.array([s.to_pydatetime() for s in ser]) instead to get a Numpy array.\n\"\"\"",
",",
"# noqa: E501",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"year_col",
"=",
"_maybe_cast",
"(",
"year_col",
")",
"month_col",
"=",
"_maybe_cast",
"(",
"month_col",
")",
"day_col",
"=",
"_maybe_cast",
"(",
"day_col",
")",
"return",
"parsing",
".",
"try_parse_year_month_day",
"(",
"year_col",
",",
"month_col",
",",
"day_col",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/date_converters.py#L28-L47 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/common.py | python | is_interval_dtype | (arr_or_dtype) | return IntervalDtype.is_dtype(arr_or_dtype) | Check whether an array-like or dtype is of the Interval dtype.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype to check.
Returns
-------
boolean
Whether or not the array-like or dtype is of the Interval dtype.
Examples
--------
>>> is_interval_dtype(object)
False
>>> is_interval_dtype(IntervalDtype())
True
>>> is_interval_dtype([1, 2, 3])
False
>>>
>>> interval = pd.Interval(1, 2, closed="right")
>>> is_interval_dtype(interval)
False
>>> is_interval_dtype(pd.IntervalIndex([interval]))
True | Check whether an array-like or dtype is of the Interval dtype. | [
"Check",
"whether",
"an",
"array",
"-",
"like",
"or",
"dtype",
"is",
"of",
"the",
"Interval",
"dtype",
"."
] | def is_interval_dtype(arr_or_dtype) -> bool:
"""
Check whether an array-like or dtype is of the Interval dtype.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype to check.
Returns
-------
boolean
Whether or not the array-like or dtype is of the Interval dtype.
Examples
--------
>>> is_interval_dtype(object)
False
>>> is_interval_dtype(IntervalDtype())
True
>>> is_interval_dtype([1, 2, 3])
False
>>>
>>> interval = pd.Interval(1, 2, closed="right")
>>> is_interval_dtype(interval)
False
>>> is_interval_dtype(pd.IntervalIndex([interval]))
True
"""
# TODO: Consider making Interval an instance of IntervalDtype
if arr_or_dtype is None:
return False
return IntervalDtype.is_dtype(arr_or_dtype) | [
"def",
"is_interval_dtype",
"(",
"arr_or_dtype",
")",
"->",
"bool",
":",
"# TODO: Consider making Interval an instance of IntervalDtype",
"if",
"arr_or_dtype",
"is",
"None",
":",
"return",
"False",
"return",
"IntervalDtype",
".",
"is_dtype",
"(",
"arr_or_dtype",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/common.py#L506-L539 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | CheckForBadCharacters | (filename, lines, error) | Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
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 for each line containing bad characters. | [
"Logs",
"an",
"error",
"for",
"each",
"line",
"containing",
"bad",
"characters",
"."
] | def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
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.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') | [
"def",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"for",
"linenum",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"u'\\ufffd'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/utf8'",
",",
"5",
",",
"'Line contains invalid UTF-8 (or Unicode replacement character).'",
")",
"if",
"'\\0'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/nul'",
",",
"5",
",",
"'Line contains NUL byte.'",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L2008-L2030 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits_classes.py | python | find_copy_constructor | (type_) | return None | Returns reference to copy constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the copy constructor | Returns reference to copy constructor. | [
"Returns",
"reference",
"to",
"copy",
"constructor",
"."
] | def find_copy_constructor(type_):
"""
Returns reference to copy constructor.
Args:
type_ (declarations.class_t): the class to be searched.
Returns:
declarations.constructor_t: the copy constructor
"""
copy_ = type_.constructors(
lambda x: is_copy_constructor(x),
recursive=False,
allow_empty=True)
if copy_:
return copy_[0]
return None | [
"def",
"find_copy_constructor",
"(",
"type_",
")",
":",
"copy_",
"=",
"type_",
".",
"constructors",
"(",
"lambda",
"x",
":",
"is_copy_constructor",
"(",
"x",
")",
",",
"recursive",
"=",
"False",
",",
"allow_empty",
"=",
"True",
")",
"if",
"copy_",
":",
"return",
"copy_",
"[",
"0",
"]",
"return",
"None"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits_classes.py#L134-L152 | |
ap--/python-seabreeze | 86e9145edf7a30cedd4dffd4658a142aeab2d2fc | setup.py | python | strtobool | (val: str) | distutils.util.strtobool(val)
Convert a string representation of truth to true (1) or false (0).
True values are y, yes, t, true, on and 1;
false values are n, no, f, false, off and 0.
Raises ValueError if val is anything else. | distutils.util.strtobool(val)
Convert a string representation of truth to true (1) or false (0). | [
"distutils",
".",
"util",
".",
"strtobool",
"(",
"val",
")",
"Convert",
"a",
"string",
"representation",
"of",
"truth",
"to",
"true",
"(",
"1",
")",
"or",
"false",
"(",
"0",
")",
"."
] | def strtobool(val: str) -> int:
"""distutils.util.strtobool(val)
Convert a string representation of truth to true (1) or false (0).
True values are y, yes, t, true, on and 1;
false values are n, no, f, false, off and 0.
Raises ValueError if val is anything else.
"""
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return 1
elif val in ("n", "no", "f", "false", "off", "0"):
return 0
else:
raise ValueError(f"invalid truth value {val!r}") | [
"def",
"strtobool",
"(",
"val",
":",
"str",
")",
"->",
"int",
":",
"val",
"=",
"val",
".",
"lower",
"(",
")",
"if",
"val",
"in",
"(",
"\"y\"",
",",
"\"yes\"",
",",
"\"t\"",
",",
"\"true\"",
",",
"\"on\"",
",",
"\"1\"",
")",
":",
"return",
"1",
"elif",
"val",
"in",
"(",
"\"n\"",
",",
"\"no\"",
",",
"\"f\"",
",",
"\"false\"",
",",
"\"off\"",
",",
"\"0\"",
")",
":",
"return",
"0",
"else",
":",
"raise",
"ValueError",
"(",
"f\"invalid truth value {val!r}\"",
")"
] | https://github.com/ap--/python-seabreeze/blob/86e9145edf7a30cedd4dffd4658a142aeab2d2fc/setup.py#L29-L43 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/frame.py | python | DataFrame.reorder_levels | (self, order, axis=0) | return result | Rearrange index levels using input order. May not drop or duplicate levels.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
axis : int
Where to reorder levels.
Returns
-------
DataFrame | Rearrange index levels using input order. May not drop or duplicate levels. | [
"Rearrange",
"index",
"levels",
"using",
"input",
"order",
".",
"May",
"not",
"drop",
"or",
"duplicate",
"levels",
"."
] | def reorder_levels(self, order, axis=0) -> "DataFrame":
"""
Rearrange index levels using input order. May not drop or duplicate levels.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
axis : int
Where to reorder levels.
Returns
-------
DataFrame
"""
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis), ABCMultiIndex): # pragma: no cover
raise TypeError("Can only reorder levels on a hierarchical axis.")
result = self.copy()
if axis == 0:
result.index = result.index.reorder_levels(order)
else:
result.columns = result.columns.reorder_levels(order)
return result | [
"def",
"reorder_levels",
"(",
"self",
",",
"order",
",",
"axis",
"=",
"0",
")",
"->",
"\"DataFrame\"",
":",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_get_axis",
"(",
"axis",
")",
",",
"ABCMultiIndex",
")",
":",
"# pragma: no cover",
"raise",
"TypeError",
"(",
"\"Can only reorder levels on a hierarchical axis.\"",
")",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"axis",
"==",
"0",
":",
"result",
".",
"index",
"=",
"result",
".",
"index",
".",
"reorder_levels",
"(",
"order",
")",
"else",
":",
"result",
".",
"columns",
"=",
"result",
".",
"columns",
".",
"reorder_levels",
"(",
"order",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/frame.py#L5250-L5276 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewEvent.GetDataObject | (*args, **kwargs) | return _dataview.DataViewEvent_GetDataObject(*args, **kwargs) | GetDataObject(self) -> wxDataObject | GetDataObject(self) -> wxDataObject | [
"GetDataObject",
"(",
"self",
")",
"-",
">",
"wxDataObject"
] | def GetDataObject(*args, **kwargs):
"""GetDataObject(self) -> wxDataObject"""
return _dataview.DataViewEvent_GetDataObject(*args, **kwargs) | [
"def",
"GetDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewEvent_GetDataObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L1972-L1974 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py | python | zfill | (x, width) | return sign + '0'*(width-n) + s | zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated. | zfill(x, width) -> string | [
"zfill",
"(",
"x",
"width",
")",
"-",
">",
"string"
] | def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if type(x) == type(''): s = x
else: s = repr(x)
n = len(s)
if n >= width: return s
sign = ''
if s[0] in ('-', '+'):
sign, s = s[0], s[1:]
return sign + '0'*(width-n) + s | [
"def",
"zfill",
"(",
"x",
",",
"width",
")",
":",
"if",
"type",
"(",
"x",
")",
"==",
"type",
"(",
"''",
")",
":",
"s",
"=",
"x",
"else",
":",
"s",
"=",
"repr",
"(",
"x",
")",
"n",
"=",
"len",
"(",
"s",
")",
"if",
"n",
">=",
"width",
":",
"return",
"s",
"sign",
"=",
"''",
"if",
"s",
"[",
"0",
"]",
"in",
"(",
"'-'",
",",
"'+'",
")",
":",
"sign",
",",
"s",
"=",
"s",
"[",
"0",
"]",
",",
"s",
"[",
"1",
":",
"]",
"return",
"sign",
"+",
"'0'",
"*",
"(",
"width",
"-",
"n",
")",
"+",
"s"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py#L310-L324 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Grid.grid_forget | (self) | Unmap this widget. | Unmap this widget. | [
"Unmap",
"this",
"widget",
"."
] | def grid_forget(self):
"""Unmap this widget."""
self.tk.call('grid', 'forget', self._w) | [
"def",
"grid_forget",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'grid'",
",",
"'forget'",
",",
"self",
".",
"_w",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1967-L1969 | ||
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | armoryengine/PyBtcAddress.py | python | PyBtcAddress.getChainCode | (self) | return self.chaincode | Return the chain code of the address. | Return the chain code of the address. | [
"Return",
"the",
"chain",
"code",
"of",
"the",
"address",
"."
] | def getChainCode(self):
'''Return the chain code of the address.'''
if len(self.chaincode) != 32:
raise KeyDataError, 'PyBtcAddress does not have a chain code!'
return self.chaincode | [
"def",
"getChainCode",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"chaincode",
")",
"!=",
"32",
":",
"raise",
"KeyDataError",
",",
"'PyBtcAddress does not have a chain code!'",
"return",
"self",
".",
"chaincode"
] | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/PyBtcAddress.py#L152-L156 | |
wangkuiyi/mapreduce-lite | 1bb92fe094dc47480ef9163c34070a3199feead6 | src/mapreduce_lite/scheduler/worker.py | python | Communicator.sigterm_handler | (self, signum, frame) | Quit when got SIGTERM signal from scheduler | Quit when got SIGTERM signal from scheduler | [
"Quit",
"when",
"got",
"SIGTERM",
"signal",
"from",
"scheduler"
] | def sigterm_handler(self, signum, frame):
""" Quit when got SIGTERM signal from scheduler
"""
logging.debug('Interrupted by SIGTERM')
self.kill_job()
self.quit(-1) | [
"def",
"sigterm_handler",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"logging",
".",
"debug",
"(",
"'Interrupted by SIGTERM'",
")",
"self",
".",
"kill_job",
"(",
")",
"self",
".",
"quit",
"(",
"-",
"1",
")"
] | https://github.com/wangkuiyi/mapreduce-lite/blob/1bb92fe094dc47480ef9163c34070a3199feead6/src/mapreduce_lite/scheduler/worker.py#L409-L414 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/config.py | python | ConfigOptionsHandler.parse_section_packages__find | (self, section_options) | return find_kwargs | Parses `packages.find` configuration file section.
To be used in conjunction with _parse_packages().
:param dict section_options: | Parses `packages.find` configuration file section. | [
"Parses",
"packages",
".",
"find",
"configuration",
"file",
"section",
"."
] | def parse_section_packages__find(self, section_options):
"""Parses `packages.find` configuration file section.
To be used in conjunction with _parse_packages().
:param dict section_options:
"""
section_data = self._parse_section_to_dict(
section_options, self._parse_list)
valid_keys = ['where', 'include', 'exclude']
find_kwargs = dict(
[(k, v) for k, v in section_data.items() if k in valid_keys and v])
where = find_kwargs.get('where')
if where is not None:
find_kwargs['where'] = where[0] # cast list to single val
return find_kwargs | [
"def",
"parse_section_packages__find",
"(",
"self",
",",
"section_options",
")",
":",
"section_data",
"=",
"self",
".",
"_parse_section_to_dict",
"(",
"section_options",
",",
"self",
".",
"_parse_list",
")",
"valid_keys",
"=",
"[",
"'where'",
",",
"'include'",
",",
"'exclude'",
"]",
"find_kwargs",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"section_data",
".",
"items",
"(",
")",
"if",
"k",
"in",
"valid_keys",
"and",
"v",
"]",
")",
"where",
"=",
"find_kwargs",
".",
"get",
"(",
"'where'",
")",
"if",
"where",
"is",
"not",
"None",
":",
"find_kwargs",
"[",
"'where'",
"]",
"=",
"where",
"[",
"0",
"]",
"# cast list to single val",
"return",
"find_kwargs"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/config.py#L587-L606 | |
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | contrib/kafka/filters/network/source/protocol/generator.py | python | Complex.compute_field_lists | (self) | return field_lists | Return field lists representing each of structure versions. | Return field lists representing each of structure versions. | [
"Return",
"field",
"lists",
"representing",
"each",
"of",
"structure",
"versions",
"."
] | def compute_field_lists(self):
"""
Return field lists representing each of structure versions.
"""
field_lists = []
for version in self.versions:
field_list = FieldList(version, version in self.flexible_versions, self.fields)
field_lists.append(field_list)
return field_lists | [
"def",
"compute_field_lists",
"(",
"self",
")",
":",
"field_lists",
"=",
"[",
"]",
"for",
"version",
"in",
"self",
".",
"versions",
":",
"field_list",
"=",
"FieldList",
"(",
"version",
",",
"version",
"in",
"self",
".",
"flexible_versions",
",",
"self",
".",
"fields",
")",
"field_lists",
".",
"append",
"(",
"field_list",
")",
"return",
"field_lists"
] | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/contrib/kafka/filters/network/source/protocol/generator.py#L676-L684 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | Grid.DisableDragGridSize | (*args, **kwargs) | return _grid.Grid_DisableDragGridSize(*args, **kwargs) | DisableDragGridSize(self) | DisableDragGridSize(self) | [
"DisableDragGridSize",
"(",
"self",
")"
] | def DisableDragGridSize(*args, **kwargs):
"""DisableDragGridSize(self)"""
return _grid.Grid_DisableDragGridSize(*args, **kwargs) | [
"def",
"DisableDragGridSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_DisableDragGridSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1646-L1648 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | nodePush | (ctxt, value) | return ret | Pushes a new element node on top of the node stack | Pushes a new element node on top of the node stack | [
"Pushes",
"a",
"new",
"element",
"node",
"on",
"top",
"of",
"the",
"node",
"stack"
] | def nodePush(ctxt, value):
"""Pushes a new element node on top of the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if value is None: value__o = None
else: value__o = value._o
ret = libxml2mod.nodePush(ctxt__o, value__o)
return ret | [
"def",
"nodePush",
"(",
"ctxt",
",",
"value",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"if",
"value",
"is",
"None",
":",
"value__o",
"=",
"None",
"else",
":",
"value__o",
"=",
"value",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"nodePush",
"(",
"ctxt__o",
",",
"value__o",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L1485-L1492 | |
emsesp/EMS-ESP | 65c4a381bf8df61d1e18ba00223b1a55933fc547 | scripts/esptool.py | python | BaseFirmwareImage.load_segment | (self, f, is_irom_segment=False) | return segment | Load the next segment from the image file | Load the next segment from the image file | [
"Load",
"the",
"next",
"segment",
"from",
"the",
"image",
"file"
] | def load_segment(self, f, is_irom_segment=False):
""" Load the next segment from the image file """
file_offs = f.tell()
(offset, size) = struct.unpack('<II', f.read(8))
self.warn_if_unusual_segment(offset, size, is_irom_segment)
segment_data = f.read(size)
if len(segment_data) < size:
raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
segment = ImageSegment(offset, segment_data, file_offs)
self.segments.append(segment)
return segment | [
"def",
"load_segment",
"(",
"self",
",",
"f",
",",
"is_irom_segment",
"=",
"False",
")",
":",
"file_offs",
"=",
"f",
".",
"tell",
"(",
")",
"(",
"offset",
",",
"size",
")",
"=",
"struct",
".",
"unpack",
"(",
"'<II'",
",",
"f",
".",
"read",
"(",
"8",
")",
")",
"self",
".",
"warn_if_unusual_segment",
"(",
"offset",
",",
"size",
",",
"is_irom_segment",
")",
"segment_data",
"=",
"f",
".",
"read",
"(",
"size",
")",
"if",
"len",
"(",
"segment_data",
")",
"<",
"size",
":",
"raise",
"FatalError",
"(",
"'End of file reading segment 0x%x, length %d (actual length %d)'",
"%",
"(",
"offset",
",",
"size",
",",
"len",
"(",
"segment_data",
")",
")",
")",
"segment",
"=",
"ImageSegment",
"(",
"offset",
",",
"segment_data",
",",
"file_offs",
")",
"self",
".",
"segments",
".",
"append",
"(",
"segment",
")",
"return",
"segment"
] | https://github.com/emsesp/EMS-ESP/blob/65c4a381bf8df61d1e18ba00223b1a55933fc547/scripts/esptool.py#L1311-L1321 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | llvm/utils/benchmark/tools/gbench/report.py | python | calculate_change | (old_val, new_val) | return float(new_val - old_val) / abs(old_val) | Return a float representing the decimal change between old_val and new_val. | Return a float representing the decimal change between old_val and new_val. | [
"Return",
"a",
"float",
"representing",
"the",
"decimal",
"change",
"between",
"old_val",
"and",
"new_val",
"."
] | def calculate_change(old_val, new_val):
"""
Return a float representing the decimal change between old_val and new_val.
"""
if old_val == 0 and new_val == 0:
return 0.0
if old_val == 0:
return float(new_val - old_val) / (float(old_val + new_val) / 2)
return float(new_val - old_val) / abs(old_val) | [
"def",
"calculate_change",
"(",
"old_val",
",",
"new_val",
")",
":",
"if",
"old_val",
"==",
"0",
"and",
"new_val",
"==",
"0",
":",
"return",
"0.0",
"if",
"old_val",
"==",
"0",
":",
"return",
"float",
"(",
"new_val",
"-",
"old_val",
")",
"/",
"(",
"float",
"(",
"old_val",
"+",
"new_val",
")",
"/",
"2",
")",
"return",
"float",
"(",
"new_val",
"-",
"old_val",
")",
"/",
"abs",
"(",
"old_val",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/utils/benchmark/tools/gbench/report.py#L60-L68 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/ao/quantization/quantize_fx.py | python | _fuse_fx | (
graph_module: GraphModule,
is_qat: bool,
fuse_custom_config_dict: Optional[Dict[str, Any]] = None,
backend_config_dict: Optional[Dict[str, Any]] = None,
) | return fuser.fuse(
graph_module, is_qat, fuse_custom_config_dict, backend_config_dict) | r""" Internal helper function to fuse modules in preparation for quantization
Args:
graph_module: GraphModule object from symbolic tracing (torch.fx.symbolic_trace) | r""" Internal helper function to fuse modules in preparation for quantization | [
"r",
"Internal",
"helper",
"function",
"to",
"fuse",
"modules",
"in",
"preparation",
"for",
"quantization"
] | def _fuse_fx(
graph_module: GraphModule,
is_qat: bool,
fuse_custom_config_dict: Optional[Dict[str, Any]] = None,
backend_config_dict: Optional[Dict[str, Any]] = None,
) -> GraphModule:
r""" Internal helper function to fuse modules in preparation for quantization
Args:
graph_module: GraphModule object from symbolic tracing (torch.fx.symbolic_trace)
"""
_check_is_graph_module(graph_module)
fuser = Fuser()
return fuser.fuse(
graph_module, is_qat, fuse_custom_config_dict, backend_config_dict) | [
"def",
"_fuse_fx",
"(",
"graph_module",
":",
"GraphModule",
",",
"is_qat",
":",
"bool",
",",
"fuse_custom_config_dict",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"backend_config_dict",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
")",
"->",
"GraphModule",
":",
"_check_is_graph_module",
"(",
"graph_module",
")",
"fuser",
"=",
"Fuser",
"(",
")",
"return",
"fuser",
".",
"fuse",
"(",
"graph_module",
",",
"is_qat",
",",
"fuse_custom_config_dict",
",",
"backend_config_dict",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/quantize_fx.py#L48-L62 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py | python | Distribution.__getattr__ | (self,attr) | return getattr(self._provider, attr) | Delegate all unrecognized public attributes to .metadata provider | Delegate all unrecognized public attributes to .metadata provider | [
"Delegate",
"all",
"unrecognized",
"public",
"attributes",
"to",
".",
"metadata",
"provider"
] | def __getattr__(self,attr):
"""Delegate all unrecognized public attributes to .metadata provider"""
if attr.startswith('_'):
raise AttributeError(attr)
return getattr(self._provider, attr) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
".",
"startswith",
"(",
"'_'",
")",
":",
"raise",
"AttributeError",
"(",
"attr",
")",
"return",
"getattr",
"(",
"self",
".",
"_provider",
",",
"attr",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py#L2371-L2375 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/sparse_ops.py | python | _SerializeSparseShape | (op) | return [tensor_shape.vector(3)] | Shape function for SerializeSparse op. | Shape function for SerializeSparse op. | [
"Shape",
"function",
"for",
"SerializeSparse",
"op",
"."
] | def _SerializeSparseShape(op): # pylint: disable=invalid-name
"""Shape function for SerializeSparse op."""
op.inputs[0].get_shape().with_rank(2)
op.inputs[1].get_shape().with_rank(1)
op.inputs[2].get_shape().with_rank(1)
return [tensor_shape.vector(3)] | [
"def",
"_SerializeSparseShape",
"(",
"op",
")",
":",
"# pylint: disable=invalid-name",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"2",
")",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"1",
")",
"op",
".",
"inputs",
"[",
"2",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"1",
")",
"return",
"[",
"tensor_shape",
".",
"vector",
"(",
"3",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/sparse_ops.py#L1119-L1125 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_utils/bullet_client.py | python | BulletClient.__init__ | (self, connection_mode=None, hostName=None, options='') | Creates a Bullet client and connects to a simulation.
Args:
connection_mode:
`None` connects to an existing simulation or, if fails, creates a
new headless simulation,
`pybullet.GUI` creates a new simulation with a GUI,
`pybullet.DIRECT` creates a headless simulation,
`pybullet.SHARED_MEMORY` connects to an existing simulation. | Creates a Bullet client and connects to a simulation. | [
"Creates",
"a",
"Bullet",
"client",
"and",
"connects",
"to",
"a",
"simulation",
"."
] | def __init__(self, connection_mode=None, hostName=None, options=''):
"""Creates a Bullet client and connects to a simulation.
Args:
connection_mode:
`None` connects to an existing simulation or, if fails, creates a
new headless simulation,
`pybullet.GUI` creates a new simulation with a GUI,
`pybullet.DIRECT` creates a headless simulation,
`pybullet.SHARED_MEMORY` connects to an existing simulation.
"""
self._shapes = {}
self._pid = os.getpid()
if connection_mode is None:
self._client = pybullet.connect(pybullet.SHARED_MEMORY, options=options)
if self._client >= 0:
return
else:
connection_mode = pybullet.DIRECT
if hostName is None:
self._client = pybullet.connect(connection_mode, options=options)
else:
self._client = pybullet.connect(connection_mode, hostName=hostName, options=options) | [
"def",
"__init__",
"(",
"self",
",",
"connection_mode",
"=",
"None",
",",
"hostName",
"=",
"None",
",",
"options",
"=",
"''",
")",
":",
"self",
".",
"_shapes",
"=",
"{",
"}",
"self",
".",
"_pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"connection_mode",
"is",
"None",
":",
"self",
".",
"_client",
"=",
"pybullet",
".",
"connect",
"(",
"pybullet",
".",
"SHARED_MEMORY",
",",
"options",
"=",
"options",
")",
"if",
"self",
".",
"_client",
">=",
"0",
":",
"return",
"else",
":",
"connection_mode",
"=",
"pybullet",
".",
"DIRECT",
"if",
"hostName",
"is",
"None",
":",
"self",
".",
"_client",
"=",
"pybullet",
".",
"connect",
"(",
"connection_mode",
",",
"options",
"=",
"options",
")",
"else",
":",
"self",
".",
"_client",
"=",
"pybullet",
".",
"connect",
"(",
"connection_mode",
",",
"hostName",
"=",
"hostName",
",",
"options",
"=",
"options",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_utils/bullet_client.py#L13-L35 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBSymbolContext.GetModule | (self) | return _lldb.SBSymbolContext_GetModule(self) | GetModule(self) -> SBModule | GetModule(self) -> SBModule | [
"GetModule",
"(",
"self",
")",
"-",
">",
"SBModule"
] | def GetModule(self):
"""GetModule(self) -> SBModule"""
return _lldb.SBSymbolContext_GetModule(self) | [
"def",
"GetModule",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBSymbolContext_GetModule",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L8260-L8262 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | GenericDirCtrl.SetDefaultPath | (*args, **kwargs) | return _controls_.GenericDirCtrl_SetDefaultPath(*args, **kwargs) | SetDefaultPath(self, String path) | SetDefaultPath(self, String path) | [
"SetDefaultPath",
"(",
"self",
"String",
"path",
")"
] | def SetDefaultPath(*args, **kwargs):
"""SetDefaultPath(self, String path)"""
return _controls_.GenericDirCtrl_SetDefaultPath(*args, **kwargs) | [
"def",
"SetDefaultPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"GenericDirCtrl_SetDefaultPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5677-L5679 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py | python | getsourcefile | (object) | Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source. | Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source. | [
"Return",
"the",
"filename",
"that",
"can",
"be",
"used",
"to",
"locate",
"an",
"object",
"s",
"source",
".",
"Return",
"None",
"if",
"no",
"way",
"can",
"be",
"identified",
"to",
"get",
"the",
"source",
"."
] | def getsourcefile(object):
"""Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
"""
filename = getfile(object)
all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
if any(filename.endswith(s) for s in all_bytecode_suffixes):
filename = (os.path.splitext(filename)[0] +
importlib.machinery.SOURCE_SUFFIXES[0])
elif any(filename.endswith(s) for s in
importlib.machinery.EXTENSION_SUFFIXES):
return None
if os.path.exists(filename):
return filename
# only return a non-existent filename if the module has a PEP 302 loader
if getattr(getmodule(object, filename), '__loader__', None) is not None:
return filename
# or it is in the linecache
if filename in linecache.cache:
return filename | [
"def",
"getsourcefile",
"(",
"object",
")",
":",
"filename",
"=",
"getfile",
"(",
"object",
")",
"all_bytecode_suffixes",
"=",
"importlib",
".",
"machinery",
".",
"DEBUG_BYTECODE_SUFFIXES",
"[",
":",
"]",
"all_bytecode_suffixes",
"+=",
"importlib",
".",
"machinery",
".",
"OPTIMIZED_BYTECODE_SUFFIXES",
"[",
":",
"]",
"if",
"any",
"(",
"filename",
".",
"endswith",
"(",
"s",
")",
"for",
"s",
"in",
"all_bytecode_suffixes",
")",
":",
"filename",
"=",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
"+",
"importlib",
".",
"machinery",
".",
"SOURCE_SUFFIXES",
"[",
"0",
"]",
")",
"elif",
"any",
"(",
"filename",
".",
"endswith",
"(",
"s",
")",
"for",
"s",
"in",
"importlib",
".",
"machinery",
".",
"EXTENSION_SUFFIXES",
")",
":",
"return",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"filename",
"# only return a non-existent filename if the module has a PEP 302 loader",
"if",
"getattr",
"(",
"getmodule",
"(",
"object",
",",
"filename",
")",
",",
"'__loader__'",
",",
"None",
")",
"is",
"not",
"None",
":",
"return",
"filename",
"# or it is in the linecache",
"if",
"filename",
"in",
"linecache",
".",
"cache",
":",
"return",
"filename"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py#L680-L700 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/mox.py | python | Regex.equals | (self, rhs) | return self.regex.search(rhs) is not None | Check to see if rhs matches regular expression pattern.
Returns:
bool | Check to see if rhs matches regular expression pattern. | [
"Check",
"to",
"see",
"if",
"rhs",
"matches",
"regular",
"expression",
"pattern",
"."
] | def equals(self, rhs):
"""Check to see if rhs matches regular expression pattern.
Returns:
bool
"""
return self.regex.search(rhs) is not None | [
"def",
"equals",
"(",
"self",
",",
"rhs",
")",
":",
"return",
"self",
".",
"regex",
".",
"search",
"(",
"rhs",
")",
"is",
"not",
"None"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/mox.py#L922-L929 | |
bingwin/MicroChat | 81d9a71a212c1cbca5bba497ec42659a7d25dccf | mars/lint/cpplint.py | python | NestingState.SeenOpenBrace | (self) | return (not self.stack) or self.stack[-1].seen_open_brace | Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace. | Check if we have seen the opening brace for the innermost block. | [
"Check",
"if",
"we",
"have",
"seen",
"the",
"opening",
"brace",
"for",
"the",
"innermost",
"block",
"."
] | def SeenOpenBrace(self):
"""Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace.
"""
return (not self.stack) or self.stack[-1].seen_open_brace | [
"def",
"SeenOpenBrace",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"stack",
")",
"or",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"seen_open_brace"
] | https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L2230-L2237 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/ccompiler.py | python | CCompiler._need_link | (self, objects, output_file) | Return true if we need to relink the files listed in 'objects'
to recreate 'output_file'. | Return true if we need to relink the files listed in 'objects'
to recreate 'output_file'. | [
"Return",
"true",
"if",
"we",
"need",
"to",
"relink",
"the",
"files",
"listed",
"in",
"objects",
"to",
"recreate",
"output_file",
"."
] | def _need_link(self, objects, output_file):
"""Return true if we need to relink the files listed in 'objects'
to recreate 'output_file'.
"""
if self.force:
return 1
else:
if self.dry_run:
newer = newer_group (objects, output_file, missing='newer')
else:
newer = newer_group (objects, output_file)
return newer | [
"def",
"_need_link",
"(",
"self",
",",
"objects",
",",
"output_file",
")",
":",
"if",
"self",
".",
"force",
":",
"return",
"1",
"else",
":",
"if",
"self",
".",
"dry_run",
":",
"newer",
"=",
"newer_group",
"(",
"objects",
",",
"output_file",
",",
"missing",
"=",
"'newer'",
")",
"else",
":",
"newer",
"=",
"newer_group",
"(",
"objects",
",",
"output_file",
")",
"return",
"newer"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/ccompiler.py#L461-L472 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py | python | StateSpaceModel.get_observation_model | (self, times) | Specifies the observation model to use.
Args:
times: A [batch dimension] int32 Tensor with times for each part of the
batch, on which the observation model can depend.
Returns:
This function, when overridden, has three possible return values:
- A [state dimension] Tensor with a static, univariate observation
model.
- A [self.num_features x state dimension] static, multivariate model.
- A [batch dimension x self.num_features x state dimension] observation
model, which may depend on `times`.
See get_broadcasted_observation_model for details of the broadcasting. | Specifies the observation model to use. | [
"Specifies",
"the",
"observation",
"model",
"to",
"use",
"."
] | def get_observation_model(self, times):
"""Specifies the observation model to use.
Args:
times: A [batch dimension] int32 Tensor with times for each part of the
batch, on which the observation model can depend.
Returns:
This function, when overridden, has three possible return values:
- A [state dimension] Tensor with a static, univariate observation
model.
- A [self.num_features x state dimension] static, multivariate model.
- A [batch dimension x self.num_features x state dimension] observation
model, which may depend on `times`.
See get_broadcasted_observation_model for details of the broadcasting.
"""
pass | [
"def",
"get_observation_model",
"(",
"self",
",",
"times",
")",
":",
"pass"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py#L857-L872 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/filters.py | python | evalcontextfilter | (f) | return f | Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4 | Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`. | [
"Decorator",
"for",
"marking",
"eval",
"-",
"context",
"dependent",
"filters",
".",
"An",
"eval",
"context",
"object",
"is",
"passed",
"as",
"first",
"argument",
".",
"For",
"more",
"information",
"about",
"the",
"eval",
"context",
"see",
":",
"ref",
":",
"eval",
"-",
"context",
"."
] | def evalcontextfilter(f):
"""Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfilter = True
return f | [
"def",
"evalcontextfilter",
"(",
"f",
")",
":",
"f",
".",
"evalcontextfilter",
"=",
"True",
"return",
"f"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/filters.py#L37-L45 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/legacy_tf_layers/base.py | python | set_keras_style | () | Use Keras-style variable management.
All tf.layers and tf RNN cells created after keras style ha been enabled
use Keras-style variable management. Creating such layers with a
scope= argument is disallowed, and reuse=True is disallowed.
The purpose of this function is to allow users of existing layers to
slowly transition to Keras layers API without breaking existing
functionality.
For more details, see the documentation for `keras_style_scope`.
Note, once keras style has been set, it is set globally for the entire
program and cannot be unset.
Example:
```python
set_keras_style()
model_1 = RNNModel(name="model_1")
model_2 = RNNModel(name="model_2")
# model_1 and model_2 are guaranteed to create their own variables.
output_1, next_state_1 = model_1(input, state)
output_2, next_state_2 = model_2(input, state)
assert len(model_1.weights) > 0
assert len(model_2.weights) > 0
assert(model_1.weights != model_2.weights)
``` | Use Keras-style variable management. | [
"Use",
"Keras",
"-",
"style",
"variable",
"management",
"."
] | def set_keras_style():
"""Use Keras-style variable management.
All tf.layers and tf RNN cells created after keras style ha been enabled
use Keras-style variable management. Creating such layers with a
scope= argument is disallowed, and reuse=True is disallowed.
The purpose of this function is to allow users of existing layers to
slowly transition to Keras layers API without breaking existing
functionality.
For more details, see the documentation for `keras_style_scope`.
Note, once keras style has been set, it is set globally for the entire
program and cannot be unset.
Example:
```python
set_keras_style()
model_1 = RNNModel(name="model_1")
model_2 = RNNModel(name="model_2")
# model_1 and model_2 are guaranteed to create their own variables.
output_1, next_state_1 = model_1(input, state)
output_2, next_state_2 = model_2(input, state)
assert len(model_1.weights) > 0
assert len(model_2.weights) > 0
assert(model_1.weights != model_2.weights)
```
"""
global _KERAS_STYLE_SCOPE
_KERAS_STYLE_SCOPE = True | [
"def",
"set_keras_style",
"(",
")",
":",
"global",
"_KERAS_STYLE_SCOPE",
"_KERAS_STYLE_SCOPE",
"=",
"True"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/legacy_tf_layers/base.py#L117-L151 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/BASISReduction.py | python | unique_workspace_name | (n=3, prefix='', suffix='') | return ws_name | r"""
Create a random sequence of `n` lowercase characters that is guaranteed
not to collide with the name of any existing Mantid workspace registered
in the analysis data service.
Parameters
----------
n: int
Size of the sequence
prefix: str
String to prefix the randon sequence
suffix: str
String to suffix the randon sequence
Returns
-------
str | r"""
Create a random sequence of `n` lowercase characters that is guaranteed
not to collide with the name of any existing Mantid workspace registered
in the analysis data service. | [
"r",
"Create",
"a",
"random",
"sequence",
"of",
"n",
"lowercase",
"characters",
"that",
"is",
"guaranteed",
"not",
"to",
"collide",
"with",
"the",
"name",
"of",
"any",
"existing",
"Mantid",
"workspace",
"registered",
"in",
"the",
"analysis",
"data",
"service",
"."
] | def unique_workspace_name(n=3, prefix='', suffix=''):
r"""
Create a random sequence of `n` lowercase characters that is guaranteed
not to collide with the name of any existing Mantid workspace registered
in the analysis data service.
Parameters
----------
n: int
Size of the sequence
prefix: str
String to prefix the randon sequence
suffix: str
String to suffix the randon sequence
Returns
-------
str
"""
n_seq = ''.join(random.choice(string.ascii_lowercase) for _ in range(n))
ws_name = '{}{}{}'.format(str(prefix), n_seq, str(suffix))
while ws_name in AnalysisDataService.getObjectNames():
characters = [random.choice(string.ascii_lowercase) for _ in range(n)]
n_seq = ''.join(characters)
ws_name = '{}{}{}'.format(str(prefix), n_seq, str(suffix))
return ws_name | [
"def",
"unique_workspace_name",
"(",
"n",
"=",
"3",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
")",
":",
"n_seq",
"=",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_lowercase",
")",
"for",
"_",
"in",
"range",
"(",
"n",
")",
")",
"ws_name",
"=",
"'{}{}{}'",
".",
"format",
"(",
"str",
"(",
"prefix",
")",
",",
"n_seq",
",",
"str",
"(",
"suffix",
")",
")",
"while",
"ws_name",
"in",
"AnalysisDataService",
".",
"getObjectNames",
"(",
")",
":",
"characters",
"=",
"[",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_lowercase",
")",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"n_seq",
"=",
"''",
".",
"join",
"(",
"characters",
")",
"ws_name",
"=",
"'{}{}{}'",
".",
"format",
"(",
"str",
"(",
"prefix",
")",
",",
"n_seq",
",",
"str",
"(",
"suffix",
")",
")",
"return",
"ws_name"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/BASISReduction.py#L28-L54 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/logging/__init__.py | python | exception | (msg, *args, exc_info=True, **kwargs) | Log a message with severity 'ERROR' on the root logger, with exception
information. If the logger has no handlers, basicConfig() is called to add
a console handler with a pre-defined format. | Log a message with severity 'ERROR' on the root logger, with exception
information. If the logger has no handlers, basicConfig() is called to add
a console handler with a pre-defined format. | [
"Log",
"a",
"message",
"with",
"severity",
"ERROR",
"on",
"the",
"root",
"logger",
"with",
"exception",
"information",
".",
"If",
"the",
"logger",
"has",
"no",
"handlers",
"basicConfig",
"()",
"is",
"called",
"to",
"add",
"a",
"console",
"handler",
"with",
"a",
"pre",
"-",
"defined",
"format",
"."
] | def exception(msg, *args, exc_info=True, **kwargs):
"""
Log a message with severity 'ERROR' on the root logger, with exception
information. If the logger has no handlers, basicConfig() is called to add
a console handler with a pre-defined format.
"""
error(msg, *args, exc_info=exc_info, **kwargs) | [
"def",
"exception",
"(",
"msg",
",",
"*",
"args",
",",
"exc_info",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"error",
"(",
"msg",
",",
"*",
"args",
",",
"exc_info",
"=",
"exc_info",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/__init__.py#L2066-L2072 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/config.py | python | ConfigHandler._parse_bool | (cls, value) | return value in ('1', 'true', 'yes') | Represents value as boolean.
:param value:
:rtype: bool | Represents value as boolean. | [
"Represents",
"value",
"as",
"boolean",
"."
] | def _parse_bool(cls, value):
"""Represents value as boolean.
:param value:
:rtype: bool
"""
value = value.lower()
return value in ('1', 'true', 'yes') | [
"def",
"_parse_bool",
"(",
"cls",
",",
"value",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"return",
"value",
"in",
"(",
"'1'",
",",
"'true'",
",",
"'yes'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/config.py#L308-L315 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Window.Center | (*args, **kwargs) | return _core_.Window_Center(*args, **kwargs) | Center(self, int direction=BOTH)
Centers the window. The parameter specifies the direction for
centering, and may be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH. It may
also include wx.CENTER_ON_SCREEN flag if you want to center the window
on the entire screen and not on its parent window. If it is a
top-level window and has no parent then it will always be centered
relative to the screen. | Center(self, int direction=BOTH) | [
"Center",
"(",
"self",
"int",
"direction",
"=",
"BOTH",
")"
] | def Center(*args, **kwargs):
"""
Center(self, int direction=BOTH)
Centers the window. The parameter specifies the direction for
centering, and may be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH. It may
also include wx.CENTER_ON_SCREEN flag if you want to center the window
on the entire screen and not on its parent window. If it is a
top-level window and has no parent then it will always be centered
relative to the screen.
"""
return _core_.Window_Center(*args, **kwargs) | [
"def",
"Center",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_Center",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L9655-L9666 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/routing.py | python | Matcher.match | (self, request: httputil.HTTPServerRequest) | Matches current instance against the request.
:arg httputil.HTTPServerRequest request: current HTTP request
:returns: a dict of parameters to be passed to the target handler
(for example, ``handler_kwargs``, ``path_args``, ``path_kwargs``
can be passed for proper `~.web.RequestHandler` instantiation).
An empty dict is a valid (and common) return value to indicate a match
when the argument-passing features are not used.
``None`` must be returned to indicate that there is no match. | Matches current instance against the request. | [
"Matches",
"current",
"instance",
"against",
"the",
"request",
"."
] | def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
"""Matches current instance against the request.
:arg httputil.HTTPServerRequest request: current HTTP request
:returns: a dict of parameters to be passed to the target handler
(for example, ``handler_kwargs``, ``path_args``, ``path_kwargs``
can be passed for proper `~.web.RequestHandler` instantiation).
An empty dict is a valid (and common) return value to indicate a match
when the argument-passing features are not used.
``None`` must be returned to indicate that there is no match."""
raise NotImplementedError() | [
"def",
"match",
"(",
"self",
",",
"request",
":",
"httputil",
".",
"HTTPServerRequest",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/routing.py#L493-L503 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/polynomial/chebyshev.py | python | chebpow | (c, pow, maxpower=16) | Raise a Chebyshev series to a power.
Returns the Chebyshev series `c` raised to the power `pow`. The
argument `c` is a sequence of coefficients ordered from low to high.
i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``
Parameters
----------
c : array_like
1-D array of Chebyshev series coefficients ordered from low to
high.
pow : integer
Power to which the series will be raised
maxpower : integer, optional
Maximum power allowed. This is mainly to limit growth of the series
to unmanageable size. Default is 16
Returns
-------
coef : ndarray
Chebyshev series of power.
See Also
--------
chebadd, chebsub, chebmulx, chebmul, chebdiv
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> C.chebpow([1, 2, 3, 4], 2)
array([15.5, 22. , 16. , 14. , 12.5, 12. , 8. ]) | Raise a Chebyshev series to a power. | [
"Raise",
"a",
"Chebyshev",
"series",
"to",
"a",
"power",
"."
] | def chebpow(c, pow, maxpower=16):
"""Raise a Chebyshev series to a power.
Returns the Chebyshev series `c` raised to the power `pow`. The
argument `c` is a sequence of coefficients ordered from low to high.
i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``
Parameters
----------
c : array_like
1-D array of Chebyshev series coefficients ordered from low to
high.
pow : integer
Power to which the series will be raised
maxpower : integer, optional
Maximum power allowed. This is mainly to limit growth of the series
to unmanageable size. Default is 16
Returns
-------
coef : ndarray
Chebyshev series of power.
See Also
--------
chebadd, chebsub, chebmulx, chebmul, chebdiv
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> C.chebpow([1, 2, 3, 4], 2)
array([15.5, 22. , 16. , 14. , 12.5, 12. , 8. ])
"""
# c is a trimmed copy
[c] = pu.as_series([c])
power = int(pow)
if power != pow or power < 0:
raise ValueError("Power must be a non-negative integer.")
elif maxpower is not None and power > maxpower:
raise ValueError("Power is too large")
elif power == 0:
return np.array([1], dtype=c.dtype)
elif power == 1:
return c
else:
# This can be made more efficient by using powers of two
# in the usual way.
zs = _cseries_to_zseries(c)
prd = zs
for i in range(2, power + 1):
prd = np.convolve(prd, zs)
return _zseries_to_cseries(prd) | [
"def",
"chebpow",
"(",
"c",
",",
"pow",
",",
"maxpower",
"=",
"16",
")",
":",
"# c is a trimmed copy",
"[",
"c",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"c",
"]",
")",
"power",
"=",
"int",
"(",
"pow",
")",
"if",
"power",
"!=",
"pow",
"or",
"power",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Power must be a non-negative integer.\"",
")",
"elif",
"maxpower",
"is",
"not",
"None",
"and",
"power",
">",
"maxpower",
":",
"raise",
"ValueError",
"(",
"\"Power is too large\"",
")",
"elif",
"power",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"1",
"]",
",",
"dtype",
"=",
"c",
".",
"dtype",
")",
"elif",
"power",
"==",
"1",
":",
"return",
"c",
"else",
":",
"# This can be made more efficient by using powers of two",
"# in the usual way.",
"zs",
"=",
"_cseries_to_zseries",
"(",
"c",
")",
"prd",
"=",
"zs",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"power",
"+",
"1",
")",
":",
"prd",
"=",
"np",
".",
"convolve",
"(",
"prd",
",",
"zs",
")",
"return",
"_zseries_to_cseries",
"(",
"prd",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/chebyshev.py#L825-L877 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/geometry/tf/src/tf/transformations.py | python | compose_matrix | (scale=None, shear=None, angles=None, translate=None,
perspective=None) | return M | Return transformation matrix from sequence of transformations.
This is the inverse of the decompose_matrix function.
Sequence of transformations:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
>>> scale = numpy.random.random(3) - 0.5
>>> shear = numpy.random.random(3) - 0.5
>>> angles = (numpy.random.random(3) - 0.5) * (2*math.pi)
>>> trans = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(4) - 0.5
>>> M0 = compose_matrix(scale, shear, angles, trans, persp)
>>> result = decompose_matrix(M0)
>>> M1 = compose_matrix(*result)
>>> is_same_transform(M0, M1)
True | Return transformation matrix from sequence of transformations. | [
"Return",
"transformation",
"matrix",
"from",
"sequence",
"of",
"transformations",
"."
] | def compose_matrix(scale=None, shear=None, angles=None, translate=None,
perspective=None):
"""Return transformation matrix from sequence of transformations.
This is the inverse of the decompose_matrix function.
Sequence of transformations:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
>>> scale = numpy.random.random(3) - 0.5
>>> shear = numpy.random.random(3) - 0.5
>>> angles = (numpy.random.random(3) - 0.5) * (2*math.pi)
>>> trans = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(4) - 0.5
>>> M0 = compose_matrix(scale, shear, angles, trans, persp)
>>> result = decompose_matrix(M0)
>>> M1 = compose_matrix(*result)
>>> is_same_transform(M0, M1)
True
"""
M = numpy.identity(4)
if perspective is not None:
P = numpy.identity(4)
P[3, :] = perspective[:4]
M = numpy.dot(M, P)
if translate is not None:
T = numpy.identity(4)
T[:3, 3] = translate[:3]
M = numpy.dot(M, T)
if angles is not None:
R = euler_matrix(angles[0], angles[1], angles[2], 'sxyz')
M = numpy.dot(M, R)
if shear is not None:
Z = numpy.identity(4)
Z[1, 2] = shear[2]
Z[0, 2] = shear[1]
Z[0, 1] = shear[0]
M = numpy.dot(M, Z)
if scale is not None:
S = numpy.identity(4)
S[0, 0] = scale[0]
S[1, 1] = scale[1]
S[2, 2] = scale[2]
M = numpy.dot(M, S)
M /= M[3, 3]
return M | [
"def",
"compose_matrix",
"(",
"scale",
"=",
"None",
",",
"shear",
"=",
"None",
",",
"angles",
"=",
"None",
",",
"translate",
"=",
"None",
",",
"perspective",
"=",
"None",
")",
":",
"M",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"if",
"perspective",
"is",
"not",
"None",
":",
"P",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"P",
"[",
"3",
",",
":",
"]",
"=",
"perspective",
"[",
":",
"4",
"]",
"M",
"=",
"numpy",
".",
"dot",
"(",
"M",
",",
"P",
")",
"if",
"translate",
"is",
"not",
"None",
":",
"T",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"T",
"[",
":",
"3",
",",
"3",
"]",
"=",
"translate",
"[",
":",
"3",
"]",
"M",
"=",
"numpy",
".",
"dot",
"(",
"M",
",",
"T",
")",
"if",
"angles",
"is",
"not",
"None",
":",
"R",
"=",
"euler_matrix",
"(",
"angles",
"[",
"0",
"]",
",",
"angles",
"[",
"1",
"]",
",",
"angles",
"[",
"2",
"]",
",",
"'sxyz'",
")",
"M",
"=",
"numpy",
".",
"dot",
"(",
"M",
",",
"R",
")",
"if",
"shear",
"is",
"not",
"None",
":",
"Z",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"Z",
"[",
"1",
",",
"2",
"]",
"=",
"shear",
"[",
"2",
"]",
"Z",
"[",
"0",
",",
"2",
"]",
"=",
"shear",
"[",
"1",
"]",
"Z",
"[",
"0",
",",
"1",
"]",
"=",
"shear",
"[",
"0",
"]",
"M",
"=",
"numpy",
".",
"dot",
"(",
"M",
",",
"Z",
")",
"if",
"scale",
"is",
"not",
"None",
":",
"S",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"S",
"[",
"0",
",",
"0",
"]",
"=",
"scale",
"[",
"0",
"]",
"S",
"[",
"1",
",",
"1",
"]",
"=",
"scale",
"[",
"1",
"]",
"S",
"[",
"2",
",",
"2",
"]",
"=",
"scale",
"[",
"2",
"]",
"M",
"=",
"numpy",
".",
"dot",
"(",
"M",
",",
"S",
")",
"M",
"/=",
"M",
"[",
"3",
",",
"3",
"]",
"return",
"M"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/geometry/tf/src/tf/transformations.py#L785-L835 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_NV_Extend_REQUEST.fromTpm | (buf) | return buf.createObj(TPM2_NV_Extend_REQUEST) | Returns new TPM2_NV_Extend_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPM2_NV_Extend_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPM2_NV_Extend_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPM2_NV_Extend_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPM2_NV_Extend_REQUEST) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPM2_NV_Extend_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16874-L16878 | |
redpony/cdec | f7c4899b174d86bc70b40b1cae68dcad364615cb | python/cdec/configobj.py | python | Section.dict | (self) | return newdict | Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict()
>>> n == a
1
>>> n is a
0 | Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict()
>>> n == a
1
>>> n is a
0 | [
"Return",
"a",
"deepcopy",
"of",
"self",
"as",
"a",
"dictionary",
".",
"All",
"members",
"that",
"are",
"Section",
"instances",
"are",
"recursively",
"turned",
"to",
"ordinary",
"dictionaries",
"-",
"by",
"calling",
"their",
"dict",
"method",
".",
">>>",
"n",
"=",
"a",
".",
"dict",
"()",
">>>",
"n",
"==",
"a",
"1",
">>>",
"n",
"is",
"a",
"0"
] | def dict(self):
"""
Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict()
>>> n == a
1
>>> n is a
0
"""
newdict = {}
for entry in self:
this_entry = self[entry]
if isinstance(this_entry, Section):
this_entry = this_entry.dict()
elif isinstance(this_entry, list):
# create a copy rather than a reference
this_entry = list(this_entry)
elif isinstance(this_entry, tuple):
# create a copy rather than a reference
this_entry = tuple(this_entry)
newdict[entry] = this_entry
return newdict | [
"def",
"dict",
"(",
"self",
")",
":",
"newdict",
"=",
"{",
"}",
"for",
"entry",
"in",
"self",
":",
"this_entry",
"=",
"self",
"[",
"entry",
"]",
"if",
"isinstance",
"(",
"this_entry",
",",
"Section",
")",
":",
"this_entry",
"=",
"this_entry",
".",
"dict",
"(",
")",
"elif",
"isinstance",
"(",
"this_entry",
",",
"list",
")",
":",
"# create a copy rather than a reference",
"this_entry",
"=",
"list",
"(",
"this_entry",
")",
"elif",
"isinstance",
"(",
"this_entry",
",",
"tuple",
")",
":",
"# create a copy rather than a reference",
"this_entry",
"=",
"tuple",
"(",
"this_entry",
")",
"newdict",
"[",
"entry",
"]",
"=",
"this_entry",
"return",
"newdict"
] | https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L770-L795 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/bindings/python/clang/cindex.py | python | Cursor.linkage | (self) | return LinkageKind.from_id(self._linkage) | Return the linkage of this cursor. | Return the linkage of this cursor. | [
"Return",
"the",
"linkage",
"of",
"this",
"cursor",
"."
] | def linkage(self):
"""Return the linkage of this cursor."""
if not hasattr(self, '_linkage'):
self._linkage = conf.lib.clang_getCursorLinkage(self)
return LinkageKind.from_id(self._linkage) | [
"def",
"linkage",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_linkage'",
")",
":",
"self",
".",
"_linkage",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorLinkage",
"(",
"self",
")",
"return",
"LinkageKind",
".",
"from_id",
"(",
"self",
".",
"_linkage",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/bindings/python/clang/cindex.py#L1585-L1590 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2B_NV_PUBLIC.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.nvPublic = buf.createSizedObj(TPMS_NV_PUBLIC) | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"nvPublic",
"=",
"buf",
".",
"createSizedObj",
"(",
"TPMS_NV_PUBLIC",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L8705-L8707 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | DataObjectComposite.GetObject | (*args, **kwargs) | return _misc_.DataObjectComposite_GetObject(*args, **kwargs) | GetObject(self, DataFormat format, wxDataObjectBase::Direction dir=Get) -> DataObjectSimple
Returns the pointer to the object which supports this format or None.
TODO: Fix this to use OOR and return the right object type. | GetObject(self, DataFormat format, wxDataObjectBase::Direction dir=Get) -> DataObjectSimple | [
"GetObject",
"(",
"self",
"DataFormat",
"format",
"wxDataObjectBase",
"::",
"Direction",
"dir",
"=",
"Get",
")",
"-",
">",
"DataObjectSimple"
] | def GetObject(*args, **kwargs):
"""
GetObject(self, DataFormat format, wxDataObjectBase::Direction dir=Get) -> DataObjectSimple
Returns the pointer to the object which supports this format or None.
TODO: Fix this to use OOR and return the right object type.
"""
return _misc_.DataObjectComposite_GetObject(*args, **kwargs) | [
"def",
"GetObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DataObjectComposite_GetObject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L5154-L5161 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/trajectory.py | python | Trajectory.remesh | (self,newtimes,tol=1e-6) | return (res,resindices) | Returns a path that has milestones at the times given in newtimes, as well
as the current milestone times. Return value is (path,newtimeidx) where
path is the remeshed path, and newtimeidx is a list of time indices for which
path.times[newtimeidx[i]] = newtimes[i].
newtimes is an iterable over floats. It does not need to be sorted.
tol is a parameter specifying how closely the returned path must interpolate
the original path. Old milestones will be dropped if they are not needed to follow
the path within this tolerance.
The end behavior is assumed to be 'halt'. | Returns a path that has milestones at the times given in newtimes, as well
as the current milestone times. Return value is (path,newtimeidx) where
path is the remeshed path, and newtimeidx is a list of time indices for which
path.times[newtimeidx[i]] = newtimes[i]. | [
"Returns",
"a",
"path",
"that",
"has",
"milestones",
"at",
"the",
"times",
"given",
"in",
"newtimes",
"as",
"well",
"as",
"the",
"current",
"milestone",
"times",
".",
"Return",
"value",
"is",
"(",
"path",
"newtimeidx",
")",
"where",
"path",
"is",
"the",
"remeshed",
"path",
"and",
"newtimeidx",
"is",
"a",
"list",
"of",
"time",
"indices",
"for",
"which",
"path",
".",
"times",
"[",
"newtimeidx",
"[",
"i",
"]]",
"=",
"newtimes",
"[",
"i",
"]",
"."
] | def remesh(self,newtimes,tol=1e-6):
"""Returns a path that has milestones at the times given in newtimes, as well
as the current milestone times. Return value is (path,newtimeidx) where
path is the remeshed path, and newtimeidx is a list of time indices for which
path.times[newtimeidx[i]] = newtimes[i].
newtimes is an iterable over floats. It does not need to be sorted.
tol is a parameter specifying how closely the returned path must interpolate
the original path. Old milestones will be dropped if they are not needed to follow
the path within this tolerance.
The end behavior is assumed to be 'halt'.
"""
sorter = [(t,-1-i) for (i,t) in enumerate(self.times)] + [(t,i) for (i,t) in enumerate(newtimes)]
sorter = sorted(sorter)
res = self.constructor()(None,None)
res.times.append(sorter[0][0])
res.milestones.append(self.milestones[0])
#maybe a constant first section
resindices = []
i = 0
while sorter[i][0] < self.startTime():
if sorter[i][1] >= 0:
resindices.append(0)
i += 1
if i != 0:
res.times.append(self.startTime())
res.milestones.append(self.milestones[0])
firstold = 0
lastold = 0
while i < len(sorter):
#check if we should add this
t,idx = sorter[i]
i+=1
if idx >= 0: #new time
if t == res.times[-1]:
resindices.append(len(res.times)-1)
continue
#it's a new mesh point, add it and check whether previous old milestones should be added
if self.times[lastold] == t:
#matched the last old mesh point, no need to call eval_state()
newx = self.milestones[lastold]
else:
newx = self.eval_state(t)
res.times.append(t)
res.milestones.append(newx)
for j in range(firstold,lastold):
if self.times[j] == t:
continue
x = res.eval_state(self.times[j])
if vectorops.norm(self.difference_state(x,self.milestones[j],1.0,1.0)) > tol:
#add it
res.times[-1] = self.times[j]
res.milestones[-1] = self.milestones[j]
res.times.append(t)
res.milestones.append(newx)
resindices.append(len(res.times)-1)
firstold = lastold+1
else:
#mark the range of old milestones to add
lastold = -idx-1
for j in range(firstold,lastold):
res.times.append(self.times[j])
res.milestones.append(self.milestones[j])
#sanity check
for i in range(len(res.times)-1):
assert res.times[i] < res.times[i+1]
for i,idx in enumerate(resindices):
assert newtimes[i] == res.times[idx],"Resindices mismatch? {} should index {} to {}".format(resindices,newtimes,res.times)
return (res,resindices) | [
"def",
"remesh",
"(",
"self",
",",
"newtimes",
",",
"tol",
"=",
"1e-6",
")",
":",
"sorter",
"=",
"[",
"(",
"t",
",",
"-",
"1",
"-",
"i",
")",
"for",
"(",
"i",
",",
"t",
")",
"in",
"enumerate",
"(",
"self",
".",
"times",
")",
"]",
"+",
"[",
"(",
"t",
",",
"i",
")",
"for",
"(",
"i",
",",
"t",
")",
"in",
"enumerate",
"(",
"newtimes",
")",
"]",
"sorter",
"=",
"sorted",
"(",
"sorter",
")",
"res",
"=",
"self",
".",
"constructor",
"(",
")",
"(",
"None",
",",
"None",
")",
"res",
".",
"times",
".",
"append",
"(",
"sorter",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"res",
".",
"milestones",
".",
"append",
"(",
"self",
".",
"milestones",
"[",
"0",
"]",
")",
"#maybe a constant first section",
"resindices",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"sorter",
"[",
"i",
"]",
"[",
"0",
"]",
"<",
"self",
".",
"startTime",
"(",
")",
":",
"if",
"sorter",
"[",
"i",
"]",
"[",
"1",
"]",
">=",
"0",
":",
"resindices",
".",
"append",
"(",
"0",
")",
"i",
"+=",
"1",
"if",
"i",
"!=",
"0",
":",
"res",
".",
"times",
".",
"append",
"(",
"self",
".",
"startTime",
"(",
")",
")",
"res",
".",
"milestones",
".",
"append",
"(",
"self",
".",
"milestones",
"[",
"0",
"]",
")",
"firstold",
"=",
"0",
"lastold",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"sorter",
")",
":",
"#check if we should add this",
"t",
",",
"idx",
"=",
"sorter",
"[",
"i",
"]",
"i",
"+=",
"1",
"if",
"idx",
">=",
"0",
":",
"#new time",
"if",
"t",
"==",
"res",
".",
"times",
"[",
"-",
"1",
"]",
":",
"resindices",
".",
"append",
"(",
"len",
"(",
"res",
".",
"times",
")",
"-",
"1",
")",
"continue",
"#it's a new mesh point, add it and check whether previous old milestones should be added",
"if",
"self",
".",
"times",
"[",
"lastold",
"]",
"==",
"t",
":",
"#matched the last old mesh point, no need to call eval_state()",
"newx",
"=",
"self",
".",
"milestones",
"[",
"lastold",
"]",
"else",
":",
"newx",
"=",
"self",
".",
"eval_state",
"(",
"t",
")",
"res",
".",
"times",
".",
"append",
"(",
"t",
")",
"res",
".",
"milestones",
".",
"append",
"(",
"newx",
")",
"for",
"j",
"in",
"range",
"(",
"firstold",
",",
"lastold",
")",
":",
"if",
"self",
".",
"times",
"[",
"j",
"]",
"==",
"t",
":",
"continue",
"x",
"=",
"res",
".",
"eval_state",
"(",
"self",
".",
"times",
"[",
"j",
"]",
")",
"if",
"vectorops",
".",
"norm",
"(",
"self",
".",
"difference_state",
"(",
"x",
",",
"self",
".",
"milestones",
"[",
"j",
"]",
",",
"1.0",
",",
"1.0",
")",
")",
">",
"tol",
":",
"#add it",
"res",
".",
"times",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"times",
"[",
"j",
"]",
"res",
".",
"milestones",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"milestones",
"[",
"j",
"]",
"res",
".",
"times",
".",
"append",
"(",
"t",
")",
"res",
".",
"milestones",
".",
"append",
"(",
"newx",
")",
"resindices",
".",
"append",
"(",
"len",
"(",
"res",
".",
"times",
")",
"-",
"1",
")",
"firstold",
"=",
"lastold",
"+",
"1",
"else",
":",
"#mark the range of old milestones to add",
"lastold",
"=",
"-",
"idx",
"-",
"1",
"for",
"j",
"in",
"range",
"(",
"firstold",
",",
"lastold",
")",
":",
"res",
".",
"times",
".",
"append",
"(",
"self",
".",
"times",
"[",
"j",
"]",
")",
"res",
".",
"milestones",
".",
"append",
"(",
"self",
".",
"milestones",
"[",
"j",
"]",
")",
"#sanity check",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"res",
".",
"times",
")",
"-",
"1",
")",
":",
"assert",
"res",
".",
"times",
"[",
"i",
"]",
"<",
"res",
".",
"times",
"[",
"i",
"+",
"1",
"]",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"resindices",
")",
":",
"assert",
"newtimes",
"[",
"i",
"]",
"==",
"res",
".",
"times",
"[",
"idx",
"]",
",",
"\"Resindices mismatch? {} should index {} to {}\"",
".",
"format",
"(",
"resindices",
",",
"newtimes",
",",
"res",
".",
"times",
")",
"return",
"(",
"res",
",",
"resindices",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L398-L468 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py | python | ZipFile._extract_member | (self, member, targetpath, pwd) | return targetpath | Extract the ZipInfo object 'member' to a physical
file on the path targetpath. | Extract the ZipInfo object 'member' to a physical
file on the path targetpath. | [
"Extract",
"the",
"ZipInfo",
"object",
"member",
"to",
"a",
"physical",
"file",
"on",
"the",
"path",
"targetpath",
"."
] | def _extract_member(self, member, targetpath, pwd):
"""Extract the ZipInfo object 'member' to a physical
file on the path targetpath.
"""
# build the destination pathname, replacing
# forward slashes to platform specific separators.
arcname = member.filename.replace('/', os.path.sep)
if os.path.altsep:
arcname = arcname.replace(os.path.altsep, os.path.sep)
# interpret absolute pathname as relative, remove drive letter or
# UNC path, redundant separators, "." and ".." components.
arcname = os.path.splitdrive(arcname)[1]
arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
if x not in ('', os.path.curdir, os.path.pardir))
if os.path.sep == '\\':
# filter illegal characters on Windows
illegal = ':<>|"?*'
if isinstance(arcname, unicode):
table = {ord(c): ord('_') for c in illegal}
else:
table = string.maketrans(illegal, '_' * len(illegal))
arcname = arcname.translate(table)
# remove trailing dots
arcname = (x.rstrip('.') for x in arcname.split(os.path.sep))
arcname = os.path.sep.join(x for x in arcname if x)
targetpath = os.path.join(targetpath, arcname)
targetpath = os.path.normpath(targetpath)
# Create all upper directories if necessary.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
if member.filename[-1] == '/':
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
with self.open(member, pwd=pwd) as source, \
file(targetpath, "wb") as target:
shutil.copyfileobj(source, target)
return targetpath | [
"def",
"_extract_member",
"(",
"self",
",",
"member",
",",
"targetpath",
",",
"pwd",
")",
":",
"# build the destination pathname, replacing",
"# forward slashes to platform specific separators.",
"arcname",
"=",
"member",
".",
"filename",
".",
"replace",
"(",
"'/'",
",",
"os",
".",
"path",
".",
"sep",
")",
"if",
"os",
".",
"path",
".",
"altsep",
":",
"arcname",
"=",
"arcname",
".",
"replace",
"(",
"os",
".",
"path",
".",
"altsep",
",",
"os",
".",
"path",
".",
"sep",
")",
"# interpret absolute pathname as relative, remove drive letter or",
"# UNC path, redundant separators, \".\" and \"..\" components.",
"arcname",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"arcname",
")",
"[",
"1",
"]",
"arcname",
"=",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"x",
"for",
"x",
"in",
"arcname",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"if",
"x",
"not",
"in",
"(",
"''",
",",
"os",
".",
"path",
".",
"curdir",
",",
"os",
".",
"path",
".",
"pardir",
")",
")",
"if",
"os",
".",
"path",
".",
"sep",
"==",
"'\\\\'",
":",
"# filter illegal characters on Windows",
"illegal",
"=",
"':<>|\"?*'",
"if",
"isinstance",
"(",
"arcname",
",",
"unicode",
")",
":",
"table",
"=",
"{",
"ord",
"(",
"c",
")",
":",
"ord",
"(",
"'_'",
")",
"for",
"c",
"in",
"illegal",
"}",
"else",
":",
"table",
"=",
"string",
".",
"maketrans",
"(",
"illegal",
",",
"'_'",
"*",
"len",
"(",
"illegal",
")",
")",
"arcname",
"=",
"arcname",
".",
"translate",
"(",
"table",
")",
"# remove trailing dots",
"arcname",
"=",
"(",
"x",
".",
"rstrip",
"(",
"'.'",
")",
"for",
"x",
"in",
"arcname",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
")",
"arcname",
"=",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"x",
"for",
"x",
"in",
"arcname",
"if",
"x",
")",
"targetpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"targetpath",
",",
"arcname",
")",
"targetpath",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"targetpath",
")",
"# Create all upper directories if necessary.",
"upperdirs",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"targetpath",
")",
"if",
"upperdirs",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"upperdirs",
")",
":",
"os",
".",
"makedirs",
"(",
"upperdirs",
")",
"if",
"member",
".",
"filename",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"targetpath",
")",
":",
"os",
".",
"mkdir",
"(",
"targetpath",
")",
"return",
"targetpath",
"with",
"self",
".",
"open",
"(",
"member",
",",
"pwd",
"=",
"pwd",
")",
"as",
"source",
",",
"file",
"(",
"targetpath",
",",
"\"wb\"",
")",
"as",
"target",
":",
"shutil",
".",
"copyfileobj",
"(",
"source",
",",
"target",
")",
"return",
"targetpath"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py#L1038-L1082 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Caret_GetBlinkTime | (*args) | return _misc_.Caret_GetBlinkTime(*args) | Caret_GetBlinkTime() -> int | Caret_GetBlinkTime() -> int | [
"Caret_GetBlinkTime",
"()",
"-",
">",
"int"
] | def Caret_GetBlinkTime(*args):
"""Caret_GetBlinkTime() -> int"""
return _misc_.Caret_GetBlinkTime(*args) | [
"def",
"Caret_GetBlinkTime",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"Caret_GetBlinkTime",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L814-L816 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/algorithm_detail/calculate_sans_transmission.py | python | _perform_fit | (transmission_workspace, direct_workspace,
transmission_roi_detector_ids, transmission_monitor_detector_id,
incident_monitor_detector_id,
calculate_transmission_state, data_type, wav_range: WavRange) | return output_workspace, unfitted_transmission_workspace | This performs the actual transmission calculation.
:param transmission_workspace: the corrected transmission workspace
:param direct_workspace: the corrected direct workspace
:param transmission_roi_detector_ids: the roi detector ids
:param transmission_monitor_detector_id: the transmission monitor detector id
:param incident_monitor_detector_id: the incident monitor id
:param calculate_transmission_state: the state for the transmission calculation
:param data_type: the data type which is currently being investigated, ie if it is a sample or a can run.
:return: a fitted workspace and an unfitted workspace | This performs the actual transmission calculation. | [
"This",
"performs",
"the",
"actual",
"transmission",
"calculation",
"."
] | def _perform_fit(transmission_workspace, direct_workspace,
transmission_roi_detector_ids, transmission_monitor_detector_id,
incident_monitor_detector_id,
calculate_transmission_state, data_type, wav_range: WavRange):
"""
This performs the actual transmission calculation.
:param transmission_workspace: the corrected transmission workspace
:param direct_workspace: the corrected direct workspace
:param transmission_roi_detector_ids: the roi detector ids
:param transmission_monitor_detector_id: the transmission monitor detector id
:param incident_monitor_detector_id: the incident monitor id
:param calculate_transmission_state: the state for the transmission calculation
:param data_type: the data type which is currently being investigated, ie if it is a sample or a can run.
:return: a fitted workspace and an unfitted workspace
"""
wavelength_step = calculate_transmission_state.wavelength_interval.wavelength_step
wavelength_step_type = calculate_transmission_state.wavelength_step_type_lin_log
prefix = 1.0 if wavelength_step_type is RangeStepType.LIN else -1.0
wavelength_step *= prefix
rebin_params = f"{wav_range[0]}, {wavelength_step}, {wav_range[1]}"
trans_name = "CalculateTransmission"
trans_options = {"SampleRunWorkspace": transmission_workspace,
"DirectRunWorkspace": direct_workspace,
"OutputWorkspace": EMPTY_NAME,
"IncidentBeamMonitor": incident_monitor_detector_id,
"RebinParams": rebin_params,
"OutputUnfittedData": True}
# If we have a region of interest we use it else we use the transmission monitor
if len(transmission_roi_detector_ids) > 0:
trans_options.update({"TransmissionROI": transmission_roi_detector_ids})
elif transmission_monitor_detector_id is not None:
trans_options.update({"TransmissionMonitor": transmission_monitor_detector_id})
else:
raise RuntimeError("No transmission monitor has been provided.")
# Get the fit setting for the correct data type, ie either for the Sample of the Can
fit_type = calculate_transmission_state.fit[data_type.value].fit_type
if fit_type is FitType.LOGARITHMIC:
fit_string = "Log"
elif fit_type is FitType.POLYNOMIAL:
fit_string = "Polynomial"
else:
fit_string = "Linear"
trans_options.update({"FitMethod": fit_string})
if fit_type is FitType.POLYNOMIAL:
polynomial_order = calculate_transmission_state.fit[data_type.value].polynomial_order
trans_options.update({"PolynomialOrder": polynomial_order})
trans_alg = create_unmanaged_algorithm(trans_name, **trans_options)
trans_alg.execute()
fitted_transmission_workspace = trans_alg.getProperty("OutputWorkspace").value
try:
unfitted_transmission_workspace = trans_alg.getProperty("UnfittedData").value
except RuntimeError:
unfitted_transmission_workspace = None
# Set the y label correctly for the fitted and unfitted transmission workspaces
y_unit_label_transmission_ratio = "Transmission"
if fitted_transmission_workspace:
fitted_transmission_workspace.setYUnitLabel(y_unit_label_transmission_ratio)
if unfitted_transmission_workspace:
unfitted_transmission_workspace.setYUnitLabel(y_unit_label_transmission_ratio)
if fit_type is FitType.NO_FIT:
output_workspace = unfitted_transmission_workspace
else:
output_workspace = fitted_transmission_workspace
return output_workspace, unfitted_transmission_workspace | [
"def",
"_perform_fit",
"(",
"transmission_workspace",
",",
"direct_workspace",
",",
"transmission_roi_detector_ids",
",",
"transmission_monitor_detector_id",
",",
"incident_monitor_detector_id",
",",
"calculate_transmission_state",
",",
"data_type",
",",
"wav_range",
":",
"WavRange",
")",
":",
"wavelength_step",
"=",
"calculate_transmission_state",
".",
"wavelength_interval",
".",
"wavelength_step",
"wavelength_step_type",
"=",
"calculate_transmission_state",
".",
"wavelength_step_type_lin_log",
"prefix",
"=",
"1.0",
"if",
"wavelength_step_type",
"is",
"RangeStepType",
".",
"LIN",
"else",
"-",
"1.0",
"wavelength_step",
"*=",
"prefix",
"rebin_params",
"=",
"f\"{wav_range[0]}, {wavelength_step}, {wav_range[1]}\"",
"trans_name",
"=",
"\"CalculateTransmission\"",
"trans_options",
"=",
"{",
"\"SampleRunWorkspace\"",
":",
"transmission_workspace",
",",
"\"DirectRunWorkspace\"",
":",
"direct_workspace",
",",
"\"OutputWorkspace\"",
":",
"EMPTY_NAME",
",",
"\"IncidentBeamMonitor\"",
":",
"incident_monitor_detector_id",
",",
"\"RebinParams\"",
":",
"rebin_params",
",",
"\"OutputUnfittedData\"",
":",
"True",
"}",
"# If we have a region of interest we use it else we use the transmission monitor",
"if",
"len",
"(",
"transmission_roi_detector_ids",
")",
">",
"0",
":",
"trans_options",
".",
"update",
"(",
"{",
"\"TransmissionROI\"",
":",
"transmission_roi_detector_ids",
"}",
")",
"elif",
"transmission_monitor_detector_id",
"is",
"not",
"None",
":",
"trans_options",
".",
"update",
"(",
"{",
"\"TransmissionMonitor\"",
":",
"transmission_monitor_detector_id",
"}",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"No transmission monitor has been provided.\"",
")",
"# Get the fit setting for the correct data type, ie either for the Sample of the Can",
"fit_type",
"=",
"calculate_transmission_state",
".",
"fit",
"[",
"data_type",
".",
"value",
"]",
".",
"fit_type",
"if",
"fit_type",
"is",
"FitType",
".",
"LOGARITHMIC",
":",
"fit_string",
"=",
"\"Log\"",
"elif",
"fit_type",
"is",
"FitType",
".",
"POLYNOMIAL",
":",
"fit_string",
"=",
"\"Polynomial\"",
"else",
":",
"fit_string",
"=",
"\"Linear\"",
"trans_options",
".",
"update",
"(",
"{",
"\"FitMethod\"",
":",
"fit_string",
"}",
")",
"if",
"fit_type",
"is",
"FitType",
".",
"POLYNOMIAL",
":",
"polynomial_order",
"=",
"calculate_transmission_state",
".",
"fit",
"[",
"data_type",
".",
"value",
"]",
".",
"polynomial_order",
"trans_options",
".",
"update",
"(",
"{",
"\"PolynomialOrder\"",
":",
"polynomial_order",
"}",
")",
"trans_alg",
"=",
"create_unmanaged_algorithm",
"(",
"trans_name",
",",
"*",
"*",
"trans_options",
")",
"trans_alg",
".",
"execute",
"(",
")",
"fitted_transmission_workspace",
"=",
"trans_alg",
".",
"getProperty",
"(",
"\"OutputWorkspace\"",
")",
".",
"value",
"try",
":",
"unfitted_transmission_workspace",
"=",
"trans_alg",
".",
"getProperty",
"(",
"\"UnfittedData\"",
")",
".",
"value",
"except",
"RuntimeError",
":",
"unfitted_transmission_workspace",
"=",
"None",
"# Set the y label correctly for the fitted and unfitted transmission workspaces",
"y_unit_label_transmission_ratio",
"=",
"\"Transmission\"",
"if",
"fitted_transmission_workspace",
":",
"fitted_transmission_workspace",
".",
"setYUnitLabel",
"(",
"y_unit_label_transmission_ratio",
")",
"if",
"unfitted_transmission_workspace",
":",
"unfitted_transmission_workspace",
".",
"setYUnitLabel",
"(",
"y_unit_label_transmission_ratio",
")",
"if",
"fit_type",
"is",
"FitType",
".",
"NO_FIT",
":",
"output_workspace",
"=",
"unfitted_transmission_workspace",
"else",
":",
"output_workspace",
"=",
"fitted_transmission_workspace",
"return",
"output_workspace",
",",
"unfitted_transmission_workspace"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/calculate_sans_transmission.py#L75-L149 | |
wy1iu/LargeMargin_Softmax_Loss | c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec | tools/extra/parse_log.py | python | parse_log | (path_to_log) | return train_dict_list, test_dict_list | Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_list are lists of dicts that define the table
rows | Parse log file
Returns (train_dict_list, test_dict_list) | [
"Parse",
"log",
"file",
"Returns",
"(",
"train_dict_list",
"test_dict_list",
")"
] | def parse_log(path_to_log):
"""Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_list are lists of dicts that define the table
rows
"""
regex_iteration = re.compile('Iteration (\d+)')
regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_learning_rate = re.compile('lr = ([-+]?[0-9]*\.?[0-9]+([eE]?[-+]?[0-9]+)?)')
# Pick out lines of interest
iteration = -1
learning_rate = float('NaN')
train_dict_list = []
test_dict_list = []
train_row = None
test_row = None
logfile_year = extract_seconds.get_log_created_year(path_to_log)
with open(path_to_log) as f:
start_time = extract_seconds.get_start_time(f, logfile_year)
for line in f:
iteration_match = regex_iteration.search(line)
if iteration_match:
iteration = float(iteration_match.group(1))
if iteration == -1:
# Only start parsing for other stuff if we've found the first
# iteration
continue
time = extract_seconds.extract_datetime_from_line(line,
logfile_year)
seconds = (time - start_time).total_seconds()
learning_rate_match = regex_learning_rate.search(line)
if learning_rate_match:
learning_rate = float(learning_rate_match.group(1))
train_dict_list, train_row = parse_line_for_net_output(
regex_train_output, train_row, train_dict_list,
line, iteration, seconds, learning_rate
)
test_dict_list, test_row = parse_line_for_net_output(
regex_test_output, test_row, test_dict_list,
line, iteration, seconds, learning_rate
)
fix_initial_nan_learning_rate(train_dict_list)
fix_initial_nan_learning_rate(test_dict_list)
return train_dict_list, test_dict_list | [
"def",
"parse_log",
"(",
"path_to_log",
")",
":",
"regex_iteration",
"=",
"re",
".",
"compile",
"(",
"'Iteration (\\d+)'",
")",
"regex_train_output",
"=",
"re",
".",
"compile",
"(",
"'Train net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'",
")",
"regex_test_output",
"=",
"re",
".",
"compile",
"(",
"'Test net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'",
")",
"regex_learning_rate",
"=",
"re",
".",
"compile",
"(",
"'lr = ([-+]?[0-9]*\\.?[0-9]+([eE]?[-+]?[0-9]+)?)'",
")",
"# Pick out lines of interest",
"iteration",
"=",
"-",
"1",
"learning_rate",
"=",
"float",
"(",
"'NaN'",
")",
"train_dict_list",
"=",
"[",
"]",
"test_dict_list",
"=",
"[",
"]",
"train_row",
"=",
"None",
"test_row",
"=",
"None",
"logfile_year",
"=",
"extract_seconds",
".",
"get_log_created_year",
"(",
"path_to_log",
")",
"with",
"open",
"(",
"path_to_log",
")",
"as",
"f",
":",
"start_time",
"=",
"extract_seconds",
".",
"get_start_time",
"(",
"f",
",",
"logfile_year",
")",
"for",
"line",
"in",
"f",
":",
"iteration_match",
"=",
"regex_iteration",
".",
"search",
"(",
"line",
")",
"if",
"iteration_match",
":",
"iteration",
"=",
"float",
"(",
"iteration_match",
".",
"group",
"(",
"1",
")",
")",
"if",
"iteration",
"==",
"-",
"1",
":",
"# Only start parsing for other stuff if we've found the first",
"# iteration",
"continue",
"time",
"=",
"extract_seconds",
".",
"extract_datetime_from_line",
"(",
"line",
",",
"logfile_year",
")",
"seconds",
"=",
"(",
"time",
"-",
"start_time",
")",
".",
"total_seconds",
"(",
")",
"learning_rate_match",
"=",
"regex_learning_rate",
".",
"search",
"(",
"line",
")",
"if",
"learning_rate_match",
":",
"learning_rate",
"=",
"float",
"(",
"learning_rate_match",
".",
"group",
"(",
"1",
")",
")",
"train_dict_list",
",",
"train_row",
"=",
"parse_line_for_net_output",
"(",
"regex_train_output",
",",
"train_row",
",",
"train_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
"test_dict_list",
",",
"test_row",
"=",
"parse_line_for_net_output",
"(",
"regex_test_output",
",",
"test_row",
",",
"test_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
"fix_initial_nan_learning_rate",
"(",
"train_dict_list",
")",
"fix_initial_nan_learning_rate",
"(",
"test_dict_list",
")",
"return",
"train_dict_list",
",",
"test_dict_list"
] | https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/tools/extra/parse_log.py#L17-L71 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/xlsgrid.py | python | XLSText.CreateFormat | (self, format, cell, datemode) | This method tries to guess the best format to apply to the current text
value.
:param `format`: an instance of `xlrd.formatting.Format` class;
:param `cell`: an instance of `xlrd.sheet.Cell` class;
:param `datemode`: the datemode associated with this Excel workbook.
:note: This method is used only if Mark Hammonds' `pywin32` package is
not available to try and format the cell text in an intelligent way.
.. warning::
The formatting applied by this method is severely limited; for
instance, you won't probably get the exact WYSIWYG between the Excel
spreadsheet and :class:`XLSGrid`. | This method tries to guess the best format to apply to the current text
value. | [
"This",
"method",
"tries",
"to",
"guess",
"the",
"best",
"format",
"to",
"apply",
"to",
"the",
"current",
"text",
"value",
"."
] | def CreateFormat(self, format, cell, datemode):
"""
This method tries to guess the best format to apply to the current text
value.
:param `format`: an instance of `xlrd.formatting.Format` class;
:param `cell`: an instance of `xlrd.sheet.Cell` class;
:param `datemode`: the datemode associated with this Excel workbook.
:note: This method is used only if Mark Hammonds' `pywin32` package is
not available to try and format the cell text in an intelligent way.
.. warning::
The formatting applied by this method is severely limited; for
instance, you won't probably get the exact WYSIWYG between the Excel
spreadsheet and :class:`XLSGrid`.
"""
ctype, value = cell.ctype, cell.value
self.value = "%s"%value
isDate = False
if ctype == xlrd.XL_CELL_DATE:
value = xlrd.xldate_as_tuple(value, datemode)
isDate = True
elif ctype in [xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK]:
return
elif ctype == xlrd.XL_CELL_TEXT:
self.value = "%s"%value
return
elif ctype == xlrd.XL_CELL_ERROR:
value = xlrd.error_text_from_code(ctype)
self.value = "%s"%value
return
self.FormatString(value, isDate, format.format_str) | [
"def",
"CreateFormat",
"(",
"self",
",",
"format",
",",
"cell",
",",
"datemode",
")",
":",
"ctype",
",",
"value",
"=",
"cell",
".",
"ctype",
",",
"cell",
".",
"value",
"self",
".",
"value",
"=",
"\"%s\"",
"%",
"value",
"isDate",
"=",
"False",
"if",
"ctype",
"==",
"xlrd",
".",
"XL_CELL_DATE",
":",
"value",
"=",
"xlrd",
".",
"xldate_as_tuple",
"(",
"value",
",",
"datemode",
")",
"isDate",
"=",
"True",
"elif",
"ctype",
"in",
"[",
"xlrd",
".",
"XL_CELL_EMPTY",
",",
"xlrd",
".",
"XL_CELL_BLANK",
"]",
":",
"return",
"elif",
"ctype",
"==",
"xlrd",
".",
"XL_CELL_TEXT",
":",
"self",
".",
"value",
"=",
"\"%s\"",
"%",
"value",
"return",
"elif",
"ctype",
"==",
"xlrd",
".",
"XL_CELL_ERROR",
":",
"value",
"=",
"xlrd",
".",
"error_text_from_code",
"(",
"ctype",
")",
"self",
".",
"value",
"=",
"\"%s\"",
"%",
"value",
"return",
"self",
".",
"FormatString",
"(",
"value",
",",
"isDate",
",",
"format",
".",
"format_str",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/xlsgrid.py#L746-L783 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/find-the-duplicate-number.py | python | Solution2.findDuplicate | (self, nums) | return left | :type nums: List[int]
:rtype: int | :type nums: List[int]
:rtype: int | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 1, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
# Get count of num <= mid.
count = 0
for num in nums:
if num <= mid:
count += 1
if count > mid:
right = mid - 1
else:
left = mid + 1
return left | [
"def",
"findDuplicate",
"(",
"self",
",",
"nums",
")",
":",
"left",
",",
"right",
"=",
"1",
",",
"len",
"(",
"nums",
")",
"-",
"1",
"while",
"left",
"<=",
"right",
":",
"mid",
"=",
"left",
"+",
"(",
"right",
"-",
"left",
")",
"/",
"2",
"# Get count of num <= mid.",
"count",
"=",
"0",
"for",
"num",
"in",
"nums",
":",
"if",
"num",
"<=",
"mid",
":",
"count",
"+=",
"1",
"if",
"count",
">",
"mid",
":",
"right",
"=",
"mid",
"-",
"1",
"else",
":",
"left",
"=",
"mid",
"+",
"1",
"return",
"left"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-the-duplicate-number.py#L31-L49 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py | python | DirichletMultinomial._check_counts | (self, counts) | return control_flow_ops.with_dependencies([
check_ops.assert_non_negative(counts),
check_ops.assert_equal(
self._n, candidate_n,
message="counts do not sum to n"
),
distribution_util.assert_integer_form(counts)], counts) | Check counts for proper shape, values, then return tensor version. | Check counts for proper shape, values, then return tensor version. | [
"Check",
"counts",
"for",
"proper",
"shape",
"values",
"then",
"return",
"tensor",
"version",
"."
] | def _check_counts(self, counts):
"""Check counts for proper shape, values, then return tensor version."""
counts = ops.convert_to_tensor(counts, name="counts")
if not self.validate_args:
return counts
candidate_n = math_ops.reduce_sum(counts, reduction_indices=[-1])
return control_flow_ops.with_dependencies([
check_ops.assert_non_negative(counts),
check_ops.assert_equal(
self._n, candidate_n,
message="counts do not sum to n"
),
distribution_util.assert_integer_form(counts)], counts) | [
"def",
"_check_counts",
"(",
"self",
",",
"counts",
")",
":",
"counts",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"counts",
",",
"name",
"=",
"\"counts\"",
")",
"if",
"not",
"self",
".",
"validate_args",
":",
"return",
"counts",
"candidate_n",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"counts",
",",
"reduction_indices",
"=",
"[",
"-",
"1",
"]",
")",
"return",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"check_ops",
".",
"assert_non_negative",
"(",
"counts",
")",
",",
"check_ops",
".",
"assert_equal",
"(",
"self",
".",
"_n",
",",
"candidate_n",
",",
"message",
"=",
"\"counts do not sum to n\"",
")",
",",
"distribution_util",
".",
"assert_integer_form",
"(",
"counts",
")",
"]",
",",
"counts",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py#L363-L376 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/Pharm3D/EmbedLib.py | python | ComputeChiralVolume | (mol, centerIdx, confId=-1) | return v1.DotProduct(v2.CrossProduct(v3)) | Computes the chiral volume of an atom
We're using the chiral volume formula from Figure 7 of
Blaney and Dixon, Rev. Comp. Chem. V, 299-335 (1994)
>>> import os.path
>>> from rdkit import RDConfig
>>> dataDir = os.path.join(RDConfig.RDCodeDir,'Chem/Pharm3D/test_data')
R configuration atoms give negative volumes:
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-r.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'R'
>>> ComputeChiralVolume(mol, 1) < 0
True
S configuration atoms give positive volumes:
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-s.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'S'
>>> ComputeChiralVolume(mol, 1) > 0
True
Non-chiral (or non-specified) atoms give zero volume:
>>> ComputeChiralVolume(mol, 0) == 0.0
True
We also work on 3-coordinate atoms (with implicit Hs):
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-r-3.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'R'
>>> ComputeChiralVolume(mol, 1) < 0
True
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-s-3.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'S'
>>> ComputeChiralVolume(mol, 1) > 0
True | Computes the chiral volume of an atom | [
"Computes",
"the",
"chiral",
"volume",
"of",
"an",
"atom"
] | def ComputeChiralVolume(mol, centerIdx, confId=-1):
""" Computes the chiral volume of an atom
We're using the chiral volume formula from Figure 7 of
Blaney and Dixon, Rev. Comp. Chem. V, 299-335 (1994)
>>> import os.path
>>> from rdkit import RDConfig
>>> dataDir = os.path.join(RDConfig.RDCodeDir,'Chem/Pharm3D/test_data')
R configuration atoms give negative volumes:
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-r.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'R'
>>> ComputeChiralVolume(mol, 1) < 0
True
S configuration atoms give positive volumes:
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-s.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'S'
>>> ComputeChiralVolume(mol, 1) > 0
True
Non-chiral (or non-specified) atoms give zero volume:
>>> ComputeChiralVolume(mol, 0) == 0.0
True
We also work on 3-coordinate atoms (with implicit Hs):
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-r-3.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'R'
>>> ComputeChiralVolume(mol, 1) < 0
True
>>> mol = Chem.MolFromMolFile(os.path.join(dataDir, 'mol-s-3.mol'))
>>> Chem.AssignStereochemistry(mol)
>>> mol.GetAtomWithIdx(1).GetProp('_CIPCode')
'S'
>>> ComputeChiralVolume(mol, 1) > 0
True
"""
conf = mol.GetConformer(confId)
Chem.AssignStereochemistry(mol)
center = mol.GetAtomWithIdx(centerIdx)
if not center.HasProp('_CIPCode'):
return 0.0
nbrs = center.GetNeighbors()
nbrRanks = [(int(nbr.GetProp('_CIPRank')), conf.GetAtomPosition(nbr.GetIdx()))
for nbr in nbrs]
# if we only have three neighbors (i.e. the determining H isn't present)
# then use the central atom as the fourth point:
if len(nbrRanks) == 3:
nbrRanks.append((-1, conf.GetAtomPosition(centerIdx)))
nbrRanks.sort()
ps = [x[1] for x in nbrRanks]
v1 = ps[0] - ps[3]
v2 = ps[1] - ps[3]
v3 = ps[2] - ps[3]
return v1.DotProduct(v2.CrossProduct(v3)) | [
"def",
"ComputeChiralVolume",
"(",
"mol",
",",
"centerIdx",
",",
"confId",
"=",
"-",
"1",
")",
":",
"conf",
"=",
"mol",
".",
"GetConformer",
"(",
"confId",
")",
"Chem",
".",
"AssignStereochemistry",
"(",
"mol",
")",
"center",
"=",
"mol",
".",
"GetAtomWithIdx",
"(",
"centerIdx",
")",
"if",
"not",
"center",
".",
"HasProp",
"(",
"'_CIPCode'",
")",
":",
"return",
"0.0",
"nbrs",
"=",
"center",
".",
"GetNeighbors",
"(",
")",
"nbrRanks",
"=",
"[",
"(",
"int",
"(",
"nbr",
".",
"GetProp",
"(",
"'_CIPRank'",
")",
")",
",",
"conf",
".",
"GetAtomPosition",
"(",
"nbr",
".",
"GetIdx",
"(",
")",
")",
")",
"for",
"nbr",
"in",
"nbrs",
"]",
"# if we only have three neighbors (i.e. the determining H isn't present)",
"# then use the central atom as the fourth point:",
"if",
"len",
"(",
"nbrRanks",
")",
"==",
"3",
":",
"nbrRanks",
".",
"append",
"(",
"(",
"-",
"1",
",",
"conf",
".",
"GetAtomPosition",
"(",
"centerIdx",
")",
")",
")",
"nbrRanks",
".",
"sort",
"(",
")",
"ps",
"=",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"nbrRanks",
"]",
"v1",
"=",
"ps",
"[",
"0",
"]",
"-",
"ps",
"[",
"3",
"]",
"v2",
"=",
"ps",
"[",
"1",
"]",
"-",
"ps",
"[",
"3",
"]",
"v3",
"=",
"ps",
"[",
"2",
"]",
"-",
"ps",
"[",
"3",
"]",
"return",
"v1",
".",
"DotProduct",
"(",
"v2",
".",
"CrossProduct",
"(",
"v3",
")",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/Pharm3D/EmbedLib.py#L1210-L1281 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py | python | _ZipDecrypter._crc32 | (self, ch, crc) | return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] | Compute the CRC32 primitive on one byte. | Compute the CRC32 primitive on one byte. | [
"Compute",
"the",
"CRC32",
"primitive",
"on",
"one",
"byte",
"."
] | def _crc32(self, ch, crc):
"""Compute the CRC32 primitive on one byte."""
return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] | [
"def",
"_crc32",
"(",
"self",
",",
"ch",
",",
"crc",
")",
":",
"return",
"(",
"(",
"crc",
">>",
"8",
")",
"&",
"0xffffff",
")",
"^",
"self",
".",
"crctable",
"[",
"(",
"crc",
"^",
"ord",
"(",
"ch",
")",
")",
"&",
"0xff",
"]"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/zipfile.py#L453-L455 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/xTelescope.py | python | xTelescope.OnNotify | (self,state,id,events) | Activated... start telescope | Activated... start telescope | [
"Activated",
"...",
"start",
"telescope"
] | def OnNotify(self,state,id,events):
"Activated... start telescope"
global LocalAvatar
global boolScopeOperator
PtDebugPrint("xTelescope:OnNotify state=%f id=%d events=" % (state,id),events,level=kDebugDumpLevel)
if state and id == Activate.id and PtWasLocallyNotified(self.key):
LocalAvatar = PtFindAvatar(events)
self.IStartTelescope()
# check if its an advance stage notify
for event in events:
if event[0] == kMultiStageEvent and event[1] == 0 and event[2] == kAdvanceNextStage:
if boolScopeOperator:
self.IEngageTelescope()
boolScopeOperator = 0
break | [
"def",
"OnNotify",
"(",
"self",
",",
"state",
",",
"id",
",",
"events",
")",
":",
"global",
"LocalAvatar",
"global",
"boolScopeOperator",
"PtDebugPrint",
"(",
"\"xTelescope:OnNotify state=%f id=%d events=\"",
"%",
"(",
"state",
",",
"id",
")",
",",
"events",
",",
"level",
"=",
"kDebugDumpLevel",
")",
"if",
"state",
"and",
"id",
"==",
"Activate",
".",
"id",
"and",
"PtWasLocallyNotified",
"(",
"self",
".",
"key",
")",
":",
"LocalAvatar",
"=",
"PtFindAvatar",
"(",
"events",
")",
"self",
".",
"IStartTelescope",
"(",
")",
"# check if its an advance stage notify",
"for",
"event",
"in",
"events",
":",
"if",
"event",
"[",
"0",
"]",
"==",
"kMultiStageEvent",
"and",
"event",
"[",
"1",
"]",
"==",
"0",
"and",
"event",
"[",
"2",
"]",
"==",
"kAdvanceNextStage",
":",
"if",
"boolScopeOperator",
":",
"self",
".",
"IEngageTelescope",
"(",
")",
"boolScopeOperator",
"=",
"0",
"break"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xTelescope.py#L126-L140 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | AuiPaneInfo.Maximize | (*args, **kwargs) | return _aui.AuiPaneInfo_Maximize(*args, **kwargs) | Maximize(self) -> AuiPaneInfo | Maximize(self) -> AuiPaneInfo | [
"Maximize",
"(",
"self",
")",
"-",
">",
"AuiPaneInfo"
] | def Maximize(*args, **kwargs):
"""Maximize(self) -> AuiPaneInfo"""
return _aui.AuiPaneInfo_Maximize(*args, **kwargs) | [
"def",
"Maximize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_Maximize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L437-L439 | |
google/perfetto | fe68c7a7f7657aa71ced68efb126dcac4107c745 | gn/standalone/toolchain/win_find_msvc.py | python | ver_to_tuple | (ver_str) | return parts | Turns '10.1.2' into [10,1,2] so it can be compared using > | Turns '10.1.2' into [10,1,2] so it can be compared using > | [
"Turns",
"10",
".",
"1",
".",
"2",
"into",
"[",
"10",
"1",
"2",
"]",
"so",
"it",
"can",
"be",
"compared",
"using",
">"
] | def ver_to_tuple(ver_str):
"""Turns '10.1.2' into [10,1,2] so it can be compared using > """
parts = [int(x) for x in ver_str.split('.')]
assert (len(parts) == 4)
return parts | [
"def",
"ver_to_tuple",
"(",
"ver_str",
")",
":",
"parts",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"ver_str",
".",
"split",
"(",
"'.'",
")",
"]",
"assert",
"(",
"len",
"(",
"parts",
")",
"==",
"4",
")",
"return",
"parts"
] | https://github.com/google/perfetto/blob/fe68c7a7f7657aa71ced68efb126dcac4107c745/gn/standalone/toolchain/win_find_msvc.py#L34-L38 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py | python | _linear_learning_rate | (num_linear_feature_columns) | return min(_LINEAR_LEARNING_RATE, default_learning_rate) | Returns the default learning rate of the linear model.
The calculation is a historical artifact of this initial implementation, but
has proven a reasonable choice.
Args:
num_linear_feature_columns: The number of feature columns of the linear
model.
Returns:
A float. | Returns the default learning rate of the linear model. | [
"Returns",
"the",
"default",
"learning",
"rate",
"of",
"the",
"linear",
"model",
"."
] | def _linear_learning_rate(num_linear_feature_columns):
"""Returns the default learning rate of the linear model.
The calculation is a historical artifact of this initial implementation, but
has proven a reasonable choice.
Args:
num_linear_feature_columns: The number of feature columns of the linear
model.
Returns:
A float.
"""
default_learning_rate = 1. / math.sqrt(num_linear_feature_columns)
return min(_LINEAR_LEARNING_RATE, default_learning_rate) | [
"def",
"_linear_learning_rate",
"(",
"num_linear_feature_columns",
")",
":",
"default_learning_rate",
"=",
"1.",
"/",
"math",
".",
"sqrt",
"(",
"num_linear_feature_columns",
")",
"return",
"min",
"(",
"_LINEAR_LEARNING_RATE",
",",
"default_learning_rate",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L86-L100 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/training/queue_runner.py | python | QueueRunner._run | (self, sess, enqueue_op, coord=None) | Execute the enqueue op in a loop, close the queue in case of error.
Args:
sess: A Session.
enqueue_op: The Operation to run.
coord: Optional Coordinator object for reporting errors and checking
for stop conditions. | Execute the enqueue op in a loop, close the queue in case of error. | [
"Execute",
"the",
"enqueue",
"op",
"in",
"a",
"loop",
"close",
"the",
"queue",
"in",
"case",
"of",
"error",
"."
] | def _run(self, sess, enqueue_op, coord=None):
"""Execute the enqueue op in a loop, close the queue in case of error.
Args:
sess: A Session.
enqueue_op: The Operation to run.
coord: Optional Coordinator object for reporting errors and checking
for stop conditions.
"""
if coord:
coord.register_thread(threading.current_thread())
decremented = False
try:
while True:
if coord and coord.should_stop():
break
try:
sess.run(enqueue_op)
except errors.OutOfRangeError:
# This exception indicates that a queue was closed.
with self._lock:
self._runs -= 1
decremented = True
if self._runs == 0:
try:
sess.run(self._close_op)
except Exception as e:
# Intentionally ignore errors from close_op.
logging.vlog(1, "Ignored exception: %s", str(e))
return
except Exception as e:
# This catches all other exceptions.
if coord:
coord.request_stop(e)
else:
logging.error("Exception in QueueRunner: %s", str(e))
with self._lock:
self._exceptions_raised.append(e)
raise
finally:
# Make sure we account for all terminations: normal or errors.
if not decremented:
with self._lock:
self._runs -= 1 | [
"def",
"_run",
"(",
"self",
",",
"sess",
",",
"enqueue_op",
",",
"coord",
"=",
"None",
")",
":",
"if",
"coord",
":",
"coord",
".",
"register_thread",
"(",
"threading",
".",
"current_thread",
"(",
")",
")",
"decremented",
"=",
"False",
"try",
":",
"while",
"True",
":",
"if",
"coord",
"and",
"coord",
".",
"should_stop",
"(",
")",
":",
"break",
"try",
":",
"sess",
".",
"run",
"(",
"enqueue_op",
")",
"except",
"errors",
".",
"OutOfRangeError",
":",
"# This exception indicates that a queue was closed.",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_runs",
"-=",
"1",
"decremented",
"=",
"True",
"if",
"self",
".",
"_runs",
"==",
"0",
":",
"try",
":",
"sess",
".",
"run",
"(",
"self",
".",
"_close_op",
")",
"except",
"Exception",
"as",
"e",
":",
"# Intentionally ignore errors from close_op.",
"logging",
".",
"vlog",
"(",
"1",
",",
"\"Ignored exception: %s\"",
",",
"str",
"(",
"e",
")",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"# This catches all other exceptions.",
"if",
"coord",
":",
"coord",
".",
"request_stop",
"(",
"e",
")",
"else",
":",
"logging",
".",
"error",
"(",
"\"Exception in QueueRunner: %s\"",
",",
"str",
"(",
"e",
")",
")",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_exceptions_raised",
".",
"append",
"(",
"e",
")",
"raise",
"finally",
":",
"# Make sure we account for all terminations: normal or errors.",
"if",
"not",
"decremented",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_runs",
"-=",
"1"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/queue_runner.py#L170-L213 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/copy_helper.py | python | _PartitionObject | (src_url, src_obj_metadata, dst_url,
download_file_name) | return components_to_download, component_lengths | Partitions an object into components to be downloaded.
Each component is a byte range of the object. The byte ranges
of the returned components are mutually exclusive and collectively
exhaustive. The byte ranges are inclusive at both end points.
Args:
src_url: Source CloudUrl.
src_obj_metadata: Metadata from the source object.
dst_url: Destination FileUrl.
download_file_name: Temporary file name to be used for the download.
Returns:
components_to_download: A list of PerformSlicedDownloadObjectToFileArgs
to be used in Apply for the sliced download. | Partitions an object into components to be downloaded. | [
"Partitions",
"an",
"object",
"into",
"components",
"to",
"be",
"downloaded",
"."
] | def _PartitionObject(src_url, src_obj_metadata, dst_url,
download_file_name):
"""Partitions an object into components to be downloaded.
Each component is a byte range of the object. The byte ranges
of the returned components are mutually exclusive and collectively
exhaustive. The byte ranges are inclusive at both end points.
Args:
src_url: Source CloudUrl.
src_obj_metadata: Metadata from the source object.
dst_url: Destination FileUrl.
download_file_name: Temporary file name to be used for the download.
Returns:
components_to_download: A list of PerformSlicedDownloadObjectToFileArgs
to be used in Apply for the sliced download.
"""
sliced_download_component_size = HumanReadableToBytes(
config.get('GSUtil', 'sliced_object_download_component_size',
DEFAULT_SLICED_OBJECT_DOWNLOAD_COMPONENT_SIZE))
max_components = config.getint(
'GSUtil', 'sliced_object_download_max_components',
DEFAULT_SLICED_OBJECT_DOWNLOAD_MAX_COMPONENTS)
num_components, component_size = _GetPartitionInfo(
src_obj_metadata.size, max_components, sliced_download_component_size)
components_to_download = []
component_lengths = []
for i in range(num_components):
start_byte = i * component_size
end_byte = min((i + 1) * (component_size) - 1, src_obj_metadata.size - 1)
component_lengths.append(end_byte - start_byte + 1)
components_to_download.append(
PerformSlicedDownloadObjectToFileArgs(
i, src_url, src_obj_metadata, dst_url, download_file_name,
start_byte, end_byte))
return components_to_download, component_lengths | [
"def",
"_PartitionObject",
"(",
"src_url",
",",
"src_obj_metadata",
",",
"dst_url",
",",
"download_file_name",
")",
":",
"sliced_download_component_size",
"=",
"HumanReadableToBytes",
"(",
"config",
".",
"get",
"(",
"'GSUtil'",
",",
"'sliced_object_download_component_size'",
",",
"DEFAULT_SLICED_OBJECT_DOWNLOAD_COMPONENT_SIZE",
")",
")",
"max_components",
"=",
"config",
".",
"getint",
"(",
"'GSUtil'",
",",
"'sliced_object_download_max_components'",
",",
"DEFAULT_SLICED_OBJECT_DOWNLOAD_MAX_COMPONENTS",
")",
"num_components",
",",
"component_size",
"=",
"_GetPartitionInfo",
"(",
"src_obj_metadata",
".",
"size",
",",
"max_components",
",",
"sliced_download_component_size",
")",
"components_to_download",
"=",
"[",
"]",
"component_lengths",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_components",
")",
":",
"start_byte",
"=",
"i",
"*",
"component_size",
"end_byte",
"=",
"min",
"(",
"(",
"i",
"+",
"1",
")",
"*",
"(",
"component_size",
")",
"-",
"1",
",",
"src_obj_metadata",
".",
"size",
"-",
"1",
")",
"component_lengths",
".",
"append",
"(",
"end_byte",
"-",
"start_byte",
"+",
"1",
")",
"components_to_download",
".",
"append",
"(",
"PerformSlicedDownloadObjectToFileArgs",
"(",
"i",
",",
"src_url",
",",
"src_obj_metadata",
",",
"dst_url",
",",
"download_file_name",
",",
"start_byte",
",",
"end_byte",
")",
")",
"return",
"components_to_download",
",",
"component_lengths"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/copy_helper.py#L1950-L1989 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py | python | MyNavigationToolbar.draw | (self) | return | Canvas is drawn called by pan(), zoom()
:return: | Canvas is drawn called by pan(), zoom()
:return: | [
"Canvas",
"is",
"drawn",
"called",
"by",
"pan",
"()",
"zoom",
"()",
":",
"return",
":"
] | def draw(self):
"""
Canvas is drawn called by pan(), zoom()
:return:
"""
NavigationToolbar2.draw(self)
self._myParent.evt_view_updated()
return | [
"def",
"draw",
"(",
"self",
")",
":",
"NavigationToolbar2",
".",
"draw",
"(",
"self",
")",
"self",
".",
"_myParent",
".",
"evt_view_updated",
"(",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py#L1849-L1858 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/combo.py | python | BitmapComboBox.GetBitmapSize | (*args, **kwargs) | return _combo.BitmapComboBox_GetBitmapSize(*args, **kwargs) | GetBitmapSize(self) -> Size
Returns size of the image used in list. | GetBitmapSize(self) -> Size | [
"GetBitmapSize",
"(",
"self",
")",
"-",
">",
"Size"
] | def GetBitmapSize(*args, **kwargs):
"""
GetBitmapSize(self) -> Size
Returns size of the image used in list.
"""
return _combo.BitmapComboBox_GetBitmapSize(*args, **kwargs) | [
"def",
"GetBitmapSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"BitmapComboBox_GetBitmapSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L1005-L1011 | |
leela-zero/leela-zero | e3ed6310d33d75078ba74c3adf887d18439fc2e3 | scripts/cpplint.py | python | CheckForIncludeWhatYouUse | (filename, clean_lines, include_state, error,
io=codecs) | Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection. | Reports for missing stl includes. | [
"Reports",
"for",
"missing",
"stl",
"includes",
"."
] | def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
io=codecs):
"""Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection.
"""
required = {} # A map of header name to linenumber and the template entity.
# Example of required: { '<functional>': (1219, 'less<>') }
for linenum in xrange(clean_lines.NumLines()):
line = clean_lines.elided[linenum]
if not line or line[0] == '#':
continue
# String is special -- it is a non-templatized type in STL.
matched = _RE_PATTERN_STRING.search(line)
if matched:
# Don't warn about strings in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required['<string>'] = (linenum, 'string')
for pattern, template, header in _re_pattern_algorithm_header:
if pattern.search(line):
required[header] = (linenum, template)
# The following function is just a speed up, no semantics are changed.
if not '<' in line: # Reduces the cpu time usage by skipping lines.
continue
for pattern, template, header in _re_pattern_templates:
if pattern.search(line):
required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.
# Let's flatten the include_state include_list and copy it into a dictionary.
include_dict = dict([item for sublist in include_state.include_list
for item in sublist])
# Did we find the header for this file (if any) and successfully load it?
header_found = False
# Use the absolute path so that matching works properly.
abs_filename = FileInfo(filename).FullName()
# For Emacs's flymake.
# If cpplint is invoked from Emacs's flymake, a temporary file is generated
# by flymake and that file name might end with '_flymake.cc'. In that case,
# restore original file name here so that the corresponding header file can be
# found.
# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
# instead of 'foo_flymake.h'
abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
# include_dict is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = include_dict.keys()
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
if same_module and UpdateIncludeState(fullpath, include_dict, io):
header_found = True
# If we can't find the header file for a .cc, assume it's because we don't
# know where to look. In that case we'll give up as we're not sure they
# didn't include it in the .h file.
# TODO(unknown): Do a better job of finding .h files so we are confident that
# not having the .h file means there isn't one.
if filename.endswith('.cc') and not header_found:
return
# All the lines have been processed, report the errors found.
for required_header_unstripped in required:
template = required[required_header_unstripped][1]
if required_header_unstripped.strip('<>"') not in include_dict:
error(filename, required[required_header_unstripped][0],
'build/include_what_you_use', 4,
'Add #include ' + required_header_unstripped + ' for ' + template) | [
"def",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
",",
"io",
"=",
"codecs",
")",
":",
"required",
"=",
"{",
"}",
"# A map of header name to linenumber and the template entity.",
"# Example of required: { '<functional>': (1219, 'less<>') }",
"for",
"linenum",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"not",
"line",
"or",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"# String is special -- it is a non-templatized type in STL.",
"matched",
"=",
"_RE_PATTERN_STRING",
".",
"search",
"(",
"line",
")",
"if",
"matched",
":",
"# Don't warn about strings in non-STL namespaces:",
"# (We check only the first match per line; good enough.)",
"prefix",
"=",
"line",
"[",
":",
"matched",
".",
"start",
"(",
")",
"]",
"if",
"prefix",
".",
"endswith",
"(",
"'std::'",
")",
"or",
"not",
"prefix",
".",
"endswith",
"(",
"'::'",
")",
":",
"required",
"[",
"'<string>'",
"]",
"=",
"(",
"linenum",
",",
"'string'",
")",
"for",
"pattern",
",",
"template",
",",
"header",
"in",
"_re_pattern_algorithm_header",
":",
"if",
"pattern",
".",
"search",
"(",
"line",
")",
":",
"required",
"[",
"header",
"]",
"=",
"(",
"linenum",
",",
"template",
")",
"# The following function is just a speed up, no semantics are changed.",
"if",
"not",
"'<'",
"in",
"line",
":",
"# Reduces the cpu time usage by skipping lines.",
"continue",
"for",
"pattern",
",",
"template",
",",
"header",
"in",
"_re_pattern_templates",
":",
"if",
"pattern",
".",
"search",
"(",
"line",
")",
":",
"required",
"[",
"header",
"]",
"=",
"(",
"linenum",
",",
"template",
")",
"# The policy is that if you #include something in foo.h you don't need to",
"# include it again in foo.cc. Here, we will look at possible includes.",
"# Let's flatten the include_state include_list and copy it into a dictionary.",
"include_dict",
"=",
"dict",
"(",
"[",
"item",
"for",
"sublist",
"in",
"include_state",
".",
"include_list",
"for",
"item",
"in",
"sublist",
"]",
")",
"# Did we find the header for this file (if any) and successfully load it?",
"header_found",
"=",
"False",
"# Use the absolute path so that matching works properly.",
"abs_filename",
"=",
"FileInfo",
"(",
"filename",
")",
".",
"FullName",
"(",
")",
"# For Emacs's flymake.",
"# If cpplint is invoked from Emacs's flymake, a temporary file is generated",
"# by flymake and that file name might end with '_flymake.cc'. In that case,",
"# restore original file name here so that the corresponding header file can be",
"# found.",
"# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'",
"# instead of 'foo_flymake.h'",
"abs_filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.cc$'",
",",
"'.cc'",
",",
"abs_filename",
")",
"# include_dict is modified during iteration, so we iterate over a copy of",
"# the keys.",
"header_keys",
"=",
"include_dict",
".",
"keys",
"(",
")",
"for",
"header",
"in",
"header_keys",
":",
"(",
"same_module",
",",
"common_path",
")",
"=",
"FilesBelongToSameModule",
"(",
"abs_filename",
",",
"header",
")",
"fullpath",
"=",
"common_path",
"+",
"header",
"if",
"same_module",
"and",
"UpdateIncludeState",
"(",
"fullpath",
",",
"include_dict",
",",
"io",
")",
":",
"header_found",
"=",
"True",
"# If we can't find the header file for a .cc, assume it's because we don't",
"# know where to look. In that case we'll give up as we're not sure they",
"# didn't include it in the .h file.",
"# TODO(unknown): Do a better job of finding .h files so we are confident that",
"# not having the .h file means there isn't one.",
"if",
"filename",
".",
"endswith",
"(",
"'.cc'",
")",
"and",
"not",
"header_found",
":",
"return",
"# All the lines have been processed, report the errors found.",
"for",
"required_header_unstripped",
"in",
"required",
":",
"template",
"=",
"required",
"[",
"required_header_unstripped",
"]",
"[",
"1",
"]",
"if",
"required_header_unstripped",
".",
"strip",
"(",
"'<>\"'",
")",
"not",
"in",
"include_dict",
":",
"error",
"(",
"filename",
",",
"required",
"[",
"required_header_unstripped",
"]",
"[",
"0",
"]",
",",
"'build/include_what_you_use'",
",",
"4",
",",
"'Add #include '",
"+",
"required_header_unstripped",
"+",
"' for '",
"+",
"template",
")"
] | https://github.com/leela-zero/leela-zero/blob/e3ed6310d33d75078ba74c3adf887d18439fc2e3/scripts/cpplint.py#L5596-L5687 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/linalg/_expm_multiply.py | python | _onenormest_matrix_power | (A, p,
t=2, itmax=5, compute_v=False, compute_w=False) | return scipy.sparse.linalg.onenormest(aslinearoperator(A) ** p) | Efficiently estimate the 1-norm of A^p.
Parameters
----------
A : ndarray
Matrix whose 1-norm of a power is to be computed.
p : int
Non-negative integer power.
t : int, optional
A positive parameter controlling the tradeoff between
accuracy versus time and memory usage.
Larger values take longer and use more memory
but give more accurate output.
itmax : int, optional
Use at most this many iterations.
compute_v : bool, optional
Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
Request a norm-maximizing linear operator output vector if True.
Returns
-------
est : float
An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
The vector such that ||Av||_1 == est*||v||_1.
It can be thought of as an input to the linear operator
that gives an output with particularly large norm.
w : ndarray, optional
The vector Av which has relatively large 1-norm.
It can be thought of as an output of the linear operator
that is relatively large in norm compared to the input. | Efficiently estimate the 1-norm of A^p. | [
"Efficiently",
"estimate",
"the",
"1",
"-",
"norm",
"of",
"A^p",
"."
] | def _onenormest_matrix_power(A, p,
t=2, itmax=5, compute_v=False, compute_w=False):
"""
Efficiently estimate the 1-norm of A^p.
Parameters
----------
A : ndarray
Matrix whose 1-norm of a power is to be computed.
p : int
Non-negative integer power.
t : int, optional
A positive parameter controlling the tradeoff between
accuracy versus time and memory usage.
Larger values take longer and use more memory
but give more accurate output.
itmax : int, optional
Use at most this many iterations.
compute_v : bool, optional
Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
Request a norm-maximizing linear operator output vector if True.
Returns
-------
est : float
An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
The vector such that ||Av||_1 == est*||v||_1.
It can be thought of as an input to the linear operator
that gives an output with particularly large norm.
w : ndarray, optional
The vector Av which has relatively large 1-norm.
It can be thought of as an output of the linear operator
that is relatively large in norm compared to the input.
"""
#XXX Eventually turn this into an API function in the _onenormest module,
#XXX and remove its underscore,
#XXX but wait until expm_multiply goes into scipy.
return scipy.sparse.linalg.onenormest(aslinearoperator(A) ** p) | [
"def",
"_onenormest_matrix_power",
"(",
"A",
",",
"p",
",",
"t",
"=",
"2",
",",
"itmax",
"=",
"5",
",",
"compute_v",
"=",
"False",
",",
"compute_w",
"=",
"False",
")",
":",
"#XXX Eventually turn this into an API function in the _onenormest module,",
"#XXX and remove its underscore,",
"#XXX but wait until expm_multiply goes into scipy.",
"return",
"scipy",
".",
"sparse",
".",
"linalg",
".",
"onenormest",
"(",
"aslinearoperator",
"(",
"A",
")",
"**",
"p",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/_expm_multiply.py#L263-L303 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/geographic_msgs/msg/_GeographicMap.py | python | GeographicMap.serialize_numpy | (self, buff, numpy) | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | [
"serialize",
"message",
"with",
"numpy",
"array",
"types",
"into",
"buffer",
":",
"param",
"buff",
":",
"buffer",
"StringIO",
":",
"param",
"numpy",
":",
"numpy",
"python",
"module"
] | def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self
buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
_x = self.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self.id.uuid
# - if encoded as a list instead, serialize as bytes instead of string
if type(_x) in [list, tuple]:
buff.write(_struct_16B.pack(*_x))
else:
buff.write(_struct_16s.pack(_x))
_x = self
buff.write(_struct_6d.pack(_x.bounds.min_pt.latitude, _x.bounds.min_pt.longitude, _x.bounds.min_pt.altitude, _x.bounds.max_pt.latitude, _x.bounds.max_pt.longitude, _x.bounds.max_pt.altitude))
length = len(self.points)
buff.write(_struct_I.pack(length))
for val1 in self.points:
_v7 = val1.id
_x = _v7.uuid
# - if encoded as a list instead, serialize as bytes instead of string
if type(_x) in [list, tuple]:
buff.write(_struct_16B.pack(*_x))
else:
buff.write(_struct_16s.pack(_x))
_v8 = val1.position
_x = _v8
buff.write(_struct_3d.pack(_x.latitude, _x.longitude, _x.altitude))
length = len(val1.props)
buff.write(_struct_I.pack(length))
for val2 in val1.props:
_x = val2.key
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = val2.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
length = len(self.features)
buff.write(_struct_I.pack(length))
for val1 in self.features:
_v9 = val1.id
_x = _v9.uuid
# - if encoded as a list instead, serialize as bytes instead of string
if type(_x) in [list, tuple]:
buff.write(_struct_16B.pack(*_x))
else:
buff.write(_struct_16s.pack(_x))
length = len(val1.components)
buff.write(_struct_I.pack(length))
for val2 in val1.components:
_x = val2.uuid
# - if encoded as a list instead, serialize as bytes instead of string
if type(_x) in [list, tuple]:
buff.write(_struct_16B.pack(*_x))
else:
buff.write(_struct_16s.pack(_x))
length = len(val1.props)
buff.write(_struct_I.pack(length))
for val2 in val1.props:
_x = val2.key
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = val2.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
length = len(self.props)
buff.write(_struct_I.pack(length))
for val1 in self.props:
_x = val1.key
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = val1.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x)))) | [
"def",
"serialize_numpy",
"(",
"self",
",",
"buff",
",",
"numpy",
")",
":",
"try",
":",
"_x",
"=",
"self",
"buff",
".",
"write",
"(",
"_struct_3I",
".",
"pack",
"(",
"_x",
".",
"header",
".",
"seq",
",",
"_x",
".",
"header",
".",
"stamp",
".",
"secs",
",",
"_x",
".",
"header",
".",
"stamp",
".",
"nsecs",
")",
")",
"_x",
"=",
"self",
".",
"header",
".",
"frame_id",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%sB'",
"%",
"length",
",",
"length",
",",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%ss'",
"%",
"length",
",",
"length",
",",
"_x",
")",
")",
"_x",
"=",
"self",
".",
"id",
".",
"uuid",
"# - if encoded as a list instead, serialize as bytes instead of string",
"if",
"type",
"(",
"_x",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"buff",
".",
"write",
"(",
"_struct_16B",
".",
"pack",
"(",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"_struct_16s",
".",
"pack",
"(",
"_x",
")",
")",
"_x",
"=",
"self",
"buff",
".",
"write",
"(",
"_struct_6d",
".",
"pack",
"(",
"_x",
".",
"bounds",
".",
"min_pt",
".",
"latitude",
",",
"_x",
".",
"bounds",
".",
"min_pt",
".",
"longitude",
",",
"_x",
".",
"bounds",
".",
"min_pt",
".",
"altitude",
",",
"_x",
".",
"bounds",
".",
"max_pt",
".",
"latitude",
",",
"_x",
".",
"bounds",
".",
"max_pt",
".",
"longitude",
",",
"_x",
".",
"bounds",
".",
"max_pt",
".",
"altitude",
")",
")",
"length",
"=",
"len",
"(",
"self",
".",
"points",
")",
"buff",
".",
"write",
"(",
"_struct_I",
".",
"pack",
"(",
"length",
")",
")",
"for",
"val1",
"in",
"self",
".",
"points",
":",
"_v7",
"=",
"val1",
".",
"id",
"_x",
"=",
"_v7",
".",
"uuid",
"# - if encoded as a list instead, serialize as bytes instead of string",
"if",
"type",
"(",
"_x",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"buff",
".",
"write",
"(",
"_struct_16B",
".",
"pack",
"(",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"_struct_16s",
".",
"pack",
"(",
"_x",
")",
")",
"_v8",
"=",
"val1",
".",
"position",
"_x",
"=",
"_v8",
"buff",
".",
"write",
"(",
"_struct_3d",
".",
"pack",
"(",
"_x",
".",
"latitude",
",",
"_x",
".",
"longitude",
",",
"_x",
".",
"altitude",
")",
")",
"length",
"=",
"len",
"(",
"val1",
".",
"props",
")",
"buff",
".",
"write",
"(",
"_struct_I",
".",
"pack",
"(",
"length",
")",
")",
"for",
"val2",
"in",
"val1",
".",
"props",
":",
"_x",
"=",
"val2",
".",
"key",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%sB'",
"%",
"length",
",",
"length",
",",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%ss'",
"%",
"length",
",",
"length",
",",
"_x",
")",
")",
"_x",
"=",
"val2",
".",
"value",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%sB'",
"%",
"length",
",",
"length",
",",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%ss'",
"%",
"length",
",",
"length",
",",
"_x",
")",
")",
"length",
"=",
"len",
"(",
"self",
".",
"features",
")",
"buff",
".",
"write",
"(",
"_struct_I",
".",
"pack",
"(",
"length",
")",
")",
"for",
"val1",
"in",
"self",
".",
"features",
":",
"_v9",
"=",
"val1",
".",
"id",
"_x",
"=",
"_v9",
".",
"uuid",
"# - if encoded as a list instead, serialize as bytes instead of string",
"if",
"type",
"(",
"_x",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"buff",
".",
"write",
"(",
"_struct_16B",
".",
"pack",
"(",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"_struct_16s",
".",
"pack",
"(",
"_x",
")",
")",
"length",
"=",
"len",
"(",
"val1",
".",
"components",
")",
"buff",
".",
"write",
"(",
"_struct_I",
".",
"pack",
"(",
"length",
")",
")",
"for",
"val2",
"in",
"val1",
".",
"components",
":",
"_x",
"=",
"val2",
".",
"uuid",
"# - if encoded as a list instead, serialize as bytes instead of string",
"if",
"type",
"(",
"_x",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"buff",
".",
"write",
"(",
"_struct_16B",
".",
"pack",
"(",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"_struct_16s",
".",
"pack",
"(",
"_x",
")",
")",
"length",
"=",
"len",
"(",
"val1",
".",
"props",
")",
"buff",
".",
"write",
"(",
"_struct_I",
".",
"pack",
"(",
"length",
")",
")",
"for",
"val2",
"in",
"val1",
".",
"props",
":",
"_x",
"=",
"val2",
".",
"key",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%sB'",
"%",
"length",
",",
"length",
",",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%ss'",
"%",
"length",
",",
"length",
",",
"_x",
")",
")",
"_x",
"=",
"val2",
".",
"value",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%sB'",
"%",
"length",
",",
"length",
",",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%ss'",
"%",
"length",
",",
"length",
",",
"_x",
")",
")",
"length",
"=",
"len",
"(",
"self",
".",
"props",
")",
"buff",
".",
"write",
"(",
"_struct_I",
".",
"pack",
"(",
"length",
")",
")",
"for",
"val1",
"in",
"self",
".",
"props",
":",
"_x",
"=",
"val1",
".",
"key",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%sB'",
"%",
"length",
",",
"length",
",",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%ss'",
"%",
"length",
",",
"length",
",",
"_x",
")",
")",
"_x",
"=",
"val1",
".",
"value",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
"'utf-8'",
")",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%sB'",
"%",
"length",
",",
"length",
",",
"*",
"_x",
")",
")",
"else",
":",
"buff",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'<I%ss'",
"%",
"length",
",",
"length",
",",
"_x",
")",
")",
"except",
"struct",
".",
"error",
"as",
"se",
":",
"self",
".",
"_check_types",
"(",
"struct",
".",
"error",
"(",
"\"%s: '%s' when writing '%s'\"",
"%",
"(",
"type",
"(",
"se",
")",
",",
"str",
"(",
"se",
")",
",",
"str",
"(",
"_x",
")",
")",
")",
")",
"except",
"TypeError",
"as",
"te",
":",
"self",
".",
"_check_types",
"(",
"ValueError",
"(",
"\"%s: '%s' when writing '%s'\"",
"%",
"(",
"type",
"(",
"te",
")",
",",
"str",
"(",
"te",
")",
",",
"str",
"(",
"_x",
")",
")",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/geographic_msgs/msg/_GeographicMap.py#L445-L567 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py | python | quaternion_from_matrix | (matrix) | return q | Return quaternion from rotation matrix.
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095])
True | Return quaternion from rotation matrix. | [
"Return",
"quaternion",
"from",
"rotation",
"matrix",
"."
] | def quaternion_from_matrix(matrix):
"""Return quaternion from rotation matrix.
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095])
True
"""
q = numpy.empty((4, ), dtype=numpy.float64)
M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:4, :4]
t = numpy.trace(M)
if t > M[3, 3]:
q[3] = t
q[2] = M[1, 0] - M[0, 1]
q[1] = M[0, 2] - M[2, 0]
q[0] = M[2, 1] - M[1, 2]
else:
i, j, k = 0, 1, 2
if M[1, 1] > M[0, 0]:
i, j, k = 1, 2, 0
if M[2, 2] > M[i, i]:
i, j, k = 2, 0, 1
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
q[i] = t
q[j] = M[i, j] + M[j, i]
q[k] = M[k, i] + M[i, k]
q[3] = M[k, j] - M[j, k]
q *= 0.5 / math.sqrt(t * M[3, 3])
return q | [
"def",
"quaternion_from_matrix",
"(",
"matrix",
")",
":",
"q",
"=",
"numpy",
".",
"empty",
"(",
"(",
"4",
",",
")",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"M",
"=",
"numpy",
".",
"array",
"(",
"matrix",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"[",
":",
"4",
",",
":",
"4",
"]",
"t",
"=",
"numpy",
".",
"trace",
"(",
"M",
")",
"if",
"t",
">",
"M",
"[",
"3",
",",
"3",
"]",
":",
"q",
"[",
"3",
"]",
"=",
"t",
"q",
"[",
"2",
"]",
"=",
"M",
"[",
"1",
",",
"0",
"]",
"-",
"M",
"[",
"0",
",",
"1",
"]",
"q",
"[",
"1",
"]",
"=",
"M",
"[",
"0",
",",
"2",
"]",
"-",
"M",
"[",
"2",
",",
"0",
"]",
"q",
"[",
"0",
"]",
"=",
"M",
"[",
"2",
",",
"1",
"]",
"-",
"M",
"[",
"1",
",",
"2",
"]",
"else",
":",
"i",
",",
"j",
",",
"k",
"=",
"0",
",",
"1",
",",
"2",
"if",
"M",
"[",
"1",
",",
"1",
"]",
">",
"M",
"[",
"0",
",",
"0",
"]",
":",
"i",
",",
"j",
",",
"k",
"=",
"1",
",",
"2",
",",
"0",
"if",
"M",
"[",
"2",
",",
"2",
"]",
">",
"M",
"[",
"i",
",",
"i",
"]",
":",
"i",
",",
"j",
",",
"k",
"=",
"2",
",",
"0",
",",
"1",
"t",
"=",
"M",
"[",
"i",
",",
"i",
"]",
"-",
"(",
"M",
"[",
"j",
",",
"j",
"]",
"+",
"M",
"[",
"k",
",",
"k",
"]",
")",
"+",
"M",
"[",
"3",
",",
"3",
"]",
"q",
"[",
"i",
"]",
"=",
"t",
"q",
"[",
"j",
"]",
"=",
"M",
"[",
"i",
",",
"j",
"]",
"+",
"M",
"[",
"j",
",",
"i",
"]",
"q",
"[",
"k",
"]",
"=",
"M",
"[",
"k",
",",
"i",
"]",
"+",
"M",
"[",
"i",
",",
"k",
"]",
"q",
"[",
"3",
"]",
"=",
"M",
"[",
"k",
",",
"j",
"]",
"-",
"M",
"[",
"j",
",",
"k",
"]",
"q",
"*=",
"0.5",
"/",
"math",
".",
"sqrt",
"(",
"t",
"*",
"M",
"[",
"3",
",",
"3",
"]",
")",
"return",
"q"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py#L1196-L1225 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | GraphicsRenderer.CreateSubBitmap | (*args, **kwargs) | return _gdi_.GraphicsRenderer_CreateSubBitmap(*args, **kwargs) | CreateSubBitmap(self, GraphicsBitmap bitmap, Double x, Double y, Double w,
Double h) -> GraphicsBitmap | CreateSubBitmap(self, GraphicsBitmap bitmap, Double x, Double y, Double w,
Double h) -> GraphicsBitmap | [
"CreateSubBitmap",
"(",
"self",
"GraphicsBitmap",
"bitmap",
"Double",
"x",
"Double",
"y",
"Double",
"w",
"Double",
"h",
")",
"-",
">",
"GraphicsBitmap"
] | def CreateSubBitmap(*args, **kwargs):
"""
CreateSubBitmap(self, GraphicsBitmap bitmap, Double x, Double y, Double w,
Double h) -> GraphicsBitmap
"""
return _gdi_.GraphicsRenderer_CreateSubBitmap(*args, **kwargs) | [
"def",
"CreateSubBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsRenderer_CreateSubBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L6658-L6663 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py | python | TextFileInitializer.initialize | (self, table) | return init_op | Initializes the table from a text file.
Args:
table: The table to be initialized.
Returns:
The operation that initializes the table.
Raises:
TypeError: when the keys and values data types do not match the table
key and value data types. | Initializes the table from a text file. | [
"Initializes",
"the",
"table",
"from",
"a",
"text",
"file",
"."
] | def initialize(self, table):
"""Initializes the table from a text file.
Args:
table: The table to be initialized.
Returns:
The operation that initializes the table.
Raises:
TypeError: when the keys and values data types do not match the table
key and value data types.
"""
# pylint: disable=protected-access
table._check_table_dtypes(self.key_dtype, self.value_dtype)
with ops.op_scope([table], self._name, "text_file_init") as scope:
filename = ops.convert_to_tensor(self._filename,
dtypes.string,
name="asset_filepath")
init_op = gen_data_flow_ops._initialize_table_from_text_file(
table.table_ref,
filename,
self._key_index,
self._value_index,
-1 if self._vocab_size is None else self._vocab_size,
self._delimiter,
name=scope)
# pylint: enable=protected-access
ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, init_op)
ops.add_to_collection(ops.GraphKeys.ASSET_FILEPATHS, filename)
return init_op | [
"def",
"initialize",
"(",
"self",
",",
"table",
")",
":",
"# pylint: disable=protected-access",
"table",
".",
"_check_table_dtypes",
"(",
"self",
".",
"key_dtype",
",",
"self",
".",
"value_dtype",
")",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"table",
"]",
",",
"self",
".",
"_name",
",",
"\"text_file_init\"",
")",
"as",
"scope",
":",
"filename",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"self",
".",
"_filename",
",",
"dtypes",
".",
"string",
",",
"name",
"=",
"\"asset_filepath\"",
")",
"init_op",
"=",
"gen_data_flow_ops",
".",
"_initialize_table_from_text_file",
"(",
"table",
".",
"table_ref",
",",
"filename",
",",
"self",
".",
"_key_index",
",",
"self",
".",
"_value_index",
",",
"-",
"1",
"if",
"self",
".",
"_vocab_size",
"is",
"None",
"else",
"self",
".",
"_vocab_size",
",",
"self",
".",
"_delimiter",
",",
"name",
"=",
"scope",
")",
"# pylint: enable=protected-access",
"ops",
".",
"add_to_collection",
"(",
"ops",
".",
"GraphKeys",
".",
"TABLE_INITIALIZERS",
",",
"init_op",
")",
"ops",
".",
"add_to_collection",
"(",
"ops",
".",
"GraphKeys",
".",
"ASSET_FILEPATHS",
",",
"filename",
")",
"return",
"init_op"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py#L444-L474 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/pyserial/serial/urlhandler/protocol_socket.py | python | SocketSerial.getDSR | (self) | return True | Read terminal status line: Data Set Ready | Read terminal status line: Data Set Ready | [
"Read",
"terminal",
"status",
"line",
":",
"Data",
"Set",
"Ready"
] | def getDSR(self):
"""Read terminal status line: Data Set Ready"""
if not self._isOpen: raise portNotOpenError
if self.logger:
self.logger.info('returning dummy for getDSR()')
return True | [
"def",
"getDSR",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"portNotOpenError",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'returning dummy for getDSR()'",
")",
"return",
"True"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/urlhandler/protocol_socket.py#L223-L228 | |
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/bottle/bottle.py | python | BaseResponse.copy | (self, cls=None) | return copy | Returns a copy of self. | Returns a copy of self. | [
"Returns",
"a",
"copy",
"of",
"self",
"."
] | def copy(self, cls=None):
''' Returns a copy of self. '''
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
copy.COOKIES.load(self.COOKIES.output())
return copy | [
"def",
"copy",
"(",
"self",
",",
"cls",
"=",
"None",
")",
":",
"cls",
"=",
"cls",
"or",
"BaseResponse",
"assert",
"issubclass",
"(",
"cls",
",",
"BaseResponse",
")",
"copy",
"=",
"cls",
"(",
")",
"copy",
".",
"status",
"=",
"self",
".",
"status",
"copy",
".",
"_headers",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
"[",
":",
"]",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"_headers",
".",
"items",
"(",
")",
")",
"copy",
".",
"COOKIES",
".",
"load",
"(",
"self",
".",
"COOKIES",
".",
"output",
"(",
")",
")",
"return",
"copy"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/bottle/bottle.py#L1433-L1441 | |
Yijunmaverick/GenerativeFaceCompletion | f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2 | scripts/cpp_lint.py | python | ReplaceAll | (pattern, rep, s) | return _regexp_compile_cache[pattern].sub(rep, s) | Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements) | Replaces instances of pattern in a string with a replacement. | [
"Replaces",
"instances",
"of",
"pattern",
"in",
"a",
"string",
"with",
"a",
"replacement",
"."
] | def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s) | [
"def",
"ReplaceAll",
"(",
"pattern",
",",
"rep",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pattern",
"]",
".",
"sub",
"(",
"rep",
",",
"s",
")"
] | https://github.com/Yijunmaverick/GenerativeFaceCompletion/blob/f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2/scripts/cpp_lint.py#L525-L540 | |
eric612/Caffe-YOLOv3-Windows | 6736ca6e16781789b828cc64218ff77cc3454e5d | scripts/cpp_lint.py | python | _CppLintState.ResetErrorCounts | (self) | Sets the module's error statistic back to zero. | Sets the module's error statistic back to zero. | [
"Sets",
"the",
"module",
"s",
"error",
"statistic",
"back",
"to",
"zero",
"."
] | def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
self.errors_by_category = {} | [
"def",
"ResetErrorCounts",
"(",
"self",
")",
":",
"self",
".",
"error_count",
"=",
"0",
"self",
".",
"errors_by_category",
"=",
"{",
"}"
] | https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/scripts/cpp_lint.py#L746-L749 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pickletools.py | python | read_bytes8 | (f) | r"""
>>> import io, struct, sys
>>> read_bytes8(io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00abc"))
b''
>>> read_bytes8(io.BytesIO(b"\x03\x00\x00\x00\x00\x00\x00\x00abcdef"))
b'abc'
>>> bigsize8 = struct.pack("<Q", sys.maxsize//3)
>>> read_bytes8(io.BytesIO(bigsize8 + b"abcdef")) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: expected ... bytes in a bytes8, but only 6 remain | r"""
>>> import io, struct, sys
>>> read_bytes8(io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00abc"))
b''
>>> read_bytes8(io.BytesIO(b"\x03\x00\x00\x00\x00\x00\x00\x00abcdef"))
b'abc'
>>> bigsize8 = struct.pack("<Q", sys.maxsize//3)
>>> read_bytes8(io.BytesIO(bigsize8 + b"abcdef")) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: expected ... bytes in a bytes8, but only 6 remain | [
"r",
">>>",
"import",
"io",
"struct",
"sys",
">>>",
"read_bytes8",
"(",
"io",
".",
"BytesIO",
"(",
"b",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00abc",
"))",
"b",
">>>",
"read_bytes8",
"(",
"io",
".",
"BytesIO",
"(",
"b",
"\\",
"x03",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00",
"\\",
"x00abcdef",
"))",
"b",
"abc",
">>>",
"bigsize8",
"=",
"struct",
".",
"pack",
"(",
"<Q",
"sys",
".",
"maxsize",
"//",
"3",
")",
">>>",
"read_bytes8",
"(",
"io",
".",
"BytesIO",
"(",
"bigsize8",
"+",
"b",
"abcdef",
"))",
"#doctest",
":",
"+",
"ELLIPSIS",
"Traceback",
"(",
"most",
"recent",
"call",
"last",
")",
":",
"...",
"ValueError",
":",
"expected",
"...",
"bytes",
"in",
"a",
"bytes8",
"but",
"only",
"6",
"remain"
] | def read_bytes8(f):
r"""
>>> import io, struct, sys
>>> read_bytes8(io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00abc"))
b''
>>> read_bytes8(io.BytesIO(b"\x03\x00\x00\x00\x00\x00\x00\x00abcdef"))
b'abc'
>>> bigsize8 = struct.pack("<Q", sys.maxsize//3)
>>> read_bytes8(io.BytesIO(bigsize8 + b"abcdef")) #doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: expected ... bytes in a bytes8, but only 6 remain
"""
n = read_uint8(f)
assert n >= 0
if n > sys.maxsize:
raise ValueError("bytes8 byte count > sys.maxsize: %d" % n)
data = f.read(n)
if len(data) == n:
return data
raise ValueError("expected %d bytes in a bytes8, but only %d remain" %
(n, len(data))) | [
"def",
"read_bytes8",
"(",
"f",
")",
":",
"n",
"=",
"read_uint8",
"(",
"f",
")",
"assert",
"n",
">=",
"0",
"if",
"n",
">",
"sys",
".",
"maxsize",
":",
"raise",
"ValueError",
"(",
"\"bytes8 byte count > sys.maxsize: %d\"",
"%",
"n",
")",
"data",
"=",
"f",
".",
"read",
"(",
"n",
")",
"if",
"len",
"(",
"data",
")",
"==",
"n",
":",
"return",
"data",
"raise",
"ValueError",
"(",
"\"expected %d bytes in a bytes8, but only %d remain\"",
"%",
"(",
"n",
",",
"len",
"(",
"data",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pickletools.py#L534-L556 | ||
9miao/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | tools/bindings-generator/clang/cindex.py | python | Token.kind | (self) | return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) | Obtain the TokenKind of the current token. | Obtain the TokenKind of the current token. | [
"Obtain",
"the",
"TokenKind",
"of",
"the",
"current",
"token",
"."
] | def kind(self):
"""Obtain the TokenKind of the current token."""
return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"TokenKind",
".",
"from_value",
"(",
"conf",
".",
"lib",
".",
"clang_getTokenKind",
"(",
"self",
")",
")"
] | https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/clang/cindex.py#L2676-L2678 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/plugins/Launch/launch/handlers.py | python | LoadCustomHandler | (xml_str) | Load a custom Launch handler an xml string
@param xml_str: Launch Xml String
@return: bool | Load a custom Launch handler an xml string
@param xml_str: Launch Xml String
@return: bool | [
"Load",
"a",
"custom",
"Launch",
"handler",
"an",
"xml",
"string",
"@param",
"xml_str",
":",
"Launch",
"Xml",
"String",
"@return",
":",
"bool"
] | def LoadCustomHandler(xml_str):
"""Load a custom Launch handler an xml string
@param xml_str: Launch Xml String
@return: bool
"""
try:
lxml = launchxml.LaunchXml()
lxml.Xml = xml_str
for hndlr in lxml.GetHandlers():
FileTypeHandler.RegisterClass(XmlHandlerDelegate(hndlr))
except:
return False
else:
return True | [
"def",
"LoadCustomHandler",
"(",
"xml_str",
")",
":",
"try",
":",
"lxml",
"=",
"launchxml",
".",
"LaunchXml",
"(",
")",
"lxml",
".",
"Xml",
"=",
"xml_str",
"for",
"hndlr",
"in",
"lxml",
".",
"GetHandlers",
"(",
")",
":",
"FileTypeHandler",
".",
"RegisterClass",
"(",
"XmlHandlerDelegate",
"(",
"hndlr",
")",
")",
"except",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/Launch/launch/handlers.py#L146-L160 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py | python | derivative_colors | (colors) | return set([('on_' + c) for c in colors] +
[('bright_' + c) for c in colors] +
[('on_bright_' + c) for c in colors]) | Return the names of valid color variants, given the base colors. | Return the names of valid color variants, given the base colors. | [
"Return",
"the",
"names",
"of",
"valid",
"color",
"variants",
"given",
"the",
"base",
"colors",
"."
] | def derivative_colors(colors):
"""Return the names of valid color variants, given the base colors."""
return set([('on_' + c) for c in colors] +
[('bright_' + c) for c in colors] +
[('on_bright_' + c) for c in colors]) | [
"def",
"derivative_colors",
"(",
"colors",
")",
":",
"return",
"set",
"(",
"[",
"(",
"'on_'",
"+",
"c",
")",
"for",
"c",
"in",
"colors",
"]",
"+",
"[",
"(",
"'bright_'",
"+",
"c",
")",
"for",
"c",
"in",
"colors",
"]",
"+",
"[",
"(",
"'on_bright_'",
"+",
"c",
")",
"for",
"c",
"in",
"colors",
"]",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py#L322-L326 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/ML/ScreenComposite.py | python | CollectResults | (indices, dataSet, composite, callback=None, appendExamples=0, errorEstimate=0) | return res | screens a set of examples through a composite and returns the
results
#DOC
**Arguments**
- examples: the examples to be screened (a sequence of sequences)
it's assumed that the last element in each example is it's "value"
- composite: the composite model to be used
- callback: (optional) if provided, this should be a function
taking a single argument that is called after each example is
screened with the number of examples screened so far as the
argument.
- appendExamples: (optional) this value is passed on to the
composite's _ClassifyExample()_ method.
- errorEstimate: (optional) calculate the "out of bag" error
estimate for the composite using Breiman's definition. This
only makes sense when screening the original data set!
[L. Breiman "Out-of-bag Estimation", UC Berkeley Dept of
Statistics Technical Report (1996)]
**Returns**
a list of 3-tuples _nExamples_ long:
1) answer: the value from the example
2) pred: the composite model's prediction
3) conf: the confidence of the composite | screens a set of examples through a composite and returns the
results
#DOC | [
"screens",
"a",
"set",
"of",
"examples",
"through",
"a",
"composite",
"and",
"returns",
"the",
"results",
"#DOC"
] | def CollectResults(indices, dataSet, composite, callback=None, appendExamples=0, errorEstimate=0):
""" screens a set of examples through a composite and returns the
results
#DOC
**Arguments**
- examples: the examples to be screened (a sequence of sequences)
it's assumed that the last element in each example is it's "value"
- composite: the composite model to be used
- callback: (optional) if provided, this should be a function
taking a single argument that is called after each example is
screened with the number of examples screened so far as the
argument.
- appendExamples: (optional) this value is passed on to the
composite's _ClassifyExample()_ method.
- errorEstimate: (optional) calculate the "out of bag" error
estimate for the composite using Breiman's definition. This
only makes sense when screening the original data set!
[L. Breiman "Out-of-bag Estimation", UC Berkeley Dept of
Statistics Technical Report (1996)]
**Returns**
a list of 3-tuples _nExamples_ long:
1) answer: the value from the example
2) pred: the composite model's prediction
3) conf: the confidence of the composite
"""
# for i in range(len(composite)):
# print(' ',i,'TRAIN:',composite[i][0]._trainIndices)
for j in range(len(composite)):
tmp = composite.GetModel(j)
if hasattr(tmp, '_trainIndices') and type(tmp._trainIndices) != dict:
tis = {}
if hasattr(tmp, '_trainIndices'):
for v in tmp._trainIndices:
tis[v] = 1
tmp._trainIndices = tis
nPts = len(indices)
res = [None] * nPts
for i in range(nPts):
idx = indices[i]
example = dataSet[idx]
if errorEstimate:
use = []
for j in range(len(composite)):
mdl = composite.GetModel(j)
if not mdl._trainIndices.get(idx, 0):
use.append(j)
else:
use = None
# print('IDX:',idx,'use:',use )
pred, conf = composite.ClassifyExample(example, appendExample=appendExamples, onlyModels=use)
if composite.GetActivityQuantBounds():
answer = composite.QuantizeActivity(example)[-1]
else:
answer = example[-1]
res[i] = answer, pred, conf
if callback:
callback(i)
return res | [
"def",
"CollectResults",
"(",
"indices",
",",
"dataSet",
",",
"composite",
",",
"callback",
"=",
"None",
",",
"appendExamples",
"=",
"0",
",",
"errorEstimate",
"=",
"0",
")",
":",
"# for i in range(len(composite)):",
"# print(' ',i,'TRAIN:',composite[i][0]._trainIndices)",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"composite",
")",
")",
":",
"tmp",
"=",
"composite",
".",
"GetModel",
"(",
"j",
")",
"if",
"hasattr",
"(",
"tmp",
",",
"'_trainIndices'",
")",
"and",
"type",
"(",
"tmp",
".",
"_trainIndices",
")",
"!=",
"dict",
":",
"tis",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"tmp",
",",
"'_trainIndices'",
")",
":",
"for",
"v",
"in",
"tmp",
".",
"_trainIndices",
":",
"tis",
"[",
"v",
"]",
"=",
"1",
"tmp",
".",
"_trainIndices",
"=",
"tis",
"nPts",
"=",
"len",
"(",
"indices",
")",
"res",
"=",
"[",
"None",
"]",
"*",
"nPts",
"for",
"i",
"in",
"range",
"(",
"nPts",
")",
":",
"idx",
"=",
"indices",
"[",
"i",
"]",
"example",
"=",
"dataSet",
"[",
"idx",
"]",
"if",
"errorEstimate",
":",
"use",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"composite",
")",
")",
":",
"mdl",
"=",
"composite",
".",
"GetModel",
"(",
"j",
")",
"if",
"not",
"mdl",
".",
"_trainIndices",
".",
"get",
"(",
"idx",
",",
"0",
")",
":",
"use",
".",
"append",
"(",
"j",
")",
"else",
":",
"use",
"=",
"None",
"# print('IDX:',idx,'use:',use )",
"pred",
",",
"conf",
"=",
"composite",
".",
"ClassifyExample",
"(",
"example",
",",
"appendExample",
"=",
"appendExamples",
",",
"onlyModels",
"=",
"use",
")",
"if",
"composite",
".",
"GetActivityQuantBounds",
"(",
")",
":",
"answer",
"=",
"composite",
".",
"QuantizeActivity",
"(",
"example",
")",
"[",
"-",
"1",
"]",
"else",
":",
"answer",
"=",
"example",
"[",
"-",
"1",
"]",
"res",
"[",
"i",
"]",
"=",
"answer",
",",
"pred",
",",
"conf",
"if",
"callback",
":",
"callback",
"(",
"i",
")",
"return",
"res"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/ScreenComposite.py#L179-L250 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftobjects/shape2dview.py | python | Shape2DView.getProjected | (self,obj,shape,direction) | returns projected edges from a shape and a direction | returns projected edges from a shape and a direction | [
"returns",
"projected",
"edges",
"from",
"a",
"shape",
"and",
"a",
"direction"
] | def getProjected(self,obj,shape,direction):
"returns projected edges from a shape and a direction"
import Part, Drawing, DraftGeomUtils
edges = []
_groups = Drawing.projectEx(shape, direction)
for g in _groups[0:5]:
if g:
edges.append(g)
if hasattr(obj,"HiddenLines"):
if obj.HiddenLines:
for g in _groups[5:]:
edges.append(g)
edges = self.cleanExcluded(obj,edges)
#return Part.makeCompound(edges)
if hasattr(obj,"Tessellation") and obj.Tessellation:
return DraftGeomUtils.cleanProjection(Part.makeCompound(edges),
obj.Tessellation,
obj.SegmentLength)
else:
return Part.makeCompound(edges) | [
"def",
"getProjected",
"(",
"self",
",",
"obj",
",",
"shape",
",",
"direction",
")",
":",
"import",
"Part",
",",
"Drawing",
",",
"DraftGeomUtils",
"edges",
"=",
"[",
"]",
"_groups",
"=",
"Drawing",
".",
"projectEx",
"(",
"shape",
",",
"direction",
")",
"for",
"g",
"in",
"_groups",
"[",
"0",
":",
"5",
"]",
":",
"if",
"g",
":",
"edges",
".",
"append",
"(",
"g",
")",
"if",
"hasattr",
"(",
"obj",
",",
"\"HiddenLines\"",
")",
":",
"if",
"obj",
".",
"HiddenLines",
":",
"for",
"g",
"in",
"_groups",
"[",
"5",
":",
"]",
":",
"edges",
".",
"append",
"(",
"g",
")",
"edges",
"=",
"self",
".",
"cleanExcluded",
"(",
"obj",
",",
"edges",
")",
"#return Part.makeCompound(edges)",
"if",
"hasattr",
"(",
"obj",
",",
"\"Tessellation\"",
")",
"and",
"obj",
".",
"Tessellation",
":",
"return",
"DraftGeomUtils",
".",
"cleanProjection",
"(",
"Part",
".",
"makeCompound",
"(",
"edges",
")",
",",
"obj",
".",
"Tessellation",
",",
"obj",
".",
"SegmentLength",
")",
"else",
":",
"return",
"Part",
".",
"makeCompound",
"(",
"edges",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/shape2dview.py#L140-L160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.