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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | bindings/python/htcondor/personal.py | python | SetCondorConfig.__init__ | (self, config_file: Path) | Parameters
----------
config_file
The path to an HTCondor configuration file. | Parameters
----------
config_file
The path to an HTCondor configuration file. | [
"Parameters",
"----------",
"config_file",
"The",
"path",
"to",
"an",
"HTCondor",
"configuration",
"file",
"."
] | def __init__(self, config_file: Path):
"""
Parameters
----------
config_file
The path to an HTCondor configuration file.
"""
self.config_file = Path(config_file)
self.previous_value = None | [
"def",
"__init__",
"(",
"self",
",",
"config_file",
":",
"Path",
")",
":",
"self",
".",
"config_file",
"=",
"Path",
"(",
"config_file",
")",
"self",
".",
"previous_value",
"=",
"None"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/personal.py#L767-L775 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py | python | Decimal.compare | (self, other, context=None) | return Decimal(self._cmp(other)) | Compare self to other. Return a decimal value:
a or b is a NaN ==> Decimal('NaN')
a < b ==> Decimal('-1')
a == b ==> Decimal('0')
a > b ==> Decimal('1') | Compare self to other. Return a decimal value: | [
"Compare",
"self",
"to",
"other",
".",
"Return",
"a",
"decimal",
"value",
":"
] | def compare(self, other, context=None):
"""Compare self to other. Return a decimal value:
a or b is a NaN ==> Decimal('NaN')
a < b ==> Decimal('-1')
a == b ==> Decimal('0')
a > b ==> Decimal('1')
"""
other = _convert_other(other, raiseit=True)
# Compare(NaN, NaN) = NaN
if (self._is_special or other and other._is_special):
ans = self._check_nans(other, context)
if ans:
return ans
return Decimal(self._cmp(other)) | [
"def",
"compare",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"# Compare(NaN, NaN) = NaN",
"if",
"(",
"self",
".",
"_is_special",
"or",
"other",
"and",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L925-L941 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/style/checkers/cpp.py | python | check_for_non_standard_constructs | (clean_lines, line_number,
class_state, error) | Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
- classes with virtual methods need virtual destructors (compiler warning
available, but not turned on yet.)
Additionally, check for constructor/destructor style violations as it
is very convenient to do so while checking for gcc-2 compliance.
Args:
clean_lines: A CleansedLines instance containing the file.
line_number: The number of the line to check.
class_state: A _ClassState instance which maintains information about
the current stack of nested class declarations being parsed.
error: A callable to which errors are reported, which takes parameters:
line number, error level, and message | Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def check_for_non_standard_constructs(clean_lines, line_number,
class_state, error):
"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
- classes with virtual methods need virtual destructors (compiler warning
available, but not turned on yet.)
Additionally, check for constructor/destructor style violations as it
is very convenient to do so while checking for gcc-2 compliance.
Args:
clean_lines: A CleansedLines instance containing the file.
line_number: The number of the line to check.
class_state: A _ClassState instance which maintains information about
the current stack of nested class declarations being parsed.
error: A callable to which errors are reported, which takes parameters:
line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[line_number]
if search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(line_number, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if search(r'printf\s*\(.*".*%\d+\$', line):
error(line_number, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if search(r'("|\').*\\(%|\[|\(|{)', line):
error(line_number, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[line_number]
if search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(auto|register|static|extern|typedef)\b',
line):
error(line_number, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if match(r'\s*#\s*endif\s*[^/\s]+', line):
error(line_number, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(line_number, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line):
error(line_number, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if search(r'\w+<.*<.*>\s+>', line):
error(line_number, 'readability/templatebrackets', 3,
'Use >> for ending template instead of > >.')
if search(r'\w+<\s+::\w+>', line):
error(line_number, 'readability/templatebrackets', 3,
'Use <:: for template start instead of < ::.')
# Track class entry and exit, and attempt to find cases within the
# class declaration that don't meet the C++ style
# guidelines. Tracking is very dependent on the code matching Google
# style guidelines, but it seems to perform well enough in testing
# to be a worthwhile addition to the checks.
classinfo_stack = class_state.classinfo_stack
# Look for a class declaration
class_decl_match = match(
r'\s*(template\s*<[\w\s<>,:]*>\s*)?(class|struct)\s+(\w+(::\w+)*)', line)
if class_decl_match:
classinfo_stack.append(_ClassInfo(class_decl_match.group(3), line_number))
# Everything else in this function uses the top of the stack if it's
# not empty.
if not classinfo_stack:
return
classinfo = classinfo_stack[-1]
# If the opening brace hasn't been seen look for it and also
# parent class declarations.
if not classinfo.seen_open_brace:
# If the line has a ';' in it, assume it's a forward declaration or
# a single-line class declaration, which we won't process.
if line.find(';') != -1:
classinfo_stack.pop()
return
classinfo.seen_open_brace = (line.find('{') != -1)
# Look for a bare ':'
if search('(^|[^:]):($|[^:])', line):
classinfo.is_derived = True
if not classinfo.seen_open_brace:
return # Everything else in this function is for after open brace
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = match(r'(?<!explicit)\s+%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args
and args.group(1) != 'void'
and not match(r'(const\s+)?%s\s*&' % re.escape(base_classname),
args.group(1).strip())):
error(line_number, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.')
# Look for methods declared virtual.
if search(r'\bvirtual\b', line):
classinfo.virtual_method_line_number = line_number
# Only look for a destructor declaration on the same line. It would
# be extremely unlikely for the destructor declaration to occupy
# more than one line.
if search(r'~%s\s*\(' % base_classname, line):
classinfo.has_virtual_destructor = True
# Look for class end.
brace_depth = classinfo.brace_depth
brace_depth = brace_depth + line.count('{') - line.count('}')
if brace_depth <= 0:
classinfo = classinfo_stack.pop()
# Try to detect missing virtual destructor declarations.
# For now, only warn if a non-derived class with virtual methods lacks
# a virtual destructor. This is to make it less likely that people will
# declare derived virtual destructors without declaring the base
# destructor virtual.
if ((classinfo.virtual_method_line_number is not None)
and (not classinfo.has_virtual_destructor)
and (not classinfo.is_derived)): # Only warn for base classes
error(classinfo.line_number, 'runtime/virtual', 4,
'The class %s probably needs a virtual destructor due to '
'having virtual method(s), one declared at line %d.'
% (classinfo.name, classinfo.virtual_method_line_number))
# Look for mixed bool and unsigned bitfields.
if (classinfo.bool_bitfields and classinfo.unsigned_bitfields):
bool_list = ', '.join(classinfo.bool_bitfields)
unsigned_list = ', '.join(classinfo.unsigned_bitfields)
error(classinfo.line_number, 'runtime/bitfields', 5,
'The class %s contains mixed unsigned and bool bitfields, '
'which will pack into separate words on the MSVC compiler.\n'
'Bool bitfields are [%s].\nUnsigned bitfields are [%s].\n'
'Consider converting bool bitfields to unsigned.'
% (classinfo.name, bool_list, unsigned_list))
else:
classinfo.brace_depth = brace_depth
well_typed_bitfield = False;
# Look for bool <name> : 1 declarations.
args = search(r'\bbool\s+(\S*)\s*:\s*\d+\s*;', line)
if args:
classinfo.bool_bitfields.append('%d: %s' % (line_number, args.group(1)))
well_typed_bitfield = True;
# Look for unsigned <name> : n declarations.
args = search(r'\bunsigned\s+(?:int\s+)?(\S+)\s*:\s*\d+\s*;', line)
if args:
classinfo.unsigned_bitfields.append('%d: %s' % (line_number, args.group(1)))
well_typed_bitfield = True;
# Look for other bitfield declarations. We don't care about those in
# size-matching structs.
if not (well_typed_bitfield or classinfo.name.startswith('SameSizeAs') or
classinfo.name.startswith('Expected')):
args = match(r'\s*(\S+)\s+(\S+)\s*:\s*\d+\s*;', line)
if args:
error(line_number, 'runtime/bitfields', 4,
'Member %s of class %s defined as a bitfield of type %s. '
'Please declare all bitfields as unsigned.'
% (args.group(2), classinfo.name, args.group(1))) | [
"def",
"check_for_non_standard_constructs",
"(",
"clean_lines",
",",
"line_number",
",",
"class_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"line_number",
"]",
"if",
"sear... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/style/checkers/cpp.py#L1303-L1492 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply/cpp.py | python | Preprocessor._macro_prescan | (self, macro) | Examine the macro value (token sequence) and identify patch points.
This is used to speed up macro expansion later on---we'll know
right away where to apply patches to the value to form the expansion | Examine the macro value (token sequence) and identify patch points. | [
"Examine",
"the",
"macro",
"value",
"(",
"token",
"sequence",
")",
"and",
"identify",
"patch",
"points",
"."
] | def _macro_prescan(self, macro):
"""Examine the macro value (token sequence) and identify patch points.
This is used to speed up macro expansion later on---we'll know
right away where to apply patches to the value to form the expansion
"""
macro.patch = [] # Standard macro arguments
macro.str_patch = [] # String conversion expansion
macro.var_comma_patch = [] # Variadic macro comma patch
i = 0
while i < len(macro.value):
if macro.value[i].type == self.t_ID and macro.value[i].value in macro.arglist:
argnum = macro.arglist.index(macro.value[i].value)
# Conversion of argument to a string
if i > 0 and macro.value[i-1].value == '#':
macro.value[i] = copy.copy(macro.value[i])
macro.value[i].type = self.t_STRING
del macro.value[i-1]
macro.str_patch.append((argnum, i - 1))
continue
# Concatenation
elif (i > 0 and macro.value[i-1].value == '##'):
macro.patch.append(('c', argnum, i - 1))
del macro.value[i-1]
continue
elif ((i+1) < len(macro.value) and macro.value[i+1].value == '##'):
macro.patch.append(('c', argnum, i))
i += 1
continue
# Standard expansion
else:
macro.patch.append(('e', argnum, i))
elif macro.value[i].value == '##':
if macro.variadic and (i > 0) and (macro.value[i - 1].value == ',') and \
((i + 1) < len(macro.value)) and (macro.value[i + 1].type == self.t_ID) and \
(macro.value[i + 1].value == macro.vararg):
macro.var_comma_patch.append(i - 1)
i += 1
macro.patch.sort(key=lambda x: x[2], reverse=True) | [
"def",
"_macro_prescan",
"(",
"self",
",",
"macro",
")",
":",
"macro",
".",
"patch",
"=",
"[",
"]",
"# Standard macro arguments",
"macro",
".",
"str_patch",
"=",
"[",
"]",
"# String conversion expansion",
"macro",
".",
"var_comma_patch",
"=",
"[",
"]",
"# Vari... | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply/cpp.py#L712-L752 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTrack/python/plotting/plotting.py | python | ROC.__init__ | (self, name, xhistoName, yhistoName, zaxis=False) | Constructor.
Arguments:
name -- String for the name of the resulting histogram
xhistoName -- String for the name of the x-axis histogram (or another "creator" object)
yhistoName -- String for the name of the y-axis histogram (or another "creator" object)
Keyword arguments:
zaxis -- If set to True (default False), create a TGraph2D with z axis showing the cut value (recommended drawStyle 'pcolz') | Constructor. | [
"Constructor",
"."
] | def __init__(self, name, xhistoName, yhistoName, zaxis=False):
"""Constructor.
Arguments:
name -- String for the name of the resulting histogram
xhistoName -- String for the name of the x-axis histogram (or another "creator" object)
yhistoName -- String for the name of the y-axis histogram (or another "creator" object)
Keyword arguments:
zaxis -- If set to True (default False), create a TGraph2D with z axis showing the cut value (recommended drawStyle 'pcolz')
"""
self._name = name
self._xhistoName = xhistoName
self._yhistoName = yhistoName
self._zaxis = zaxis | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"xhistoName",
",",
"yhistoName",
",",
"zaxis",
"=",
"False",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_xhistoName",
"=",
"xhistoName",
"self",
".",
"_yhistoName",
"=",
"yhistoName",
"sel... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/plotting.py#L1123-L1137 | ||
weichengkuo/DeepBox | c4f8c065b6a51cf296540cc453a44f0519aaacc9 | caffe-fast-rcnn/scripts/cpp_lint.py | python | _NestingState.CheckCompletedBlocks | (self, filename, error) | Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found. | Checks that all classes and namespaces have been completely parsed. | [
"Checks",
"that",
"all",
"classes",
"and",
"namespaces",
"have",
"been",
"completely",
"parsed",
"."
] | def CheckCompletedBlocks(self, filename, error):
"""Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
elif isinstance(obj, _NamespaceInfo):
error(filename, obj.starting_linenum, 'build/namespaces', 5,
'Failed to find complete declaration of namespace %s' %
obj.name) | [
"def",
"CheckCompletedBlocks",
"(",
"self",
",",
"filename",
",",
"error",
")",
":",
"# Note: This test can result in false positives if #ifdef constructs",
"# get in the way of brace matching. See the testBuildClass test in",
"# cpplint_unittest.py for an example of this.",
"for",
"obj"... | https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L2172-L2191 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py | python | originalTextFor | (expr, asString=True) | return matchExpr | Helper to return the original, untokenized text for a given expression. Useful to
restore the parsed fields of an HTML start tag into the raw tag text itself, or to
revert separate tokens with intervening whitespace back to the original matching
input text. By default, returns astring containing the original parsed text.
If the optional C{asString} argument is passed as C{False}, then the return value is a
C{L{ParseResults}} containing any results names that were originally matched, and a
single token containing the original matched text from the input string. So if
the expression passed to C{L{originalTextFor}} contains expressions with defined
results names, you must set C{asString} to C{False} if you want to preserve those
results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>'] | Helper to return the original, untokenized text for a given expression. Useful to
restore the parsed fields of an HTML start tag into the raw tag text itself, or to
revert separate tokens with intervening whitespace back to the original matching
input text. By default, returns astring containing the original parsed text.
If the optional C{asString} argument is passed as C{False}, then the return value is a
C{L{ParseResults}} containing any results names that were originally matched, and a
single token containing the original matched text from the input string. So if
the expression passed to C{L{originalTextFor}} contains expressions with defined
results names, you must set C{asString} to C{False} if you want to preserve those
results name values. | [
"Helper",
"to",
"return",
"the",
"original",
"untokenized",
"text",
"for",
"a",
"given",
"expression",
".",
"Useful",
"to",
"restore",
"the",
"parsed",
"fields",
"of",
"an",
"HTML",
"start",
"tag",
"into",
"the",
"raw",
"tag",
"text",
"itself",
"or",
"to",... | def originalTextFor(expr, asString=True):
"""
Helper to return the original, untokenized text for a given expression. Useful to
restore the parsed fields of an HTML start tag into the raw tag text itself, or to
revert separate tokens with intervening whitespace back to the original matching
input text. By default, returns astring containing the original parsed text.
If the optional C{asString} argument is passed as C{False}, then the return value is a
C{L{ParseResults}} containing any results names that were originally matched, and a
single token containing the original matched text from the input string. So if
the expression passed to C{L{originalTextFor}} contains expressions with defined
results names, you must set C{asString} to C{False} if you want to preserve those
results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>']
"""
locMarker = Empty().setParseAction(lambda s,loc,t: loc)
endlocMarker = locMarker.copy()
endlocMarker.callPreparse = False
matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
if asString:
extractText = lambda s,l,t: s[t._original_start:t._original_end]
else:
def extractText(s,l,t):
t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]]
matchExpr.setParseAction(extractText)
matchExpr.ignoreExprs = expr.ignoreExprs
return matchExpr | [
"def",
"originalTextFor",
"(",
"expr",
",",
"asString",
"=",
"True",
")",
":",
"locMarker",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"lambda",
"s",
",",
"loc",
",",
"t",
":",
"loc",
")",
"endlocMarker",
"=",
"locMarker",
".",
"copy",
"(",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L4682-L4717 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.htmlNodeDumpOutput | (self, buf, cur, encoding) | Dump an HTML node, recursive behaviour,children are printed
too, and formatting returns/spaces are added. | Dump an HTML node, recursive behaviour,children are printed
too, and formatting returns/spaces are added. | [
"Dump",
"an",
"HTML",
"node",
"recursive",
"behaviour",
"children",
"are",
"printed",
"too",
"and",
"formatting",
"returns",
"/",
"spaces",
"are",
"added",
"."
] | def htmlNodeDumpOutput(self, buf, cur, encoding):
"""Dump an HTML node, recursive behaviour,children are printed
too, and formatting returns/spaces are added. """
if buf is None: buf__o = None
else: buf__o = buf._o
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.htmlNodeDumpOutput(buf__o, self._o, cur__o, encoding) | [
"def",
"htmlNodeDumpOutput",
"(",
"self",
",",
"buf",
",",
"cur",
",",
"encoding",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf__o",
"=",
"None",
"else",
":",
"buf__o",
"=",
"buf",
".",
"_o",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L3982-L3989 | ||
bryanyzhu/Hidden-Two-Stream | f7f684adbdacb6df6b1cf196c3a476cd23484a0f | scripts/cpp_lint.py | python | FileInfo.FullName | (self) | return os.path.abspath(self._filename).replace('\\', '/') | Make Windows paths like Unix. | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix",
"."
] | def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/') | [
"def",
"FullName",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L881-L883 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | xmlTextReader.ReadInnerXml | (self) | return ret | Reads the contents of the current node, including child
nodes and markup. | Reads the contents of the current node, including child
nodes and markup. | [
"Reads",
"the",
"contents",
"of",
"the",
"current",
"node",
"including",
"child",
"nodes",
"and",
"markup",
"."
] | def ReadInnerXml(self):
"""Reads the contents of the current node, including child
nodes and markup. """
ret = libxml2mod.xmlTextReaderReadInnerXml(self._o)
return ret | [
"def",
"ReadInnerXml",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderReadInnerXml",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L6048-L6052 | |
dmlc/dmlc-core | 20ec5bee3a655e8d66e50e3abf7ab5c35ea028fe | tracker/dmlc_tracker/tracker.py | python | RabitTracker.get_link_map | (self, nslave) | return tree_map_, parent_map_, ring_map_ | get the link map, this is a bit hacky, call for better algorithm
to place similar nodes together | get the link map, this is a bit hacky, call for better algorithm
to place similar nodes together | [
"get",
"the",
"link",
"map",
"this",
"is",
"a",
"bit",
"hacky",
"call",
"for",
"better",
"algorithm",
"to",
"place",
"similar",
"nodes",
"together"
] | def get_link_map(self, nslave):
"""
get the link map, this is a bit hacky, call for better algorithm
to place similar nodes together
"""
tree_map, parent_map = self.get_tree(nslave)
ring_map = self.get_ring(tree_map, parent_map)
rmap = {0 : 0}
k = 0
for i in range(nslave - 1):
k = ring_map[k][1]
rmap[k] = i + 1
ring_map_ = {}
tree_map_ = {}
parent_map_ = {}
for k, v in ring_map.items():
ring_map_[rmap[k]] = (rmap[v[0]], rmap[v[1]])
for k, v in tree_map.items():
tree_map_[rmap[k]] = [rmap[x] for x in v]
for k, v in parent_map.items():
if k != 0:
parent_map_[rmap[k]] = rmap[v]
else:
parent_map_[rmap[k]] = -1
return tree_map_, parent_map_, ring_map_ | [
"def",
"get_link_map",
"(",
"self",
",",
"nslave",
")",
":",
"tree_map",
",",
"parent_map",
"=",
"self",
".",
"get_tree",
"(",
"nslave",
")",
"ring_map",
"=",
"self",
".",
"get_ring",
"(",
"tree_map",
",",
"parent_map",
")",
"rmap",
"=",
"{",
"0",
":",... | https://github.com/dmlc/dmlc-core/blob/20ec5bee3a655e8d66e50e3abf7ab5c35ea028fe/tracker/dmlc_tracker/tracker.py#L227-L252 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/build_ext.py | python | build_ext.check_extensions_list | (self, extensions) | Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here.
Raise DistutilsSetupError if the structure is invalid anywhere;
just returns otherwise. | Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here. | [
"Ensure",
"that",
"the",
"list",
"of",
"extensions",
"(",
"presumably",
"provided",
"as",
"a",
"command",
"option",
"extensions",
")",
"is",
"valid",
"i",
".",
"e",
".",
"it",
"is",
"a",
"list",
"of",
"Extension",
"objects",
".",
"We",
"also",
"support",... | def check_extensions_list(self, extensions):
"""Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here.
Raise DistutilsSetupError if the structure is invalid anywhere;
just returns otherwise.
"""
if not isinstance(extensions, list):
raise DistutilsSetupError, \
"'ext_modules' option must be a list of Extension instances"
for i, ext in enumerate(extensions):
if isinstance(ext, Extension):
continue # OK! (assume type-checking done
# by Extension constructor)
if not isinstance(ext, tuple) or len(ext) != 2:
raise DistutilsSetupError, \
("each element of 'ext_modules' option must be an "
"Extension instance or 2-tuple")
ext_name, build_info = ext
log.warn(("old-style (ext_name, build_info) tuple found in "
"ext_modules for extension '%s'"
"-- please convert to Extension instance" % ext_name))
if not (isinstance(ext_name, str) and
extension_name_re.match(ext_name)):
raise DistutilsSetupError, \
("first element of each tuple in 'ext_modules' "
"must be the extension name (a string)")
if not isinstance(build_info, dict):
raise DistutilsSetupError, \
("second element of each tuple in 'ext_modules' "
"must be a dictionary (build info)")
# OK, the (ext_name, build_info) dict is type-safe: convert it
# to an Extension instance.
ext = Extension(ext_name, build_info['sources'])
# Easy stuff: one-to-one mapping from dict elements to
# instance attributes.
for key in ('include_dirs', 'library_dirs', 'libraries',
'extra_objects', 'extra_compile_args',
'extra_link_args'):
val = build_info.get(key)
if val is not None:
setattr(ext, key, val)
# Medium-easy stuff: same syntax/semantics, different names.
ext.runtime_library_dirs = build_info.get('rpath')
if 'def_file' in build_info:
log.warn("'def_file' element of build info dict "
"no longer supported")
# Non-trivial stuff: 'macros' split into 'define_macros'
# and 'undef_macros'.
macros = build_info.get('macros')
if macros:
ext.define_macros = []
ext.undef_macros = []
for macro in macros:
if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
raise DistutilsSetupError, \
("'macros' element of build info dict "
"must be 1- or 2-tuple")
if len(macro) == 1:
ext.undef_macros.append(macro[0])
elif len(macro) == 2:
ext.define_macros.append(macro)
extensions[i] = ext | [
"def",
"check_extensions_list",
"(",
"self",
",",
"extensions",
")",
":",
"if",
"not",
"isinstance",
"(",
"extensions",
",",
"list",
")",
":",
"raise",
"DistutilsSetupError",
",",
"\"'ext_modules' option must be a list of Extension instances\"",
"for",
"i",
",",
"ext"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/command/build_ext.py#L344-L420 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/robotinterface.py | python | RobotInterfaceBase.destinationVelocity | (self) | Retrieves the final velocity of a motion queue controller. | Retrieves the final velocity of a motion queue controller. | [
"Retrieves",
"the",
"final",
"velocity",
"of",
"a",
"motion",
"queue",
"controller",
"."
] | def destinationVelocity(self) -> Vector:
"""Retrieves the final velocity of a motion queue controller.
"""
raise NotImplementedError() | [
"def",
"destinationVelocity",
"(",
"self",
")",
"->",
"Vector",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterface.py#L464-L467 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/utils.py | python | unicode_urlencode | (obj, charset='utf-8', for_qs=False) | return rv | URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first. | URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions. | [
"URL",
"escapes",
"a",
"single",
"bytestring",
"or",
"unicode",
"string",
"with",
"the",
"given",
"charset",
"if",
"applicable",
"to",
"URL",
"safe",
"quoting",
"under",
"all",
"rules",
"that",
"need",
"to",
"be",
"considered",
"under",
"all",
"supported",
"... | def unicode_urlencode(obj, charset='utf-8', for_qs=False):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
safe = not for_qs and b'/' or b''
rv = text_type(url_quote(obj, safe))
if for_qs:
rv = rv.replace('%20', '+')
return rv | [
"def",
"unicode_urlencode",
"(",
"obj",
",",
"charset",
"=",
"'utf-8'",
",",
"for_qs",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"obj",
"=",
"text_type",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/utils.py#L287-L303 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ctc_ops.py | python | _state_to_olabel_unique | (labels, num_labels, states, unique) | return array_ops.concat([blank_olabels, label_olabels], axis=-1) | Sum state log probs to ilabel log probs using unique label indices. | Sum state log probs to ilabel log probs using unique label indices. | [
"Sum",
"state",
"log",
"probs",
"to",
"ilabel",
"log",
"probs",
"using",
"unique",
"label",
"indices",
"."
] | def _state_to_olabel_unique(labels, num_labels, states, unique):
"""Sum state log probs to ilabel log probs using unique label indices."""
num_label_states = _get_dim(labels, 1) + 1
label_states = states[:, :, 1:num_label_states]
blank_states = states[:, :, num_label_states:]
unique_y, unique_idx = unique
mul_reduce = _sum_states(unique_idx, label_states)
num_frames = states.shape[0]
batch_size = states.shape[1]
num_states = num_label_states - 1
batch_state_major = array_ops.transpose(mul_reduce, perm=[1, 2, 0])
batch_state_major = array_ops.reshape(batch_state_major,
[batch_size * num_states, num_frames])
batch_offset = math_ops.range(batch_size, dtype=unique_y.dtype) * num_labels
indices = unique_y + array_ops.expand_dims(batch_offset, axis=-1)
indices = array_ops.reshape(indices, [-1, 1])
scatter = array_ops.scatter_nd(
indices=indices,
updates=batch_state_major,
shape=[batch_size * num_labels, num_frames])
scatter = array_ops.reshape(scatter, [batch_size, num_labels, num_frames])
mask = array_ops.ones_like(batch_state_major, dtype=dtypes.bool)
mask = array_ops.scatter_nd(
indices=indices,
updates=mask,
shape=[batch_size * num_labels, num_frames])
mask = array_ops.reshape(mask, [batch_size, num_labels, num_frames])
scatter = array_ops.where(
mask, scatter,
array_ops.fill(array_ops.shape(scatter), math_ops.log(0.0)))
label_olabels = array_ops.transpose(scatter, [2, 0, 1])
label_olabels = label_olabels[:, :, 1:]
blank_olabels = math_ops.reduce_logsumexp(blank_states, axis=2, keepdims=True)
return array_ops.concat([blank_olabels, label_olabels], axis=-1) | [
"def",
"_state_to_olabel_unique",
"(",
"labels",
",",
"num_labels",
",",
"states",
",",
"unique",
")",
":",
"num_label_states",
"=",
"_get_dim",
"(",
"labels",
",",
"1",
")",
"+",
"1",
"label_states",
"=",
"states",
"[",
":",
",",
":",
",",
"1",
":",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ctc_ops.py#L626-L667 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py | python | SocketHandler.createSocket | (self) | Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored. | Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored. | [
"Try",
"to",
"create",
"a",
"socket",
"using",
"an",
"exponential",
"backoff",
"with",
"a",
"max",
"retry",
"time",
".",
"Thanks",
"to",
"Robert",
"Olson",
"for",
"the",
"original",
"patch",
"(",
"SF",
"#815911",
")",
"which",
"has",
"been",
"slightly",
... | def createSocket(self):
"""
Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored.
"""
now = time.time()
# Either retryTime is None, in which case this
# is the first time back after a disconnect, or
# we've waited long enough.
if self.retryTime is None:
attempt = True
else:
attempt = (now >= self.retryTime)
if attempt:
try:
self.sock = self.makeSocket()
self.retryTime = None # next time, no delay before trying
except OSError:
#Creation failed, so set the retry time and return.
if self.retryTime is None:
self.retryPeriod = self.retryStart
else:
self.retryPeriod = self.retryPeriod * self.retryFactor
if self.retryPeriod > self.retryMax:
self.retryPeriod = self.retryMax
self.retryTime = now + self.retryPeriod | [
"def",
"createSocket",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# Either retryTime is None, in which case this",
"# is the first time back after a disconnect, or",
"# we've waited long enough.",
"if",
"self",
".",
"retryTime",
"is",
"None",
":",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py#L538-L564 | ||
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/core/mpi.py | python | Finalize | () | Finalize the MPI env.
Returns
-------
None
Notes
-----
This function should be called to close the initialized MPI env. | Finalize the MPI env. | [
"Finalize",
"the",
"MPI",
"env",
"."
] | def Finalize():
"""Finalize the MPI env.
Returns
-------
None
Notes
-----
This function should be called to close the initialized MPI env.
"""
_check_init()
MPIFinalizeCC() | [
"def",
"Finalize",
"(",
")",
":",
"_check_init",
"(",
")",
"MPIFinalizeCC",
"(",
")"
] | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/core/mpi.py#L246-L259 | ||
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/update/remove_drift.py | python | RemoveDrift._add | (self, simulation) | Add the operation to a simulation. | Add the operation to a simulation. | [
"Add",
"the",
"operation",
"to",
"a",
"simulation",
"."
] | def _add(self, simulation):
"""Add the operation to a simulation."""
super()._add(simulation) | [
"def",
"_add",
"(",
"self",
",",
"simulation",
")",
":",
"super",
"(",
")",
".",
"_add",
"(",
"simulation",
")"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/update/remove_drift.py#L42-L44 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Wrapping/Generators/Python/itk/support/extras.py | python | output | (input) | return input | If input object has attribute "GetOutput()" then return an itk image,
otherwise this function simply returns the input value | If input object has attribute "GetOutput()" then return an itk image,
otherwise this function simply returns the input value | [
"If",
"input",
"object",
"has",
"attribute",
"GetOutput",
"()",
"then",
"return",
"an",
"itk",
"image",
"otherwise",
"this",
"function",
"simply",
"returns",
"the",
"input",
"value"
] | def output(input):
"""
If input object has attribute "GetOutput()" then return an itk image,
otherwise this function simply returns the input value
"""
if hasattr(input, "GetOutput"):
return input.GetOutput()
return input | [
"def",
"output",
"(",
"input",
")",
":",
"if",
"hasattr",
"(",
"input",
",",
"\"GetOutput\"",
")",
":",
"return",
"input",
".",
"GetOutput",
"(",
")",
"return",
"input"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Wrapping/Generators/Python/itk/support/extras.py#L118-L125 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/EditorLib/LabelEffect.py | python | LabelEffectTool.rotateSliceToImage | (self) | adjusts the slice node to align with the
native space of the image data so that paint
operations can happen cleanly between image
space and screen space | adjusts the slice node to align with the
native space of the image data so that paint
operations can happen cleanly between image
space and screen space | [
"adjusts",
"the",
"slice",
"node",
"to",
"align",
"with",
"the",
"native",
"space",
"of",
"the",
"image",
"data",
"so",
"that",
"paint",
"operations",
"can",
"happen",
"cleanly",
"between",
"image",
"space",
"and",
"screen",
"space"
] | def rotateSliceToImage(self):
"""adjusts the slice node to align with the
native space of the image data so that paint
operations can happen cleanly between image
space and screen space"""
sliceLogic = self.sliceWidget.sliceLogic()
sliceNode = self.sliceWidget.mrmlSliceNode()
volumeNode = sliceLogic.GetBackgroundLayer().GetVolumeNode()
sliceNode.RotateToVolumePlane(volumeNode)
# make sure the slice plane does not lie on an index boundary
# - (to avoid rounding issues)
sliceLogic.SnapSliceOffsetToIJK()
sliceNode.UpdateMatrices() | [
"def",
"rotateSliceToImage",
"(",
"self",
")",
":",
"sliceLogic",
"=",
"self",
".",
"sliceWidget",
".",
"sliceLogic",
"(",
")",
"sliceNode",
"=",
"self",
".",
"sliceWidget",
".",
"mrmlSliceNode",
"(",
")",
"volumeNode",
"=",
"sliceLogic",
".",
"GetBackgroundLa... | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/LabelEffect.py#L183-L197 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Random/__init__.py | python | new | (*args, **kwargs) | return _UrandomRNG() | Return a file-like object that outputs cryptographically random bytes. | Return a file-like object that outputs cryptographically random bytes. | [
"Return",
"a",
"file",
"-",
"like",
"object",
"that",
"outputs",
"cryptographically",
"random",
"bytes",
"."
] | def new(*args, **kwargs):
"""Return a file-like object that outputs cryptographically random bytes."""
return _UrandomRNG() | [
"def",
"new",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_UrandomRNG",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Random/__init__.py#L46-L48 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/MQTTLib.py | python | _AWSIoTMQTTDelegatingClient.disconnect | (self) | return self._AWSIoTMQTTClient.disconnect() | **Description**
Disconnect from AWS IoT. This is a public facing API inherited by application level public clients.
**Syntax**
.. code:: python
myShadowClient.disconnect()
myJobsClient.disconnect()
**Parameters**
None
**Returns**
True if the disconnect attempt succeeded. False if failed. | **Description** | [
"**",
"Description",
"**"
] | def disconnect(self):
"""
**Description**
Disconnect from AWS IoT. This is a public facing API inherited by application level public clients.
**Syntax**
.. code:: python
myShadowClient.disconnect()
myJobsClient.disconnect()
**Parameters**
None
**Returns**
True if the disconnect attempt succeeded. False if failed.
"""
return self._AWSIoTMQTTClient.disconnect() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"return",
"self",
".",
"_AWSIoTMQTTClient",
".",
"disconnect",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/MQTTLib.py#L1278-L1300 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/function_base.py | python | trapz | (y, x=None, dx=1.0, axis=-1) | return ret | r"""
Integrate along the given axis using the composite trapezoidal rule.
If `x` is provided, the integration happens in sequence along its
elements - they are not sorted.
Integrate `y` (`x`) along each 1d slice on the given axis, compute
:math:`\int y(x) dx`.
When `x` is specified, this integrates along the parametric curve,
computing :math:`\int_t y(t) dt =
\int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
Parameters
----------
y : array_like
Input array to integrate.
x : array_like, optional
The sample points corresponding to the `y` values. If `x` is None,
the sample points are assumed to be evenly spaced `dx` apart. The
default is None.
dx : scalar, optional
The spacing between sample points when `x` is None. The default is 1.
axis : int, optional
The axis along which to integrate.
Returns
-------
trapz : float or ndarray
Definite integral of 'y' = n-dimensional array as approximated along
a single axis by the trapezoidal rule. If 'y' is a 1-dimensional array,
then the result is a float. If 'n' is greater than 1, then the result
is an 'n-1' dimensional array.
See Also
--------
sum, cumsum
Notes
-----
Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
will be taken from `y` array, by default x-axis distances between
points will be 1.0, alternatively they can be provided with `x` array
or with `dx` scalar. Return value will be equal to combined area under
the red lines.
References
----------
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
.. [2] Illustration image:
https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
Examples
--------
>>> np.trapz([1,2,3])
4.0
>>> np.trapz([1,2,3], x=[4,6,8])
8.0
>>> np.trapz([1,2,3], dx=2)
8.0
Using a decreasing `x` corresponds to integrating in reverse:
>>> np.trapz([1,2,3], x=[8,6,4])
-8.0
More generally `x` is used to integrate along a parametric curve.
This finds the area of a circle, noting we repeat the sample which closes
the curve:
>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
>>> np.trapz(np.cos(theta), x=np.sin(theta))
3.141571941375841
>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.trapz(a, axis=0)
array([1.5, 2.5, 3.5])
>>> np.trapz(a, axis=1)
array([2., 8.]) | r"""
Integrate along the given axis using the composite trapezoidal rule. | [
"r",
"Integrate",
"along",
"the",
"given",
"axis",
"using",
"the",
"composite",
"trapezoidal",
"rule",
"."
] | def trapz(y, x=None, dx=1.0, axis=-1):
r"""
Integrate along the given axis using the composite trapezoidal rule.
If `x` is provided, the integration happens in sequence along its
elements - they are not sorted.
Integrate `y` (`x`) along each 1d slice on the given axis, compute
:math:`\int y(x) dx`.
When `x` is specified, this integrates along the parametric curve,
computing :math:`\int_t y(t) dt =
\int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
Parameters
----------
y : array_like
Input array to integrate.
x : array_like, optional
The sample points corresponding to the `y` values. If `x` is None,
the sample points are assumed to be evenly spaced `dx` apart. The
default is None.
dx : scalar, optional
The spacing between sample points when `x` is None. The default is 1.
axis : int, optional
The axis along which to integrate.
Returns
-------
trapz : float or ndarray
Definite integral of 'y' = n-dimensional array as approximated along
a single axis by the trapezoidal rule. If 'y' is a 1-dimensional array,
then the result is a float. If 'n' is greater than 1, then the result
is an 'n-1' dimensional array.
See Also
--------
sum, cumsum
Notes
-----
Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
will be taken from `y` array, by default x-axis distances between
points will be 1.0, alternatively they can be provided with `x` array
or with `dx` scalar. Return value will be equal to combined area under
the red lines.
References
----------
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
.. [2] Illustration image:
https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
Examples
--------
>>> np.trapz([1,2,3])
4.0
>>> np.trapz([1,2,3], x=[4,6,8])
8.0
>>> np.trapz([1,2,3], dx=2)
8.0
Using a decreasing `x` corresponds to integrating in reverse:
>>> np.trapz([1,2,3], x=[8,6,4])
-8.0
More generally `x` is used to integrate along a parametric curve.
This finds the area of a circle, noting we repeat the sample which closes
the curve:
>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
>>> np.trapz(np.cos(theta), x=np.sin(theta))
3.141571941375841
>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.trapz(a, axis=0)
array([1.5, 2.5, 3.5])
>>> np.trapz(a, axis=1)
array([2., 8.])
"""
y = asanyarray(y)
if x is None:
d = dx
else:
x = asanyarray(x)
if x.ndim == 1:
d = diff(x)
# reshape to correct shape
shape = [1]*y.ndim
shape[axis] = d.shape[0]
d = d.reshape(shape)
else:
d = diff(x, axis=axis)
nd = y.ndim
slice1 = [slice(None)]*nd
slice2 = [slice(None)]*nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
try:
ret = (d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0).sum(axis)
except ValueError:
# Operations didn't work, cast to ndarray
d = np.asarray(d)
y = np.asarray(y)
ret = add.reduce(d * (y[tuple(slice1)]+y[tuple(slice2)])/2.0, axis)
return ret | [
"def",
"trapz",
"(",
"y",
",",
"x",
"=",
"None",
",",
"dx",
"=",
"1.0",
",",
"axis",
"=",
"-",
"1",
")",
":",
"y",
"=",
"asanyarray",
"(",
"y",
")",
"if",
"x",
"is",
"None",
":",
"d",
"=",
"dx",
"else",
":",
"x",
"=",
"asanyarray",
"(",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/function_base.py#L4130-L4240 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/prefilter.py | python | PrefilterManager.find_handler | (self, line_info) | return self.get_handler_by_name('normal') | Find a handler for the line_info by trying checkers. | Find a handler for the line_info by trying checkers. | [
"Find",
"a",
"handler",
"for",
"the",
"line_info",
"by",
"trying",
"checkers",
"."
] | def find_handler(self, line_info):
"""Find a handler for the line_info by trying checkers."""
for checker in self.checkers:
if checker.enabled:
handler = checker.check(line_info)
if handler:
return handler
return self.get_handler_by_name('normal') | [
"def",
"find_handler",
"(",
"self",
",",
"line_info",
")",
":",
"for",
"checker",
"in",
"self",
".",
"checkers",
":",
"if",
"checker",
".",
"enabled",
":",
"handler",
"=",
"checker",
".",
"check",
"(",
"line_info",
")",
"if",
"handler",
":",
"return",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/prefilter.py#L255-L262 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/websocket.py | python | WebSocketProtocol._abort | (self) | Instantly aborts the WebSocket connection by closing the socket | Instantly aborts the WebSocket connection by closing the socket | [
"Instantly",
"aborts",
"the",
"WebSocket",
"connection",
"by",
"closing",
"the",
"socket"
] | def _abort(self) -> None:
"""Instantly aborts the WebSocket connection by closing the socket"""
self.client_terminated = True
self.server_terminated = True
if self.stream is not None:
self.stream.close() # forcibly tear down the connection
self.close() | [
"def",
"_abort",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"client_terminated",
"=",
"True",
"self",
".",
"server_terminated",
"=",
"True",
"if",
"self",
".",
"stream",
"is",
"not",
"None",
":",
"self",
".",
"stream",
".",
"close",
"(",
")",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/websocket.py#L662-L668 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/tools/docs/parser.py | python | _ClassPageInfo.bases | (self) | return self._bases | Returns a list of `_LinkInfo` objects pointing to the class' parents. | Returns a list of `_LinkInfo` objects pointing to the class' parents. | [
"Returns",
"a",
"list",
"of",
"_LinkInfo",
"objects",
"pointing",
"to",
"the",
"class",
"parents",
"."
] | def bases(self):
"""Returns a list of `_LinkInfo` objects pointing to the class' parents."""
return self._bases | [
"def",
"bases",
"(",
"self",
")",
":",
"return",
"self",
".",
"_bases"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/tools/docs/parser.py#L952-L954 | |
rbgirshick/caffe-fast-rcnn | 28a579eaf0668850705598b3075b8969f22226d9 | scripts/cpp_lint.py | python | Search | (pattern, s) | return _regexp_compile_cache[pattern].search(s) | Searches the string for the pattern, caching the compiled regexp. | Searches the string for the pattern, caching the compiled regexp. | [
"Searches",
"the",
"string",
"for",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) | [
"def",
"Search",
"(",
"pattern",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pat... | https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L543-L547 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/common.py | python | get_filepath_or_buffer | (
filepath_or_buffer: FilePathOrBuffer,
encoding: Optional[str] = None,
compression: Optional[str] = None,
mode: Optional[str] = None,
) | return filepath_or_buffer, None, compression, False | If the filepath_or_buffer is a url, translate and return the buffer.
Otherwise passthrough.
Parameters
----------
filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),
or buffer
compression : {{'gzip', 'bz2', 'zip', 'xz', None}}, optional
encoding : the encoding to use to decode bytes, default is 'utf-8'
mode : str, optional
Returns
-------
tuple of ({a filepath_ or buffer or S3File instance},
encoding, str,
compression, str,
should_close, bool) | If the filepath_or_buffer is a url, translate and return the buffer.
Otherwise passthrough. | [
"If",
"the",
"filepath_or_buffer",
"is",
"a",
"url",
"translate",
"and",
"return",
"the",
"buffer",
".",
"Otherwise",
"passthrough",
"."
] | def get_filepath_or_buffer(
filepath_or_buffer: FilePathOrBuffer,
encoding: Optional[str] = None,
compression: Optional[str] = None,
mode: Optional[str] = None,
):
"""
If the filepath_or_buffer is a url, translate and return the buffer.
Otherwise passthrough.
Parameters
----------
filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),
or buffer
compression : {{'gzip', 'bz2', 'zip', 'xz', None}}, optional
encoding : the encoding to use to decode bytes, default is 'utf-8'
mode : str, optional
Returns
-------
tuple of ({a filepath_ or buffer or S3File instance},
encoding, str,
compression, str,
should_close, bool)
"""
filepath_or_buffer = stringify_path(filepath_or_buffer)
if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer):
req = urlopen(filepath_or_buffer)
content_encoding = req.headers.get("Content-Encoding", None)
if content_encoding == "gzip":
# Override compression based on Content-Encoding header
compression = "gzip"
reader = BytesIO(req.read())
req.close()
return reader, encoding, compression, True
if is_s3_url(filepath_or_buffer):
from pandas.io import s3
return s3.get_filepath_or_buffer(
filepath_or_buffer, encoding=encoding, compression=compression, mode=mode
)
if is_gcs_url(filepath_or_buffer):
from pandas.io import gcs
return gcs.get_filepath_or_buffer(
filepath_or_buffer, encoding=encoding, compression=compression, mode=mode
)
if isinstance(filepath_or_buffer, (str, bytes, mmap.mmap)):
return _expand_user(filepath_or_buffer), None, compression, False
if not is_file_like(filepath_or_buffer):
msg = f"Invalid file path or buffer object type: {type(filepath_or_buffer)}"
raise ValueError(msg)
return filepath_or_buffer, None, compression, False | [
"def",
"get_filepath_or_buffer",
"(",
"filepath_or_buffer",
":",
"FilePathOrBuffer",
",",
"encoding",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"compression",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"mode",
":",
"Optional",
"[",
"str",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/common.py#L144-L202 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pathlib.py | python | PurePath.joinpath | (self, *args) | return self._make_child(args) | Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored). | Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored). | [
"Combine",
"this",
"path",
"with",
"one",
"or",
"several",
"arguments",
"and",
"return",
"a",
"new",
"path",
"representing",
"either",
"a",
"subpath",
"(",
"if",
"all",
"arguments",
"are",
"relative",
"paths",
")",
"or",
"a",
"totally",
"different",
"path",
... | def joinpath(self, *args):
"""Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored).
"""
return self._make_child(args) | [
"def",
"joinpath",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"_make_child",
"(",
"args",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pathlib.py#L916-L922 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/core/memory_cache_http_server.py | python | _MemoryCacheHTTPServerImpl.AddDirectoryToResourceMap | (self, directory_path) | Loads all files in directory_path into the in-memory resource map. | Loads all files in directory_path into the in-memory resource map. | [
"Loads",
"all",
"files",
"in",
"directory_path",
"into",
"the",
"in",
"-",
"memory",
"resource",
"map",
"."
] | def AddDirectoryToResourceMap(self, directory_path):
"""Loads all files in directory_path into the in-memory resource map."""
for root, dirs, files in os.walk(directory_path):
# Skip hidden files and folders (like .svn and .git).
files = [f for f in files if f[0] != '.']
dirs[:] = [d for d in dirs if d[0] != '.']
for f in files:
file_path = os.path.join(root, f)
if not os.path.exists(file_path): # Allow for '.#' files
continue
self.AddFileToResourceMap(file_path) | [
"def",
"AddDirectoryToResourceMap",
"(",
"self",
",",
"directory_path",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory_path",
")",
":",
"# Skip hidden files and folders (like .svn and .git).",
"files",
"=",
"[",
"f",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/memory_cache_http_server.py#L164-L175 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xpathParserContext.context | (self) | return __tmp | Get the xpathContext from an xpathParserContext | Get the xpathContext from an xpathParserContext | [
"Get",
"the",
"xpathContext",
"from",
"an",
"xpathParserContext"
] | def context(self):
"""Get the xpathContext from an xpathParserContext """
ret = libxml2mod.xmlXPathParserGetContext(self._o)
if ret is None:raise xpathError('xmlXPathParserGetContext() failed')
__tmp = xpathContext(_obj=ret)
return __tmp | [
"def",
"context",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathParserGetContext",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathParserGetContext() failed'",
")",
"__tmp",
"=",
"xpathContext... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6637-L6642 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/req/req_install.py | python | InstallRequirement.uninstall | (self, auto_confirm=False) | Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation within a virtual environment can only
modify that virtual environment, even if the virtualenv is
linked to global site-packages. | Uninstall the distribution currently satisfying this requirement. | [
"Uninstall",
"the",
"distribution",
"currently",
"satisfying",
"this",
"requirement",
"."
] | def uninstall(self, auto_confirm=False):
"""
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation within a virtual environment can only
modify that virtual environment, even if the virtualenv is
linked to global site-packages.
"""
if not self.check_if_exists():
raise UninstallationError(
"Cannot uninstall requirement %s, not installed" % (self.name,)
)
dist = self.satisfied_by or self.conflicts_with
paths_to_remove = UninstallPathSet(dist)
develop_egg_link = egg_link_path(dist)
develop_egg_link_egg_info = '{0}.egg-info'.format(
pkg_resources.to_filename(dist.project_name))
egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info)
# Special case for distutils installed package
distutils_egg_info = getattr(dist._provider, 'path', None)
# Uninstall cases order do matter as in the case of 2 installs of the
# same package, pip needs to uninstall the currently detected version
if (egg_info_exists and dist.egg_info.endswith('.egg-info') and
not dist.egg_info.endswith(develop_egg_link_egg_info)):
# if dist.egg_info.endswith(develop_egg_link_egg_info), we
# are in fact in the develop_egg_link case
paths_to_remove.add(dist.egg_info)
if dist.has_metadata('installed-files.txt'):
for installed_file in dist.get_metadata(
'installed-files.txt').splitlines():
path = os.path.normpath(
os.path.join(dist.egg_info, installed_file)
)
paths_to_remove.add(path)
# FIXME: need a test for this elif block
# occurs with --single-version-externally-managed/--record outside
# of pip
elif dist.has_metadata('top_level.txt'):
if dist.has_metadata('namespace_packages.txt'):
namespaces = dist.get_metadata('namespace_packages.txt')
else:
namespaces = []
for top_level_pkg in [
p for p
in dist.get_metadata('top_level.txt').splitlines()
if p and p not in namespaces]:
path = os.path.join(dist.location, top_level_pkg)
paths_to_remove.add(path)
paths_to_remove.add(path + '.py')
paths_to_remove.add(path + '.pyc')
elif distutils_egg_info:
warnings.warn(
"Uninstalling a distutils installed project ({0}) has been "
"deprecated and will be removed in a future version. This is "
"due to the fact that uninstalling a distutils project will "
"only partially uninstall the project.".format(self.name),
RemovedInPip8Warning,
)
paths_to_remove.add(distutils_egg_info)
elif dist.location.endswith('.egg'):
# package installed by easy_install
# We cannot match on dist.egg_name because it can slightly vary
# i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg
paths_to_remove.add(dist.location)
easy_install_egg = os.path.split(dist.location)[1]
easy_install_pth = os.path.join(os.path.dirname(dist.location),
'easy-install.pth')
paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg)
elif develop_egg_link:
# develop egg
with open(develop_egg_link, 'r') as fh:
link_pointer = os.path.normcase(fh.readline().strip())
assert (link_pointer == dist.location), (
'Egg-link %s does not match installed location of %s '
'(at %s)' % (link_pointer, self.name, dist.location)
)
paths_to_remove.add(develop_egg_link)
easy_install_pth = os.path.join(os.path.dirname(develop_egg_link),
'easy-install.pth')
paths_to_remove.add_pth(easy_install_pth, dist.location)
elif egg_info_exists and dist.egg_info.endswith('.dist-info'):
for path in pip.wheel.uninstallation_paths(dist):
paths_to_remove.add(path)
else:
logger.debug(
'Not sure how to uninstall: %s - Check: %s',
dist, dist.location)
# find distutils scripts= scripts
if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'):
for script in dist.metadata_listdir('scripts'):
if dist_in_usersite(dist):
bin_dir = bin_user
else:
bin_dir = bin_py
paths_to_remove.add(os.path.join(bin_dir, script))
if WINDOWS:
paths_to_remove.add(os.path.join(bin_dir, script) + '.bat')
# find console_scripts
if dist.has_metadata('entry_points.txt'):
config = configparser.SafeConfigParser()
config.readfp(
FakeFile(dist.get_metadata_lines('entry_points.txt'))
)
if config.has_section('console_scripts'):
for name, value in config.items('console_scripts'):
if dist_in_usersite(dist):
bin_dir = bin_user
else:
bin_dir = bin_py
paths_to_remove.add(os.path.join(bin_dir, name))
if WINDOWS:
paths_to_remove.add(
os.path.join(bin_dir, name) + '.exe'
)
paths_to_remove.add(
os.path.join(bin_dir, name) + '.exe.manifest'
)
paths_to_remove.add(
os.path.join(bin_dir, name) + '-script.py'
)
paths_to_remove.remove(auto_confirm)
self.uninstalled = paths_to_remove | [
"def",
"uninstall",
"(",
"self",
",",
"auto_confirm",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"check_if_exists",
"(",
")",
":",
"raise",
"UninstallationError",
"(",
"\"Cannot uninstall requirement %s, not installed\"",
"%",
"(",
"self",
".",
"name",
",... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/req/req_install.py#L586-L722 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/ShapeOptimizationApplication/python_scripts/algorithms/algorithm_gradient_projection.py | python | AlgorithmGradientProjection.__computeControlPointUpdate | (self) | adapted from https://msulaiman.org/onewebmedia/GradProj_2.pdf | adapted from https://msulaiman.org/onewebmedia/GradProj_2.pdf | [
"adapted",
"from",
"https",
":",
"//",
"msulaiman",
".",
"org",
"/",
"onewebmedia",
"/",
"GradProj_2",
".",
"pdf"
] | def __computeControlPointUpdate(self):
"""adapted from https://msulaiman.org/onewebmedia/GradProj_2.pdf"""
g_a, g_a_variables = self.__getActiveConstraints()
KM.Logger.PrintInfo("ShapeOpt", "Assemble vector of objective gradient.")
nabla_f = KM.Vector()
s = KM.Vector()
self.optimization_utilities.AssembleVector(self.design_surface, nabla_f, KSO.DF1DX_MAPPED)
if len(g_a) == 0:
KM.Logger.PrintInfo("ShapeOpt", "No constraints active, use negative objective gradient as search direction.")
s = nabla_f * (-1.0)
s *= self.step_size / s.norm_inf()
self.optimization_utilities.AssignVectorToVariable(self.design_surface, s, KSO.SEARCH_DIRECTION)
self.optimization_utilities.AssignVectorToVariable(self.design_surface, [0.0]*len(s), KSO.CORRECTION)
self.optimization_utilities.AssignVectorToVariable(self.design_surface, s, KSO.CONTROL_POINT_UPDATE)
return
KM.Logger.PrintInfo("ShapeOpt", "Assemble matrix of constraint gradient.")
N = KM.Matrix()
self.optimization_utilities.AssembleMatrix(self.design_surface, N, g_a_variables) # TODO check if gradients are 0.0! - in cpp
settings = KM.Parameters('{ "solver_type" : "LinearSolversApplication.dense_col_piv_householder_qr" }')
solver = dense_linear_solver_factory.ConstructSolver(settings)
KM.Logger.PrintInfo("ShapeOpt", "Calculate projected search direction and correction.")
c = KM.Vector()
self.optimization_utilities.CalculateProjectedSearchDirectionAndCorrection(
nabla_f,
N,
g_a,
solver,
s,
c)
if c.norm_inf() != 0.0:
if c.norm_inf() <= self.max_correction_share * self.step_size:
delta = self.step_size - c.norm_inf()
s *= delta/s.norm_inf()
else:
KM.Logger.PrintWarning("ShapeOpt", f"Correction is scaled down from {c.norm_inf()} to {self.max_correction_share * self.step_size}.")
c *= self.max_correction_share * self.step_size / c.norm_inf()
s *= (1.0 - self.max_correction_share) * self.step_size / s.norm_inf()
else:
s *= self.step_size / s.norm_inf()
self.optimization_utilities.AssignVectorToVariable(self.design_surface, s, KSO.SEARCH_DIRECTION)
self.optimization_utilities.AssignVectorToVariable(self.design_surface, c, KSO.CORRECTION)
self.optimization_utilities.AssignVectorToVariable(self.design_surface, s+c, KSO.CONTROL_POINT_UPDATE) | [
"def",
"__computeControlPointUpdate",
"(",
"self",
")",
":",
"g_a",
",",
"g_a_variables",
"=",
"self",
".",
"__getActiveConstraints",
"(",
")",
"KM",
".",
"Logger",
".",
"PrintInfo",
"(",
"\"ShapeOpt\"",
",",
"\"Assemble vector of objective gradient.\"",
")",
"nabla... | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ShapeOptimizationApplication/python_scripts/algorithms/algorithm_gradient_projection.py#L203-L252 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_reactive_env.py | python | MinitaurReactiveEnv._get_true_observation | (self) | return self._true_observation | Get the true observations of this environment.
It includes the roll, the pitch, the roll dot and the pitch dot of the base.
If _use_angle_in_observation is true, eight motor angles are added into the
observation.
Returns:
The observation list, which is a numpy array of floating-point values. | Get the true observations of this environment. | [
"Get",
"the",
"true",
"observations",
"of",
"this",
"environment",
"."
] | def _get_true_observation(self):
"""Get the true observations of this environment.
It includes the roll, the pitch, the roll dot and the pitch dot of the base.
If _use_angle_in_observation is true, eight motor angles are added into the
observation.
Returns:
The observation list, which is a numpy array of floating-point values.
"""
roll, pitch, _ = self.minitaur.GetTrueBaseRollPitchYaw()
roll_rate, pitch_rate, _ = self.minitaur.GetTrueBaseRollPitchYawRate()
observation = [roll, pitch, roll_rate, pitch_rate]
if self._use_angle_in_observation:
observation.extend(self.minitaur.GetMotorAngles().tolist())
self._true_observation = np.array(observation)
return self._true_observation | [
"def",
"_get_true_observation",
"(",
"self",
")",
":",
"roll",
",",
"pitch",
",",
"_",
"=",
"self",
".",
"minitaur",
".",
"GetTrueBaseRollPitchYaw",
"(",
")",
"roll_rate",
",",
"pitch_rate",
",",
"_",
"=",
"self",
".",
"minitaur",
".",
"GetTrueBaseRollPitchY... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_reactive_env.py#L170-L186 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/frame.py | python | DataFrame.to_parquet | (
self,
path: FilePathOrBuffer | None = None,
engine: str = "auto",
compression: str | None = "snappy",
index: bool | None = None,
partition_cols: list[str] | None = None,
storage_options: StorageOptions = None,
**kwargs,
) | return to_parquet(
self,
path,
engine,
compression=compression,
index=index,
partition_cols=partition_cols,
storage_options=storage_options,
**kwargs,
) | Write a DataFrame to the binary parquet format.
This function writes the dataframe as a `parquet file
<https://parquet.apache.org/>`_. You can choose different parquet
backends, and have the option of compression. See
:ref:`the user guide <io.parquet>` for more details.
Parameters
----------
path : str or file-like object, default None
If a string, it will be used as Root Directory path
when writing a partitioned dataset. By file-like object,
we refer to objects with a write() method, such as a file handle
(e.g. via builtin open function) or io.BytesIO. The engine
fastparquet does not accept file-like objects. If path is None,
a bytes object is returned.
.. versionchanged:: 1.2.0
Previously this was "fname"
engine : {{'auto', 'pyarrow', 'fastparquet'}}, default 'auto'
Parquet library to use. If 'auto', then the option
``io.parquet.engine`` is used. The default ``io.parquet.engine``
behavior is to try 'pyarrow', falling back to 'fastparquet' if
'pyarrow' is unavailable.
compression : {{'snappy', 'gzip', 'brotli', None}}, default 'snappy'
Name of the compression to use. Use ``None`` for no compression.
index : bool, default None
If ``True``, include the dataframe's index(es) in the file output.
If ``False``, they will not be written to the file.
If ``None``, similar to ``True`` the dataframe's index(es)
will be saved. However, instead of being saved as values,
the RangeIndex will be stored as a range in the metadata so it
doesn't require much space and is faster. Other indexes will
be included as columns in the file output.
partition_cols : list, optional, default None
Column names by which to partition the dataset.
Columns are partitioned in the order they are given.
Must be None if path is not a string.
{storage_options}
.. versionadded:: 1.2.0
**kwargs
Additional arguments passed to the parquet library. See
:ref:`pandas io <io.parquet>` for more details.
Returns
-------
bytes if no path argument is provided else None
See Also
--------
read_parquet : Read a parquet file.
DataFrame.to_csv : Write a csv file.
DataFrame.to_sql : Write to a sql table.
DataFrame.to_hdf : Write to hdf.
Notes
-----
This function requires either the `fastparquet
<https://pypi.org/project/fastparquet>`_ or `pyarrow
<https://arrow.apache.org/docs/python/>`_ library.
Examples
--------
>>> df = pd.DataFrame(data={{'col1': [1, 2], 'col2': [3, 4]}})
>>> df.to_parquet('df.parquet.gzip',
... compression='gzip') # doctest: +SKIP
>>> pd.read_parquet('df.parquet.gzip') # doctest: +SKIP
col1 col2
0 1 3
1 2 4
If you want to get a buffer to the parquet content you can use a io.BytesIO
object, as long as you don't use partition_cols, which creates multiple files.
>>> import io
>>> f = io.BytesIO()
>>> df.to_parquet(f)
>>> f.seek(0)
0
>>> content = f.read() | Write a DataFrame to the binary parquet format. | [
"Write",
"a",
"DataFrame",
"to",
"the",
"binary",
"parquet",
"format",
"."
] | def to_parquet(
self,
path: FilePathOrBuffer | None = None,
engine: str = "auto",
compression: str | None = "snappy",
index: bool | None = None,
partition_cols: list[str] | None = None,
storage_options: StorageOptions = None,
**kwargs,
) -> bytes | None:
"""
Write a DataFrame to the binary parquet format.
This function writes the dataframe as a `parquet file
<https://parquet.apache.org/>`_. You can choose different parquet
backends, and have the option of compression. See
:ref:`the user guide <io.parquet>` for more details.
Parameters
----------
path : str or file-like object, default None
If a string, it will be used as Root Directory path
when writing a partitioned dataset. By file-like object,
we refer to objects with a write() method, such as a file handle
(e.g. via builtin open function) or io.BytesIO. The engine
fastparquet does not accept file-like objects. If path is None,
a bytes object is returned.
.. versionchanged:: 1.2.0
Previously this was "fname"
engine : {{'auto', 'pyarrow', 'fastparquet'}}, default 'auto'
Parquet library to use. If 'auto', then the option
``io.parquet.engine`` is used. The default ``io.parquet.engine``
behavior is to try 'pyarrow', falling back to 'fastparquet' if
'pyarrow' is unavailable.
compression : {{'snappy', 'gzip', 'brotli', None}}, default 'snappy'
Name of the compression to use. Use ``None`` for no compression.
index : bool, default None
If ``True``, include the dataframe's index(es) in the file output.
If ``False``, they will not be written to the file.
If ``None``, similar to ``True`` the dataframe's index(es)
will be saved. However, instead of being saved as values,
the RangeIndex will be stored as a range in the metadata so it
doesn't require much space and is faster. Other indexes will
be included as columns in the file output.
partition_cols : list, optional, default None
Column names by which to partition the dataset.
Columns are partitioned in the order they are given.
Must be None if path is not a string.
{storage_options}
.. versionadded:: 1.2.0
**kwargs
Additional arguments passed to the parquet library. See
:ref:`pandas io <io.parquet>` for more details.
Returns
-------
bytes if no path argument is provided else None
See Also
--------
read_parquet : Read a parquet file.
DataFrame.to_csv : Write a csv file.
DataFrame.to_sql : Write to a sql table.
DataFrame.to_hdf : Write to hdf.
Notes
-----
This function requires either the `fastparquet
<https://pypi.org/project/fastparquet>`_ or `pyarrow
<https://arrow.apache.org/docs/python/>`_ library.
Examples
--------
>>> df = pd.DataFrame(data={{'col1': [1, 2], 'col2': [3, 4]}})
>>> df.to_parquet('df.parquet.gzip',
... compression='gzip') # doctest: +SKIP
>>> pd.read_parquet('df.parquet.gzip') # doctest: +SKIP
col1 col2
0 1 3
1 2 4
If you want to get a buffer to the parquet content you can use a io.BytesIO
object, as long as you don't use partition_cols, which creates multiple files.
>>> import io
>>> f = io.BytesIO()
>>> df.to_parquet(f)
>>> f.seek(0)
0
>>> content = f.read()
"""
from pandas.io.parquet import to_parquet
return to_parquet(
self,
path,
engine,
compression=compression,
index=index,
partition_cols=partition_cols,
storage_options=storage_options,
**kwargs,
) | [
"def",
"to_parquet",
"(",
"self",
",",
"path",
":",
"FilePathOrBuffer",
"|",
"None",
"=",
"None",
",",
"engine",
":",
"str",
"=",
"\"auto\"",
",",
"compression",
":",
"str",
"|",
"None",
"=",
"\"snappy\"",
",",
"index",
":",
"bool",
"|",
"None",
"=",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/frame.py#L2579-L2686 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py | python | IMAP4.copy | (self, message_set, new_mailbox) | return self._simple_command('COPY', message_set, new_mailbox) | Copy 'message_set' messages onto end of 'new_mailbox'.
(typ, [data]) = <instance>.copy(message_set, new_mailbox) | Copy 'message_set' messages onto end of 'new_mailbox'. | [
"Copy",
"message_set",
"messages",
"onto",
"end",
"of",
"new_mailbox",
"."
] | def copy(self, message_set, new_mailbox):
"""Copy 'message_set' messages onto end of 'new_mailbox'.
(typ, [data]) = <instance>.copy(message_set, new_mailbox)
"""
return self._simple_command('COPY', message_set, new_mailbox) | [
"def",
"copy",
"(",
"self",
",",
"message_set",
",",
"new_mailbox",
")",
":",
"return",
"self",
".",
"_simple_command",
"(",
"'COPY'",
",",
"message_set",
",",
"new_mailbox",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py#L388-L393 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/RemoteConsole/ly_remote_console/ly_remote_console/remote_console_commands.py | python | RemoteConsole.start | (self, timeout=10) | Starts the socket connection to the Launcher instance.
:param timeout: The timeout in seconds for the pump thread to get ready before raising an exception. | Starts the socket connection to the Launcher instance.
:param timeout: The timeout in seconds for the pump thread to get ready before raising an exception. | [
"Starts",
"the",
"socket",
"connection",
"to",
"the",
"Launcher",
"instance",
".",
":",
"param",
"timeout",
":",
"The",
"timeout",
"in",
"seconds",
"for",
"the",
"pump",
"thread",
"to",
"get",
"ready",
"before",
"raising",
"an",
"exception",
"."
] | def start(self, timeout=10):
# type: (int) -> None
"""
Starts the socket connection to the Launcher instance.
:param timeout: The timeout in seconds for the pump thread to get ready before raising an exception.
"""
if self.connected:
logger.warning('RemoteConsole is already connected.')
return
# Do not wait more than 3.0 seconds per connection attempt.
self.socket.settimeout(3.0)
num_ports_to_scan = 8
max_port = self.port + num_ports_to_scan
while self.port < max_port:
try:
self.socket.connect((self.addr, self.port))
logger.info('Successfully connected to port: {}'.format(self.port))
break
except:
self.port += 1
if self.port >= max_port:
from_port_to_port = "from port {} to port {}".format(
self.port-num_ports_to_scan, self.port-1)
raise Exception(
"Remote console connection never became ready after scanning {}".format(
from_port_to_port))
# Clear the timeout. Further socket operations won't timeout.
self.socket.settimeout(None)
self.pump_thread.start()
if not self.ready.wait(timeout):
raise Exception("Remote console connection never became ready")
self.connected = True
logger.info('Remote Console Started at port {}'.format(self.port)) | [
"def",
"start",
"(",
"self",
",",
"timeout",
"=",
"10",
")",
":",
"# type: (int) -> None",
"if",
"self",
".",
"connected",
":",
"logger",
".",
"warning",
"(",
"'RemoteConsole is already connected.'",
")",
"return",
"# Do not wait more than 3.0 seconds per connection att... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/RemoteConsole/ly_remote_console/ly_remote_console/remote_console_commands.py#L122-L155 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | ListCtrl.GetFocusedItem | (self) | return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_FOCUSED) | get the currently focused item or -1 if none | get the currently focused item or -1 if none | [
"get",
"the",
"currently",
"focused",
"item",
"or",
"-",
"1",
"if",
"none"
] | def GetFocusedItem(self):
'''get the currently focused item or -1 if none'''
return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_FOCUSED) | [
"def",
"GetFocusedItem",
"(",
"self",
")",
":",
"return",
"self",
".",
"GetNextItem",
"(",
"-",
"1",
",",
"wx",
".",
"LIST_NEXT_ALL",
",",
"wx",
".",
"LIST_STATE_FOCUSED",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4773-L4775 | |
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | python/caffe/coord_map.py | python | coord_map_from_to | (top_from, top_to) | Determine the coordinate mapping betweeen a top (from) and a top (to).
Walk the graph to find a common ancestor while composing the coord maps for
from and to until they meet. As a last step the from map is inverted. | Determine the coordinate mapping betweeen a top (from) and a top (to).
Walk the graph to find a common ancestor while composing the coord maps for
from and to until they meet. As a last step the from map is inverted. | [
"Determine",
"the",
"coordinate",
"mapping",
"betweeen",
"a",
"top",
"(",
"from",
")",
"and",
"a",
"top",
"(",
"to",
")",
".",
"Walk",
"the",
"graph",
"to",
"find",
"a",
"common",
"ancestor",
"while",
"composing",
"the",
"coord",
"maps",
"for",
"from",
... | def coord_map_from_to(top_from, top_to):
"""
Determine the coordinate mapping betweeen a top (from) and a top (to).
Walk the graph to find a common ancestor while composing the coord maps for
from and to until they meet. As a last step the from map is inverted.
"""
# We need to find a common ancestor of top_from and top_to.
# We'll assume that all ancestors are equivalent here (otherwise the graph
# is an inconsistent state (which we could improve this to check for)).
# For now use a brute-force algorithm.
def collect_bottoms(top):
"""
Collect the bottoms to walk for the coordinate mapping.
The general rule is that all the bottoms of a layer can be mapped, as
most layers have the same coordinate mapping for each bottom.
Crop layer is a notable exception. Only the first/cropped bottom is
mappable; the second/dimensions bottom is excluded from the walk.
"""
bottoms = top.fn.inputs
if top.fn.type_name == 'Crop':
bottoms = bottoms[:1]
return bottoms
# walk back from top_from, keeping the coord map as we go
from_maps = {top_from: (None, 1, 0)}
frontier = {top_from}
while frontier:
top = frontier.pop()
try:
bottoms = collect_bottoms(top)
for bottom in bottoms:
from_maps[bottom] = compose(from_maps[top], coord_map(top.fn))
frontier.add(bottom)
except UndefinedMapException:
pass
# now walk back from top_to until we hit a common blob
to_maps = {top_to: (None, 1, 0)}
frontier = {top_to}
while frontier:
top = frontier.pop()
if top in from_maps:
return compose(to_maps[top], inverse(from_maps[top]))
try:
bottoms = collect_bottoms(top)
for bottom in bottoms:
to_maps[bottom] = compose(to_maps[top], coord_map(top.fn))
frontier.add(bottom)
except UndefinedMapException:
continue
# if we got here, we did not find a blob in common
raise RuntimeError('Could not compute map between tops; are they '
'connected by spatial layers?') | [
"def",
"coord_map_from_to",
"(",
"top_from",
",",
"top_to",
")",
":",
"# We need to find a common ancestor of top_from and top_to.",
"# We'll assume that all ancestors are equivalent here (otherwise the graph",
"# is an inconsistent state (which we could improve this to check for)).",
"# For n... | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/python/caffe/coord_map.py#L115-L169 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject._EncodeComment | (self, comment) | return '/* ' + comment.replace('*/', '(*)/') + ' */' | Encodes a comment to be placed in the project file output, mimicing
Xcode behavior. | Encodes a comment to be placed in the project file output, mimicing
Xcode behavior. | [
"Encodes",
"a",
"comment",
"to",
"be",
"placed",
"in",
"the",
"project",
"file",
"output",
"mimicing",
"Xcode",
"behavior",
"."
] | def _EncodeComment(self, comment):
"""Encodes a comment to be placed in the project file output, mimicing
Xcode behavior.
"""
# This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If
# the string already contains a "*/", it is turned into "(*)/". This keeps
# the file writer from outputting something that would be treated as the
# end of a comment in the middle of something intended to be entirely a
# comment.
return '/* ' + comment.replace('*/', '(*)/') + ' */' | [
"def",
"_EncodeComment",
"(",
"self",
",",
"comment",
")",
":",
"# This mimics Xcode behavior by wrapping the comment in \"/*\" and \"*/\". If",
"# the string already contains a \"*/\", it is turned into \"(*)/\". This keeps",
"# the file writer from outputting something that would be treated ... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py#L504-L515 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/tensor_forest/hybrid/python/hybrid_model.py | python | HybridModel._base_inference | (self, data, data_spec=None) | return output | Returns an op that performs inference without a softmax. | Returns an op that performs inference without a softmax. | [
"Returns",
"an",
"op",
"that",
"performs",
"inference",
"without",
"a",
"softmax",
"."
] | def _base_inference(self, data, data_spec=None):
"""Returns an op that performs inference without a softmax."""
inference_result = self._do_layer_inference(self.layers[0], data)
for layer in self.layers[1:]:
inference_result = self._do_layer_inference(layer, inference_result)
output_size = 1 if self.is_regression else self.params.num_classes
output = layers.fully_connected(
inference_result, output_size, activation_fn=array_ops.identity)
return output | [
"def",
"_base_inference",
"(",
"self",
",",
"data",
",",
"data_spec",
"=",
"None",
")",
":",
"inference_result",
"=",
"self",
".",
"_do_layer_inference",
"(",
"self",
".",
"layers",
"[",
"0",
"]",
",",
"data",
")",
"for",
"layer",
"in",
"self",
".",
"l... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/tensor_forest/hybrid/python/hybrid_model.py#L75-L86 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/tools/quantization/quant_utils.py | python | get_mul_node | (inputs, output, name) | return onnx.helper.make_node("Mul", inputs, [output], name) | Helper function to create a Mul node.
parameter inputs: list of input names.
parameter output: output name.
parameter name: name of the node.
return: Mul node in NodeProto format. | Helper function to create a Mul node.
parameter inputs: list of input names.
parameter output: output name.
parameter name: name of the node.
return: Mul node in NodeProto format. | [
"Helper",
"function",
"to",
"create",
"a",
"Mul",
"node",
".",
"parameter",
"inputs",
":",
"list",
"of",
"input",
"names",
".",
"parameter",
"output",
":",
"output",
"name",
".",
"parameter",
"name",
":",
"name",
"of",
"the",
"node",
".",
"return",
":",
... | def get_mul_node(inputs, output, name):
'''
Helper function to create a Mul node.
parameter inputs: list of input names.
parameter output: output name.
parameter name: name of the node.
return: Mul node in NodeProto format.
'''
return onnx.helper.make_node("Mul", inputs, [output], name) | [
"def",
"get_mul_node",
"(",
"inputs",
",",
"output",
",",
"name",
")",
":",
"return",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"\"Mul\"",
",",
"inputs",
",",
"[",
"output",
"]",
",",
"name",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/quantization/quant_utils.py#L329-L337 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/connection.py | python | Client | (address, family=None, authkey=None) | return c | Returns a connection to the address of a `Listener` | Returns a connection to the address of a `Listener` | [
"Returns",
"a",
"connection",
"to",
"the",
"address",
"of",
"a",
"Listener"
] | def Client(address, family=None, authkey=None):
'''
Returns a connection to the address of a `Listener`
'''
family = family or address_type(address)
if family == 'AF_PIPE':
c = PipeClient(address)
else:
c = SocketClient(address)
if authkey is not None and not isinstance(authkey, bytes):
raise TypeError, 'authkey should be a byte string'
if authkey is not None:
answer_challenge(c, authkey)
deliver_challenge(c, authkey)
return c | [
"def",
"Client",
"(",
"address",
",",
"family",
"=",
"None",
",",
"authkey",
"=",
"None",
")",
":",
"family",
"=",
"family",
"or",
"address_type",
"(",
"address",
")",
"if",
"family",
"==",
"'AF_PIPE'",
":",
"c",
"=",
"PipeClient",
"(",
"address",
")",... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/connection.py#L161-L178 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_FlushContext_REQUEST.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(TPM2_FlushContext_REQUEST) | Returns new TPM2_FlushContext_REQUEST object constructed from its
marshaled representation in the given byte buffer | Returns new TPM2_FlushContext_REQUEST object constructed from its
marshaled representation in the given byte buffer | [
"Returns",
"new",
"TPM2_FlushContext_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new TPM2_FlushContext_REQUEST object constructed from its
marshaled representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(TPM2_FlushContext_REQUEST) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"TPM2_FlushContext_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16225-L16229 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/externals/joblib/_parallel_backends.py | python | ThreadingBackend.configure | (self, n_jobs=1, parallel=None, **backend_args) | return n_jobs | Build a process or thread pool and return the number of workers | Build a process or thread pool and return the number of workers | [
"Build",
"a",
"process",
"or",
"thread",
"pool",
"and",
"return",
"the",
"number",
"of",
"workers"
] | def configure(self, n_jobs=1, parallel=None, **backend_args):
"""Build a process or thread pool and return the number of workers"""
n_jobs = self.effective_n_jobs(n_jobs)
if n_jobs == 1:
# Avoid unnecessary overhead and use sequential backend instead.
raise FallbackToBackend(SequentialBackend())
self.parallel = parallel
self._pool = ThreadPool(n_jobs)
return n_jobs | [
"def",
"configure",
"(",
"self",
",",
"n_jobs",
"=",
"1",
",",
"parallel",
"=",
"None",
",",
"*",
"*",
"backend_args",
")",
":",
"n_jobs",
"=",
"self",
".",
"effective_n_jobs",
"(",
"n_jobs",
")",
"if",
"n_jobs",
"==",
"1",
":",
"# Avoid unnecessary over... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/joblib/_parallel_backends.py#L239-L247 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/metadata.py | python | Metadata.is_field | (self, name) | return name in _ALL_FIELDS | return True if name is a valid metadata key | return True if name is a valid metadata key | [
"return",
"True",
"if",
"name",
"is",
"a",
"valid",
"metadata",
"key"
] | def is_field(self, name):
"""return True if name is a valid metadata key"""
name = self._convert_name(name)
return name in _ALL_FIELDS | [
"def",
"is_field",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"_convert_name",
"(",
"name",
")",
"return",
"name",
"in",
"_ALL_FIELDS"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/metadata.py#L413-L416 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | fromstring | (s, t) | return masked_array(numeric.fromstring(s, t)) | Construct a masked array from a string. Result will have no mask. | Construct a masked array from a string. Result will have no mask. | [
"Construct",
"a",
"masked",
"array",
"from",
"a",
"string",
".",
"Result",
"will",
"have",
"no",
"mask",
"."
] | def fromstring (s, t):
"Construct a masked array from a string. Result will have no mask."
return masked_array(numeric.fromstring(s, t)) | [
"def",
"fromstring",
"(",
"s",
",",
"t",
")",
":",
"return",
"masked_array",
"(",
"numeric",
".",
"fromstring",
"(",
"s",
",",
"t",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1508-L1510 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | GBPosition.GetCol | (*args, **kwargs) | return _core_.GBPosition_GetCol(*args, **kwargs) | GetCol(self) -> int | GetCol(self) -> int | [
"GetCol",
"(",
"self",
")",
"-",
">",
"int"
] | def GetCol(*args, **kwargs):
"""GetCol(self) -> int"""
return _core_.GBPosition_GetCol(*args, **kwargs) | [
"def",
"GetCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"GBPosition_GetCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L15576-L15578 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-configure-cache.py | python | rearrange_cache_entries | (current_prefix_len, new_prefix_len) | Move cache files if prefix length changed.
Move the existing cache files to new directories of the
appropriate name length and clean up the old directories. | Move cache files if prefix length changed. | [
"Move",
"cache",
"files",
"if",
"prefix",
"length",
"changed",
"."
] | def rearrange_cache_entries(current_prefix_len, new_prefix_len):
'''Move cache files if prefix length changed.
Move the existing cache files to new directories of the
appropriate name length and clean up the old directories.
'''
print('Changing prefix length from', current_prefix_len,
'to', new_prefix_len)
dirs = set()
old_dirs = set()
for file in glob.iglob(os.path.join('*', '*')):
name = os.path.basename(file)
dname = name[:current_prefix_len].upper()
if dname not in old_dirs:
print('Migrating', dname)
old_dirs.add(dname)
dname = name[:new_prefix_len].upper()
if dname not in dirs:
os.mkdir(dname)
dirs.add(dname)
os.rename(file, os.path.join(dname, name))
# Now delete the original directories
for dname in old_dirs:
os.rmdir(dname) | [
"def",
"rearrange_cache_entries",
"(",
"current_prefix_len",
",",
"new_prefix_len",
")",
":",
"print",
"(",
"'Changing prefix length from'",
",",
"current_prefix_len",
",",
"'to'",
",",
"new_prefix_len",
")",
"dirs",
"=",
"set",
"(",
")",
"old_dirs",
"=",
"set",
"... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-configure-cache.py#L53-L77 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.get_all_side_set_params | (self) | return totNumSetSides, totNumSetNodes, totNumSetDistFacts | get total number of sides, nodes, and distribution factors
(e.g. nodal 'weights') combined among all side sets
>>> tot_num_ss_sides, tot_num_ss_nodes, tot_num_ss_dist_facts =
... exo.get_all_side_set_params()
Returns
-------
<int> tot_num_ss_sides
<int> tot_num_ss_nodes
<int> tot_num_ss_dist_facts
Note:
-----
The number of nodes (and distribution factors) in a side set is
the sum of all face nodes. A single node can be counted more
than once, i.e. once for each face it belongs to in the side set. | get total number of sides, nodes, and distribution factors
(e.g. nodal 'weights') combined among all side sets | [
"get",
"total",
"number",
"of",
"sides",
"nodes",
"and",
"distribution",
"factors",
"(",
"e",
".",
"g",
".",
"nodal",
"weights",
")",
"combined",
"among",
"all",
"side",
"sets"
] | def get_all_side_set_params(self):
"""
get total number of sides, nodes, and distribution factors
(e.g. nodal 'weights') combined among all side sets
>>> tot_num_ss_sides, tot_num_ss_nodes, tot_num_ss_dist_facts =
... exo.get_all_side_set_params()
Returns
-------
<int> tot_num_ss_sides
<int> tot_num_ss_nodes
<int> tot_num_ss_dist_facts
Note:
-----
The number of nodes (and distribution factors) in a side set is
the sum of all face nodes. A single node can be counted more
than once, i.e. once for each face it belongs to in the side set.
"""
ids = self.__ex_get_ids('EX_SIDE_SET')
totNumSetSides, totNumSetDistFacts = 0, 0 # totNumSetDistFacts = totNumSetNodes
for sideSetId in ids:
(numSetSides, numSetDistFacts) = self.__ex_get_set_param('EX_SIDE_SET', sideSetId)
totNumSetSides += numSetSides
totNumSetDistFacts += numSetDistFacts
totNumSetNodes = totNumSetDistFacts
return totNumSetSides, totNumSetNodes, totNumSetDistFacts | [
"def",
"get_all_side_set_params",
"(",
"self",
")",
":",
"ids",
"=",
"self",
".",
"__ex_get_ids",
"(",
"'EX_SIDE_SET'",
")",
"totNumSetSides",
",",
"totNumSetDistFacts",
"=",
"0",
",",
"0",
"# totNumSetDistFacts = totNumSetNodes",
"for",
"sideSetId",
"in",
"ids",
... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L3834-L3861 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | DC.SetBrush | (*args, **kwargs) | return _gdi_.DC_SetBrush(*args, **kwargs) | SetBrush(self, Brush brush)
Sets the current brush for the DC.
If the argument is ``wx.NullBrush``, the current brush is selected out
of the device context, and the original brush restored, allowing the
current brush to be destroyed safely. | SetBrush(self, Brush brush) | [
"SetBrush",
"(",
"self",
"Brush",
"brush",
")"
] | def SetBrush(*args, **kwargs):
"""
SetBrush(self, Brush brush)
Sets the current brush for the DC.
If the argument is ``wx.NullBrush``, the current brush is selected out
of the device context, and the original brush restored, allowing the
current brush to be destroyed safely.
"""
return _gdi_.DC_SetBrush(*args, **kwargs) | [
"def",
"SetBrush",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_SetBrush",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L4026-L4036 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | MaskedArray.filled | (self, fill_value=None) | A numeric array with masked values filled. If fill_value is None,
use self.fill_value().
If mask is nomask, copy data only if not contiguous.
Result is always a contiguous, numeric array.
# Is contiguous really necessary now? | A numeric array with masked values filled. If fill_value is None,
use self.fill_value(). | [
"A",
"numeric",
"array",
"with",
"masked",
"values",
"filled",
".",
"If",
"fill_value",
"is",
"None",
"use",
"self",
".",
"fill_value",
"()",
"."
] | def filled (self, fill_value=None):
"""A numeric array with masked values filled. If fill_value is None,
use self.fill_value().
If mask is nomask, copy data only if not contiguous.
Result is always a contiguous, numeric array.
# Is contiguous really necessary now?
"""
d = self._data
m = self._mask
if m is nomask:
if d.flags['CONTIGUOUS']:
return d
else:
return d.copy()
else:
if fill_value is None:
value = self._fill_value
else:
value = fill_value
if self is masked:
result = numeric.array(value)
else:
try:
result = numeric.array(d, dtype=d.dtype, copy=1)
result[m] = value
except (TypeError, AttributeError):
#ok, can't put that value in here
value = numeric.array(value, dtype=object)
d = d.astype(object)
result = fromnumeric.choose(m, (d, value))
return result | [
"def",
"filled",
"(",
"self",
",",
"fill_value",
"=",
"None",
")",
":",
"d",
"=",
"self",
".",
"_data",
"m",
"=",
"self",
".",
"_mask",
"if",
"m",
"is",
"nomask",
":",
"if",
"d",
".",
"flags",
"[",
"'CONTIGUOUS'",
"]",
":",
"return",
"d",
"else",... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1236-L1268 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Runtime/VART/vart/rnn-runner/apps/open_information_extraction/utils/stacked_alternating_lstm_dpu_new_v2.py | python | StackedAlternatingLstm.forward | (
self, inputs: PackedSequence, initial_state: Optional[TensorPair] = None
) | return output_sequence, (final_hidden_state, final_cell_state) | Parameters
----------
inputs : ``PackedSequence``, required.
A batch first ``PackedSequence`` to run the stacked LSTM over.
initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)
A tuple (state, memory) representing the initial hidden state and memory
of the LSTM. Each tensor has shape (1, batch_size, output_dimension).
Returns
-------
output_sequence : PackedSequence
The encoded sequence of shape (batch_size, sequence_length, hidden_size)
final_states: Tuple[torch.Tensor, torch.Tensor]
The per-layer final (state, memory) states of the LSTM, each with shape
(num_layers, batch_size, hidden_size). | Parameters
----------
inputs : ``PackedSequence``, required.
A batch first ``PackedSequence`` to run the stacked LSTM over.
initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)
A tuple (state, memory) representing the initial hidden state and memory
of the LSTM. Each tensor has shape (1, batch_size, output_dimension). | [
"Parameters",
"----------",
"inputs",
":",
"PackedSequence",
"required",
".",
"A",
"batch",
"first",
"PackedSequence",
"to",
"run",
"the",
"stacked",
"LSTM",
"over",
".",
"initial_state",
":",
"Tuple",
"[",
"torch",
".",
"Tensor",
"torch",
".",
"Tensor",
"]",
... | def forward(
self, inputs: PackedSequence, initial_state: Optional[TensorPair] = None
) -> Tuple[Union[torch.Tensor, PackedSequence], TensorPair]:
"""
Parameters
----------
inputs : ``PackedSequence``, required.
A batch first ``PackedSequence`` to run the stacked LSTM over.
initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)
A tuple (state, memory) representing the initial hidden state and memory
of the LSTM. Each tensor has shape (1, batch_size, output_dimension).
Returns
-------
output_sequence : PackedSequence
The encoded sequence of shape (batch_size, sequence_length, hidden_size)
final_states: Tuple[torch.Tensor, torch.Tensor]
The per-layer final (state, memory) states of the LSTM, each with shape
(num_layers, batch_size, hidden_size).
"""
if not initial_state:
hidden_states: List[Optional[TensorPair]] = [
None] * len(self.lstm_layers)
elif initial_state[0].size()[0] != len(self.lstm_layers):
raise ConfigurationError(
"Initial states were passed to forward() but the number of "
"initial states does not match the number of layers."
)
else:
hidden_states = list(
zip(initial_state[0].split(1, 0), initial_state[1].split(1, 0)))
t1 = time.time()
dpu_time = 0
out_pos = self.xgraph.get_root_subgraph().get_attr('output_fix2float')
in_pos = self.xgraph.get_root_subgraph().get_attr('input_float2fix')
input_scale = 2.0**in_pos
output_scale = 2.0**out_pos
sequence_tensor, batch_lengths = pad_packed_sequence(
inputs, batch_first=True)
frame_num = len(sequence_tensor[0])
zeros_cat = np.zeros((frame_num, 24), dtype=np.int16)
frame_size = len(sequence_tensor[0]) * 224 * 2
layer_output = []
for i in range(sequence_tensor.shape[0]):
hw_input = torch.floor(
sequence_tensor.data[i] * input_scale).cpu().short().numpy()
# padding the input as 224
hw_input = np.concatenate((hw_input, zeros_cat), axis=1)
output = np.zeros((1, frame_num, 300), dtype=np.int16)
hw_output = np.zeros((1, frame_num, 320), dtype=np.int16)
t3 = time.time()
self.model_lstm.execute_async([hw_input.reshape(1, frame_num, 224)],
[hw_output.reshape(1, frame_num, 320)], True)
t4 = time.time()
output = hw_output[:, :, :300]
layer_output.append(output.reshape(frame_num, 300))
dpu_time += (t4-t3)
torch_output = torch.from_numpy(
np.array(layer_output, dtype=np.float32)/output_scale)
output_sequence = pack_padded_sequence(
torch_output, batch_lengths, batch_first=True)
new_shape = (len(hidden_states), len(batch_lengths),
len(output_sequence.data[0]))
final_hidden_state = torch.zeros(new_shape)
final_cell_state = torch.zeros(new_shape)
t2 = time.time()
print()
print("DPU LSTM time: ", t2 - t1)
print("DPU time (without memcpy): ", dpu_time)
return output_sequence, (final_hidden_state, final_cell_state) | [
"def",
"forward",
"(",
"self",
",",
"inputs",
":",
"PackedSequence",
",",
"initial_state",
":",
"Optional",
"[",
"TensorPair",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"Union",
"[",
"torch",
".",
"Tensor",
",",
"PackedSequence",
"]",
",",
"TensorPair",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/rnn-runner/apps/open_information_extraction/utils/stacked_alternating_lstm_dpu_new_v2.py#L302-L376 | |
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/json_format.py | python | _Printer._ListValueMessageToJsonObject | (self, message) | return [self._ValueMessageToJsonObject(value)
for value in message.values] | Converts ListValue message according to Proto3 JSON Specification. | Converts ListValue message according to Proto3 JSON Specification. | [
"Converts",
"ListValue",
"message",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | def _ListValueMessageToJsonObject(self, message):
"""Converts ListValue message according to Proto3 JSON Specification."""
return [self._ValueMessageToJsonObject(value)
for value in message.values] | [
"def",
"_ListValueMessageToJsonObject",
"(",
"self",
",",
"message",
")",
":",
"return",
"[",
"self",
".",
"_ValueMessageToJsonObject",
"(",
"value",
")",
"for",
"value",
"in",
"message",
".",
"values",
"]"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/json_format.py#L263-L266 | |
blackberry/Boost | fc90c3fde129c62565c023f091eddc4a7ed9902b | tools/build/v2/build/scanner.py | python | registered | (scanner_class) | return __scanners.has_key(str(scanner_class)) | Returns true iff a scanner of that class is registered | Returns true iff a scanner of that class is registered | [
"Returns",
"true",
"iff",
"a",
"scanner",
"of",
"that",
"class",
"is",
"registered"
] | def registered(scanner_class):
""" Returns true iff a scanner of that class is registered
"""
return __scanners.has_key(str(scanner_class)) | [
"def",
"registered",
"(",
"scanner_class",
")",
":",
"return",
"__scanners",
".",
"has_key",
"(",
"str",
"(",
"scanner_class",
")",
")"
] | https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/scanner.py#L61-L64 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py | python | _NamespaceLoader.module_repr | (cls, module) | return '<module {!r} (namespace)>'.format(module.__name__) | Return repr for the module.
The method is deprecated. The import machinery does the job itself. | Return repr for the module. | [
"Return",
"repr",
"for",
"the",
"module",
"."
] | def module_repr(cls, module):
"""Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
return '<module {!r} (namespace)>'.format(module.__name__) | [
"def",
"module_repr",
"(",
"cls",
",",
"module",
")",
":",
"return",
"'<module {!r} (namespace)>'",
".",
"format",
"(",
"module",
".",
"__name__",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py#L1139-L1145 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/opset1/ops.py | python | divide | (
left_node: NodeInput,
right_node: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) | return _get_node_factory_opset1().create(
"Divide", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
) | Return node which applies f(x) = A/B to the input nodes element-wise.
:param left_node: The node providing dividend data.
:param right_node: The node providing divisor data.
:param auto_broadcast: Specifies rules used for auto-broadcasting of input tensors.
:param name: Optional name for output node.
:return: The node performing element-wise division. | Return node which applies f(x) = A/B to the input nodes element-wise. | [
"Return",
"node",
"which",
"applies",
"f",
"(",
"x",
")",
"=",
"A",
"/",
"B",
"to",
"the",
"input",
"nodes",
"element",
"-",
"wise",
"."
] | def divide(
left_node: NodeInput,
right_node: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) -> Node:
"""Return node which applies f(x) = A/B to the input nodes element-wise.
:param left_node: The node providing dividend data.
:param right_node: The node providing divisor data.
:param auto_broadcast: Specifies rules used for auto-broadcasting of input tensors.
:param name: Optional name for output node.
:return: The node performing element-wise division.
"""
return _get_node_factory_opset1().create(
"Divide", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
) | [
"def",
"divide",
"(",
"left_node",
":",
"NodeInput",
",",
"right_node",
":",
"NodeInput",
",",
"auto_broadcast",
":",
"str",
"=",
"\"NUMPY\"",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Node",
":",
"return",
"_get_node_f... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset1/ops.py#L770-L786 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/platform/tf_logging.py | python | set_verbosity | (v) | Sets the threshold for what messages will be logged. | Sets the threshold for what messages will be logged. | [
"Sets",
"the",
"threshold",
"for",
"what",
"messages",
"will",
"be",
"logged",
"."
] | def set_verbosity(v):
"""Sets the threshold for what messages will be logged."""
_logger.setLevel(v) | [
"def",
"set_verbosity",
"(",
"v",
")",
":",
"_logger",
".",
"setLevel",
"(",
"v",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/platform/tf_logging.py#L231-L233 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | ParseBaseException._from_exception | (cls, pe) | return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses | [] | def _from_exception(cls, pe):
"""
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
"""
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | [
"def",
"_from_exception",
"(",
"cls",
",",
"pe",
")",
":",
"return",
"cls",
"(",
"pe",
".",
"pstr",
",",
"pe",
".",
"loc",
",",
"pe",
".",
"msg",
",",
"pe",
".",
"parserElement",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L631-L641 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | TextEntryBase.Undo | (*args, **kwargs) | return _core_.TextEntryBase_Undo(*args, **kwargs) | Undo(self)
Undoes the last edit in the text field | Undo(self) | [
"Undo",
"(",
"self",
")"
] | def Undo(*args, **kwargs):
"""
Undo(self)
Undoes the last edit in the text field
"""
return _core_.TextEntryBase_Undo(*args, **kwargs) | [
"def",
"Undo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"TextEntryBase_Undo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13207-L13213 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/name.py | python | Name.__hash__ | (self) | return int(h % sys.maxint) | Return a case-insensitive hash of the name.
@rtype: int | Return a case-insensitive hash of the name. | [
"Return",
"a",
"case",
"-",
"insensitive",
"hash",
"of",
"the",
"name",
"."
] | def __hash__(self):
"""Return a case-insensitive hash of the name.
@rtype: int
"""
h = 0L
for label in self.labels:
for c in label:
h += ( h << 3 ) + ord(c.lower())
return int(h % sys.maxint) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"h",
"=",
"0L",
"for",
"label",
"in",
"self",
".",
"labels",
":",
"for",
"c",
"in",
"label",
":",
"h",
"+=",
"(",
"h",
"<<",
"3",
")",
"+",
"ord",
"(",
"c",
".",
"lower",
"(",
")",
")",
"return",
"i... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/name.py#L165-L174 | |
christinaa/LLVM-VideoCore4 | 7773c3c9e5d22b785d4b96ed0acea37c8aa9c183 | utils/llvm-build/llvmbuild/main.py | python | make_install_dir | (path) | make_install_dir(path) -> None
Create the given directory path for installation, including any parents. | make_install_dir(path) -> None | [
"make_install_dir",
"(",
"path",
")",
"-",
">",
"None"
] | def make_install_dir(path):
"""
make_install_dir(path) -> None
Create the given directory path for installation, including any parents.
"""
# os.makedirs considers it an error to be called with an existent path.
if not os.path.exists(path):
os.makedirs(path) | [
"def",
"make_install_dir",
"(",
"path",
")",
":",
"# os.makedirs considers it an error to be called with an existent path.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")"
] | https://github.com/christinaa/LLVM-VideoCore4/blob/7773c3c9e5d22b785d4b96ed0acea37c8aa9c183/utils/llvm-build/llvmbuild/main.py#L51-L60 | ||
ideawu/ssdb | f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4 | deps/cpy/antlr3/recognizers.py | python | BaseRecognizer.recoverFromMismatchedToken | (self, input, ttype, follow) | Attempt to recover from a single missing or extra token.
EXTRA TOKEN
LA(1) is not what we are looking for. If LA(2) has the right token,
however, then assume LA(1) is some extra spurious token. Delete it
and LA(2) as if we were doing a normal match(), which advances the
input.
MISSING TOKEN
If current token is consistent with what could come after
ttype then it is ok to 'insert' the missing token, else throw
exception For example, Input 'i=(3;' is clearly missing the
')'. When the parser returns from the nested call to expr, it
will have call chain:
stat -> expr -> atom
and it will be trying to match the ')' at this point in the
derivation:
=> ID '=' '(' INT ')' ('+' atom)* ';'
^
match() will see that ';' doesn't match ')' and report a
mismatched token error. To recover, it sees that LA(1)==';'
is in the set of tokens that can follow the ')' token
reference in rule atom. It can assume that you forgot the ')'. | Attempt to recover from a single missing or extra token. | [
"Attempt",
"to",
"recover",
"from",
"a",
"single",
"missing",
"or",
"extra",
"token",
"."
] | def recoverFromMismatchedToken(self, input, ttype, follow):
"""Attempt to recover from a single missing or extra token.
EXTRA TOKEN
LA(1) is not what we are looking for. If LA(2) has the right token,
however, then assume LA(1) is some extra spurious token. Delete it
and LA(2) as if we were doing a normal match(), which advances the
input.
MISSING TOKEN
If current token is consistent with what could come after
ttype then it is ok to 'insert' the missing token, else throw
exception For example, Input 'i=(3;' is clearly missing the
')'. When the parser returns from the nested call to expr, it
will have call chain:
stat -> expr -> atom
and it will be trying to match the ')' at this point in the
derivation:
=> ID '=' '(' INT ')' ('+' atom)* ';'
^
match() will see that ';' doesn't match ')' and report a
mismatched token error. To recover, it sees that LA(1)==';'
is in the set of tokens that can follow the ')' token
reference in rule atom. It can assume that you forgot the ')'.
"""
e = None
# if next token is what we are looking for then "delete" this token
if self. mismatchIsUnwantedToken(input, ttype):
e = UnwantedTokenException(ttype, input)
self.beginResync()
input.consume() # simply delete extra token
self.endResync()
# report after consuming so AW sees the token in the exception
self.reportError(e)
# we want to return the token we're actually matching
matchedSymbol = self.getCurrentInputSymbol(input)
# move past ttype token as if all were ok
input.consume()
return matchedSymbol
# can't recover with single token deletion, try insertion
if self.mismatchIsMissingToken(input, follow):
inserted = self.getMissingSymbol(input, e, ttype, follow)
e = MissingTokenException(ttype, input, inserted)
# report after inserting so AW sees the token in the exception
self.reportError(e)
return inserted
# even that didn't work; must throw the exception
e = MismatchedTokenException(ttype, input)
raise e | [
"def",
"recoverFromMismatchedToken",
"(",
"self",
",",
"input",
",",
"ttype",
",",
"follow",
")",
":",
"e",
"=",
"None",
"# if next token is what we are looking for then \"delete\" this token",
"if",
"self",
".",
"mismatchIsUnwantedToken",
"(",
"input",
",",
"ttype",
... | https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/recognizers.py#L712-L774 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/service.py | python | GDataService.GetWithRetries | (self, uri, extra_headers=None, redirects_remaining=4,
encoding='UTF-8', converter=None, num_retries=DEFAULT_NUM_RETRIES,
delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF, logger=None) | This is a wrapper method for Get with retring capability.
To avoid various errors while retrieving bulk entities by retring
specified times.
Note this method relies on the time module and so may not be usable
by default in Python2.2.
Args:
num_retries: integer The retry count.
delay: integer The initial delay for retring.
backoff: integer how much the delay should lengthen after each failure.
logger: an object which has a debug(str) method to receive logging
messages. Recommended that you pass in the logging module.
Raises:
ValueError if any of the parameters has an invalid value.
RanOutOfTries on failure after number of retries. | This is a wrapper method for Get with retring capability. | [
"This",
"is",
"a",
"wrapper",
"method",
"for",
"Get",
"with",
"retring",
"capability",
"."
] | def GetWithRetries(self, uri, extra_headers=None, redirects_remaining=4,
encoding='UTF-8', converter=None, num_retries=DEFAULT_NUM_RETRIES,
delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF, logger=None):
"""This is a wrapper method for Get with retring capability.
To avoid various errors while retrieving bulk entities by retring
specified times.
Note this method relies on the time module and so may not be usable
by default in Python2.2.
Args:
num_retries: integer The retry count.
delay: integer The initial delay for retring.
backoff: integer how much the delay should lengthen after each failure.
logger: an object which has a debug(str) method to receive logging
messages. Recommended that you pass in the logging module.
Raises:
ValueError if any of the parameters has an invalid value.
RanOutOfTries on failure after number of retries.
"""
# Moved import for time module inside this method since time is not a
# default module in Python2.2. This method will not be usable in
# Python2.2.
import time
if backoff <= 1:
raise ValueError("backoff must be greater than 1")
num_retries = int(num_retries)
if num_retries < 0:
raise ValueError("num_retries must be 0 or greater")
if delay <= 0:
raise ValueError("delay must be greater than 0")
# Let's start
mtries, mdelay = num_retries, delay
while mtries > 0:
if mtries != num_retries:
if logger:
logger.debug("Retrying...")
try:
rv = self.Get(uri, extra_headers=extra_headers,
redirects_remaining=redirects_remaining,
encoding=encoding, converter=converter)
except (SystemExit, RequestError):
# Allow these errors
raise
except Exception, e:
if logger:
logger.debug(e)
mtries -= 1
time.sleep(mdelay)
mdelay *= backoff
else:
# This is the right path.
if logger:
logger.debug("Succeeeded...")
return rv
raise RanOutOfTries('Ran out of tries.') | [
"def",
"GetWithRetries",
"(",
"self",
",",
"uri",
",",
"extra_headers",
"=",
"None",
",",
"redirects_remaining",
"=",
"4",
",",
"encoding",
"=",
"'UTF-8'",
",",
"converter",
"=",
"None",
",",
"num_retries",
"=",
"DEFAULT_NUM_RETRIES",
",",
"delay",
"=",
"DEF... | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/service.py#L973-L1032 | ||
CaoWGG/TensorRT-CenterNet | f949252e37b51e60f873808f46d3683f15735e79 | onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py | python | TranslationUnit.get_extent | (self, filename, locations) | return SourceRange.from_locations(start_location, end_location) | Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15))) | Obtain a SourceRange from this translation unit. | [
"Obtain",
"a",
"SourceRange",
"from",
"this",
"translation",
"unit",
"."
] | def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15)))
"""
f = self.get_file(filename)
if len(locations) < 2:
raise Exception('Must pass object with at least 2 elements')
start_location, end_location = locations
if hasattr(start_location, '__len__'):
start_location = SourceLocation.from_position(self, f,
start_location[0], start_location[1])
elif isinstance(start_location, int):
start_location = SourceLocation.from_offset(self, f,
start_location)
if hasattr(end_location, '__len__'):
end_location = SourceLocation.from_position(self, f,
end_location[0], end_location[1])
elif isinstance(end_location, int):
end_location = SourceLocation.from_offset(self, f, end_location)
assert isinstance(start_location, SourceLocation)
assert isinstance(end_location, SourceLocation)
return SourceRange.from_locations(start_location, end_location) | [
"def",
"get_extent",
"(",
"self",
",",
"filename",
",",
"locations",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"len",
"(",
"locations",
")",
"<",
"2",
":",
"raise",
"Exception",
"(",
"'Must pass object with at least 2 elements'... | https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L2626-L2664 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/webkit.py | python | WebKitNewWindowEvent.SetURL | (*args, **kwargs) | return _webkit.WebKitNewWindowEvent_SetURL(*args, **kwargs) | SetURL(self, String url) | SetURL(self, String url) | [
"SetURL",
"(",
"self",
"String",
"url",
")"
] | def SetURL(*args, **kwargs):
"""SetURL(self, String url)"""
return _webkit.WebKitNewWindowEvent_SetURL(*args, **kwargs) | [
"def",
"SetURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_webkit",
".",
"WebKitNewWindowEvent_SetURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/webkit.py#L266-L268 | |
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_data.py | python | SymbolList.__repr__ | (self) | return 'SymbolList(%s)' % super(SymbolList, self).__repr__() | Representation of SymbolList | Representation of SymbolList | [
"Representation",
"of",
"SymbolList"
] | def __repr__(self) -> str:
""" Representation of SymbolList """
return 'SymbolList(%s)' % super(SymbolList, self).__repr__() | [
"def",
"__repr__",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'SymbolList(%s)'",
"%",
"super",
"(",
"SymbolList",
",",
"self",
")",
".",
"__repr__",
"(",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_data.py#L548-L550 | |
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | api/ctpx/ctptd.py | python | CtpTd.onRtnQuote | (self, QuoteField) | 报价通知 | 报价通知 | [
"报价通知"
] | def onRtnQuote(self, QuoteField):
"""报价通知"""
pass | [
"def",
"onRtnQuote",
"(",
"self",
",",
"QuoteField",
")",
":",
"pass"
] | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L399-L401 | ||
raymondlu/super-animation-samples | 04234269112ff0dc32447f27a761dbbb00b8ba17 | samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | TranslationUnit.reparse | (self, unsaved_files=None, options=0) | Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects. | Reparse an already parsed translation unit. | [
"Reparse",
"an",
"already",
"parsed",
"translation",
"unit",
"."
] | def reparse(self, unsaved_files=None, options=0):
"""
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print value
if not isinstance(value, str):
raise TypeError,'Unexpected unsaved file contents.'
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
unsaved_files_array, options) | [
"def",
"reparse",
"(",
"self",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
")",
":",
"if",
"unsaved_files",
"is",
"None",
":",
"unsaved_files",
"=",
"[",
"]",
"unsaved_files_array",
"=",
"0",
"if",
"len",
"(",
"unsaved_files",
")",
":",
... | https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L2199-L2226 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.ParaDownExtend | (*args, **kwargs) | return _stc.StyledTextCtrl_ParaDownExtend(*args, **kwargs) | ParaDownExtend(self) | ParaDownExtend(self) | [
"ParaDownExtend",
"(",
"self",
")"
] | def ParaDownExtend(*args, **kwargs):
"""ParaDownExtend(self)"""
return _stc.StyledTextCtrl_ParaDownExtend(*args, **kwargs) | [
"def",
"ParaDownExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_ParaDownExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L5288-L5290 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/_pyio.py | python | RawIOBase.readinto | (self, b) | Read up to len(b) bytes into b.
Returns number of bytes read (0 for EOF), or None if the object
is set not to block and has no data to read. | Read up to len(b) bytes into b. | [
"Read",
"up",
"to",
"len",
"(",
"b",
")",
"bytes",
"into",
"b",
"."
] | def readinto(self, b):
"""Read up to len(b) bytes into b.
Returns number of bytes read (0 for EOF), or None if the object
is set not to block and has no data to read.
"""
self._unsupported("readinto") | [
"def",
"readinto",
"(",
"self",
",",
"b",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"readinto\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/_pyio.py#L572-L578 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/multi.py | python | MultiIndex._nbytes | (self, deep: bool = False) | return result | return the number of bytes in the underlying data
deeply introspect the level data if deep=True
include the engine hashtable
*this is in internal routine* | return the number of bytes in the underlying data
deeply introspect the level data if deep=True | [
"return",
"the",
"number",
"of",
"bytes",
"in",
"the",
"underlying",
"data",
"deeply",
"introspect",
"the",
"level",
"data",
"if",
"deep",
"=",
"True"
] | def _nbytes(self, deep: bool = False) -> int:
"""
return the number of bytes in the underlying data
deeply introspect the level data if deep=True
include the engine hashtable
*this is in internal routine*
"""
# for implementations with no useful getsizeof (PyPy)
objsize = 24
level_nbytes = sum(i.memory_usage(deep=deep) for i in self.levels)
label_nbytes = sum(i.nbytes for i in self.codes)
names_nbytes = sum(getsizeof(i, objsize) for i in self.names)
result = level_nbytes + label_nbytes + names_nbytes
# include our engine hashtable
result += self._engine.sizeof(deep=deep)
return result | [
"def",
"_nbytes",
"(",
"self",
",",
"deep",
":",
"bool",
"=",
"False",
")",
"->",
"int",
":",
"# for implementations with no useful getsizeof (PyPy)",
"objsize",
"=",
"24",
"level_nbytes",
"=",
"sum",
"(",
"i",
".",
"memory_usage",
"(",
"deep",
"=",
"deep",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/multi.py#L1023-L1044 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/tools/gcc.py | python | init | (version = None, command = None, options = None) | Initializes the gcc toolset for the given version. If necessary, command may
be used to specify where the compiler is located. The parameter 'options' is a
space-delimited list of options, each one specified as
<option-name>option-value. Valid option names are: cxxflags, linkflags and
linker-type. Accepted linker-type values are gnu, darwin, osf, hpux or sun
and the default value will be selected based on the current OS.
Example:
using gcc : 3.4 : : <cxxflags>foo <linkflags>bar <linker-type>sun ; | Initializes the gcc toolset for the given version. If necessary, command may
be used to specify where the compiler is located. The parameter 'options' is a
space-delimited list of options, each one specified as
<option-name>option-value. Valid option names are: cxxflags, linkflags and
linker-type. Accepted linker-type values are gnu, darwin, osf, hpux or sun
and the default value will be selected based on the current OS.
Example:
using gcc : 3.4 : : <cxxflags>foo <linkflags>bar <linker-type>sun ; | [
"Initializes",
"the",
"gcc",
"toolset",
"for",
"the",
"given",
"version",
".",
"If",
"necessary",
"command",
"may",
"be",
"used",
"to",
"specify",
"where",
"the",
"compiler",
"is",
"located",
".",
"The",
"parameter",
"options",
"is",
"a",
"space",
"-",
"de... | def init(version = None, command = None, options = None):
"""
Initializes the gcc toolset for the given version. If necessary, command may
be used to specify where the compiler is located. The parameter 'options' is a
space-delimited list of options, each one specified as
<option-name>option-value. Valid option names are: cxxflags, linkflags and
linker-type. Accepted linker-type values are gnu, darwin, osf, hpux or sun
and the default value will be selected based on the current OS.
Example:
using gcc : 3.4 : : <cxxflags>foo <linkflags>bar <linker-type>sun ;
"""
options = to_seq(options)
command = to_seq(command)
# Information about the gcc command...
# The command.
command = to_seq(common.get_invocation_command('gcc', 'g++', command))
# The root directory of the tool install.
root = feature.get_values('<root>', options)
root = root[0] if root else ''
# The bin directory where to find the command to execute.
bin = None
# The flavor of compiler.
flavor = feature.get_values('<flavor>', options)
flavor = flavor[0] if flavor else ''
# Autodetect the root and bin dir if not given.
if command:
if not bin:
bin = common.get_absolute_tool_path(command[-1])
if not root:
root = os.path.dirname(bin)
# Autodetect the version and flavor if not given.
if command:
machine_info = subprocess.Popen(command + ['-dumpmachine'], stdout=subprocess.PIPE).communicate()[0]
machine = __machine_match.search(machine_info).group(1)
version_info = subprocess.Popen(command + ['-dumpversion'], stdout=subprocess.PIPE).communicate()[0]
version = __version_match.search(version_info).group(1)
if not flavor and machine.find('mingw') != -1:
flavor = 'mingw'
condition = None
if flavor:
condition = common.check_init_parameters('gcc', None,
('version', version),
('flavor', flavor))
else:
condition = common.check_init_parameters('gcc', None,
('version', version))
if command:
command = command[0]
common.handle_options('gcc', condition, command, options)
linker = feature.get_values('<linker-type>', options)
if not linker:
if os_name() == 'OSF':
linker = 'osf'
elif os_name() == 'HPUX':
linker = 'hpux' ;
else:
linker = 'gnu'
init_link_flags('gcc', linker, condition)
# If gcc is installed in non-standard location, we'd need to add
# LD_LIBRARY_PATH when running programs created with it (for unit-test/run
# rules).
if command:
# On multilib 64-bit boxes, there are both 32-bit and 64-bit libraries
# and all must be added to LD_LIBRARY_PATH. The linker will pick the
# right ones. Note that we don't provide a clean way to build 32-bit
# binary with 64-bit compiler, but user can always pass -m32 manually.
lib_path = [os.path.join(root, 'bin'),
os.path.join(root, 'lib'),
os.path.join(root, 'lib32'),
os.path.join(root, 'lib64')]
if debug():
print 'notice: using gcc libraries ::', condition, '::', lib_path
toolset.flags('gcc.link', 'RUN_PATH', condition, lib_path)
# If it's not a system gcc install we should adjust the various programs as
# needed to prefer using the install specific versions. This is essential
# for correct use of MinGW and for cross-compiling.
# - The archive builder.
archiver = common.get_invocation_command('gcc',
'ar', feature.get_values('<archiver>', options), [bin], path_last=True)
toolset.flags('gcc.archive', '.AR', condition, [archiver])
if debug():
print 'notice: using gcc archiver ::', condition, '::', archiver
# - Ranlib
ranlib = common.get_invocation_command('gcc',
'ranlib', feature.get_values('<ranlib>', options), [bin], path_last=True)
toolset.flags('gcc.archive', '.RANLIB', condition, [ranlib])
if debug():
print 'notice: using gcc archiver ::', condition, '::', ranlib
# - The resource compiler.
rc_command = common.get_invocation_command_nodefault('gcc',
'windres', feature.get_values('<rc>', options), [bin], path_last=True)
rc_type = feature.get_values('<rc-type>', options)
if not rc_type:
rc_type = 'windres'
if not rc_command:
# If we can't find an RC compiler we fallback to a null RC compiler that
# creates empty object files. This allows the same Jamfiles to work
# across the board. The null RC uses the assembler to create the empty
# objects, so configure that.
rc_command = common.get_invocation_command('gcc', 'as', [], [bin], path_last=True)
rc_type = 'null'
rc.configure([rc_command], condition, ['<rc-type>' + rc_type]) | [
"def",
"init",
"(",
"version",
"=",
"None",
",",
"command",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"to_seq",
"(",
"options",
")",
"command",
"=",
"to_seq",
"(",
"command",
")",
"# Information about the gcc command...",
"# The c... | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/tools/gcc.py#L87-L203 | ||
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | scripts/cpp_lint.py | python | _CppLintState.PrintErrorCounts | (self) | Print a summary of errors by category, and the total. | Print a summary of errors by category, and the total. | [
"Print",
"a",
"summary",
"of",
"errors",
"by",
"category",
"and",
"the",
"total",
"."
] | def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in iteritems(self.errors_by_category):
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stderr.write('Total errors found: %d\n' % self.error_count) | [
"def",
"PrintErrorCounts",
"(",
"self",
")",
":",
"for",
"category",
",",
"count",
"in",
"iteritems",
"(",
"self",
".",
"errors_by_category",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Category \\'%s\\' errors found: %d\\n'",
"%",
"(",
"category",
",... | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L761-L766 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/codecs.py | python | StreamReader.readlines | (self, sizehint=None, keepends=True) | return data.splitlines(keepends) | Read all lines available on the input stream
and return them as list of lines.
Line breaks are implemented using the codec's decoder
method and are included in the list entries.
sizehint, if given, is ignored since there is no efficient
way to finding the true end-of-line. | Read all lines available on the input stream
and return them as list of lines. | [
"Read",
"all",
"lines",
"available",
"on",
"the",
"input",
"stream",
"and",
"return",
"them",
"as",
"list",
"of",
"lines",
"."
] | def readlines(self, sizehint=None, keepends=True):
""" Read all lines available on the input stream
and return them as list of lines.
Line breaks are implemented using the codec's decoder
method and are included in the list entries.
sizehint, if given, is ignored since there is no efficient
way to finding the true end-of-line.
"""
data = self.read()
return data.splitlines(keepends) | [
"def",
"readlines",
"(",
"self",
",",
"sizehint",
"=",
"None",
",",
"keepends",
"=",
"True",
")",
":",
"data",
"=",
"self",
".",
"read",
"(",
")",
"return",
"data",
".",
"splitlines",
"(",
"keepends",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/codecs.py#L571-L584 | |
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/win/Source/Includes/QtIncludes/src/3rdparty/freetype/src/tools/glnames.py | python | adobe_glyph_values | () | return glyphs, values | return the list of glyph names and their unicode values | return the list of glyph names and their unicode values | [
"return",
"the",
"list",
"of",
"glyph",
"names",
"and",
"their",
"unicode",
"values"
] | def adobe_glyph_values():
"""return the list of glyph names and their unicode values"""
lines = string.split( adobe_glyph_list, '\n' )
glyphs = []
values = []
for line in lines:
if line:
fields = string.split( line, ';' )
# print fields[1] + ' - ' + fields[0]
subfields = string.split( fields[1], ' ' )
if len( subfields ) == 1:
glyphs.append( fields[0] )
values.append( fields[1] )
return glyphs, values | [
"def",
"adobe_glyph_values",
"(",
")",
":",
"lines",
"=",
"string",
".",
"split",
"(",
"adobe_glyph_list",
",",
"'\\n'",
")",
"glyphs",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
":",
"fields",
"=",
"stri... | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/Includes/QtIncludes/src/3rdparty/freetype/src/tools/glnames.py#L4952-L4968 | |
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/roi_data_layer/minibatch.py | python | _get_bbox_regression_labels | (bbox_target_data, num_classes) | return bbox_targets, bbox_inside_weights | Bounding-box regression targets are stored in a compact form in the
roidb.
This function expands those targets into the 4-of-4*K representation used
by the network (i.e. only one class has non-zero targets). The loss weights
are similarly expanded.
Returns:
bbox_target_data (ndarray): N x 4K blob of regression targets
bbox_inside_weights (ndarray): N x 4K blob of loss weights | Bounding-box regression targets are stored in a compact form in the
roidb. | [
"Bounding",
"-",
"box",
"regression",
"targets",
"are",
"stored",
"in",
"a",
"compact",
"form",
"in",
"the",
"roidb",
"."
] | def _get_bbox_regression_labels(bbox_target_data, num_classes):
"""Bounding-box regression targets are stored in a compact form in the
roidb.
This function expands those targets into the 4-of-4*K representation used
by the network (i.e. only one class has non-zero targets). The loss weights
are similarly expanded.
Returns:
bbox_target_data (ndarray): N x 4K blob of regression targets
bbox_inside_weights (ndarray): N x 4K blob of loss weights
"""
clss = bbox_target_data[:, 0]
num_reg_class = 2 if cfg.TRAIN.AGNOSTIC else num_classes
bbox_targets = np.zeros((clss.size, 4 * num_reg_class), dtype=np.float32)
bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)
inds = np.where(clss > 0)[0]
if cfg.TRAIN.AGNOSTIC:
for ind in inds:
cls = clss[ind]
start = 4 * (1 if cls > 0 else 0)
end = start + 4
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
else:
for ind in inds:
cls = clss[ind]
start = 4 * cls
end = start + 4
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
return bbox_targets, bbox_inside_weights | [
"def",
"_get_bbox_regression_labels",
"(",
"bbox_target_data",
",",
"num_classes",
")",
":",
"clss",
"=",
"bbox_target_data",
"[",
":",
",",
"0",
"]",
"num_reg_class",
"=",
"2",
"if",
"cfg",
".",
"TRAIN",
".",
"AGNOSTIC",
"else",
"num_classes",
"bbox_targets",
... | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/roi_data_layer/minibatch.py#L158-L191 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | src/python/gem5/simulate/simulator.py | python | Simulator.add_json_stats_output | (self, path: str) | This function is used to set an output location for JSON. If specified,
when stats are dumped they will be output to this location as a JSON
file, in addition to any other stats' output locations specified.
:param path: That path in which the JSON should be output to. | This function is used to set an output location for JSON. If specified,
when stats are dumped they will be output to this location as a JSON
file, in addition to any other stats' output locations specified. | [
"This",
"function",
"is",
"used",
"to",
"set",
"an",
"output",
"location",
"for",
"JSON",
".",
"If",
"specified",
"when",
"stats",
"are",
"dumped",
"they",
"will",
"be",
"output",
"to",
"this",
"location",
"as",
"a",
"JSON",
"file",
"in",
"addition",
"to... | def add_json_stats_output(self, path: str) -> None:
"""
This function is used to set an output location for JSON. If specified,
when stats are dumped they will be output to this location as a JSON
file, in addition to any other stats' output locations specified.
:param path: That path in which the JSON should be output to.
"""
if not os.is_path_exists_or_creatable(path):
raise Exception(
f"Path '{path}' is is not a valid JSON output location."
)
addStatVisitor(f"json://{path}") | [
"def",
"add_json_stats_output",
"(",
"self",
",",
"path",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"os",
".",
"is_path_exists_or_creatable",
"(",
"path",
")",
":",
"raise",
"Exception",
"(",
"f\"Path '{path}' is is not a valid JSON output location.\"",
")",
... | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/gem5/simulate/simulator.py#L211-L223 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/categorical.py | python | contains | (cat, key, container) | Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``container``.
Parameters
----------
cat : :class:`Categorical`or :class:`categoricalIndex`
key : a hashable object
The key to check membership for.
container : Container (e.g. list-like or mapping)
The container to check for membership in.
Returns
-------
is_in : bool
True if ``key`` is in ``self.categories`` and location of
``key`` in ``categories`` is in ``container``, else False.
Notes
-----
This method does not check for NaN values. Do that separately
before calling this method. | Helper for membership check for ``key`` in ``cat``. | [
"Helper",
"for",
"membership",
"check",
"for",
"key",
"in",
"cat",
"."
] | def contains(cat, key, container):
"""
Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``container``.
Parameters
----------
cat : :class:`Categorical`or :class:`categoricalIndex`
key : a hashable object
The key to check membership for.
container : Container (e.g. list-like or mapping)
The container to check for membership in.
Returns
-------
is_in : bool
True if ``key`` is in ``self.categories`` and location of
``key`` in ``categories`` is in ``container``, else False.
Notes
-----
This method does not check for NaN values. Do that separately
before calling this method.
"""
hash(key)
# get location of key in categories.
# If a KeyError, the key isn't in categories, so logically
# can't be in container either.
try:
loc = cat.categories.get_loc(key)
except (KeyError, TypeError):
return False
# loc is the location of key in categories, but also the *value*
# for key in container. So, `key` may be in categories,
# but still not in `container`. Example ('b' in categories,
# but not in values):
# 'b' in Categorical(['a'], categories=['a', 'b']) # False
if is_scalar(loc):
return loc in container
else:
# if categories is an IntervalIndex, loc is an array.
return any(loc_ in container for loc_ in loc) | [
"def",
"contains",
"(",
"cat",
",",
"key",
",",
"container",
")",
":",
"hash",
"(",
"key",
")",
"# get location of key in categories.",
"# If a KeyError, the key isn't in categories, so logically",
"# can't be in container either.",
"try",
":",
"loc",
"=",
"cat",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/categorical.py#L197-L245 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/make_distrib.py | python | combine_libs | (build_dir, libs, dest_lib) | Combine multiple static libraries into a single static library. | Combine multiple static libraries into a single static library. | [
"Combine",
"multiple",
"static",
"libraries",
"into",
"a",
"single",
"static",
"library",
"."
] | def combine_libs(build_dir, libs, dest_lib):
""" Combine multiple static libraries into a single static library. """
cmdline = 'msvs_env.bat win%s python combine_libs.py -o "%s"' % (platform_arch, dest_lib)
for lib in libs:
lib_path = os.path.join(build_dir, lib)
for path in get_files(lib_path): # Expand wildcards in |lib_path|.
if not path_exists(path):
raise Exception('File not found: ' + path)
cmdline = cmdline + ' "%s"' % path
run(cmdline, os.path.join(cef_dir, 'tools')) | [
"def",
"combine_libs",
"(",
"build_dir",
",",
"libs",
",",
"dest_lib",
")",
":",
"cmdline",
"=",
"'msvs_env.bat win%s python combine_libs.py -o \"%s\"'",
"%",
"(",
"platform_arch",
",",
"dest_lib",
")",
"for",
"lib",
"in",
"libs",
":",
"lib_path",
"=",
"os",
"."... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/make_distrib.py#L242-L251 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/util.py | python | set_package | (fxn) | return set_package_wrapper | Set __package__ on the returned module.
This function is deprecated. | Set __package__ on the returned module. | [
"Set",
"__package__",
"on",
"the",
"returned",
"module",
"."
] | def set_package(fxn):
"""Set __package__ on the returned module.
This function is deprecated.
"""
@functools.wraps(fxn)
def set_package_wrapper(*args, **kwargs):
warnings.warn('The import system now takes care of this automatically.',
DeprecationWarning, stacklevel=2)
module = fxn(*args, **kwargs)
if getattr(module, '__package__', None) is None:
module.__package__ = module.__name__
if not hasattr(module, '__path__'):
module.__package__ = module.__package__.rpartition('.')[0]
return module
return set_package_wrapper | [
"def",
"set_package",
"(",
"fxn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fxn",
")",
"def",
"set_package_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'The import system now takes care of this automatical... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/util.py#L144-L160 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py | python | spawn.sendeof | (self) | This sends an EOF to the child. This sends a character which causes
the pending parent output buffer to be sent to the waiting child
program without waiting for end-of-line. If it is the first character
of the line, the read() in the user program returns 0, which signifies
end-of-file. This means to work as expected a sendeof() has to be
called at the beginning of a line. This method does not send a newline.
It is the responsibility of the caller to ensure the eof is sent at the
beginning of a line. | This sends an EOF to the child. This sends a character which causes
the pending parent output buffer to be sent to the waiting child
program without waiting for end-of-line. If it is the first character
of the line, the read() in the user program returns 0, which signifies
end-of-file. This means to work as expected a sendeof() has to be
called at the beginning of a line. This method does not send a newline.
It is the responsibility of the caller to ensure the eof is sent at the
beginning of a line. | [
"This",
"sends",
"an",
"EOF",
"to",
"the",
"child",
".",
"This",
"sends",
"a",
"character",
"which",
"causes",
"the",
"pending",
"parent",
"output",
"buffer",
"to",
"be",
"sent",
"to",
"the",
"waiting",
"child",
"program",
"without",
"waiting",
"for",
"end... | def sendeof(self):
'''This sends an EOF to the child. This sends a character which causes
the pending parent output buffer to be sent to the waiting child
program without waiting for end-of-line. If it is the first character
of the line, the read() in the user program returns 0, which signifies
end-of-file. This means to work as expected a sendeof() has to be
called at the beginning of a line. This method does not send a newline.
It is the responsibility of the caller to ensure the eof is sent at the
beginning of a line. '''
n, byte = self.ptyproc.sendeof()
self._log_control(byte) | [
"def",
"sendeof",
"(",
"self",
")",
":",
"n",
",",
"byte",
"=",
"self",
".",
"ptyproc",
".",
"sendeof",
"(",
")",
"self",
".",
"_log_control",
"(",
"byte",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/third_party/Python/module/pexpect-4.6/pexpect/pty_spawn.py#L576-L587 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/ttk.py | python | _script_from_settings | (settings) | return '\n'.join(script) | Returns an appropriate script, based on settings, according to
theme_settings definition to be used by theme_settings and
theme_create. | Returns an appropriate script, based on settings, according to
theme_settings definition to be used by theme_settings and
theme_create. | [
"Returns",
"an",
"appropriate",
"script",
"based",
"on",
"settings",
"according",
"to",
"theme_settings",
"definition",
"to",
"be",
"used",
"by",
"theme_settings",
"and",
"theme_create",
"."
] | def _script_from_settings(settings):
"""Returns an appropriate script, based on settings, according to
theme_settings definition to be used by theme_settings and
theme_create."""
script = []
# a script will be generated according to settings passed, which
# will then be evaluated by Tcl
for name, opts in settings.iteritems():
# will format specific keys according to Tcl code
if opts.get('configure'): # format 'configure'
s = ' '.join(_format_optdict(opts['configure'], True))
script.append("ttk::style configure %s %s;" % (name, s))
if opts.get('map'): # format 'map'
s = ' '.join(_format_mapdict(opts['map'], True))
script.append("ttk::style map %s %s;" % (name, s))
if 'layout' in opts: # format 'layout' which may be empty
if not opts['layout']:
s = 'null' # could be any other word, but this one makes sense
else:
s, _ = _format_layoutlist(opts['layout'])
script.append("ttk::style layout %s {\n%s\n}" % (name, s))
if opts.get('element create'): # format 'element create'
eopts = opts['element create']
etype = eopts[0]
# find where args end, and where kwargs start
argc = 1 # etype was the first one
while argc < len(eopts) and not hasattr(eopts[argc], 'iteritems'):
argc += 1
elemargs = eopts[1:argc]
elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {}
spec, opts = _format_elemcreate(etype, True, *elemargs, **elemkw)
script.append("ttk::style element create %s %s %s %s" % (
name, etype, spec, opts))
return '\n'.join(script) | [
"def",
"_script_from_settings",
"(",
"settings",
")",
":",
"script",
"=",
"[",
"]",
"# a script will be generated according to settings passed, which",
"# will then be evaluated by Tcl",
"for",
"name",
",",
"opts",
"in",
"settings",
".",
"iteritems",
"(",
")",
":",
"# w... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L203-L243 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | TextEntryBase.ChangeValue | (*args, **kwargs) | return _core_.TextEntryBase_ChangeValue(*args, **kwargs) | ChangeValue(self, String value)
Set the value in the text entry field. Does not generate a text change event. | ChangeValue(self, String value) | [
"ChangeValue",
"(",
"self",
"String",
"value",
")"
] | def ChangeValue(*args, **kwargs):
"""
ChangeValue(self, String value)
Set the value in the text entry field. Does not generate a text change event.
"""
return _core_.TextEntryBase_ChangeValue(*args, **kwargs) | [
"def",
"ChangeValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"TextEntryBase_ChangeValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13077-L13083 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/concatenation-of-array.py | python | Solution2.getConcatenation | (self, nums) | return nums+nums | :type nums: List[int]
:rtype: List[int] | :type nums: List[int]
:rtype: List[int] | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return nums+nums | [
"def",
"getConcatenation",
"(",
"self",
",",
"nums",
")",
":",
"return",
"nums",
"+",
"nums"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/concatenation-of-array.py#L17-L22 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/distributions/transformed_distribution.py | python | _static_value | (x) | return tensor_util.constant_value(ops.convert_to_tensor(x)) | Returns the static value of a `Tensor` or `None`. | Returns the static value of a `Tensor` or `None`. | [
"Returns",
"the",
"static",
"value",
"of",
"a",
"Tensor",
"or",
"None",
"."
] | def _static_value(x):
"""Returns the static value of a `Tensor` or `None`."""
return tensor_util.constant_value(ops.convert_to_tensor(x)) | [
"def",
"_static_value",
"(",
"x",
")",
":",
"return",
"tensor_util",
".",
"constant_value",
"(",
"ops",
".",
"convert_to_tensor",
"(",
"x",
")",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/transformed_distribution.py#L46-L48 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py | python | read_binary_bool_token | (file_desc: io.BufferedReader) | return get_bool(file_desc.read(1)) | Get next bool value from file
The carriage moves forward to 1 position.
:param file_desc: file descriptor
:return: next boolean value in file | Get next bool value from file
The carriage moves forward to 1 position.
:param file_desc: file descriptor
:return: next boolean value in file | [
"Get",
"next",
"bool",
"value",
"from",
"file",
"The",
"carriage",
"moves",
"forward",
"to",
"1",
"position",
".",
":",
"param",
"file_desc",
":",
"file",
"descriptor",
":",
"return",
":",
"next",
"boolean",
"value",
"in",
"file"
] | def read_binary_bool_token(file_desc: io.BufferedReader) -> bool:
"""
Get next bool value from file
The carriage moves forward to 1 position.
:param file_desc: file descriptor
:return: next boolean value in file
"""
return get_bool(file_desc.read(1)) | [
"def",
"read_binary_bool_token",
"(",
"file_desc",
":",
"io",
".",
"BufferedReader",
")",
"->",
"bool",
":",
"return",
"get_bool",
"(",
"file_desc",
".",
"read",
"(",
"1",
")",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py#L101-L108 | |
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | examples/demoapps/ContributionsExample.py | python | MyEventHandler.__init__ | (self, stop) | Construct a handler | Construct a handler | [
"Construct",
"a",
"handler"
] | def __init__(self, stop):
""" Construct a handler """
self.stop = stop | [
"def",
"__init__",
"(",
"self",
",",
"stop",
")",
":",
"self",
".",
"stop",
"=",
"stop"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/examples/demoapps/ContributionsExample.py#L30-L32 | ||
Stellarium/stellarium | f289cda0d618180bbd3afe82f23d86ec0ac3c5e9 | util/DSSToStellarium/dssUtils.py | python | DssWcs.raDecToPixel | (self, raDecPos) | return ret | Return the pixel pos for a given RA DEC sky position (even if outside the plate)
the passed wcs must be the one laying in the preparedPlates directory | Return the pixel pos for a given RA DEC sky position (even if outside the plate)
the passed wcs must be the one laying in the preparedPlates directory | [
"Return",
"the",
"pixel",
"pos",
"for",
"a",
"given",
"RA",
"DEC",
"sky",
"position",
"(",
"even",
"if",
"outside",
"the",
"plate",
")",
"the",
"passed",
"wcs",
"must",
"be",
"the",
"one",
"laying",
"in",
"the",
"preparedPlates",
"directory"
] | def raDecToPixel(self, raDecPos):
"""Return the pixel pos for a given RA DEC sky position (even if outside the plate)
the passed wcs must be the one laying in the preparedPlates directory"""
arr = numpy.array([[raDecPos[0], raDecPos[1]]], numpy.float_)
ret = self.w.wcs_world2pix(arr, 1)
ret = [(ret[0][0] - 1.5) * 64., (ret[0][1] - 1.5) * 64.]
# Add offset to compensate for linear WCS model errors
if self.gridOffset != None:
nearestOffset = scipy.interpolate.griddata(self.gridPixelPos, self.gridOffset, [ret], method='nearest')
ret = [ret[0] + nearestOffset[0][0], ret[1] + nearestOffset[0][1]]
return ret | [
"def",
"raDecToPixel",
"(",
"self",
",",
"raDecPos",
")",
":",
"arr",
"=",
"numpy",
".",
"array",
"(",
"[",
"[",
"raDecPos",
"[",
"0",
"]",
",",
"raDecPos",
"[",
"1",
"]",
"]",
"]",
",",
"numpy",
".",
"float_",
")",
"ret",
"=",
"self",
".",
"w"... | https://github.com/Stellarium/stellarium/blob/f289cda0d618180bbd3afe82f23d86ec0ac3c5e9/util/DSSToStellarium/dssUtils.py#L163-L175 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/py_targets.py | python | py_binary | (name,
srcs=[],
deps=[],
prebuilt=False,
**kwargs) | python binary - aka, python egg. | python binary - aka, python egg. | [
"python",
"binary",
"-",
"aka",
"python",
"egg",
"."
] | def py_binary(name,
srcs=[],
deps=[],
prebuilt=False,
**kwargs):
"""python binary - aka, python egg. """
target = PythonBinaryTarget(name,
srcs,
deps,
prebuilt,
blade.blade,
kwargs)
blade.blade.register_target(target) | [
"def",
"py_binary",
"(",
"name",
",",
"srcs",
"=",
"[",
"]",
",",
"deps",
"=",
"[",
"]",
",",
"prebuilt",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"target",
"=",
"PythonBinaryTarget",
"(",
"name",
",",
"srcs",
",",
"deps",
",",
"prebuilt",
... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/py_targets.py#L92-L104 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/insights/health.py | python | HealthHistorySlot._now | () | return now | Control now time for easier testing | Control now time for easier testing | [
"Control",
"now",
"time",
"for",
"easier",
"testing"
] | def _now():
"""Control now time for easier testing"""
now = datetime.datetime.utcnow()
if NOW_OFFSET is not None:
now = now + NOW_OFFSET
return now | [
"def",
"_now",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"NOW_OFFSET",
"is",
"not",
"None",
":",
"now",
"=",
"now",
"+",
"NOW_OFFSET",
"return",
"now"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/insights/health.py#L180-L185 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/_base_index.py | python | BaseIndex.to_frame | (self, index=True, name=None) | return cudf.DataFrame(
{col_name: self._values}, index=self if index else None
) | Create a DataFrame with a column containing this Index
Parameters
----------
index : boolean, default True
Set the index of the returned DataFrame as the original Index
name : str, default None
Name to be used for the column
Returns
-------
DataFrame
cudf DataFrame | Create a DataFrame with a column containing this Index | [
"Create",
"a",
"DataFrame",
"with",
"a",
"column",
"containing",
"this",
"Index"
] | def to_frame(self, index=True, name=None):
"""Create a DataFrame with a column containing this Index
Parameters
----------
index : boolean, default True
Set the index of the returned DataFrame as the original Index
name : str, default None
Name to be used for the column
Returns
-------
DataFrame
cudf DataFrame
"""
if name is not None:
col_name = name
elif self.name is None:
col_name = 0
else:
col_name = self.name
return cudf.DataFrame(
{col_name: self._values}, index=self if index else None
) | [
"def",
"to_frame",
"(",
"self",
",",
"index",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"col_name",
"=",
"name",
"elif",
"self",
".",
"name",
"is",
"None",
":",
"col_name",
"=",
"0",
"else",
":",
"co... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/_base_index.py#L514-L538 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/data.py | python | Expansion.concat | (self, o) | Concatenate the other expansion on to this one. | Concatenate the other expansion on to this one. | [
"Concatenate",
"the",
"other",
"expansion",
"on",
"to",
"this",
"one",
"."
] | def concat(self, o):
"""Concatenate the other expansion on to this one."""
if o.simple:
self.appendstr(o.s)
else:
self.extend(o) | [
"def",
"concat",
"(",
"self",
",",
"o",
")",
":",
"if",
"o",
".",
"simple",
":",
"self",
".",
"appendstr",
"(",
"o",
".",
"s",
")",
"else",
":",
"self",
".",
"extend",
"(",
"o",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/data.py#L246-L251 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/distributions/special_math.py | python | ndtri | (p, name="ndtri") | The inverse of the CDF of the Normal distribution function.
Returns x such that the area under the pdf from minus infinity to x is equal
to p.
A piece-wise rational approximation is done for the function.
This is a port of the implementation in netlib.
Args:
p: `Tensor` of type `float32`, `float64`.
name: Python string. A name for the operation (default="ndtri").
Returns:
x: `Tensor` with `dtype=p.dtype`.
Raises:
TypeError: if `p` is not floating-type. | The inverse of the CDF of the Normal distribution function. | [
"The",
"inverse",
"of",
"the",
"CDF",
"of",
"the",
"Normal",
"distribution",
"function",
"."
] | def ndtri(p, name="ndtri"):
"""The inverse of the CDF of the Normal distribution function.
Returns x such that the area under the pdf from minus infinity to x is equal
to p.
A piece-wise rational approximation is done for the function.
This is a port of the implementation in netlib.
Args:
p: `Tensor` of type `float32`, `float64`.
name: Python string. A name for the operation (default="ndtri").
Returns:
x: `Tensor` with `dtype=p.dtype`.
Raises:
TypeError: if `p` is not floating-type.
"""
with ops.name_scope(name, values=[p]):
p = ops.convert_to_tensor(p, name="p")
if p.dtype.as_numpy_dtype not in [np.float32, np.float64]:
raise TypeError(
"p.dtype=%s is not handled, see docstring for supported types."
% p.dtype)
return _ndtri(p) | [
"def",
"ndtri",
"(",
"p",
",",
"name",
"=",
"\"ndtri\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"values",
"=",
"[",
"p",
"]",
")",
":",
"p",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"p",
",",
"name",
"=",
"\"p\"",
")",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/special_math.py#L155-L181 | ||
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/DualClass.py | python | DCOpenProfsWindow | () | return | Opens the proficiency selection window. | Opens the proficiency selection window. | [
"Opens",
"the",
"proficiency",
"selection",
"window",
"."
] | def DCOpenProfsWindow ():
"""Opens the proficiency selection window."""
global DCProfsWindow, DCProfsDoneButton
# load up our window and set some basic variables
DCProfsWindow = GemRB.LoadWindow (15)
NewClassId = CommonTables.Classes.GetValue (ClassName, "ID", GTV_INT)
if GameCheck.IsBG2():
LUProfsSelection.SetupProfsWindow (pc, \
LUProfsSelection.LUPROFS_TYPE_DUALCLASS, DCProfsWindow, DCProfsRedraw, classid=NewClassId)
else:
LUProfsSelection.SetupProfsWindow (pc, \
LUProfsSelection.LUPROFS_TYPE_DUALCLASS, DCProfsWindow, \
DCProfsRedraw, [0,0,0], [1,1,1], NewClassId, False, 0)
# setup the done and cancel
DCProfsDoneButton = DCProfsWindow.GetControl (76)
DCProfsDoneButton.SetText (11973)
DCProfsDoneButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, DCProfsDonePress)
DCProfsDoneButton.SetState (IE_GUI_BUTTON_DISABLED)
DCProfsDoneButton.MakeDefault()
DCProfsCancelButton = DCProfsWindow.GetControl (77)
DCProfsCancelButton.SetText (13727)
DCProfsCancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, DCProfsCancelPress)
DCProfsCancelButton.SetState (IE_GUI_BUTTON_ENABLED)
DCProfsCancelButton.MakeEscape ()
# show the window and draw away
DCProfsWindow.ShowModal (MODAL_SHADOW_GRAY)
DCProfsRedraw ()
return | [
"def",
"DCOpenProfsWindow",
"(",
")",
":",
"global",
"DCProfsWindow",
",",
"DCProfsDoneButton",
"# load up our window and set some basic variables",
"DCProfsWindow",
"=",
"GemRB",
".",
"LoadWindow",
"(",
"15",
")",
"NewClassId",
"=",
"CommonTables",
".",
"Classes",
".",... | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/DualClass.py#L473-L505 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | TarInfo._posix_split_name | (self, name) | return prefix, name | Split a name longer than 100 chars into a prefix
and a name part. | Split a name longer than 100 chars into a prefix
and a name part. | [
"Split",
"a",
"name",
"longer",
"than",
"100",
"chars",
"into",
"a",
"prefix",
"and",
"a",
"name",
"part",
"."
] | def _posix_split_name(self, name):
"""Split a name longer than 100 chars into a prefix
and a name part.
"""
prefix = name[:LENGTH_PREFIX + 1]
while prefix and prefix[-1] != "/":
prefix = prefix[:-1]
name = name[len(prefix):]
prefix = prefix[:-1]
if not prefix or len(name) > LENGTH_NAME:
raise ValueError("name is too long")
return prefix, name | [
"def",
"_posix_split_name",
"(",
"self",
",",
"name",
")",
":",
"prefix",
"=",
"name",
"[",
":",
"LENGTH_PREFIX",
"+",
"1",
"]",
"while",
"prefix",
"and",
"prefix",
"[",
"-",
"1",
"]",
"!=",
"\"/\"",
":",
"prefix",
"=",
"prefix",
"[",
":",
"-",
"1"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1098-L1111 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/util/tf_export.py | python | get_canonical_name_for_symbol | (
symbol, api_name=TENSORFLOW_API_NAME,
add_prefix_to_v1_names=False) | return v1_canonical_name | Get canonical name for the API symbol.
Args:
symbol: API function or class.
api_name: API name (tensorflow or estimator).
add_prefix_to_v1_names: Specifies whether a name available only in V1
should be prefixed with compat.v1.
Returns:
Canonical name for the API symbol (for e.g. initializers.zeros) if
canonical name could be determined. Otherwise, returns None. | Get canonical name for the API symbol. | [
"Get",
"canonical",
"name",
"for",
"the",
"API",
"symbol",
"."
] | def get_canonical_name_for_symbol(
symbol, api_name=TENSORFLOW_API_NAME,
add_prefix_to_v1_names=False):
"""Get canonical name for the API symbol.
Args:
symbol: API function or class.
api_name: API name (tensorflow or estimator).
add_prefix_to_v1_names: Specifies whether a name available only in V1
should be prefixed with compat.v1.
Returns:
Canonical name for the API symbol (for e.g. initializers.zeros) if
canonical name could be determined. Otherwise, returns None.
"""
if not hasattr(symbol, '__dict__'):
return None
api_names_attr = API_ATTRS[api_name].names
_, undecorated_symbol = tf_decorator.unwrap(symbol)
if api_names_attr not in undecorated_symbol.__dict__:
return None
api_names = getattr(undecorated_symbol, api_names_attr)
deprecated_api_names = undecorated_symbol.__dict__.get(
'_tf_deprecated_api_names', [])
canonical_name = get_canonical_name(api_names, deprecated_api_names)
if canonical_name:
return canonical_name
# If there is no V2 canonical name, get V1 canonical name.
api_names_attr = API_ATTRS_V1[api_name].names
api_names = getattr(undecorated_symbol, api_names_attr)
v1_canonical_name = get_canonical_name(api_names, deprecated_api_names)
if add_prefix_to_v1_names:
return 'compat.v1.%s' % v1_canonical_name
return v1_canonical_name | [
"def",
"get_canonical_name_for_symbol",
"(",
"symbol",
",",
"api_name",
"=",
"TENSORFLOW_API_NAME",
",",
"add_prefix_to_v1_names",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"symbol",
",",
"'__dict__'",
")",
":",
"return",
"None",
"api_names_attr",
"=",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/tf_export.py#L100-L135 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/lib2to3/refactor.py | python | RefactoringTool.log_message | (self, msg, *args) | Hook to log a message. | Hook to log a message. | [
"Hook",
"to",
"log",
"a",
"message",
"."
] | def log_message(self, msg, *args):
"""Hook to log a message."""
if args:
msg = msg % args
self.logger.info(msg) | [
"def",
"log_message",
"(",
"self",
",",
"msg",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"msg",
"=",
"msg",
"%",
"args",
"self",
".",
"logger",
".",
"info",
"(",
"msg",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/lib2to3/refactor.py#L259-L263 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/_masked/__init__.py | python | _reduction_identity | (op_name: str, input: Tensor, *args) | Return identity value as scalar tensor of a reduction operation on
given input, or None, if the identity value cannot be uniquely
defined for the given input.
The identity value of the operation is defined as the initial
value to reduction operation that has a property ``op(op_identity,
value) == value`` for any value in the domain of the operation.
Or put it another way, including or exlucing the identity value in
a list of operands will not change the reduction result.
See https://github.com/pytorch/rfcs/pull/27 for more information. | Return identity value as scalar tensor of a reduction operation on
given input, or None, if the identity value cannot be uniquely
defined for the given input. | [
"Return",
"identity",
"value",
"as",
"scalar",
"tensor",
"of",
"a",
"reduction",
"operation",
"on",
"given",
"input",
"or",
"None",
"if",
"the",
"identity",
"value",
"cannot",
"be",
"uniquely",
"defined",
"for",
"the",
"given",
"input",
"."
] | def _reduction_identity(op_name: str, input: Tensor, *args):
"""Return identity value as scalar tensor of a reduction operation on
given input, or None, if the identity value cannot be uniquely
defined for the given input.
The identity value of the operation is defined as the initial
value to reduction operation that has a property ``op(op_identity,
value) == value`` for any value in the domain of the operation.
Or put it another way, including or exlucing the identity value in
a list of operands will not change the reduction result.
See https://github.com/pytorch/rfcs/pull/27 for more information.
"""
dtype: DType = input.dtype
device = input.device
op_name = op_name.rsplit('.', 1)[-1] # lstrip module name when present
if op_name == 'sum':
return torch.tensor(0, dtype=dtype, device=device)
elif op_name == 'prod':
return torch.tensor(1, dtype=dtype, device=device)
elif op_name == 'amax':
if torch.is_floating_point(input):
return torch.tensor(-torch.inf, dtype=dtype, device=device)
elif torch.is_signed(input) or dtype == torch.uint8:
return torch.tensor(torch.iinfo(dtype).min, dtype=dtype, device=device)
elif op_name == 'amin':
if torch.is_floating_point(input):
return torch.tensor(torch.inf, dtype=dtype, device=device)
elif torch.is_signed(input) or dtype == torch.uint8:
return torch.tensor(torch.iinfo(dtype).max, dtype=dtype, device=device)
elif op_name == 'mean':
# Strictly speaking, the identity value of the mean operation
# is the mean of the input. Since the mean value depends on
# the dim argument and it may be a non-scalar tensor, we
# consider the identity value of the mean operation ambiguous.
# Moreover, the mean value of empty input is undefined.
return None
elif op_name == 'norm':
ord = args[0] if args else 2
if ord == float('-inf'):
assert torch.is_floating_point(input), input.dtype
return torch.tensor(torch.inf, dtype=dtype, device=device)
return torch.tensor(0, dtype=dtype, device=device)
elif op_name == 'var':
return None
raise NotImplementedError(f'identity of {op_name} on {dtype} input') | [
"def",
"_reduction_identity",
"(",
"op_name",
":",
"str",
",",
"input",
":",
"Tensor",
",",
"*",
"args",
")",
":",
"dtype",
":",
"DType",
"=",
"input",
".",
"dtype",
"device",
"=",
"input",
".",
"device",
"op_name",
"=",
"op_name",
".",
"rsplit",
"(",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/_masked/__init__.py#L308-L354 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py | python | SimpleXMLRPCDispatcher.register_function | (self, function=None, name=None) | return function | Registers a function to respond to XML-RPC requests.
The optional name argument can be used to set a Unicode name
for the function. | Registers a function to respond to XML-RPC requests. | [
"Registers",
"a",
"function",
"to",
"respond",
"to",
"XML",
"-",
"RPC",
"requests",
"."
] | def register_function(self, function=None, name=None):
"""Registers a function to respond to XML-RPC requests.
The optional name argument can be used to set a Unicode name
for the function.
"""
# decorator factory
if function is None:
return partial(self.register_function, name=name)
if name is None:
name = function.__name__
self.funcs[name] = function
return function | [
"def",
"register_function",
"(",
"self",
",",
"function",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# decorator factory",
"if",
"function",
"is",
"None",
":",
"return",
"partial",
"(",
"self",
".",
"register_function",
",",
"name",
"=",
"name",
")"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py#L209-L223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.