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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LLNL/blt | 4eafa66ddb99ee5a4a0f75f3d7d790679add6e01 | thirdparty_builtin/benchmark-1.5.0/tools/gbench/report.py | python | partition_benchmarks | (json1, json2) | return partitions | While preserving the ordering, find benchmarks with the same names in
both of the inputs, and group them.
(i.e. partition/filter into groups with common name) | While preserving the ordering, find benchmarks with the same names in
both of the inputs, and group them.
(i.e. partition/filter into groups with common name) | [
"While",
"preserving",
"the",
"ordering",
"find",
"benchmarks",
"with",
"the",
"same",
"names",
"in",
"both",
"of",
"the",
"inputs",
"and",
"group",
"them",
".",
"(",
"i",
".",
"e",
".",
"partition",
"/",
"filter",
"into",
"groups",
"with",
"common",
"name",
")"
] | def partition_benchmarks(json1, json2):
"""
While preserving the ordering, find benchmarks with the same names in
both of the inputs, and group them.
(i.e. partition/filter into groups with common name)
"""
json1_unique_names = get_unique_benchmark_names(json1)
json2_unique_names = get_unique_benchmark_names(json2)
names = intersect(json1_unique_names, json2_unique_names)
partitions = []
for name in names:
time_unit = None
# Pick the time unit from the first entry of the lhs benchmark.
# We should be careful not to crash with unexpected input.
for x in json1['benchmarks']:
if (x['name'] == name and is_potentially_comparable_benchmark(x)):
time_unit = x['time_unit']
break
if time_unit is None:
continue
# Filter by name and time unit.
# All the repetitions are assumed to be comparable.
lhs = [x for x in json1['benchmarks'] if x['name'] == name and
x['time_unit'] == time_unit]
rhs = [x for x in json2['benchmarks'] if x['name'] == name and
x['time_unit'] == time_unit]
partitions.append([lhs, rhs])
return partitions | [
"def",
"partition_benchmarks",
"(",
"json1",
",",
"json2",
")",
":",
"json1_unique_names",
"=",
"get_unique_benchmark_names",
"(",
"json1",
")",
"json2_unique_names",
"=",
"get_unique_benchmark_names",
"(",
"json2",
")",
"names",
"=",
"intersect",
"(",
"json1_unique_names",
",",
"json2_unique_names",
")",
"partitions",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"time_unit",
"=",
"None",
"# Pick the time unit from the first entry of the lhs benchmark.",
"# We should be careful not to crash with unexpected input.",
"for",
"x",
"in",
"json1",
"[",
"'benchmarks'",
"]",
":",
"if",
"(",
"x",
"[",
"'name'",
"]",
"==",
"name",
"and",
"is_potentially_comparable_benchmark",
"(",
"x",
")",
")",
":",
"time_unit",
"=",
"x",
"[",
"'time_unit'",
"]",
"break",
"if",
"time_unit",
"is",
"None",
":",
"continue",
"# Filter by name and time unit.",
"# All the repetitions are assumed to be comparable.",
"lhs",
"=",
"[",
"x",
"for",
"x",
"in",
"json1",
"[",
"'benchmarks'",
"]",
"if",
"x",
"[",
"'name'",
"]",
"==",
"name",
"and",
"x",
"[",
"'time_unit'",
"]",
"==",
"time_unit",
"]",
"rhs",
"=",
"[",
"x",
"for",
"x",
"in",
"json2",
"[",
"'benchmarks'",
"]",
"if",
"x",
"[",
"'name'",
"]",
"==",
"name",
"and",
"x",
"[",
"'time_unit'",
"]",
"==",
"time_unit",
"]",
"partitions",
".",
"append",
"(",
"[",
"lhs",
",",
"rhs",
"]",
")",
"return",
"partitions"
] | https://github.com/LLNL/blt/blob/4eafa66ddb99ee5a4a0f75f3d7d790679add6e01/thirdparty_builtin/benchmark-1.5.0/tools/gbench/report.py#L121-L148 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/driver_nbody_helper.py | python | electrostatic_embedding | (metadata, pair) | Add atom-centered point charges for fragments whose basis sets are not included in the computation. | Add atom-centered point charges for fragments whose basis sets are not included in the computation. | [
"Add",
"atom",
"-",
"centered",
"point",
"charges",
"for",
"fragments",
"whose",
"basis",
"sets",
"are",
"not",
"included",
"in",
"the",
"computation",
"."
] | def electrostatic_embedding(metadata, pair):
"""
Add atom-centered point charges for fragments whose basis sets are not included in the computation.
"""
from psi4.driver import constants, qmmm
if not metadata['return_total_data']:
raise Exception('Cannot return interaction data when using embedding scheme.')
# Add embedding point charges
Chrgfield = qmmm.QMMM()
for p in metadata['embedding_charges']:
if p in pair[1]: continue
mol = metadata['molecule'].extract_subsets([p])
for i in range(mol.natom()):
geom = np.array([mol.x(i), mol.y(i), mol.z(i)])
if mol.units() == 'Angstrom':
geom *= constants.bohr2angstroms
Chrgfield.extern.addCharge(metadata['embedding_charges'][p][i], geom[0], geom[1], geom[2])
core.set_global_option_python('EXTERN', Chrgfield.extern) | [
"def",
"electrostatic_embedding",
"(",
"metadata",
",",
"pair",
")",
":",
"from",
"psi4",
".",
"driver",
"import",
"constants",
",",
"qmmm",
"if",
"not",
"metadata",
"[",
"'return_total_data'",
"]",
":",
"raise",
"Exception",
"(",
"'Cannot return interaction data when using embedding scheme.'",
")",
"# Add embedding point charges",
"Chrgfield",
"=",
"qmmm",
".",
"QMMM",
"(",
")",
"for",
"p",
"in",
"metadata",
"[",
"'embedding_charges'",
"]",
":",
"if",
"p",
"in",
"pair",
"[",
"1",
"]",
":",
"continue",
"mol",
"=",
"metadata",
"[",
"'molecule'",
"]",
".",
"extract_subsets",
"(",
"[",
"p",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"mol",
".",
"natom",
"(",
")",
")",
":",
"geom",
"=",
"np",
".",
"array",
"(",
"[",
"mol",
".",
"x",
"(",
"i",
")",
",",
"mol",
".",
"y",
"(",
"i",
")",
",",
"mol",
".",
"z",
"(",
"i",
")",
"]",
")",
"if",
"mol",
".",
"units",
"(",
")",
"==",
"'Angstrom'",
":",
"geom",
"*=",
"constants",
".",
"bohr2angstroms",
"Chrgfield",
".",
"extern",
".",
"addCharge",
"(",
"metadata",
"[",
"'embedding_charges'",
"]",
"[",
"p",
"]",
"[",
"i",
"]",
",",
"geom",
"[",
"0",
"]",
",",
"geom",
"[",
"1",
"]",
",",
"geom",
"[",
"2",
"]",
")",
"core",
".",
"set_global_option_python",
"(",
"'EXTERN'",
",",
"Chrgfield",
".",
"extern",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/driver_nbody_helper.py#L184-L202 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/gensuitemodule.py | python | SuiteCompiler.compileevent | (self, event) | Generate code for a single event | Generate code for a single event | [
"Generate",
"code",
"for",
"a",
"single",
"event"
] | def compileevent(self, event):
"""Generate code for a single event"""
[name, desc, code, subcode, returns, accepts, arguments] = event
fp = self.fp
funcname = identify(name)
#
# generate name->keyword map
#
if arguments:
fp.write(" _argmap_%s = {\n"%funcname)
for a in arguments:
fp.write(" %r : %r,\n"%(identify(a[0]), a[1]))
fp.write(" }\n\n")
#
# Generate function header
#
has_arg = (not is_null(accepts))
opt_arg = (has_arg and is_optional(accepts))
fp.write(" def %s(self, "%funcname)
if has_arg:
if not opt_arg:
fp.write("_object, ") # Include direct object, if it has one
else:
fp.write("_object=None, ") # Also include if it is optional
else:
fp.write("_no_object=None, ") # For argument checking
fp.write("_attributes={}, **_arguments):\n") # include attribute dict and args
#
# Generate doc string (important, since it may be the only
# available documentation, due to our name-remaping)
#
fp.write(' """%s: %s\n'%(ascii(name), ascii(desc)))
if has_arg:
fp.write(" Required argument: %s\n"%getdatadoc(accepts))
elif opt_arg:
fp.write(" Optional argument: %s\n"%getdatadoc(accepts))
for arg in arguments:
fp.write(" Keyword argument %s: %s\n"%(identify(arg[0]),
getdatadoc(arg[2])))
fp.write(" Keyword argument _attributes: AppleEvent attribute dictionary\n")
if not is_null(returns):
fp.write(" Returns: %s\n"%getdatadoc(returns))
fp.write(' """\n')
#
# Fiddle the args so everything ends up in 'arguments' dictionary
#
fp.write(" _code = %r\n"% (code,))
fp.write(" _subcode = %r\n\n"% (subcode,))
#
# Do keyword name substitution
#
if arguments:
fp.write(" aetools.keysubst(_arguments, self._argmap_%s)\n"%funcname)
else:
fp.write(" if _arguments: raise TypeError, 'No optional args expected'\n")
#
# Stuff required arg (if there is one) into arguments
#
if has_arg:
fp.write(" _arguments['----'] = _object\n")
elif opt_arg:
fp.write(" if _object:\n")
fp.write(" _arguments['----'] = _object\n")
else:
fp.write(" if _no_object is not None: raise TypeError, 'No direct arg expected'\n")
fp.write("\n")
#
# Do enum-name substitution
#
for a in arguments:
if is_enum(a[2]):
kname = a[1]
ename = a[2][0]
if ename != '****':
fp.write(" aetools.enumsubst(_arguments, %r, _Enum_%s)\n" %
(kname, identify(ename)))
self.enumsneeded[ename] = 1
fp.write("\n")
#
# Do the transaction
#
fp.write(" _reply, _arguments, _attributes = self.send(_code, _subcode,\n")
fp.write(" _arguments, _attributes)\n")
#
# Error handling
#
fp.write(" if _arguments.get('errn', 0):\n")
fp.write(" raise aetools.Error, aetools.decodeerror(_arguments)\n")
fp.write(" # XXXX Optionally decode result\n")
#
# Decode result
#
fp.write(" if '----' in _arguments:\n")
if is_enum(returns):
fp.write(" # XXXX Should do enum remapping here...\n")
fp.write(" return _arguments['----']\n")
fp.write("\n") | [
"def",
"compileevent",
"(",
"self",
",",
"event",
")",
":",
"[",
"name",
",",
"desc",
",",
"code",
",",
"subcode",
",",
"returns",
",",
"accepts",
",",
"arguments",
"]",
"=",
"event",
"fp",
"=",
"self",
".",
"fp",
"funcname",
"=",
"identify",
"(",
"name",
")",
"#",
"# generate name->keyword map",
"#",
"if",
"arguments",
":",
"fp",
".",
"write",
"(",
"\" _argmap_%s = {\\n\"",
"%",
"funcname",
")",
"for",
"a",
"in",
"arguments",
":",
"fp",
".",
"write",
"(",
"\" %r : %r,\\n\"",
"%",
"(",
"identify",
"(",
"a",
"[",
"0",
"]",
")",
",",
"a",
"[",
"1",
"]",
")",
")",
"fp",
".",
"write",
"(",
"\" }\\n\\n\"",
")",
"#",
"# Generate function header",
"#",
"has_arg",
"=",
"(",
"not",
"is_null",
"(",
"accepts",
")",
")",
"opt_arg",
"=",
"(",
"has_arg",
"and",
"is_optional",
"(",
"accepts",
")",
")",
"fp",
".",
"write",
"(",
"\" def %s(self, \"",
"%",
"funcname",
")",
"if",
"has_arg",
":",
"if",
"not",
"opt_arg",
":",
"fp",
".",
"write",
"(",
"\"_object, \"",
")",
"# Include direct object, if it has one",
"else",
":",
"fp",
".",
"write",
"(",
"\"_object=None, \"",
")",
"# Also include if it is optional",
"else",
":",
"fp",
".",
"write",
"(",
"\"_no_object=None, \"",
")",
"# For argument checking",
"fp",
".",
"write",
"(",
"\"_attributes={}, **_arguments):\\n\"",
")",
"# include attribute dict and args",
"#",
"# Generate doc string (important, since it may be the only",
"# available documentation, due to our name-remaping)",
"#",
"fp",
".",
"write",
"(",
"' \"\"\"%s: %s\\n'",
"%",
"(",
"ascii",
"(",
"name",
")",
",",
"ascii",
"(",
"desc",
")",
")",
")",
"if",
"has_arg",
":",
"fp",
".",
"write",
"(",
"\" Required argument: %s\\n\"",
"%",
"getdatadoc",
"(",
"accepts",
")",
")",
"elif",
"opt_arg",
":",
"fp",
".",
"write",
"(",
"\" Optional argument: %s\\n\"",
"%",
"getdatadoc",
"(",
"accepts",
")",
")",
"for",
"arg",
"in",
"arguments",
":",
"fp",
".",
"write",
"(",
"\" Keyword argument %s: %s\\n\"",
"%",
"(",
"identify",
"(",
"arg",
"[",
"0",
"]",
")",
",",
"getdatadoc",
"(",
"arg",
"[",
"2",
"]",
")",
")",
")",
"fp",
".",
"write",
"(",
"\" Keyword argument _attributes: AppleEvent attribute dictionary\\n\"",
")",
"if",
"not",
"is_null",
"(",
"returns",
")",
":",
"fp",
".",
"write",
"(",
"\" Returns: %s\\n\"",
"%",
"getdatadoc",
"(",
"returns",
")",
")",
"fp",
".",
"write",
"(",
"' \"\"\"\\n'",
")",
"#",
"# Fiddle the args so everything ends up in 'arguments' dictionary",
"#",
"fp",
".",
"write",
"(",
"\" _code = %r\\n\"",
"%",
"(",
"code",
",",
")",
")",
"fp",
".",
"write",
"(",
"\" _subcode = %r\\n\\n\"",
"%",
"(",
"subcode",
",",
")",
")",
"#",
"# Do keyword name substitution",
"#",
"if",
"arguments",
":",
"fp",
".",
"write",
"(",
"\" aetools.keysubst(_arguments, self._argmap_%s)\\n\"",
"%",
"funcname",
")",
"else",
":",
"fp",
".",
"write",
"(",
"\" if _arguments: raise TypeError, 'No optional args expected'\\n\"",
")",
"#",
"# Stuff required arg (if there is one) into arguments",
"#",
"if",
"has_arg",
":",
"fp",
".",
"write",
"(",
"\" _arguments['----'] = _object\\n\"",
")",
"elif",
"opt_arg",
":",
"fp",
".",
"write",
"(",
"\" if _object:\\n\"",
")",
"fp",
".",
"write",
"(",
"\" _arguments['----'] = _object\\n\"",
")",
"else",
":",
"fp",
".",
"write",
"(",
"\" if _no_object is not None: raise TypeError, 'No direct arg expected'\\n\"",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")",
"#",
"# Do enum-name substitution",
"#",
"for",
"a",
"in",
"arguments",
":",
"if",
"is_enum",
"(",
"a",
"[",
"2",
"]",
")",
":",
"kname",
"=",
"a",
"[",
"1",
"]",
"ename",
"=",
"a",
"[",
"2",
"]",
"[",
"0",
"]",
"if",
"ename",
"!=",
"'****'",
":",
"fp",
".",
"write",
"(",
"\" aetools.enumsubst(_arguments, %r, _Enum_%s)\\n\"",
"%",
"(",
"kname",
",",
"identify",
"(",
"ename",
")",
")",
")",
"self",
".",
"enumsneeded",
"[",
"ename",
"]",
"=",
"1",
"fp",
".",
"write",
"(",
"\"\\n\"",
")",
"#",
"# Do the transaction",
"#",
"fp",
".",
"write",
"(",
"\" _reply, _arguments, _attributes = self.send(_code, _subcode,\\n\"",
")",
"fp",
".",
"write",
"(",
"\" _arguments, _attributes)\\n\"",
")",
"#",
"# Error handling",
"#",
"fp",
".",
"write",
"(",
"\" if _arguments.get('errn', 0):\\n\"",
")",
"fp",
".",
"write",
"(",
"\" raise aetools.Error, aetools.decodeerror(_arguments)\\n\"",
")",
"fp",
".",
"write",
"(",
"\" # XXXX Optionally decode result\\n\"",
")",
"#",
"# Decode result",
"#",
"fp",
".",
"write",
"(",
"\" if '----' in _arguments:\\n\"",
")",
"if",
"is_enum",
"(",
"returns",
")",
":",
"fp",
".",
"write",
"(",
"\" # XXXX Should do enum remapping here...\\n\"",
")",
"fp",
".",
"write",
"(",
"\" return _arguments['----']\\n\"",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/gensuitemodule.py#L710-L808 | ||
ValveSoftware/source-sdk-2013 | 0d8dceea4310fde5706b3ce1c70609d72a38efdf | sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py | python | _Tokenizer.ConsumeInt32 | (self) | return result | Consumes a signed 32bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 32bit integer couldn't be consumed. | Consumes a signed 32bit integer number. | [
"Consumes",
"a",
"signed",
"32bit",
"integer",
"number",
"."
] | def ConsumeInt32(self):
"""Consumes a signed 32bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 32bit integer couldn't be consumed.
"""
try:
result = self._ParseInteger(self.token, is_signed=True, is_long=False)
except ValueError, e:
raise self._IntegerParseError(e)
self.NextToken()
return result | [
"def",
"ConsumeInt32",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"_ParseInteger",
"(",
"self",
".",
"token",
",",
"is_signed",
"=",
"True",
",",
"is_long",
"=",
"False",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"self",
".",
"_IntegerParseError",
"(",
"e",
")",
"self",
".",
"NextToken",
"(",
")",
"return",
"result"
] | https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py#L410-L424 | |
MhLiao/TextBoxes_plusplus | 39d4898de1504c53a2ed3d67966a57b3595836d0 | scripts/cpp_lint.py | python | CheckLanguage | (filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error) | Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks rules from the 'C++ language rules' section of cppguide.html. | [
"Checks",
"rules",
"from",
"the",
"C",
"++",
"language",
"rules",
"section",
"of",
"cppguide",
".",
"html",
"."
] | def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# If the line is empty or consists of entirely a comment, no need to
# check it.
line = clean_lines.elided[linenum]
if not line:
return
match = _RE_PATTERN_INCLUDE.search(line)
if match:
CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
return
# Reset include state across preprocessor directives. This is meant
# to silence warnings for conditional includes.
if Match(r'^\s*#\s*(?:ifdef|elif|else|endif)\b', line):
include_state.ResetSection()
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
# TODO(unknown): figure out if they're using default arguments in fn proto.
# Check to see if they're using an conversion function cast.
# I just try to capture the most common basic types, though there are more.
# Parameterless conversion functions, such as bool(), are allowed as they are
# probably a member operator declaration or default constructor.
match = Search(
r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
r'(\([^)].*)', line)
if match:
matched_new = match.group(1)
matched_type = match.group(2)
matched_funcptr = match.group(3)
# gMock methods are defined using some variant of MOCK_METHODx(name, type)
# where type may be float(), int(string), etc. Without context they are
# virtually indistinguishable from int(x) casts. Likewise, gMock's
# MockCallback takes a template parameter of the form return_type(arg_type),
# which looks much like the cast we're trying to detect.
#
# std::function<> wrapper has a similar problem.
#
# Return types for function pointers also look like casts if they
# don't have an extra space.
if (matched_new is None and # If new operator, then this isn't a cast
not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
Search(r'\bMockCallback<.*>', line) or
Search(r'\bstd::function<.*>', line)) and
not (matched_funcptr and
Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
matched_funcptr))):
# Try a bit harder to catch gmock lines: the only place where
# something looks like an old-style cast is where we declare the
# return type of the mocked method, and the only time when we
# are missing context is if MOCK_METHOD was split across
# multiple lines. The missing MOCK_METHOD is usually one or two
# lines back, so scan back one or two lines.
#
# It's not possible for gmock macros to appear in the first 2
# lines, since the class head + section name takes up 2 lines.
if (linenum < 2 or
not (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]))):
error(filename, linenum, 'readability/casting', 4,
'Using deprecated casting style. '
'Use static_cast<%s>(...) instead' %
matched_type)
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'static_cast',
r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
# This doesn't catch all cases. Consider (const char * const)"hello".
#
# (char *) "foo" should always be a const_cast (reinterpret_cast won't
# compile).
if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
pass
else:
# Check pointer casts for other than string constants
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
# point where you think.
match = Search(
r'(?:&\(([^)]+)\)[\w(])|'
r'(?:&(static|dynamic|down|reinterpret)_cast\b)', line)
if match and match.group(1) != '*':
error(filename, linenum, 'runtime/casting', 4,
('Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'))
# Create an extended_line, which is the concatenation of the current and
# next lines, for more effective checking of code that may span more than one
# line.
if linenum + 1 < clean_lines.NumLines():
extended_line = line + clean_lines.elided[linenum + 1]
else:
extended_line = line
# Check for people declaring static/global STL strings at the top level.
# This is dangerous because the C++ language does not guarantee that
# globals with constructors are initialized before the first access.
match = Match(
r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
line)
# Make sure it's not a function.
# Function template specialization looks like: "string foo<Type>(...".
# Class template definitions look like: "string Foo<Type>::Method(...".
#
# Also ignore things that look like operators. These are matched separately
# because operator names cross non-word boundaries. If we change the pattern
# above, we would decrease the accuracy of matching identifiers.
if (match and
not Search(r'\boperator\W', line) and
not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3))):
error(filename, linenum, 'runtime/string', 4,
'For a static/global string constant, use a C style string instead: '
'"%schar %s[]".' %
(match.group(1), match.group(2)))
if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
error(filename, linenum, 'runtime/init', 4,
'You seem to be initializing a member variable with itself.')
if file_extension == 'h':
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
# (level 1 error)
pass
# Check if people are using the verboten C basic types. The only exception
# we regularly allow is "unsigned short port" for port.
if Search(r'\bshort port\b', line):
if not Search(r'\bunsigned short port\b', line):
error(filename, linenum, 'runtime/int', 4,
'Use "unsigned short" for ports, not "short"')
else:
match = Search(r'\b(short|long(?! +double)|long long)\b', line)
if match:
error(filename, linenum, 'runtime/int', 4,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
# When snprintf is used, the second argument shouldn't be a literal.
match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
if match and match.group(2) != '0':
# If 2nd arg is zero, snprintf is used to calculate size.
error(filename, linenum, 'runtime/printf', 3,
'If you can, use sizeof(%s) instead of %s as the 2nd arg '
'to snprintf.' % (match.group(1), match.group(2)))
# Check if some verboten C functions are being used.
if Search(r'\bsprintf\b', line):
error(filename, linenum, 'runtime/printf', 5,
'Never use sprintf. Use snprintf instead.')
match = Search(r'\b(strcpy|strcat)\b', line)
if match:
error(filename, linenum, 'runtime/printf', 4,
'Almost always, snprintf is better than %s' % match.group(1))
# Check if some verboten operator overloading is going on
# TODO(unknown): catch out-of-line unary operator&:
# class X {};
# int operator&(const X& x) { return 42; } // unary operator&
# The trick is it's hard to tell apart from binary operator&:
# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
if Search(r'\boperator\s*&\s*\(\s*\)', line):
error(filename, linenum, 'runtime/operator', 4,
'Unary operator& is dangerous. Do not use it.')
# Check for suspicious usage of "if" like
# } if (a == b) {
if Search(r'\}\s*if\s*\(', line):
error(filename, linenum, 'readability/braces', 4,
'Did you mean "else if"? If not, start a new line for "if".')
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
# TODO(sugawarayu): Catch the following case. Need to change the calling
# convention of the whole function to process multiple line to handle it.
# printf(
# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
if printf_args:
match = Match(r'([\w.\->()]+)$', printf_args)
if match and match.group(1) != '__VA_ARGS__':
function_name = re.search(r'\b((?:string)?printf)\s*\(',
line, re.I).group(1)
error(filename, linenum, 'runtime/printf', 4,
'Potential format string bug. Do %s("%%s", %s) instead.'
% (function_name, match.group(1)))
# Check for potential memset bugs like memset(buf, sizeof(buf), 0).
match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
error(filename, linenum, 'runtime/memset', 4,
'Did you mean "memset(%s, 0, %s)"?'
% (match.group(1), match.group(2)))
if Search(r'\busing namespace\b', line):
error(filename, linenum, 'build/namespaces', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
# Detect variable-length arrays.
match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
match.group(3).find(']') == -1):
# Split the size using space and arithmetic operators as delimiters.
# If any of the resulting tokens are not compile time constants then
# report the error.
tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
is_const = True
skip_next = False
for tok in tokens:
if skip_next:
skip_next = False
continue
if Search(r'sizeof\(.+\)', tok): continue
if Search(r'arraysize\(\w+\)', tok): continue
tok = tok.lstrip('(')
tok = tok.rstrip(')')
if not tok: continue
if Match(r'\d+', tok): continue
if Match(r'0[xX][0-9a-fA-F]+', tok): continue
if Match(r'k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
# A catch all for tricky sizeof cases, including 'sizeof expression',
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
# requires skipping the next token because we split on ' ' and '*'.
if tok.startswith('sizeof'):
skip_next = True
continue
is_const = False
break
if not is_const:
error(filename, linenum, 'runtime/arrays', 1,
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
# in the class declaration.
match = Match(
(r'\s*'
r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
r'\(.*\);$'),
line)
if match and linenum + 1 < clean_lines.NumLines():
next_line = clean_lines.elided[linenum + 1]
# We allow some, but not all, declarations of variables to be present
# in the statement that defines the class. The [\w\*,\s]* fragment of
# the regular expression below allows users to declare instances of
# the class or pointers to instances, but not less common types such
# as function pointers or arrays. It's a tradeoff between allowing
# reasonable code and avoiding trying to parse more C++ using regexps.
if not Search(r'^\s*}[\w\*,\s]*;', next_line):
error(filename, linenum, 'readability/constructors', 3,
match.group(1) + ' should be the last thing in the class')
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
if (file_extension == 'h'
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.') | [
"def",
"CheckLanguage",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"include_state",
",",
"nesting_state",
",",
"error",
")",
":",
"# If the line is empty or consists of entirely a comment, no need to",
"# check it.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"not",
"line",
":",
"return",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
"return",
"# Reset include state across preprocessor directives. This is meant",
"# to silence warnings for conditional includes.",
"if",
"Match",
"(",
"r'^\\s*#\\s*(?:ifdef|elif|else|endif)\\b'",
",",
"line",
")",
":",
"include_state",
".",
"ResetSection",
"(",
")",
"# Make Windows paths like Unix.",
"fullname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"# TODO(unknown): figure out if they're using default arguments in fn proto.",
"# Check to see if they're using an conversion function cast.",
"# I just try to capture the most common basic types, though there are more.",
"# Parameterless conversion functions, such as bool(), are allowed as they are",
"# probably a member operator declaration or default constructor.",
"match",
"=",
"Search",
"(",
"r'(\\bnew\\s+)?\\b'",
"# Grab 'new' operator, if it's there",
"r'(int|float|double|bool|char|int32|uint32|int64|uint64)'",
"r'(\\([^)].*)'",
",",
"line",
")",
"if",
"match",
":",
"matched_new",
"=",
"match",
".",
"group",
"(",
"1",
")",
"matched_type",
"=",
"match",
".",
"group",
"(",
"2",
")",
"matched_funcptr",
"=",
"match",
".",
"group",
"(",
"3",
")",
"# gMock methods are defined using some variant of MOCK_METHODx(name, type)",
"# where type may be float(), int(string), etc. Without context they are",
"# virtually indistinguishable from int(x) casts. Likewise, gMock's",
"# MockCallback takes a template parameter of the form return_type(arg_type),",
"# which looks much like the cast we're trying to detect.",
"#",
"# std::function<> wrapper has a similar problem.",
"#",
"# Return types for function pointers also look like casts if they",
"# don't have an extra space.",
"if",
"(",
"matched_new",
"is",
"None",
"and",
"# If new operator, then this isn't a cast",
"not",
"(",
"Match",
"(",
"r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('",
",",
"line",
")",
"or",
"Search",
"(",
"r'\\bMockCallback<.*>'",
",",
"line",
")",
"or",
"Search",
"(",
"r'\\bstd::function<.*>'",
",",
"line",
")",
")",
"and",
"not",
"(",
"matched_funcptr",
"and",
"Match",
"(",
"r'\\((?:[^() ]+::\\s*\\*\\s*)?[^() ]+\\)\\s*\\('",
",",
"matched_funcptr",
")",
")",
")",
":",
"# Try a bit harder to catch gmock lines: the only place where",
"# something looks like an old-style cast is where we declare the",
"# return type of the mocked method, and the only time when we",
"# are missing context is if MOCK_METHOD was split across",
"# multiple lines. The missing MOCK_METHOD is usually one or two",
"# lines back, so scan back one or two lines.",
"#",
"# It's not possible for gmock macros to appear in the first 2",
"# lines, since the class head + section name takes up 2 lines.",
"if",
"(",
"linenum",
"<",
"2",
"or",
"not",
"(",
"Match",
"(",
"r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
"or",
"Match",
"(",
"r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\(\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"2",
"]",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using deprecated casting style. '",
"'Use static_cast<%s>(...) instead'",
"%",
"matched_type",
")",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'static_cast'",
",",
"r'\\((int|float|double|bool|char|u?int(16|32|64))\\)'",
",",
"error",
")",
"# This doesn't catch all cases. Consider (const char * const)\"hello\".",
"#",
"# (char *) \"foo\" should always be a const_cast (reinterpret_cast won't",
"# compile).",
"if",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'const_cast'",
",",
"r'\\((char\\s?\\*+\\s?)\\)\\s*\"'",
",",
"error",
")",
":",
"pass",
"else",
":",
"# Check pointer casts for other than string constants",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'reinterpret_cast'",
",",
"r'\\((\\w+\\s?\\*+\\s?)\\)'",
",",
"error",
")",
"# In addition, we look for people taking the address of a cast. This",
"# is dangerous -- casts can assign to temporaries, so the pointer doesn't",
"# point where you think.",
"match",
"=",
"Search",
"(",
"r'(?:&\\(([^)]+)\\)[\\w(])|'",
"r'(?:&(static|dynamic|down|reinterpret)_cast\\b)'",
",",
"line",
")",
"if",
"match",
"and",
"match",
".",
"group",
"(",
"1",
")",
"!=",
"'*'",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/casting'",
",",
"4",
",",
"(",
"'Are you taking an address of a cast? '",
"'This is dangerous: could be a temp var. '",
"'Take the address before doing the cast, rather than after'",
")",
")",
"# Create an extended_line, which is the concatenation of the current and",
"# next lines, for more effective checking of code that may span more than one",
"# line.",
"if",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"extended_line",
"=",
"line",
"+",
"clean_lines",
".",
"elided",
"[",
"linenum",
"+",
"1",
"]",
"else",
":",
"extended_line",
"=",
"line",
"# Check for people declaring static/global STL strings at the top level.",
"# This is dangerous because the C++ language does not guarantee that",
"# globals with constructors are initialized before the first access.",
"match",
"=",
"Match",
"(",
"r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\\b(.*)'",
",",
"line",
")",
"# Make sure it's not a function.",
"# Function template specialization looks like: \"string foo<Type>(...\".",
"# Class template definitions look like: \"string Foo<Type>::Method(...\".",
"#",
"# Also ignore things that look like operators. These are matched separately",
"# because operator names cross non-word boundaries. If we change the pattern",
"# above, we would decrease the accuracy of matching identifiers.",
"if",
"(",
"match",
"and",
"not",
"Search",
"(",
"r'\\boperator\\W'",
",",
"line",
")",
"and",
"not",
"Match",
"(",
"r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)?\\s*\\(([^\"]|$)'",
",",
"match",
".",
"group",
"(",
"3",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/string'",
",",
"4",
",",
"'For a static/global string constant, use a C style string instead: '",
"'\"%schar %s[]\".'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"if",
"Search",
"(",
"r'\\b([A-Za-z0-9_]*_)\\(\\1\\)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/init'",
",",
"4",
",",
"'You seem to be initializing a member variable with itself.'",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"# TODO(unknown): check that 1-arg constructors are explicit.",
"# How to tell it's a constructor?",
"# (handled in CheckForNonStandardConstructs for now)",
"# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS",
"# (level 1 error)",
"pass",
"# Check if people are using the verboten C basic types. The only exception",
"# we regularly allow is \"unsigned short port\" for port.",
"if",
"Search",
"(",
"r'\\bshort port\\b'",
",",
"line",
")",
":",
"if",
"not",
"Search",
"(",
"r'\\bunsigned short port\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/int'",
",",
"4",
",",
"'Use \"unsigned short\" for ports, not \"short\"'",
")",
"else",
":",
"match",
"=",
"Search",
"(",
"r'\\b(short|long(?! +double)|long long)\\b'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/int'",
",",
"4",
",",
"'Use int16/int64/etc, rather than the C type %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# When snprintf is used, the second argument shouldn't be a literal.",
"match",
"=",
"Search",
"(",
"r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,'",
",",
"line",
")",
"if",
"match",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'0'",
":",
"# If 2nd arg is zero, snprintf is used to calculate size.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"3",
",",
"'If you can, use sizeof(%s) instead of %s as the 2nd arg '",
"'to snprintf.'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"# Check if some verboten C functions are being used.",
"if",
"Search",
"(",
"r'\\bsprintf\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"5",
",",
"'Never use sprintf. Use snprintf instead.'",
")",
"match",
"=",
"Search",
"(",
"r'\\b(strcpy|strcat)\\b'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"4",
",",
"'Almost always, snprintf is better than %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# Check if some verboten operator overloading is going on",
"# TODO(unknown): catch out-of-line unary operator&:",
"# class X {};",
"# int operator&(const X& x) { return 42; } // unary operator&",
"# The trick is it's hard to tell apart from binary operator&:",
"# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&",
"if",
"Search",
"(",
"r'\\boperator\\s*&\\s*\\(\\s*\\)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/operator'",
",",
"4",
",",
"'Unary operator& is dangerous. Do not use it.'",
")",
"# Check for suspicious usage of \"if\" like",
"# } if (a == b) {",
"if",
"Search",
"(",
"r'\\}\\s*if\\s*\\('",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/braces'",
",",
"4",
",",
"'Did you mean \"else if\"? If not, start a new line for \"if\".'",
")",
"# Check for potential format string bugs like printf(foo).",
"# We constrain the pattern not to pick things like DocidForPrintf(foo).",
"# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())",
"# TODO(sugawarayu): Catch the following case. Need to change the calling",
"# convention of the whole function to process multiple line to handle it.",
"# printf(",
"# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);",
"printf_args",
"=",
"_GetTextInside",
"(",
"line",
",",
"r'(?i)\\b(string)?printf\\s*\\('",
")",
"if",
"printf_args",
":",
"match",
"=",
"Match",
"(",
"r'([\\w.\\->()]+)$'",
",",
"printf_args",
")",
"if",
"match",
"and",
"match",
".",
"group",
"(",
"1",
")",
"!=",
"'__VA_ARGS__'",
":",
"function_name",
"=",
"re",
".",
"search",
"(",
"r'\\b((?:string)?printf)\\s*\\('",
",",
"line",
",",
"re",
".",
"I",
")",
".",
"group",
"(",
"1",
")",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"4",
",",
"'Potential format string bug. Do %s(\"%%s\", %s) instead.'",
"%",
"(",
"function_name",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"# Check for potential memset bugs like memset(buf, sizeof(buf), 0).",
"match",
"=",
"Search",
"(",
"r'memset\\s*\\(([^,]*),\\s*([^,]*),\\s*0\\s*\\)'",
",",
"line",
")",
"if",
"match",
"and",
"not",
"Match",
"(",
"r\"^''|-?[0-9]+|0x[0-9A-Fa-f]$\"",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/memset'",
",",
"4",
",",
"'Did you mean \"memset(%s, 0, %s)\"?'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"if",
"Search",
"(",
"r'\\busing namespace\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces'",
",",
"5",
",",
"'Do not use namespace using-directives. '",
"'Use using-declarations instead.'",
")",
"# Detect variable-length arrays.",
"match",
"=",
"Match",
"(",
"r'\\s*(.+::)?(\\w+) [a-z]\\w*\\[(.+)];'",
",",
"line",
")",
"if",
"(",
"match",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'return'",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'delete'",
"and",
"match",
".",
"group",
"(",
"3",
")",
".",
"find",
"(",
"']'",
")",
"==",
"-",
"1",
")",
":",
"# Split the size using space and arithmetic operators as delimiters.",
"# If any of the resulting tokens are not compile time constants then",
"# report the error.",
"tokens",
"=",
"re",
".",
"split",
"(",
"r'\\s|\\+|\\-|\\*|\\/|<<|>>]'",
",",
"match",
".",
"group",
"(",
"3",
")",
")",
"is_const",
"=",
"True",
"skip_next",
"=",
"False",
"for",
"tok",
"in",
"tokens",
":",
"if",
"skip_next",
":",
"skip_next",
"=",
"False",
"continue",
"if",
"Search",
"(",
"r'sizeof\\(.+\\)'",
",",
"tok",
")",
":",
"continue",
"if",
"Search",
"(",
"r'arraysize\\(\\w+\\)'",
",",
"tok",
")",
":",
"continue",
"tok",
"=",
"tok",
".",
"lstrip",
"(",
"'('",
")",
"tok",
"=",
"tok",
".",
"rstrip",
"(",
"')'",
")",
"if",
"not",
"tok",
":",
"continue",
"if",
"Match",
"(",
"r'\\d+'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'0[xX][0-9a-fA-F]+'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'k[A-Z0-9]\\w*'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'(.+::)?k[A-Z0-9]\\w*'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'(.+::)?[A-Z][A-Z0-9_]*'",
",",
"tok",
")",
":",
"continue",
"# A catch all for tricky sizeof cases, including 'sizeof expression',",
"# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'",
"# requires skipping the next token because we split on ' ' and '*'.",
"if",
"tok",
".",
"startswith",
"(",
"'sizeof'",
")",
":",
"skip_next",
"=",
"True",
"continue",
"is_const",
"=",
"False",
"break",
"if",
"not",
"is_const",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/arrays'",
",",
"1",
",",
"'Do not use variable-length arrays. Use an appropriately named '",
"\"('k' followed by CamelCase) compile-time constant for the size.\"",
")",
"# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or",
"# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing",
"# in the class declaration.",
"match",
"=",
"Match",
"(",
"(",
"r'\\s*'",
"r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'",
"r'\\(.*\\);$'",
")",
",",
"line",
")",
"if",
"match",
"and",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"next_line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"+",
"1",
"]",
"# We allow some, but not all, declarations of variables to be present",
"# in the statement that defines the class. The [\\w\\*,\\s]* fragment of",
"# the regular expression below allows users to declare instances of",
"# the class or pointers to instances, but not less common types such",
"# as function pointers or arrays. It's a tradeoff between allowing",
"# reasonable code and avoiding trying to parse more C++ using regexps.",
"if",
"not",
"Search",
"(",
"r'^\\s*}[\\w\\*,\\s]*;'",
",",
"next_line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/constructors'",
",",
"3",
",",
"match",
".",
"group",
"(",
"1",
")",
"+",
"' should be the last thing in the class'",
")",
"# Check for use of unnamed namespaces in header files. Registration",
"# macros are typically OK, so we allow use of \"namespace {\" on lines",
"# that end with backslashes.",
"if",
"(",
"file_extension",
"==",
"'h'",
"and",
"Search",
"(",
"r'\\bnamespace\\s*{'",
",",
"line",
")",
"and",
"line",
"[",
"-",
"1",
"]",
"!=",
"'\\\\'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces'",
",",
"4",
",",
"'Do not use unnamed namespaces in header files. See '",
"'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'",
"' for more information.'",
")"
] | https://github.com/MhLiao/TextBoxes_plusplus/blob/39d4898de1504c53a2ed3d67966a57b3595836d0/scripts/cpp_lint.py#L3838-L4136 | ||
maidsafe-archive/MaidSafe | defd65e1c8cfb6a1cbdeaaa0eee31d065421792d | tools/cpplint.py | python | _NestingState.InnermostClass | (self) | return None | Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise. | Get class info on the top of the stack. | [
"Get",
"class",
"info",
"on",
"the",
"top",
"of",
"the",
"stack",
"."
] | def InnermostClass(self):
"""Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise.
"""
for i in range(len(self.stack), 0, -1):
classinfo = self.stack[i - 1]
if isinstance(classinfo, _ClassInfo):
return classinfo
return None | [
"def",
"InnermostClass",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"stack",
")",
",",
"0",
",",
"-",
"1",
")",
":",
"classinfo",
"=",
"self",
".",
"stack",
"[",
"i",
"-",
"1",
"]",
"if",
"isinstance",
"(",
"classinfo",
",",
"_ClassInfo",
")",
":",
"return",
"classinfo",
"return",
"None"
] | https://github.com/maidsafe-archive/MaidSafe/blob/defd65e1c8cfb6a1cbdeaaa0eee31d065421792d/tools/cpplint.py#L1729-L1739 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiMDIParentFrame.SetActiveChild | (*args, **kwargs) | return _aui.AuiMDIParentFrame_SetActiveChild(*args, **kwargs) | SetActiveChild(self, AuiMDIChildFrame pChildFrame) | SetActiveChild(self, AuiMDIChildFrame pChildFrame) | [
"SetActiveChild",
"(",
"self",
"AuiMDIChildFrame",
"pChildFrame",
")"
] | def SetActiveChild(*args, **kwargs):
"""SetActiveChild(self, AuiMDIChildFrame pChildFrame)"""
return _aui.AuiMDIParentFrame_SetActiveChild(*args, **kwargs) | [
"def",
"SetActiveChild",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiMDIParentFrame_SetActiveChild",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1457-L1459 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/os.py | python | execvp | (file, args) | execvp(file, args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process.
args may be a list or tuple of strings. | execvp(file, args) | [
"execvp",
"(",
"file",
"args",
")"
] | def execvp(file, args):
"""execvp(file, args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process.
args may be a list or tuple of strings. """
_execvpe(file, args) | [
"def",
"execvp",
"(",
"file",
",",
"args",
")",
":",
"_execvpe",
"(",
"file",
",",
"args",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/os.py#L568-L574 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/command/frame_filters.py | python | DisableFrameFilter.complete | (self, text, word) | Completion function for both frame filter dictionary, and
frame filter name. | Completion function for both frame filter dictionary, and
frame filter name. | [
"Completion",
"function",
"for",
"both",
"frame",
"filter",
"dictionary",
"and",
"frame",
"filter",
"name",
"."
] | def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
frame filter name."""
if text.count(" ") == 0:
return _complete_frame_filter_list(text, word, True)
else:
printer_list = gdb.frames.return_list(text.split()[0].rstrip())
return _complete_frame_filter_name(word, printer_list) | [
"def",
"complete",
"(",
"self",
",",
"text",
",",
"word",
")",
":",
"if",
"text",
".",
"count",
"(",
"\" \"",
")",
"==",
"0",
":",
"return",
"_complete_frame_filter_list",
"(",
"text",
",",
"word",
",",
"True",
")",
"else",
":",
"printer_list",
"=",
"gdb",
".",
"frames",
".",
"return_list",
"(",
"text",
".",
"split",
"(",
")",
"[",
"0",
"]",
".",
"rstrip",
"(",
")",
")",
"return",
"_complete_frame_filter_name",
"(",
"word",
",",
"printer_list",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/command/frame_filters.py#L270-L277 | ||
bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | bridge/py_api/setup.py | python | _regex_replace | (pattern, repl, src) | return re.sub(pattern, repl, src) | Replacing matches in `src` with `repl` using regex `pattern` | Replacing matches in `src` with `repl` using regex `pattern` | [
"Replacing",
"matches",
"in",
"src",
"with",
"repl",
"using",
"regex",
"pattern"
] | def _regex_replace(pattern, repl, src):
"""Replacing matches in `src` with `repl` using regex `pattern`"""
print ("config.ini: replacing: '%s' => '%s'" % (pattern, repl))
return re.sub(pattern, repl, src) | [
"def",
"_regex_replace",
"(",
"pattern",
",",
"repl",
",",
"src",
")",
":",
"print",
"(",
"\"config.ini: replacing: '%s' => '%s'\"",
"%",
"(",
"pattern",
",",
"repl",
")",
")",
"return",
"re",
".",
"sub",
"(",
"pattern",
",",
"repl",
",",
"src",
")"
] | https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/bridge/py_api/setup.py#L80-L83 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/gzip.py | python | _GzipReader._read_exact | (self, n) | return data | Read exactly *n* bytes from `self._fp`
This method is required because self._fp may be unbuffered,
i.e. return short reads. | Read exactly *n* bytes from `self._fp` | [
"Read",
"exactly",
"*",
"n",
"*",
"bytes",
"from",
"self",
".",
"_fp"
] | def _read_exact(self, n):
'''Read exactly *n* bytes from `self._fp`
This method is required because self._fp may be unbuffered,
i.e. return short reads.
'''
data = self._fp.read(n)
while len(data) < n:
b = self._fp.read(n - len(data))
if not b:
raise EOFError("Compressed file ended before the "
"end-of-stream marker was reached")
data += b
return data | [
"def",
"_read_exact",
"(",
"self",
",",
"n",
")",
":",
"data",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
"n",
")",
"while",
"len",
"(",
"data",
")",
"<",
"n",
":",
"b",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
"n",
"-",
"len",
"(",
"data",
")",
")",
"if",
"not",
"b",
":",
"raise",
"EOFError",
"(",
"\"Compressed file ended before the \"",
"\"end-of-stream marker was reached\"",
")",
"data",
"+=",
"b",
"return",
"data"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/gzip.py#L400-L414 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/debug/cli/readline_ui.py | python | ReadlineUI.run_ui | (self,
init_command=None,
title=None,
title_color=None,
enable_mouse_on_start=True) | return exit_token | Run the CLI: See the doc of base_ui.BaseUI.run_ui for more details. | Run the CLI: See the doc of base_ui.BaseUI.run_ui for more details. | [
"Run",
"the",
"CLI",
":",
"See",
"the",
"doc",
"of",
"base_ui",
".",
"BaseUI",
".",
"run_ui",
"for",
"more",
"details",
"."
] | def run_ui(self,
init_command=None,
title=None,
title_color=None,
enable_mouse_on_start=True):
"""Run the CLI: See the doc of base_ui.BaseUI.run_ui for more details."""
print(title)
if init_command is not None:
self._dispatch_command(init_command)
exit_token = self._ui_loop()
if self._on_ui_exit:
self._on_ui_exit()
return exit_token | [
"def",
"run_ui",
"(",
"self",
",",
"init_command",
"=",
"None",
",",
"title",
"=",
"None",
",",
"title_color",
"=",
"None",
",",
"enable_mouse_on_start",
"=",
"True",
")",
":",
"print",
"(",
"title",
")",
"if",
"init_command",
"is",
"not",
"None",
":",
"self",
".",
"_dispatch_command",
"(",
"init_command",
")",
"exit_token",
"=",
"self",
".",
"_ui_loop",
"(",
")",
"if",
"self",
".",
"_on_ui_exit",
":",
"self",
".",
"_on_ui_exit",
"(",
")",
"return",
"exit_token"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/readline_ui.py#L55-L72 | |
microsoft/DirectXShaderCompiler | 8348ff8d9e0287610ba05d3a828e10af981a1c05 | tools/clang/bindings/python/clang/cindex.py | python | Type.translation_unit | (self) | return self._tu | The TranslationUnit to which this Type is associated. | The TranslationUnit to which this Type is associated. | [
"The",
"TranslationUnit",
"to",
"which",
"this",
"Type",
"is",
"associated",
"."
] | def translation_unit(self):
"""The TranslationUnit to which this Type is associated."""
# If this triggers an AttributeError, the instance was not properly
# instantiated.
return self._tu | [
"def",
"translation_unit",
"(",
"self",
")",
":",
"# If this triggers an AttributeError, the instance was not properly",
"# instantiated.",
"return",
"self",
".",
"_tu"
] | https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/tools/clang/bindings/python/clang/cindex.py#L1771-L1775 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/add_impl.py | python | _tuple_add_tensor | (x, y) | return F.tensor_add(x, y) | Tuple is added to tensor.
Args:
x (Tuple): x
y (Tensor): The dtype is same as x.
Returns:
Tensor, has the same dtype as x. | Tuple is added to tensor. | [
"Tuple",
"is",
"added",
"to",
"tensor",
"."
] | def _tuple_add_tensor(x, y):
"""
Tuple is added to tensor.
Args:
x (Tuple): x
y (Tensor): The dtype is same as x.
Returns:
Tensor, has the same dtype as x.
"""
x = utils.sequence_to_tensor(x, y.dtype)
return F.tensor_add(x, y) | [
"def",
"_tuple_add_tensor",
"(",
"x",
",",
"y",
")",
":",
"x",
"=",
"utils",
".",
"sequence_to_tensor",
"(",
"x",
",",
"y",
".",
"dtype",
")",
"return",
"F",
".",
"tensor_add",
"(",
"x",
",",
"y",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/add_impl.py#L120-L132 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/utils/telemetry_utils.py | python | send_op_names_info | (framework: str, graph: Graph) | This function sends information about operations in model.
:param framework: framework name.
:param graph: model graph. | This function sends information about operations in model.
:param framework: framework name.
:param graph: model graph. | [
"This",
"function",
"sends",
"information",
"about",
"operations",
"in",
"model",
".",
":",
"param",
"framework",
":",
"framework",
"name",
".",
":",
"param",
"graph",
":",
"model",
"graph",
"."
] | def send_op_names_info(framework: str, graph: Graph):
"""
This function sends information about operations in model.
:param framework: framework name.
:param graph: model graph.
"""
op_counter = Counter()
def gather_op_statistics(g: Graph, op_c: Counter = op_counter):
if hasattr(g, 'op_names_statistic'):
op_c += g.op_names_statistic
for_graph_and_each_sub_graph_recursively(graph, gather_op_statistics)
t = tm.Telemetry()
for op_name in op_counter:
t.send_event('mo', 'op_count', "{}_{}".format(framework, op_name), op_counter[op_name]) | [
"def",
"send_op_names_info",
"(",
"framework",
":",
"str",
",",
"graph",
":",
"Graph",
")",
":",
"op_counter",
"=",
"Counter",
"(",
")",
"def",
"gather_op_statistics",
"(",
"g",
":",
"Graph",
",",
"op_c",
":",
"Counter",
"=",
"op_counter",
")",
":",
"if",
"hasattr",
"(",
"g",
",",
"'op_names_statistic'",
")",
":",
"op_c",
"+=",
"g",
".",
"op_names_statistic",
"for_graph_and_each_sub_graph_recursively",
"(",
"graph",
",",
"gather_op_statistics",
")",
"t",
"=",
"tm",
".",
"Telemetry",
"(",
")",
"for",
"op_name",
"in",
"op_counter",
":",
"t",
".",
"send_event",
"(",
"'mo'",
",",
"'op_count'",
",",
"\"{}_{}\"",
".",
"format",
"(",
"framework",
",",
"op_name",
")",
",",
"op_counter",
"[",
"op_name",
"]",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/telemetry_utils.py#L20-L36 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/client.py | python | _encode | (data, name='data') | Call data.encode("latin-1") but show a better error message. | Call data.encode("latin-1") but show a better error message. | [
"Call",
"data",
".",
"encode",
"(",
"latin",
"-",
"1",
")",
"but",
"show",
"a",
"better",
"error",
"message",
"."
] | def _encode(data, name='data'):
"""Call data.encode("latin-1") but show a better error message."""
try:
return data.encode("latin-1")
except UnicodeEncodeError as err:
raise UnicodeEncodeError(
err.encoding,
err.object,
err.start,
err.end,
"%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
"if you want to send it encoded in UTF-8." %
(name.title(), data[err.start:err.end], name)) from None | [
"def",
"_encode",
"(",
"data",
",",
"name",
"=",
"'data'",
")",
":",
"try",
":",
"return",
"data",
".",
"encode",
"(",
"\"latin-1\"",
")",
"except",
"UnicodeEncodeError",
"as",
"err",
":",
"raise",
"UnicodeEncodeError",
"(",
"err",
".",
"encoding",
",",
"err",
".",
"object",
",",
"err",
".",
"start",
",",
"err",
".",
"end",
",",
"\"%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') \"",
"\"if you want to send it encoded in UTF-8.\"",
"%",
"(",
"name",
".",
"title",
"(",
")",
",",
"data",
"[",
"err",
".",
"start",
":",
"err",
".",
"end",
"]",
",",
"name",
")",
")",
"from",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/client.py#L162-L174 | ||
nasa/astrobee | 9241e67e6692810d6e275abb3165b6d02f4ca5ef | scripts/git/cpplint.py | python | ParseArguments | (args) | return filenames | Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | Parses the command line arguments. | [
"Parses",
"the",
"command",
"line",
"arguments",
"."
] | def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(
args,
"",
[
"help",
"output=",
"verbose=",
"counting=",
"filter=",
"root=",
"linelength=",
"extensions=",
],
)
except getopt.GetoptError:
PrintUsage("Invalid arguments.")
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ""
counting_style = ""
for (opt, val) in opts:
if opt == "--help":
PrintUsage(None)
elif opt == "--output":
if val not in ("emacs", "vs7", "eclipse"):
PrintUsage(
"The only allowed output formats are emacs, vs7 and eclipse."
)
output_format = val
elif opt == "--verbose":
verbosity = int(val)
elif opt == "--filter":
filters = val
if not filters:
PrintCategories()
elif opt == "--counting":
if val not in ("total", "toplevel", "detailed"):
PrintUsage("Valid counting options are total, toplevel, and detailed")
counting_style = val
elif opt == "--root":
global _root
_root = val
elif opt == "--linelength":
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage("Line length must be digits.")
elif opt == "--extensions":
global _valid_extensions
try:
_valid_extensions = set(val.split(","))
except ValueError:
PrintUsage("Extensions must be comma seperated list.")
if not filenames:
PrintUsage("No files were specified.")
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames | [
"def",
"ParseArguments",
"(",
"args",
")",
":",
"try",
":",
"(",
"opts",
",",
"filenames",
")",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"\"\"",
",",
"[",
"\"help\"",
",",
"\"output=\"",
",",
"\"verbose=\"",
",",
"\"counting=\"",
",",
"\"filter=\"",
",",
"\"root=\"",
",",
"\"linelength=\"",
",",
"\"extensions=\"",
",",
"]",
",",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"PrintUsage",
"(",
"\"Invalid arguments.\"",
")",
"verbosity",
"=",
"_VerboseLevel",
"(",
")",
"output_format",
"=",
"_OutputFormat",
"(",
")",
"filters",
"=",
"\"\"",
"counting_style",
"=",
"\"\"",
"for",
"(",
"opt",
",",
"val",
")",
"in",
"opts",
":",
"if",
"opt",
"==",
"\"--help\"",
":",
"PrintUsage",
"(",
"None",
")",
"elif",
"opt",
"==",
"\"--output\"",
":",
"if",
"val",
"not",
"in",
"(",
"\"emacs\"",
",",
"\"vs7\"",
",",
"\"eclipse\"",
")",
":",
"PrintUsage",
"(",
"\"The only allowed output formats are emacs, vs7 and eclipse.\"",
")",
"output_format",
"=",
"val",
"elif",
"opt",
"==",
"\"--verbose\"",
":",
"verbosity",
"=",
"int",
"(",
"val",
")",
"elif",
"opt",
"==",
"\"--filter\"",
":",
"filters",
"=",
"val",
"if",
"not",
"filters",
":",
"PrintCategories",
"(",
")",
"elif",
"opt",
"==",
"\"--counting\"",
":",
"if",
"val",
"not",
"in",
"(",
"\"total\"",
",",
"\"toplevel\"",
",",
"\"detailed\"",
")",
":",
"PrintUsage",
"(",
"\"Valid counting options are total, toplevel, and detailed\"",
")",
"counting_style",
"=",
"val",
"elif",
"opt",
"==",
"\"--root\"",
":",
"global",
"_root",
"_root",
"=",
"val",
"elif",
"opt",
"==",
"\"--linelength\"",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"\"Line length must be digits.\"",
")",
"elif",
"opt",
"==",
"\"--extensions\"",
":",
"global",
"_valid_extensions",
"try",
":",
"_valid_extensions",
"=",
"set",
"(",
"val",
".",
"split",
"(",
"\",\"",
")",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"\"Extensions must be comma seperated list.\"",
")",
"if",
"not",
"filenames",
":",
"PrintUsage",
"(",
"\"No files were specified.\"",
")",
"_SetOutputFormat",
"(",
"output_format",
")",
"_SetVerboseLevel",
"(",
"verbosity",
")",
"_SetFilters",
"(",
"filters",
")",
"_SetCountingStyle",
"(",
"counting_style",
")",
"return",
"filenames"
] | https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L6965-L7042 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/push/search/util/search_schema_parser.py | python | SearchSchemaParser.__EndElement | (self, elem) | End element handler.
Args:
elem: current element. | End element handler. | [
"End",
"element",
"handler",
"."
] | def __EndElement(self, elem):
"""End element handler.
Args:
elem: current element.
"""
self._current_tag = elem.tag
self._element_end(elem) | [
"def",
"__EndElement",
"(",
"self",
",",
"elem",
")",
":",
"self",
".",
"_current_tag",
"=",
"elem",
".",
"tag",
"self",
".",
"_element_end",
"(",
"elem",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/push/search/util/search_schema_parser.py#L246-L253 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/nn_ops.py | python | relu6 | (features, name=None) | Computes Rectified Linear 6: `min(max(features, 0), 6)`.
Args:
features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,
`int16`, or `int8`.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `features`. | Computes Rectified Linear 6: `min(max(features, 0), 6)`. | [
"Computes",
"Rectified",
"Linear",
"6",
":",
"min",
"(",
"max",
"(",
"features",
"0",
")",
"6",
")",
"."
] | def relu6(features, name=None):
"""Computes Rectified Linear 6: `min(max(features, 0), 6)`.
Args:
features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,
`int16`, or `int8`.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `features`.
"""
with ops.name_scope(name, "Relu6", [features]) as name:
features = ops.convert_to_tensor(features, name="features")
return gen_nn_ops._relu6(features, name=name) | [
"def",
"relu6",
"(",
"features",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"Relu6\"",
",",
"[",
"features",
"]",
")",
"as",
"name",
":",
"features",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"features",
",",
"name",
"=",
"\"features\"",
")",
"return",
"gen_nn_ops",
".",
"_relu6",
"(",
"features",
",",
"name",
"=",
"name",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/nn_ops.py#L995-L1008 | ||
raboof/nethogs | ca8fa246be8ddfedad5c911eeec8687d7ba921f8 | contrib/python-wrapper.py | python | dev_args | (devnames) | return ctypes.c_int(devc), ctypes.cast(
devnames_arg, ctypes.POINTER(ctypes.c_char_p)
) | Return the appropriate ctypes arguments for a device name list, to pass
to libnethogs ``nethogsmonitor_loop_devices``. The return value is a
2-tuple of devc (``ctypes.c_int``) and devicenames (``ctypes.POINTER``)
to an array of ``ctypes.c_char``).
:param devnames: list of device names to monitor
:type devnames: list
:return: 2-tuple of devc, devicenames ctypes arguments
:rtype: tuple | Return the appropriate ctypes arguments for a device name list, to pass
to libnethogs ``nethogsmonitor_loop_devices``. The return value is a
2-tuple of devc (``ctypes.c_int``) and devicenames (``ctypes.POINTER``)
to an array of ``ctypes.c_char``). | [
"Return",
"the",
"appropriate",
"ctypes",
"arguments",
"for",
"a",
"device",
"name",
"list",
"to",
"pass",
"to",
"libnethogs",
"nethogsmonitor_loop_devices",
".",
"The",
"return",
"value",
"is",
"a",
"2",
"-",
"tuple",
"of",
"devc",
"(",
"ctypes",
".",
"c_int",
")",
"and",
"devicenames",
"(",
"ctypes",
".",
"POINTER",
")",
"to",
"an",
"array",
"of",
"ctypes",
".",
"c_char",
")",
"."
] | def dev_args(devnames):
"""
Return the appropriate ctypes arguments for a device name list, to pass
to libnethogs ``nethogsmonitor_loop_devices``. The return value is a
2-tuple of devc (``ctypes.c_int``) and devicenames (``ctypes.POINTER``)
to an array of ``ctypes.c_char``).
:param devnames: list of device names to monitor
:type devnames: list
:return: 2-tuple of devc, devicenames ctypes arguments
:rtype: tuple
"""
devc = len(devnames)
devnames_type = ctypes.c_char_p * devc
devnames_arg = devnames_type()
for idx, val in enumerate(devnames):
devnames_arg[idx] = (val + chr(0)).encode('ascii')
return ctypes.c_int(devc), ctypes.cast(
devnames_arg, ctypes.POINTER(ctypes.c_char_p)
) | [
"def",
"dev_args",
"(",
"devnames",
")",
":",
"devc",
"=",
"len",
"(",
"devnames",
")",
"devnames_type",
"=",
"ctypes",
".",
"c_char_p",
"*",
"devc",
"devnames_arg",
"=",
"devnames_type",
"(",
")",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"devnames",
")",
":",
"devnames_arg",
"[",
"idx",
"]",
"=",
"(",
"val",
"+",
"chr",
"(",
"0",
")",
")",
".",
"encode",
"(",
"'ascii'",
")",
"return",
"ctypes",
".",
"c_int",
"(",
"devc",
")",
",",
"ctypes",
".",
"cast",
"(",
"devnames_arg",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char_p",
")",
")"
] | https://github.com/raboof/nethogs/blob/ca8fa246be8ddfedad5c911eeec8687d7ba921f8/contrib/python-wrapper.py#L84-L103 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/array_ops.py | python | _OneHotShape | (op) | return [tensor_shape.TensorShape(new_shape)] | Shape function for the OneHot op.
It closely follows the code in the .cc implementation.
Args:
op: A OneHot Operation.
Returns:
A single-element list containing the shape of the output.
Raises:
ValueError: if axis < -1. | Shape function for the OneHot op. | [
"Shape",
"function",
"for",
"the",
"OneHot",
"op",
"."
] | def _OneHotShape(op):
"""Shape function for the OneHot op.
It closely follows the code in the .cc implementation.
Args:
op: A OneHot Operation.
Returns:
A single-element list containing the shape of the output.
Raises:
ValueError: if axis < -1.
"""
indices_shape = op.inputs[0].get_shape()
indices_dims = indices_shape.ndims
depth = tensor_util.constant_value(op.inputs[1])
axis = op.get_attr("axis")
if axis < -1:
raise ValueError("axis must be >= -1")
new_shape = None
if indices_dims is not None:
new_shape = indices_shape.as_list()
new_shape.insert(axis % (indices_dims + 1), depth)
return [tensor_shape.TensorShape(new_shape)] | [
"def",
"_OneHotShape",
"(",
"op",
")",
":",
"indices_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
"indices_dims",
"=",
"indices_shape",
".",
"ndims",
"depth",
"=",
"tensor_util",
".",
"constant_value",
"(",
"op",
".",
"inputs",
"[",
"1",
"]",
")",
"axis",
"=",
"op",
".",
"get_attr",
"(",
"\"axis\"",
")",
"if",
"axis",
"<",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"axis must be >= -1\"",
")",
"new_shape",
"=",
"None",
"if",
"indices_dims",
"is",
"not",
"None",
":",
"new_shape",
"=",
"indices_shape",
".",
"as_list",
"(",
")",
"new_shape",
".",
"insert",
"(",
"axis",
"%",
"(",
"indices_dims",
"+",
"1",
")",
",",
"depth",
")",
"return",
"[",
"tensor_shape",
".",
"TensorShape",
"(",
"new_shape",
")",
"]"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L2721-L2748 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/nvmspi.py | python | NvmAccessProviderCmsisDapSpi.read | (self, memory_info, offset, numbytes) | return data | Read the memory in chunks
:param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class
:param offset: relative offset in the memory type
:param numbytes: number of bytes to read
:return: array of bytes read | Read the memory in chunks | [
"Read",
"the",
"memory",
"in",
"chunks"
] | def read(self, memory_info, offset, numbytes):
"""
Read the memory in chunks
:param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class
:param offset: relative offset in the memory type
:param numbytes: number of bytes to read
:return: array of bytes read
"""
if memory_info[DeviceMemoryInfoKeys.NAME] == MemoryNames.FLASH:
_dummy = memory_info
data = []
read_chunk_size = 0x100
while numbytes:
if numbytes < read_chunk_size:
read_chunk_size = numbytes
self.logger.debug("Reading %d bytes from address 0x%06X", read_chunk_size, offset)
data += self.isp.read_flash_chunk(offset, read_chunk_size)
offset += read_chunk_size
numbytes -= read_chunk_size
elif memory_info[DeviceMemoryInfoKeys.NAME] == MemoryNames.SIGNATURES:
data = self.isp.read_signature_bytes(offset, numbytes)
elif memory_info[DeviceMemoryInfoKeys.NAME] == MemoryNames.CALIBRATION_ROW:
data = self.isp.read_calibration_bytes(offset, numbytes)
else:
raise PymcuprogNotSupportedError(
"Currently only Flash, Signature and Calibration memories are supported by read for SPI/ISP")
return data | [
"def",
"read",
"(",
"self",
",",
"memory_info",
",",
"offset",
",",
"numbytes",
")",
":",
"if",
"memory_info",
"[",
"DeviceMemoryInfoKeys",
".",
"NAME",
"]",
"==",
"MemoryNames",
".",
"FLASH",
":",
"_dummy",
"=",
"memory_info",
"data",
"=",
"[",
"]",
"read_chunk_size",
"=",
"0x100",
"while",
"numbytes",
":",
"if",
"numbytes",
"<",
"read_chunk_size",
":",
"read_chunk_size",
"=",
"numbytes",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Reading %d bytes from address 0x%06X\"",
",",
"read_chunk_size",
",",
"offset",
")",
"data",
"+=",
"self",
".",
"isp",
".",
"read_flash_chunk",
"(",
"offset",
",",
"read_chunk_size",
")",
"offset",
"+=",
"read_chunk_size",
"numbytes",
"-=",
"read_chunk_size",
"elif",
"memory_info",
"[",
"DeviceMemoryInfoKeys",
".",
"NAME",
"]",
"==",
"MemoryNames",
".",
"SIGNATURES",
":",
"data",
"=",
"self",
".",
"isp",
".",
"read_signature_bytes",
"(",
"offset",
",",
"numbytes",
")",
"elif",
"memory_info",
"[",
"DeviceMemoryInfoKeys",
".",
"NAME",
"]",
"==",
"MemoryNames",
".",
"CALIBRATION_ROW",
":",
"data",
"=",
"self",
".",
"isp",
".",
"read_calibration_bytes",
"(",
"offset",
",",
"numbytes",
")",
"else",
":",
"raise",
"PymcuprogNotSupportedError",
"(",
"\"Currently only Flash, Signature and Calibration memories are supported by read for SPI/ISP\"",
")",
"return",
"data"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvmspi.py#L86-L113 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_tensor.py | python | _assert_sparse_indices_are_ragged_right | (indices) | return [control_flow_ops.Assert(sparse_indices_are_ragged_right, message)] | Checks that the given SparseTensor.indices tensor is ragged-right.
Example: `indices = [[0, 0], [0, 1], [2, 0], [3, 1]]` is not ragged right
because the entry `[3, 1]` skips a cell.
Args:
indices: The SparseTensor indices to check.
Returns:
A list of control dependency op tensors. | Checks that the given SparseTensor.indices tensor is ragged-right. | [
"Checks",
"that",
"the",
"given",
"SparseTensor",
".",
"indices",
"tensor",
"is",
"ragged",
"-",
"right",
"."
] | def _assert_sparse_indices_are_ragged_right(indices):
"""Checks that the given SparseTensor.indices tensor is ragged-right.
Example: `indices = [[0, 0], [0, 1], [2, 0], [3, 1]]` is not ragged right
because the entry `[3, 1]` skips a cell.
Args:
indices: The SparseTensor indices to check.
Returns:
A list of control dependency op tensors.
"""
index_prefix = indices[:, :-1]
index_suffix = indices[:, -1]
# Check whether each index is starting a new row in the innermost dimension
# (prefix[i] != prefix[i-1]) or continuing a row (prefix[i] == prefix[i-1]).
# (Note: this skips the first index; we will check that separately below.)
index_prefix_changed = math_ops.reduce_any(
math_ops.not_equal(index_prefix[1:], index_prefix[:-1]), axis=1)
# Check two cases:
# * For indices that start a new row: index_suffix[i] must be zero.
# * For indices that continue a row: index_suffix[i] must be equal to
# index_suffix[i-1]+1.
index_ok = array_ops.where(
index_prefix_changed, math_ops.equal(index_suffix[1:], 0),
math_ops.equal(index_suffix[1:], index_suffix[:-1] + 1))
# Also check that the very first index didn't skip any cells. The first
# index starts a new row (by definition), so its suffix should be zero.
sparse_indices_are_ragged_right = math_ops.logical_and(
math_ops.reduce_all(math_ops.equal(index_suffix[:1], 0)),
math_ops.reduce_all(index_ok))
message = [
"SparseTensor is not right-ragged", "SparseTensor.indices =", indices
]
return [control_flow_ops.Assert(sparse_indices_are_ragged_right, message)] | [
"def",
"_assert_sparse_indices_are_ragged_right",
"(",
"indices",
")",
":",
"index_prefix",
"=",
"indices",
"[",
":",
",",
":",
"-",
"1",
"]",
"index_suffix",
"=",
"indices",
"[",
":",
",",
"-",
"1",
"]",
"# Check whether each index is starting a new row in the innermost dimension",
"# (prefix[i] != prefix[i-1]) or continuing a row (prefix[i] == prefix[i-1]).",
"# (Note: this skips the first index; we will check that separately below.)",
"index_prefix_changed",
"=",
"math_ops",
".",
"reduce_any",
"(",
"math_ops",
".",
"not_equal",
"(",
"index_prefix",
"[",
"1",
":",
"]",
",",
"index_prefix",
"[",
":",
"-",
"1",
"]",
")",
",",
"axis",
"=",
"1",
")",
"# Check two cases:",
"# * For indices that start a new row: index_suffix[i] must be zero.",
"# * For indices that continue a row: index_suffix[i] must be equal to",
"# index_suffix[i-1]+1.",
"index_ok",
"=",
"array_ops",
".",
"where",
"(",
"index_prefix_changed",
",",
"math_ops",
".",
"equal",
"(",
"index_suffix",
"[",
"1",
":",
"]",
",",
"0",
")",
",",
"math_ops",
".",
"equal",
"(",
"index_suffix",
"[",
"1",
":",
"]",
",",
"index_suffix",
"[",
":",
"-",
"1",
"]",
"+",
"1",
")",
")",
"# Also check that the very first index didn't skip any cells. The first",
"# index starts a new row (by definition), so its suffix should be zero.",
"sparse_indices_are_ragged_right",
"=",
"math_ops",
".",
"logical_and",
"(",
"math_ops",
".",
"reduce_all",
"(",
"math_ops",
".",
"equal",
"(",
"index_suffix",
"[",
":",
"1",
"]",
",",
"0",
")",
")",
",",
"math_ops",
".",
"reduce_all",
"(",
"index_ok",
")",
")",
"message",
"=",
"[",
"\"SparseTensor is not right-ragged\"",
",",
"\"SparseTensor.indices =\"",
",",
"indices",
"]",
"return",
"[",
"control_flow_ops",
".",
"Assert",
"(",
"sparse_indices_are_ragged_right",
",",
"message",
")",
"]"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_tensor.py#L2751-L2789 | |
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | 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",
"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",
")"
] | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/scripts/cpp_lint.py#L2172-L2191 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pdfviewer/dcgraphics.py | python | dcGraphicsPath.AddLineToPoint | (self, x, y) | Adds a straight line from the current point to (x,y) | Adds a straight line from the current point to (x,y) | [
"Adds",
"a",
"straight",
"line",
"from",
"the",
"current",
"point",
"to",
"(",
"x",
"y",
")"
] | def AddLineToPoint(self, x, y):
"""
Adds a straight line from the current point to (x,y)
"""
x2 = self.gstate.Get_x(x, y)
y2 = self.gstate.Get_y(x, y)
if self.isfilled:
self.allpoints.extend([wx.Point(self.xc, self.yc), wx.Point(x2, y2)])
else:
self.commands.append(['DrawLine', (self.xc, self.yc, x2, y2), {}])
self.xc = x2
self.yc = y2 | [
"def",
"AddLineToPoint",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"x2",
"=",
"self",
".",
"gstate",
".",
"Get_x",
"(",
"x",
",",
"y",
")",
"y2",
"=",
"self",
".",
"gstate",
".",
"Get_y",
"(",
"x",
",",
"y",
")",
"if",
"self",
".",
"isfilled",
":",
"self",
".",
"allpoints",
".",
"extend",
"(",
"[",
"wx",
".",
"Point",
"(",
"self",
".",
"xc",
",",
"self",
".",
"yc",
")",
",",
"wx",
".",
"Point",
"(",
"x2",
",",
"y2",
")",
"]",
")",
"else",
":",
"self",
".",
"commands",
".",
"append",
"(",
"[",
"'DrawLine'",
",",
"(",
"self",
".",
"xc",
",",
"self",
".",
"yc",
",",
"x2",
",",
"y2",
")",
",",
"{",
"}",
"]",
")",
"self",
".",
"xc",
"=",
"x2",
"self",
".",
"yc",
"=",
"y2"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pdfviewer/dcgraphics.py#L310-L321 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/boost/1.78.0/libs/metaparse/tools/benchmark/char_stat.py | python | count_characters | (root, out) | Count the occurrances of the different characters in the files | Count the occurrances of the different characters in the files | [
"Count",
"the",
"occurrances",
"of",
"the",
"different",
"characters",
"in",
"the",
"files"
] | def count_characters(root, out):
"""Count the occurrances of the different characters in the files"""
if os.path.isfile(root):
with open(root, 'rb') as in_f:
for line in in_f:
for char in line:
if char not in out:
out[char] = 0
out[char] = out[char] + 1
elif os.path.isdir(root):
for filename in os.listdir(root):
count_characters(os.path.join(root, filename), out) | [
"def",
"count_characters",
"(",
"root",
",",
"out",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"root",
")",
":",
"with",
"open",
"(",
"root",
",",
"'rb'",
")",
"as",
"in_f",
":",
"for",
"line",
"in",
"in_f",
":",
"for",
"char",
"in",
"line",
":",
"if",
"char",
"not",
"in",
"out",
":",
"out",
"[",
"char",
"]",
"=",
"0",
"out",
"[",
"char",
"]",
"=",
"out",
"[",
"char",
"]",
"+",
"1",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"root",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"root",
")",
":",
"count_characters",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
",",
"out",
")"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/boost/1.78.0/libs/metaparse/tools/benchmark/char_stat.py#L13-L24 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibar.py | python | AuiToolBar.AddSeparator | (self) | return self._items[-1] | Adds a separator for spacing groups of tools. | Adds a separator for spacing groups of tools. | [
"Adds",
"a",
"separator",
"for",
"spacing",
"groups",
"of",
"tools",
"."
] | def AddSeparator(self):
""" Adds a separator for spacing groups of tools. """
item = AuiToolBarItem()
item.window = None
item.label = ""
item.bitmap = wx.NullBitmap
item.disabled_bitmap = wx.NullBitmap
item.active = True
item.dropdown = False
item.id = -1
item.state = 0
item.proportion = 0
item.kind = ITEM_SEPARATOR
item.sizer_item = None
item.min_size = wx.Size(-1, -1)
item.user_data = 0
item.sticky = False
item.orientation = self._tool_orientation
self._items.append(item)
return self._items[-1] | [
"def",
"AddSeparator",
"(",
"self",
")",
":",
"item",
"=",
"AuiToolBarItem",
"(",
")",
"item",
".",
"window",
"=",
"None",
"item",
".",
"label",
"=",
"\"\"",
"item",
".",
"bitmap",
"=",
"wx",
".",
"NullBitmap",
"item",
".",
"disabled_bitmap",
"=",
"wx",
".",
"NullBitmap",
"item",
".",
"active",
"=",
"True",
"item",
".",
"dropdown",
"=",
"False",
"item",
".",
"id",
"=",
"-",
"1",
"item",
".",
"state",
"=",
"0",
"item",
".",
"proportion",
"=",
"0",
"item",
".",
"kind",
"=",
"ITEM_SEPARATOR",
"item",
".",
"sizer_item",
"=",
"None",
"item",
".",
"min_size",
"=",
"wx",
".",
"Size",
"(",
"-",
"1",
",",
"-",
"1",
")",
"item",
".",
"user_data",
"=",
"0",
"item",
".",
"sticky",
"=",
"False",
"item",
".",
"orientation",
"=",
"self",
".",
"_tool_orientation",
"self",
".",
"_items",
".",
"append",
"(",
"item",
")",
"return",
"self",
".",
"_items",
"[",
"-",
"1",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L1932-L1953 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/training/server_lib.py | python | Server.__init__ | (self,
server_or_cluster_def,
job_name=None,
task_index=None,
protocol=None,
config=None,
start=True) | Creates a new server with the given definition.
The `job_name`, `task_index`, and `protocol` arguments are optional, and
override any information provided in `server_or_cluster_def`.
Args:
server_or_cluster_def: A `tf.train.ServerDef` or
`tf.train.ClusterDef` protocol buffer, or a
`tf.train.ClusterSpec` object, describing the server to be
created and/or the cluster of which it is a member.
job_name: (Optional.) Specifies the name of the job of which the server
is a member. Defaults to the value in `server_or_cluster_def`, if
specified.
task_index: (Optional.) Specifies the task index of the server in its
job. Defaults to the value in `server_or_cluster_def`, if specified.
Otherwise defaults to 0 if the server's job has only one task.
protocol: (Optional.) Specifies the protocol to be used by the server.
Acceptable values include `"grpc"`. Defaults to the value in
`server_or_cluster_def`, if specified. Otherwise defaults to `"grpc"`.
config: (Options.) A `tf.ConfigProto` that specifies default
configuration options for all sessions that run on this server.
start: (Optional.) Boolean, indicating whether to start the server
after creating it. Defaults to `True`.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
creating the TensorFlow server. | Creates a new server with the given definition. | [
"Creates",
"a",
"new",
"server",
"with",
"the",
"given",
"definition",
"."
] | def __init__(self,
server_or_cluster_def,
job_name=None,
task_index=None,
protocol=None,
config=None,
start=True):
"""Creates a new server with the given definition.
The `job_name`, `task_index`, and `protocol` arguments are optional, and
override any information provided in `server_or_cluster_def`.
Args:
server_or_cluster_def: A `tf.train.ServerDef` or
`tf.train.ClusterDef` protocol buffer, or a
`tf.train.ClusterSpec` object, describing the server to be
created and/or the cluster of which it is a member.
job_name: (Optional.) Specifies the name of the job of which the server
is a member. Defaults to the value in `server_or_cluster_def`, if
specified.
task_index: (Optional.) Specifies the task index of the server in its
job. Defaults to the value in `server_or_cluster_def`, if specified.
Otherwise defaults to 0 if the server's job has only one task.
protocol: (Optional.) Specifies the protocol to be used by the server.
Acceptable values include `"grpc"`. Defaults to the value in
`server_or_cluster_def`, if specified. Otherwise defaults to `"grpc"`.
config: (Options.) A `tf.ConfigProto` that specifies default
configuration options for all sessions that run on this server.
start: (Optional.) Boolean, indicating whether to start the server
after creating it. Defaults to `True`.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
creating the TensorFlow server.
"""
self._server_def = _make_server_def(server_or_cluster_def,
job_name, task_index, protocol, config)
with errors.raise_exception_on_not_ok_status() as status:
self._server = pywrap_tensorflow.PyServer_New(
self._server_def.SerializeToString(), status)
if start:
self.start() | [
"def",
"__init__",
"(",
"self",
",",
"server_or_cluster_def",
",",
"job_name",
"=",
"None",
",",
"task_index",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"config",
"=",
"None",
",",
"start",
"=",
"True",
")",
":",
"self",
".",
"_server_def",
"=",
"_make_server_def",
"(",
"server_or_cluster_def",
",",
"job_name",
",",
"task_index",
",",
"protocol",
",",
"config",
")",
"with",
"errors",
".",
"raise_exception_on_not_ok_status",
"(",
")",
"as",
"status",
":",
"self",
".",
"_server",
"=",
"pywrap_tensorflow",
".",
"PyServer_New",
"(",
"self",
".",
"_server_def",
".",
"SerializeToString",
"(",
")",
",",
"status",
")",
"if",
"start",
":",
"self",
".",
"start",
"(",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/server_lib.py#L114-L155 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/internals/blocks.py | python | ExtensionBlock.take_nd | (
self,
indexer,
axis: int = 0,
new_mgr_locs: BlockPlacement | None = None,
fill_value=lib.no_default,
) | return self.make_block_same_class(new_values, new_mgr_locs) | Take values according to indexer and return them as a block. | Take values according to indexer and return them as a block. | [
"Take",
"values",
"according",
"to",
"indexer",
"and",
"return",
"them",
"as",
"a",
"block",
"."
] | def take_nd(
self,
indexer,
axis: int = 0,
new_mgr_locs: BlockPlacement | None = None,
fill_value=lib.no_default,
) -> Block:
"""
Take values according to indexer and return them as a block.
"""
if fill_value is lib.no_default:
fill_value = None
# TODO(EA2D): special case not needed with 2D EAs
# axis doesn't matter; we are really a single-dim object
# but are passed the axis depending on the calling routing
# if its REALLY axis 0, then this will be a reindex and not a take
new_values = self.values.take(indexer, fill_value=fill_value, allow_fill=True)
# Called from three places in managers, all of which satisfy
# this assertion
assert not (self.ndim == 1 and new_mgr_locs is None)
if new_mgr_locs is None:
new_mgr_locs = self._mgr_locs
return self.make_block_same_class(new_values, new_mgr_locs) | [
"def",
"take_nd",
"(",
"self",
",",
"indexer",
",",
"axis",
":",
"int",
"=",
"0",
",",
"new_mgr_locs",
":",
"BlockPlacement",
"|",
"None",
"=",
"None",
",",
"fill_value",
"=",
"lib",
".",
"no_default",
",",
")",
"->",
"Block",
":",
"if",
"fill_value",
"is",
"lib",
".",
"no_default",
":",
"fill_value",
"=",
"None",
"# TODO(EA2D): special case not needed with 2D EAs",
"# axis doesn't matter; we are really a single-dim object",
"# but are passed the axis depending on the calling routing",
"# if its REALLY axis 0, then this will be a reindex and not a take",
"new_values",
"=",
"self",
".",
"values",
".",
"take",
"(",
"indexer",
",",
"fill_value",
"=",
"fill_value",
",",
"allow_fill",
"=",
"True",
")",
"# Called from three places in managers, all of which satisfy",
"# this assertion",
"assert",
"not",
"(",
"self",
".",
"ndim",
"==",
"1",
"and",
"new_mgr_locs",
"is",
"None",
")",
"if",
"new_mgr_locs",
"is",
"None",
":",
"new_mgr_locs",
"=",
"self",
".",
"_mgr_locs",
"return",
"self",
".",
"make_block_same_class",
"(",
"new_values",
",",
"new_mgr_locs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/blocks.py#L1494-L1519 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | MouseEvent.GetWheelDelta | (*args, **kwargs) | return _core_.MouseEvent_GetWheelDelta(*args, **kwargs) | GetWheelDelta(self) -> int
Get wheel delta, normally 120. This is the threshold for action to be
taken, and one such action (for example, scrolling one increment)
should occur for each delta. | GetWheelDelta(self) -> int | [
"GetWheelDelta",
"(",
"self",
")",
"-",
">",
"int"
] | def GetWheelDelta(*args, **kwargs):
"""
GetWheelDelta(self) -> int
Get wheel delta, normally 120. This is the threshold for action to be
taken, and one such action (for example, scrolling one increment)
should occur for each delta.
"""
return _core_.MouseEvent_GetWheelDelta(*args, **kwargs) | [
"def",
"GetWheelDelta",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MouseEvent_GetWheelDelta",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L5812-L5820 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/array_ops.py | python | Diag.__init__ | (self) | Initialize Diag | Initialize Diag | [
"Initialize",
"Diag"
] | def __init__(self):
"""Initialize Diag""" | [
"def",
"__init__",
"(",
"self",
")",
":"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/array_ops.py#L3542-L3543 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/ao/quantization/fx/_equalize.py | python | node_supports_equalization | (node: Node, modules) | return False | Checks if the current node supports equalization
Currently we only support nn.Linear/F.Linear and nn.Conv/F.conv layers | Checks if the current node supports equalization
Currently we only support nn.Linear/F.Linear and nn.Conv/F.conv layers | [
"Checks",
"if",
"the",
"current",
"node",
"supports",
"equalization",
"Currently",
"we",
"only",
"support",
"nn",
".",
"Linear",
"/",
"F",
".",
"Linear",
"and",
"nn",
".",
"Conv",
"/",
"F",
".",
"conv",
"layers"
] | def node_supports_equalization(node: Node, modules) -> bool:
""" Checks if the current node supports equalization
Currently we only support nn.Linear/F.Linear and nn.Conv/F.conv layers
"""
if node.op == 'call_module':
return nn_module_supports_equalization(modules[str(node.target)]) or \
fused_module_supports_equalization(modules[str(node.target)])
elif node.op == 'call_function':
return node.target in [F.linear, F.conv1d, F.conv2d, F.conv3d]
return False | [
"def",
"node_supports_equalization",
"(",
"node",
":",
"Node",
",",
"modules",
")",
"->",
"bool",
":",
"if",
"node",
".",
"op",
"==",
"'call_module'",
":",
"return",
"nn_module_supports_equalization",
"(",
"modules",
"[",
"str",
"(",
"node",
".",
"target",
")",
"]",
")",
"or",
"fused_module_supports_equalization",
"(",
"modules",
"[",
"str",
"(",
"node",
".",
"target",
")",
"]",
")",
"elif",
"node",
".",
"op",
"==",
"'call_function'",
":",
"return",
"node",
".",
"target",
"in",
"[",
"F",
".",
"linear",
",",
"F",
".",
"conv1d",
",",
"F",
".",
"conv2d",
",",
"F",
".",
"conv3d",
"]",
"return",
"False"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/_equalize.py#L244-L253 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/utils/io/io_pdb.py | python | print_pdb | (atoms, cell, filedesc = sys.stdout, title="") | Prints the atom configurations, into a pdb formatted file.
Also prints the cell parameters in standard pdb form. Note
that the angles are in degrees.
Args:
atoms: An atoms object giving the atom positions.
cell: A cell object giving the system box.
filedesc: An open writable file object. Defaults to standard output.
title: An optional string of max. 70 characters. | Prints the atom configurations, into a pdb formatted file. | [
"Prints",
"the",
"atom",
"configurations",
"into",
"a",
"pdb",
"formatted",
"file",
"."
] | def print_pdb(atoms, cell, filedesc = sys.stdout, title=""):
"""Prints the atom configurations, into a pdb formatted file.
Also prints the cell parameters in standard pdb form. Note
that the angles are in degrees.
Args:
atoms: An atoms object giving the atom positions.
cell: A cell object giving the system box.
filedesc: An open writable file object. Defaults to standard output.
title: An optional string of max. 70 characters.
"""
if title != "" :
filedesc.write("TITLE %70s\n" % (title))
a, b, c, alpha, beta, gamma = mt.h2abc_deg(cell.h)
z = 1
filedesc.write("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f%s%4i\n" % (a, b, c, alpha, beta, gamma, " P 1 ", z))
natoms = atoms.natoms
qs = depstrip(atoms.q)
lab = depstrip(atoms.names)
for i in range(natoms):
filedesc.write("ATOM %5i %4s%1s%3s %1s%4i%1s %8.3f%8.3f%8.3f%6.2f%6.2f %2s%2i\n" % (i+1, lab[i], ' ', ' 1', ' ', 1, ' ', qs[3*i], qs[3*i+1], qs[3*i+2], 0.0, 0.0, ' ', 0))
filedesc.write("END\n") | [
"def",
"print_pdb",
"(",
"atoms",
",",
"cell",
",",
"filedesc",
"=",
"sys",
".",
"stdout",
",",
"title",
"=",
"\"\"",
")",
":",
"if",
"title",
"!=",
"\"\"",
":",
"filedesc",
".",
"write",
"(",
"\"TITLE %70s\\n\"",
"%",
"(",
"title",
")",
")",
"a",
",",
"b",
",",
"c",
",",
"alpha",
",",
"beta",
",",
"gamma",
"=",
"mt",
".",
"h2abc_deg",
"(",
"cell",
".",
"h",
")",
"z",
"=",
"1",
"filedesc",
".",
"write",
"(",
"\"CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f%s%4i\\n\"",
"%",
"(",
"a",
",",
"b",
",",
"c",
",",
"alpha",
",",
"beta",
",",
"gamma",
",",
"\" P 1 \"",
",",
"z",
")",
")",
"natoms",
"=",
"atoms",
".",
"natoms",
"qs",
"=",
"depstrip",
"(",
"atoms",
".",
"q",
")",
"lab",
"=",
"depstrip",
"(",
"atoms",
".",
"names",
")",
"for",
"i",
"in",
"range",
"(",
"natoms",
")",
":",
"filedesc",
".",
"write",
"(",
"\"ATOM %5i %4s%1s%3s %1s%4i%1s %8.3f%8.3f%8.3f%6.2f%6.2f %2s%2i\\n\"",
"%",
"(",
"i",
"+",
"1",
",",
"lab",
"[",
"i",
"]",
",",
"' '",
",",
"' 1'",
",",
"' '",
",",
"1",
",",
"' '",
",",
"qs",
"[",
"3",
"*",
"i",
"]",
",",
"qs",
"[",
"3",
"*",
"i",
"+",
"1",
"]",
",",
"qs",
"[",
"3",
"*",
"i",
"+",
"2",
"]",
",",
"0.0",
",",
"0.0",
",",
"' '",
",",
"0",
")",
")",
"filedesc",
".",
"write",
"(",
"\"END\\n\"",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/utils/io/io_pdb.py#L72-L100 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/_dirmon.py | python | WatcherThread.Shutdown | (self) | Shut the thread down | Shut the thread down | [
"Shut",
"the",
"thread",
"down"
] | def Shutdown(self):
"""Shut the thread down"""
self._continue = False | [
"def",
"Shutdown",
"(",
"self",
")",
":",
"self",
".",
"_continue",
"=",
"False"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/_dirmon.py#L319-L321 | ||
pytorch/xla | 93174035e8149d5d03cee446486de861f56493e1 | torch_xla/utils/gcsfs.py | python | list | (path) | return blobs | Lists the content of a GCS bucket.
Args:
path (string): The GCS path of the file. Must be "gs://BUCKET_NAME/PATH"
where ``BUCKET_NAME`` is the name of the GCS bucket, and ``PATH`` is a `/`
delimited path.
Returns:
A list of ``GcsBlob`` objects. | Lists the content of a GCS bucket. | [
"Lists",
"the",
"content",
"of",
"a",
"GCS",
"bucket",
"."
] | def list(path):
"""Lists the content of a GCS bucket.
Args:
path (string): The GCS path of the file. Must be "gs://BUCKET_NAME/PATH"
where ``BUCKET_NAME`` is the name of the GCS bucket, and ``PATH`` is a `/`
delimited path.
Returns:
A list of ``GcsBlob`` objects.
"""
blobs = []
for mpath in torch_xla._XLAC._xla_tffs_list(path):
try:
fstat = torch_xla._XLAC._xla_tffile_stat(mpath)
blobs.append(_mkblob(mpath, fstat))
except:
pass
return blobs | [
"def",
"list",
"(",
"path",
")",
":",
"blobs",
"=",
"[",
"]",
"for",
"mpath",
"in",
"torch_xla",
".",
"_XLAC",
".",
"_xla_tffs_list",
"(",
"path",
")",
":",
"try",
":",
"fstat",
"=",
"torch_xla",
".",
"_XLAC",
".",
"_xla_tffile_stat",
"(",
"mpath",
")",
"blobs",
".",
"append",
"(",
"_mkblob",
"(",
"mpath",
",",
"fstat",
")",
")",
"except",
":",
"pass",
"return",
"blobs"
] | https://github.com/pytorch/xla/blob/93174035e8149d5d03cee446486de861f56493e1/torch_xla/utils/gcsfs.py#L154-L172 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/indexes/base.py | python | Index.is_all_dates | (self) | return self._is_all_dates | Whether or not the index values only consist of dates. | Whether or not the index values only consist of dates. | [
"Whether",
"or",
"not",
"the",
"index",
"values",
"only",
"consist",
"of",
"dates",
"."
] | def is_all_dates(self) -> bool:
"""
Whether or not the index values only consist of dates.
"""
warnings.warn(
"Index.is_all_dates is deprecated, will be removed in a future version. "
"check index.inferred_type instead",
FutureWarning,
stacklevel=2,
)
return self._is_all_dates | [
"def",
"is_all_dates",
"(",
"self",
")",
"->",
"bool",
":",
"warnings",
".",
"warn",
"(",
"\"Index.is_all_dates is deprecated, will be removed in a future version. \"",
"\"check index.inferred_type instead\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"return",
"self",
".",
"_is_all_dates"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L2398-L2408 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/opt/python/training/external_optimizer.py | python | ExternalOptimizerInterface._minimize | (self, initial_val, loss_grad_func, equality_funcs,
equality_grad_funcs, inequality_funcs, inequality_grad_funcs,
step_callback, optimizer_kwargs) | Wrapper for a particular optimization algorithm implementation.
It would be appropriate for a subclass implementation of this method to
raise `NotImplementedError` if unsupported arguments are passed: e.g. if an
algorithm does not support constraints but `len(equality_funcs) > 0`.
Args:
initial_val: A NumPy vector of initial values.
loss_grad_func: A function accepting a NumPy packed variable vector and
returning two outputs, a loss value and the gradient of that loss with
respect to the packed variable vector.
equality_funcs: A list of functions each of which specifies a scalar
quantity that an optimizer should hold exactly zero.
equality_grad_funcs: A list of gradients of equality_funcs.
inequality_funcs: A list of functions each of which specifies a scalar
quantity that an optimizer should hold >= 0.
inequality_grad_funcs: A list of gradients of inequality_funcs.
step_callback: A callback function to execute at each optimization step,
supplied with the current value of the packed variable vector.
optimizer_kwargs: Other key-value arguments available to the optimizer.
Returns:
The optimal variable vector as a NumPy vector. | Wrapper for a particular optimization algorithm implementation. | [
"Wrapper",
"for",
"a",
"particular",
"optimization",
"algorithm",
"implementation",
"."
] | def _minimize(self, initial_val, loss_grad_func, equality_funcs,
equality_grad_funcs, inequality_funcs, inequality_grad_funcs,
step_callback, optimizer_kwargs):
"""Wrapper for a particular optimization algorithm implementation.
It would be appropriate for a subclass implementation of this method to
raise `NotImplementedError` if unsupported arguments are passed: e.g. if an
algorithm does not support constraints but `len(equality_funcs) > 0`.
Args:
initial_val: A NumPy vector of initial values.
loss_grad_func: A function accepting a NumPy packed variable vector and
returning two outputs, a loss value and the gradient of that loss with
respect to the packed variable vector.
equality_funcs: A list of functions each of which specifies a scalar
quantity that an optimizer should hold exactly zero.
equality_grad_funcs: A list of gradients of equality_funcs.
inequality_funcs: A list of functions each of which specifies a scalar
quantity that an optimizer should hold >= 0.
inequality_grad_funcs: A list of gradients of inequality_funcs.
step_callback: A callback function to execute at each optimization step,
supplied with the current value of the packed variable vector.
optimizer_kwargs: Other key-value arguments available to the optimizer.
Returns:
The optimal variable vector as a NumPy vector.
"""
raise NotImplementedError(
'To use ExternalOptimizerInterface, subclass from it and implement '
'the _minimize() method.') | [
"def",
"_minimize",
"(",
"self",
",",
"initial_val",
",",
"loss_grad_func",
",",
"equality_funcs",
",",
"equality_grad_funcs",
",",
"inequality_funcs",
",",
"inequality_grad_funcs",
",",
"step_callback",
",",
"optimizer_kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'To use ExternalOptimizerInterface, subclass from it and implement '",
"'the _minimize() method.'",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/opt/python/training/external_optimizer.py#L170-L199 | ||
deepmind/reverb | ef3c8f0be1b720a741d2dee335e15e44668c291a | reverb/client.py | python | Writer.append | (self, data: Any) | Appends data to the internal buffer.
NOTE: Calling this method alone does not result in anything being inserted
into the replay. To trigger data insertion, `create_item`
must be called so that the resulting sequence includes the data.
Consider the following example:
```python
A, B, C = ...
client = Client(...)
with client.writer(max_sequence_length=2) as writer:
writer.append(A) # A is added to the internal buffer.
writer.append(B) # B is added to the internal buffer.
# The buffer is now full so when this is called C is added and A is
# removed from the internal buffer and since A was never referenced by
# a prioritized item it was never sent to the server.
writer.append(C)
# A sequence of length 1 is created referencing only C and thus C is
# sent to the server.
writer.create_item('my_table', 1, 5.0)
# Writer is now closed and B was never referenced by a prioritized item
# and thus never sent to the server.
```
Args:
data: The (possibly nested) structure to make available for new
items to reference. | Appends data to the internal buffer. | [
"Appends",
"data",
"to",
"the",
"internal",
"buffer",
"."
] | def append(self, data: Any):
"""Appends data to the internal buffer.
NOTE: Calling this method alone does not result in anything being inserted
into the replay. To trigger data insertion, `create_item`
must be called so that the resulting sequence includes the data.
Consider the following example:
```python
A, B, C = ...
client = Client(...)
with client.writer(max_sequence_length=2) as writer:
writer.append(A) # A is added to the internal buffer.
writer.append(B) # B is added to the internal buffer.
# The buffer is now full so when this is called C is added and A is
# removed from the internal buffer and since A was never referenced by
# a prioritized item it was never sent to the server.
writer.append(C)
# A sequence of length 1 is created referencing only C and thus C is
# sent to the server.
writer.create_item('my_table', 1, 5.0)
# Writer is now closed and B was never referenced by a prioritized item
# and thus never sent to the server.
```
Args:
data: The (possibly nested) structure to make available for new
items to reference.
"""
self._writer.Append(tree.flatten(data)) | [
"def",
"append",
"(",
"self",
",",
"data",
":",
"Any",
")",
":",
"self",
".",
"_writer",
".",
"Append",
"(",
"tree",
".",
"flatten",
"(",
"data",
")",
")"
] | https://github.com/deepmind/reverb/blob/ef3c8f0be1b720a741d2dee335e15e44668c291a/reverb/client.py#L65-L101 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/errors.py | python | ParserContext.add_unknown_root_node_error | (self, node) | Add an error about an unknown YAML root node. | Add an error about an unknown YAML root node. | [
"Add",
"an",
"error",
"about",
"an",
"unknown",
"YAML",
"root",
"node",
"."
] | def add_unknown_root_node_error(self, node):
# type: (yaml.nodes.Node) -> None
"""Add an error about an unknown YAML root node."""
self._add_node_error(
node, ERROR_ID_UNKNOWN_ROOT,
("Unrecognized IDL specification root level node '%s', only " +
" (global, import, types, commands, and structs) are accepted") % (node.value)) | [
"def",
"add_unknown_root_node_error",
"(",
"self",
",",
"node",
")",
":",
"# type: (yaml.nodes.Node) -> None",
"self",
".",
"_add_node_error",
"(",
"node",
",",
"ERROR_ID_UNKNOWN_ROOT",
",",
"(",
"\"Unrecognized IDL specification root level node '%s', only \"",
"+",
"\" (global, import, types, commands, and structs) are accepted\"",
")",
"%",
"(",
"node",
".",
"value",
")",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/errors.py#L253-L259 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/request_track.py | python | CachingPolicy.HasValidators | (self) | return (self.request.GetHTTPResponseHeader('Last-Modified')
or self.request.GetHTTPResponseHeader('Etag')) | Returns wether the request has a validator. | Returns wether the request has a validator. | [
"Returns",
"wether",
"the",
"request",
"has",
"a",
"validator",
"."
] | def HasValidators(self):
"""Returns wether the request has a validator."""
# Assuming HTTP 1.1+.
return (self.request.GetHTTPResponseHeader('Last-Modified')
or self.request.GetHTTPResponseHeader('Etag')) | [
"def",
"HasValidators",
"(",
"self",
")",
":",
"# Assuming HTTP 1.1+.",
"return",
"(",
"self",
".",
"request",
".",
"GetHTTPResponseHeader",
"(",
"'Last-Modified'",
")",
"or",
"self",
".",
"request",
".",
"GetHTTPResponseHeader",
"(",
"'Etag'",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/request_track.py#L450-L454 | |
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/operators/initializer.py | python | Fill | (shape, value=0, **kwargs) | return _wrap_output_shape(output, shape) | Return a Tensor with specific value filled.
Parameters
----------
shape : list, tuple or Tensor
The output shape.
value : basic numerical type
The value to fill.
Returns
-------
Tensor
The constant-filled tensor. | Return a Tensor with specific value filled. | [
"Return",
"a",
"Tensor",
"with",
"specific",
"value",
"filled",
"."
] | def Fill(shape, value=0, **kwargs):
"""Return a Tensor with specific value filled.
Parameters
----------
shape : list, tuple or Tensor
The output shape.
value : basic numerical type
The value to fill.
Returns
-------
Tensor
The constant-filled tensor.
"""
arguments = ParseArguments(locals())
arguments['value'] = float(value)
arguments = _wrap_input_shape(arguments, shape)
output = Tensor.CreateOperator([], nout=1, op_type='Fill', **arguments)
return _wrap_output_shape(output, shape) | [
"def",
"Fill",
"(",
"shape",
",",
"value",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"arguments",
"=",
"ParseArguments",
"(",
"locals",
"(",
")",
")",
"arguments",
"[",
"'value'",
"]",
"=",
"float",
"(",
"value",
")",
"arguments",
"=",
"_wrap_input_shape",
"(",
"arguments",
",",
"shape",
")",
"output",
"=",
"Tensor",
".",
"CreateOperator",
"(",
"[",
"]",
",",
"nout",
"=",
"1",
",",
"op_type",
"=",
"'Fill'",
",",
"*",
"*",
"arguments",
")",
"return",
"_wrap_output_shape",
"(",
"output",
",",
"shape",
")"
] | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/operators/initializer.py#L34-L54 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridManager.GetPage | (*args) | return _propgrid.PropertyGridManager_GetPage(*args) | GetPage(self, int ind) -> PropertyGridPage
GetPage(self, String name) -> PropertyGridPage | GetPage(self, int ind) -> PropertyGridPage
GetPage(self, String name) -> PropertyGridPage | [
"GetPage",
"(",
"self",
"int",
"ind",
")",
"-",
">",
"PropertyGridPage",
"GetPage",
"(",
"self",
"String",
"name",
")",
"-",
">",
"PropertyGridPage"
] | def GetPage(*args):
"""
GetPage(self, int ind) -> PropertyGridPage
GetPage(self, String name) -> PropertyGridPage
"""
return _propgrid.PropertyGridManager_GetPage(*args) | [
"def",
"GetPage",
"(",
"*",
"args",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_GetPage",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L3482-L3487 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/third_party/Python/module/pexpect-4.6/pexpect/utils.py | python | select_ignore_interrupts | (iwtd, owtd, ewtd, timeout=None) | This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). | This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). | [
"This",
"is",
"a",
"wrapper",
"around",
"select",
".",
"select",
"()",
"that",
"ignores",
"signals",
".",
"If",
"select",
".",
"select",
"raises",
"a",
"select",
".",
"error",
"exception",
"and",
"errno",
"is",
"an",
"EINTR",
"error",
"then",
"it",
"is",
"ignored",
".",
"Mainly",
"this",
"is",
"used",
"to",
"ignore",
"sigwinch",
"(",
"terminal",
"resize",
")",
"."
] | def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None):
'''This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). '''
# if select() is interrupted by a signal (errno==EINTR) then
# we loop back and enter the select() again.
if timeout is not None:
end_time = time.time() + timeout
while True:
try:
return select.select(iwtd, owtd, ewtd, timeout)
except InterruptedError:
err = sys.exc_info()[1]
if err.args[0] == errno.EINTR:
# if we loop back we have to subtract the
# amount of time we already waited.
if timeout is not None:
timeout = end_time - time.time()
if timeout < 0:
return([], [], [])
else:
# something else caused the select.error, so
# this actually is an exception.
raise | [
"def",
"select_ignore_interrupts",
"(",
"iwtd",
",",
"owtd",
",",
"ewtd",
",",
"timeout",
"=",
"None",
")",
":",
"# if select() is interrupted by a signal (errno==EINTR) then",
"# we loop back and enter the select() again.",
"if",
"timeout",
"is",
"not",
"None",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"True",
":",
"try",
":",
"return",
"select",
".",
"select",
"(",
"iwtd",
",",
"owtd",
",",
"ewtd",
",",
"timeout",
")",
"except",
"InterruptedError",
":",
"err",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"err",
".",
"args",
"[",
"0",
"]",
"==",
"errno",
".",
"EINTR",
":",
"# if we loop back we have to subtract the",
"# amount of time we already waited.",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"end_time",
"-",
"time",
".",
"time",
"(",
")",
"if",
"timeout",
"<",
"0",
":",
"return",
"(",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
"else",
":",
"# something else caused the select.error, so",
"# this actually is an exception.",
"raise"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/third_party/Python/module/pexpect-4.6/pexpect/utils.py#L130-L156 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/frame.py | python | DataFrame.from_records | (cls, data, index=None, exclude=None, columns=None,
coerce_float=False, nrows=None) | return cls(mgr) | Convert structured or record ndarray to DataFrame.
Parameters
----------
data : ndarray (structured dtype), list of tuples, dict, or DataFrame
index : string, list of fields, array-like
Field of array to use as the index, alternately a specific set of
input labels to use
exclude : sequence, default None
Columns or fields to exclude
columns : sequence, default None
Column names to use. If the passed data do not have names
associated with them, this argument provides names for the
columns. Otherwise this argument indicates the order of the columns
in the result (any names not found in the data will become all-NA
columns)
coerce_float : boolean, default False
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
nrows : int, default None
Number of rows to read if data is an iterator
Returns
-------
df : DataFrame | Convert structured or record ndarray to DataFrame. | [
"Convert",
"structured",
"or",
"record",
"ndarray",
"to",
"DataFrame",
"."
] | def from_records(cls, data, index=None, exclude=None, columns=None,
coerce_float=False, nrows=None):
"""
Convert structured or record ndarray to DataFrame.
Parameters
----------
data : ndarray (structured dtype), list of tuples, dict, or DataFrame
index : string, list of fields, array-like
Field of array to use as the index, alternately a specific set of
input labels to use
exclude : sequence, default None
Columns or fields to exclude
columns : sequence, default None
Column names to use. If the passed data do not have names
associated with them, this argument provides names for the
columns. Otherwise this argument indicates the order of the columns
in the result (any names not found in the data will become all-NA
columns)
coerce_float : boolean, default False
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
nrows : int, default None
Number of rows to read if data is an iterator
Returns
-------
df : DataFrame
"""
# Make a copy of the input columns so we can modify it
if columns is not None:
columns = ensure_index(columns)
if is_iterator(data):
if nrows == 0:
return cls()
try:
first_row = next(data)
except StopIteration:
return cls(index=index, columns=columns)
dtype = None
if hasattr(first_row, 'dtype') and first_row.dtype.names:
dtype = first_row.dtype
values = [first_row]
if nrows is None:
values += data
else:
values.extend(itertools.islice(data, nrows - 1))
if dtype is not None:
data = np.array(values, dtype=dtype)
else:
data = values
if isinstance(data, dict):
if columns is None:
columns = arr_columns = ensure_index(sorted(data))
arrays = [data[k] for k in columns]
else:
arrays = []
arr_columns = []
for k, v in compat.iteritems(data):
if k in columns:
arr_columns.append(k)
arrays.append(v)
arrays, arr_columns = reorder_arrays(arrays, arr_columns,
columns)
elif isinstance(data, (np.ndarray, DataFrame)):
arrays, columns = to_arrays(data, columns)
if columns is not None:
columns = ensure_index(columns)
arr_columns = columns
else:
arrays, arr_columns = to_arrays(data, columns,
coerce_float=coerce_float)
arr_columns = ensure_index(arr_columns)
if columns is not None:
columns = ensure_index(columns)
else:
columns = arr_columns
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
result_index = None
if index is not None:
if (isinstance(index, compat.string_types) or
not hasattr(index, "__iter__")):
i = columns.get_loc(index)
exclude.add(index)
if len(arrays) > 0:
result_index = Index(arrays[i], name=index)
else:
result_index = Index([], name=index)
else:
try:
to_remove = [arr_columns.get_loc(field) for field in index]
index_data = [arrays[i] for i in to_remove]
result_index = ensure_index_from_sequences(index_data,
names=index)
exclude.update(index)
except Exception:
result_index = index
if any(exclude):
arr_exclude = [x for x in exclude if x in arr_columns]
to_remove = [arr_columns.get_loc(col) for col in arr_exclude]
arrays = [v for i, v in enumerate(arrays) if i not in to_remove]
arr_columns = arr_columns.drop(arr_exclude)
columns = columns.drop(exclude)
mgr = arrays_to_mgr(arrays, arr_columns, result_index, columns)
return cls(mgr) | [
"def",
"from_records",
"(",
"cls",
",",
"data",
",",
"index",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"coerce_float",
"=",
"False",
",",
"nrows",
"=",
"None",
")",
":",
"# Make a copy of the input columns so we can modify it",
"if",
"columns",
"is",
"not",
"None",
":",
"columns",
"=",
"ensure_index",
"(",
"columns",
")",
"if",
"is_iterator",
"(",
"data",
")",
":",
"if",
"nrows",
"==",
"0",
":",
"return",
"cls",
"(",
")",
"try",
":",
"first_row",
"=",
"next",
"(",
"data",
")",
"except",
"StopIteration",
":",
"return",
"cls",
"(",
"index",
"=",
"index",
",",
"columns",
"=",
"columns",
")",
"dtype",
"=",
"None",
"if",
"hasattr",
"(",
"first_row",
",",
"'dtype'",
")",
"and",
"first_row",
".",
"dtype",
".",
"names",
":",
"dtype",
"=",
"first_row",
".",
"dtype",
"values",
"=",
"[",
"first_row",
"]",
"if",
"nrows",
"is",
"None",
":",
"values",
"+=",
"data",
"else",
":",
"values",
".",
"extend",
"(",
"itertools",
".",
"islice",
"(",
"data",
",",
"nrows",
"-",
"1",
")",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"data",
"=",
"np",
".",
"array",
"(",
"values",
",",
"dtype",
"=",
"dtype",
")",
"else",
":",
"data",
"=",
"values",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"if",
"columns",
"is",
"None",
":",
"columns",
"=",
"arr_columns",
"=",
"ensure_index",
"(",
"sorted",
"(",
"data",
")",
")",
"arrays",
"=",
"[",
"data",
"[",
"k",
"]",
"for",
"k",
"in",
"columns",
"]",
"else",
":",
"arrays",
"=",
"[",
"]",
"arr_columns",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"compat",
".",
"iteritems",
"(",
"data",
")",
":",
"if",
"k",
"in",
"columns",
":",
"arr_columns",
".",
"append",
"(",
"k",
")",
"arrays",
".",
"append",
"(",
"v",
")",
"arrays",
",",
"arr_columns",
"=",
"reorder_arrays",
"(",
"arrays",
",",
"arr_columns",
",",
"columns",
")",
"elif",
"isinstance",
"(",
"data",
",",
"(",
"np",
".",
"ndarray",
",",
"DataFrame",
")",
")",
":",
"arrays",
",",
"columns",
"=",
"to_arrays",
"(",
"data",
",",
"columns",
")",
"if",
"columns",
"is",
"not",
"None",
":",
"columns",
"=",
"ensure_index",
"(",
"columns",
")",
"arr_columns",
"=",
"columns",
"else",
":",
"arrays",
",",
"arr_columns",
"=",
"to_arrays",
"(",
"data",
",",
"columns",
",",
"coerce_float",
"=",
"coerce_float",
")",
"arr_columns",
"=",
"ensure_index",
"(",
"arr_columns",
")",
"if",
"columns",
"is",
"not",
"None",
":",
"columns",
"=",
"ensure_index",
"(",
"columns",
")",
"else",
":",
"columns",
"=",
"arr_columns",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"set",
"(",
")",
"else",
":",
"exclude",
"=",
"set",
"(",
"exclude",
")",
"result_index",
"=",
"None",
"if",
"index",
"is",
"not",
"None",
":",
"if",
"(",
"isinstance",
"(",
"index",
",",
"compat",
".",
"string_types",
")",
"or",
"not",
"hasattr",
"(",
"index",
",",
"\"__iter__\"",
")",
")",
":",
"i",
"=",
"columns",
".",
"get_loc",
"(",
"index",
")",
"exclude",
".",
"add",
"(",
"index",
")",
"if",
"len",
"(",
"arrays",
")",
">",
"0",
":",
"result_index",
"=",
"Index",
"(",
"arrays",
"[",
"i",
"]",
",",
"name",
"=",
"index",
")",
"else",
":",
"result_index",
"=",
"Index",
"(",
"[",
"]",
",",
"name",
"=",
"index",
")",
"else",
":",
"try",
":",
"to_remove",
"=",
"[",
"arr_columns",
".",
"get_loc",
"(",
"field",
")",
"for",
"field",
"in",
"index",
"]",
"index_data",
"=",
"[",
"arrays",
"[",
"i",
"]",
"for",
"i",
"in",
"to_remove",
"]",
"result_index",
"=",
"ensure_index_from_sequences",
"(",
"index_data",
",",
"names",
"=",
"index",
")",
"exclude",
".",
"update",
"(",
"index",
")",
"except",
"Exception",
":",
"result_index",
"=",
"index",
"if",
"any",
"(",
"exclude",
")",
":",
"arr_exclude",
"=",
"[",
"x",
"for",
"x",
"in",
"exclude",
"if",
"x",
"in",
"arr_columns",
"]",
"to_remove",
"=",
"[",
"arr_columns",
".",
"get_loc",
"(",
"col",
")",
"for",
"col",
"in",
"arr_exclude",
"]",
"arrays",
"=",
"[",
"v",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"arrays",
")",
"if",
"i",
"not",
"in",
"to_remove",
"]",
"arr_columns",
"=",
"arr_columns",
".",
"drop",
"(",
"arr_exclude",
")",
"columns",
"=",
"columns",
".",
"drop",
"(",
"exclude",
")",
"mgr",
"=",
"arrays_to_mgr",
"(",
"arrays",
",",
"arr_columns",
",",
"result_index",
",",
"columns",
")",
"return",
"cls",
"(",
"mgr",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/frame.py#L1431-L1556 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchSchedule.py | python | ArchScheduleTaskPanel.accept | (self) | return True | Saves the changes and closes the dialog | Saves the changes and closes the dialog | [
"Saves",
"the",
"changes",
"and",
"closes",
"the",
"dialog"
] | def accept(self):
"""Saves the changes and closes the dialog"""
# store widths
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
p.SetInt("ScheduleColumnWidth0",self.form.list.columnWidth(0))
p.SetInt("ScheduleColumnWidth1",self.form.list.columnWidth(1))
p.SetInt("ScheduleColumnWidth2",self.form.list.columnWidth(2))
p.SetInt("ScheduleColumnWidth3",self.form.list.columnWidth(3))
p.SetInt("ScheduleDialogWidth",self.form.width())
p.SetInt("ScheduleDialogHeight",self.form.height())
# commit values
self.writeValues()
self.form.hide()
return True | [
"def",
"accept",
"(",
"self",
")",
":",
"# store widths",
"p",
"=",
"FreeCAD",
".",
"ParamGet",
"(",
"\"User parameter:BaseApp/Preferences/Mod/Arch\"",
")",
"p",
".",
"SetInt",
"(",
"\"ScheduleColumnWidth0\"",
",",
"self",
".",
"form",
".",
"list",
".",
"columnWidth",
"(",
"0",
")",
")",
"p",
".",
"SetInt",
"(",
"\"ScheduleColumnWidth1\"",
",",
"self",
".",
"form",
".",
"list",
".",
"columnWidth",
"(",
"1",
")",
")",
"p",
".",
"SetInt",
"(",
"\"ScheduleColumnWidth2\"",
",",
"self",
".",
"form",
".",
"list",
".",
"columnWidth",
"(",
"2",
")",
")",
"p",
".",
"SetInt",
"(",
"\"ScheduleColumnWidth3\"",
",",
"self",
".",
"form",
".",
"list",
".",
"columnWidth",
"(",
"3",
")",
")",
"p",
".",
"SetInt",
"(",
"\"ScheduleDialogWidth\"",
",",
"self",
".",
"form",
".",
"width",
"(",
")",
")",
"p",
".",
"SetInt",
"(",
"\"ScheduleDialogHeight\"",
",",
"self",
".",
"form",
".",
"height",
"(",
")",
")",
"# commit values",
"self",
".",
"writeValues",
"(",
")",
"self",
".",
"form",
".",
"hide",
"(",
")",
"return",
"True"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchSchedule.py#L630-L646 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/transforms/transform_bnn.py | python | TransformToBNN._get_conv_args | (self, conv_layer) | return conv_args | Get arguments from conv2d layer. | Get arguments from conv2d layer. | [
"Get",
"arguments",
"from",
"conv2d",
"layer",
"."
] | def _get_conv_args(self, conv_layer):
"""Get arguments from conv2d layer."""
conv_args = {"in_channels": conv_layer.in_channels, "out_channels": conv_layer.out_channels,
"pad_mode": conv_layer.pad_mode, "kernel_size": conv_layer.kernel_size,
"stride": conv_layer.stride, "has_bias": conv_layer.has_bias,
"padding": conv_layer.padding, "dilation": conv_layer.dilation,
"group": conv_layer.group}
return conv_args | [
"def",
"_get_conv_args",
"(",
"self",
",",
"conv_layer",
")",
":",
"conv_args",
"=",
"{",
"\"in_channels\"",
":",
"conv_layer",
".",
"in_channels",
",",
"\"out_channels\"",
":",
"conv_layer",
".",
"out_channels",
",",
"\"pad_mode\"",
":",
"conv_layer",
".",
"pad_mode",
",",
"\"kernel_size\"",
":",
"conv_layer",
".",
"kernel_size",
",",
"\"stride\"",
":",
"conv_layer",
".",
"stride",
",",
"\"has_bias\"",
":",
"conv_layer",
".",
"has_bias",
",",
"\"padding\"",
":",
"conv_layer",
".",
"padding",
",",
"\"dilation\"",
":",
"conv_layer",
".",
"dilation",
",",
"\"group\"",
":",
"conv_layer",
".",
"group",
"}",
"return",
"conv_args"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/transforms/transform_bnn.py#L210-L217 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/SaveReflections.py | python | SaveHKLFormat.__call__ | (self, file_name, workspace, _, scale) | Write a PeaksWorkspace to an ASCII file using this formatter.
:param file_name: the file name to output data to.
:param workspace: the PeaksWorkspace to write to file.
:param _: Ignored parameter for compatability with other savers | Write a PeaksWorkspace to an ASCII file using this formatter. | [
"Write",
"a",
"PeaksWorkspace",
"to",
"an",
"ASCII",
"file",
"using",
"this",
"formatter",
"."
] | def __call__(self, file_name, workspace, _, scale):
"""Write a PeaksWorkspace to an ASCII file using this formatter.
:param file_name: the file name to output data to.
:param workspace: the PeaksWorkspace to write to file.
:param _: Ignored parameter for compatability with other savers
"""
if has_modulated_indexing(workspace):
raise RuntimeError(
"Cannot currently save modulated structures to GSAS or SHELX formats")
from mantid.simpleapi import SaveHKL
SaveHKL(Filename=file_name, InputWorkspace=workspace, OutputWorkspace=workspace.name(), ScalePeaks=scale) | [
"def",
"__call__",
"(",
"self",
",",
"file_name",
",",
"workspace",
",",
"_",
",",
"scale",
")",
":",
"if",
"has_modulated_indexing",
"(",
"workspace",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot currently save modulated structures to GSAS or SHELX formats\"",
")",
"from",
"mantid",
".",
"simpleapi",
"import",
"SaveHKL",
"SaveHKL",
"(",
"Filename",
"=",
"file_name",
",",
"InputWorkspace",
"=",
"workspace",
",",
"OutputWorkspace",
"=",
"workspace",
".",
"name",
"(",
")",
",",
"ScalePeaks",
"=",
"scale",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/SaveReflections.py#L396-L408 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/errors_impl.py | python | FailedPreconditionError.__init__ | (self, node_def, op, message) | Creates a `FailedPreconditionError`. | Creates a `FailedPreconditionError`. | [
"Creates",
"a",
"FailedPreconditionError",
"."
] | def __init__(self, node_def, op, message):
"""Creates a `FailedPreconditionError`."""
super(FailedPreconditionError, self).__init__(node_def, op, message,
FAILED_PRECONDITION) | [
"def",
"__init__",
"(",
"self",
",",
"node_def",
",",
"op",
",",
"message",
")",
":",
"super",
"(",
"FailedPreconditionError",
",",
"self",
")",
".",
"__init__",
"(",
"node_def",
",",
"op",
",",
"message",
",",
"FAILED_PRECONDITION",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/errors_impl.py#L315-L318 | ||
google/ml-metadata | b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d | ml_metadata/metadata_store/types.py | python | Execution._get_from_protos | (cls, store: metadata_store.MetadataStore,
executions: typing.Sequence[metadata_store_pb2.Execution]
) | return [
Execution(x, new_types[x.type_id], input_structs.get(x.id),
output_structs.get(x.id)) for x in executions
] | Converts proto Executions to the executions of this kind. | Converts proto Executions to the executions of this kind. | [
"Converts",
"proto",
"Executions",
"to",
"the",
"executions",
"of",
"this",
"kind",
"."
] | def _get_from_protos(cls, store: metadata_store.MetadataStore,
executions: typing.Sequence[metadata_store_pb2.Execution]
) -> typing.List["Execution"]:
"""Converts proto Executions to the executions of this kind."""
execution_ids = [x.id for x in executions]
input_structs = _get_artifact_structs(
store, execution_ids, metadata_store_pb2.Event.DECLARED_INPUT)
output_structs = _get_artifact_structs(
store, execution_ids, metadata_store_pb2.Event.DECLARED_OUTPUT)
unique_type_ids = _unique_elements([x.type_id for x in executions])
new_types = {
x.id: x for x in ExecutionType.find_by_ids(store, unique_type_ids)
}
return [
Execution(x, new_types[x.type_id], input_structs.get(x.id),
output_structs.get(x.id)) for x in executions
] | [
"def",
"_get_from_protos",
"(",
"cls",
",",
"store",
":",
"metadata_store",
".",
"MetadataStore",
",",
"executions",
":",
"typing",
".",
"Sequence",
"[",
"metadata_store_pb2",
".",
"Execution",
"]",
")",
"->",
"typing",
".",
"List",
"[",
"\"Execution\"",
"]",
":",
"execution_ids",
"=",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"executions",
"]",
"input_structs",
"=",
"_get_artifact_structs",
"(",
"store",
",",
"execution_ids",
",",
"metadata_store_pb2",
".",
"Event",
".",
"DECLARED_INPUT",
")",
"output_structs",
"=",
"_get_artifact_structs",
"(",
"store",
",",
"execution_ids",
",",
"metadata_store_pb2",
".",
"Event",
".",
"DECLARED_OUTPUT",
")",
"unique_type_ids",
"=",
"_unique_elements",
"(",
"[",
"x",
".",
"type_id",
"for",
"x",
"in",
"executions",
"]",
")",
"new_types",
"=",
"{",
"x",
".",
"id",
":",
"x",
"for",
"x",
"in",
"ExecutionType",
".",
"find_by_ids",
"(",
"store",
",",
"unique_type_ids",
")",
"}",
"return",
"[",
"Execution",
"(",
"x",
",",
"new_types",
"[",
"x",
".",
"type_id",
"]",
",",
"input_structs",
".",
"get",
"(",
"x",
".",
"id",
")",
",",
"output_structs",
".",
"get",
"(",
"x",
".",
"id",
")",
")",
"for",
"x",
"in",
"executions",
"]"
] | https://github.com/google/ml-metadata/blob/b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d/ml_metadata/metadata_store/types.py#L1102-L1120 | |
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/tools/scan-build-py/libscanbuild/compilation.py | python | classify_source | (filename, c_compiler=True) | return mapping.get(extension) | Return the language from file name extension. | Return the language from file name extension. | [
"Return",
"the",
"language",
"from",
"file",
"name",
"extension",
"."
] | def classify_source(filename, c_compiler=True):
""" Return the language from file name extension. """
mapping = {
'.c': 'c' if c_compiler else 'c++',
'.i': 'c-cpp-output' if c_compiler else 'c++-cpp-output',
'.ii': 'c++-cpp-output',
'.m': 'objective-c',
'.mi': 'objective-c-cpp-output',
'.mm': 'objective-c++',
'.mii': 'objective-c++-cpp-output',
'.C': 'c++',
'.cc': 'c++',
'.CC': 'c++',
'.cp': 'c++',
'.cpp': 'c++',
'.cxx': 'c++',
'.c++': 'c++',
'.C++': 'c++',
'.txx': 'c++'
}
__, extension = os.path.splitext(os.path.basename(filename))
return mapping.get(extension) | [
"def",
"classify_source",
"(",
"filename",
",",
"c_compiler",
"=",
"True",
")",
":",
"mapping",
"=",
"{",
"'.c'",
":",
"'c'",
"if",
"c_compiler",
"else",
"'c++'",
",",
"'.i'",
":",
"'c-cpp-output'",
"if",
"c_compiler",
"else",
"'c++-cpp-output'",
",",
"'.ii'",
":",
"'c++-cpp-output'",
",",
"'.m'",
":",
"'objective-c'",
",",
"'.mi'",
":",
"'objective-c-cpp-output'",
",",
"'.mm'",
":",
"'objective-c++'",
",",
"'.mii'",
":",
"'objective-c++-cpp-output'",
",",
"'.C'",
":",
"'c++'",
",",
"'.cc'",
":",
"'c++'",
",",
"'.CC'",
":",
"'c++'",
",",
"'.cp'",
":",
"'c++'",
",",
"'.cpp'",
":",
"'c++'",
",",
"'.cxx'",
":",
"'c++'",
",",
"'.c++'",
":",
"'c++'",
",",
"'.C++'",
":",
"'c++'",
",",
"'.txx'",
":",
"'c++'",
"}",
"__",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
")",
"return",
"mapping",
".",
"get",
"(",
"extension",
")"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/tools/scan-build-py/libscanbuild/compilation.py#L103-L126 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/cpu/gather_d.py | python | _gather_cpu | () | return | GatherD cpu register | GatherD cpu register | [
"GatherD",
"cpu",
"register"
] | def _gather_cpu():
"""GatherD cpu register"""
return | [
"def",
"_gather_cpu",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/cpu/gather_d.py#L47-L49 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_NULL_SIG_SCHEME.GetUnionSelector | (self) | return TPM_ALG_ID.NULL | TpmUnion method | TpmUnion method | [
"TpmUnion",
"method"
] | def GetUnionSelector(self): # TPM_ALG_ID
""" TpmUnion method """
return TPM_ALG_ID.NULL | [
"def",
"GetUnionSelector",
"(",
"self",
")",
":",
"# TPM_ALG_ID",
"return",
"TPM_ALG_ID",
".",
"NULL"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6593-L6595 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/nn/functional/common.py | python | dropout2d | (x, p=0.5, training=True, data_format='NCHW', name=None) | return dropout(
x,
p=p,
axis=[0, 1] if data_format == 'NCHW' else [0, 3],
training=training,
mode="upscale_in_train",
name=name) | Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` ,
a channel is a 2D feature map with the shape `HW` ). Each channel will be zeroed out independently
on every forward call with probability `p` using samples from a Bernoulli distribution.
See ``paddle.nn.functional.dropout`` for more details.
Args:
x (Tensor): The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C].
The data type is float32 or float64.
p (float): Probability of setting units to zero. Default 0.5.
training (bool): A flag indicating whether it is in train phrase or not. Default True.
data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCHW` or `NHWC` . The default is `NCHW` . When it is `NCHW` , the data is stored in the order of: [batch_size, input_channels, input_height, input_width].
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
A Tensor representing the dropout2d, has same shape and data type as `x` .
Examples:
.. code-block:: python
import paddle
import numpy as np
x = np.random.random(size=(2, 3, 4, 5)).astype('float32')
x = paddle.to_tensor(x)
y_train = paddle.nn.functional.dropout2d(x) #train
y_test = paddle.nn.functional.dropout2d(x, training=False) #test
for i in range(2):
for j in range(3):
print(x.numpy()[i,j,:,:])
print(y_train.numpy()[i,j,:,:]) # may all 0
print(y_test.numpy()[i,j,:,:]) | Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` ,
a channel is a 2D feature map with the shape `HW` ). Each channel will be zeroed out independently
on every forward call with probability `p` using samples from a Bernoulli distribution. | [
"Randomly",
"zero",
"out",
"entire",
"channels",
"(",
"in",
"the",
"batched",
"input",
"4d",
"tensor",
"with",
"the",
"shape",
"NCHW",
"a",
"channel",
"is",
"a",
"2D",
"feature",
"map",
"with",
"the",
"shape",
"HW",
")",
".",
"Each",
"channel",
"will",
"be",
"zeroed",
"out",
"independently",
"on",
"every",
"forward",
"call",
"with",
"probability",
"p",
"using",
"samples",
"from",
"a",
"Bernoulli",
"distribution",
"."
] | def dropout2d(x, p=0.5, training=True, data_format='NCHW', name=None):
"""
Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` ,
a channel is a 2D feature map with the shape `HW` ). Each channel will be zeroed out independently
on every forward call with probability `p` using samples from a Bernoulli distribution.
See ``paddle.nn.functional.dropout`` for more details.
Args:
x (Tensor): The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C].
The data type is float32 or float64.
p (float): Probability of setting units to zero. Default 0.5.
training (bool): A flag indicating whether it is in train phrase or not. Default True.
data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCHW` or `NHWC` . The default is `NCHW` . When it is `NCHW` , the data is stored in the order of: [batch_size, input_channels, input_height, input_width].
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
A Tensor representing the dropout2d, has same shape and data type as `x` .
Examples:
.. code-block:: python
import paddle
import numpy as np
x = np.random.random(size=(2, 3, 4, 5)).astype('float32')
x = paddle.to_tensor(x)
y_train = paddle.nn.functional.dropout2d(x) #train
y_test = paddle.nn.functional.dropout2d(x, training=False) #test
for i in range(2):
for j in range(3):
print(x.numpy()[i,j,:,:])
print(y_train.numpy()[i,j,:,:]) # may all 0
print(y_test.numpy()[i,j,:,:])
"""
input_shape = x.shape
if len(input_shape) != 4:
raise ValueError("dimensions of x should be 4, but received {} != 4"\
.format(len(input_shape)))
if data_format not in ["NCHW", "NHWC"]:
raise ValueError(
"Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
"Attr(data_format): %s." % str(data_format))
return dropout(
x,
p=p,
axis=[0, 1] if data_format == 'NCHW' else [0, 3],
training=training,
mode="upscale_in_train",
name=name) | [
"def",
"dropout2d",
"(",
"x",
",",
"p",
"=",
"0.5",
",",
"training",
"=",
"True",
",",
"data_format",
"=",
"'NCHW'",
",",
"name",
"=",
"None",
")",
":",
"input_shape",
"=",
"x",
".",
"shape",
"if",
"len",
"(",
"input_shape",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"dimensions of x should be 4, but received {} != 4\"",
".",
"format",
"(",
"len",
"(",
"input_shape",
")",
")",
")",
"if",
"data_format",
"not",
"in",
"[",
"\"NCHW\"",
",",
"\"NHWC\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Attr(data_format) should be 'NCHW' or 'NHWC'. Received \"",
"\"Attr(data_format): %s.\"",
"%",
"str",
"(",
"data_format",
")",
")",
"return",
"dropout",
"(",
"x",
",",
"p",
"=",
"p",
",",
"axis",
"=",
"[",
"0",
",",
"1",
"]",
"if",
"data_format",
"==",
"'NCHW'",
"else",
"[",
"0",
",",
"3",
"]",
",",
"training",
"=",
"training",
",",
"mode",
"=",
"\"upscale_in_train\"",
",",
"name",
"=",
"name",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/functional/common.py#L980-L1032 | |
baidu/lac | 3e10dbed9bfd87bea927c84a6627a167c17b5617 | python/LAC/cmdline.py | python | main | (args=args) | return 0 | 主程序入口 | 主程序入口 | [
"主程序入口"
] | def main(args=args):
"""主程序入口"""
from LAC import LAC
from LAC._compat import strdecode
import sys
if args.segonly:
lac = LAC(mode='seg')
elif args.rank:
lac = LAC(mode='rank')
else:
lac = LAC()
while True:
line = sys.stdin.readline()
if not line:
break
line = strdecode(line.strip())
if args.segonly:
print(u" ".join(lac.run(line)))
elif args.rank:
words, tags, words_rank = lac.run(line)
print(u" ".join(u"%s/%s" % (word, rank)
for word, tag, rank in zip(words, tags, words_rank)))
else :
words, tags = lac.run(line)
print(u" ".join(u"%s/%s" % (word, tag)
for word, tag in zip(words, tags)))
return 0 | [
"def",
"main",
"(",
"args",
"=",
"args",
")",
":",
"from",
"LAC",
"import",
"LAC",
"from",
"LAC",
".",
"_compat",
"import",
"strdecode",
"import",
"sys",
"if",
"args",
".",
"segonly",
":",
"lac",
"=",
"LAC",
"(",
"mode",
"=",
"'seg'",
")",
"elif",
"args",
".",
"rank",
":",
"lac",
"=",
"LAC",
"(",
"mode",
"=",
"'rank'",
")",
"else",
":",
"lac",
"=",
"LAC",
"(",
")",
"while",
"True",
":",
"line",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"line",
"=",
"strdecode",
"(",
"line",
".",
"strip",
"(",
")",
")",
"if",
"args",
".",
"segonly",
":",
"print",
"(",
"u\" \"",
".",
"join",
"(",
"lac",
".",
"run",
"(",
"line",
")",
")",
")",
"elif",
"args",
".",
"rank",
":",
"words",
",",
"tags",
",",
"words_rank",
"=",
"lac",
".",
"run",
"(",
"line",
")",
"print",
"(",
"u\" \"",
".",
"join",
"(",
"u\"%s/%s\"",
"%",
"(",
"word",
",",
"rank",
")",
"for",
"word",
",",
"tag",
",",
"rank",
"in",
"zip",
"(",
"words",
",",
"tags",
",",
"words_rank",
")",
")",
")",
"else",
":",
"words",
",",
"tags",
"=",
"lac",
".",
"run",
"(",
"line",
")",
"print",
"(",
"u\" \"",
".",
"join",
"(",
"u\"%s/%s\"",
"%",
"(",
"word",
",",
"tag",
")",
"for",
"word",
",",
"tag",
"in",
"zip",
"(",
"words",
",",
"tags",
")",
")",
")",
"return",
"0"
] | https://github.com/baidu/lac/blob/3e10dbed9bfd87bea927c84a6627a167c17b5617/python/LAC/cmdline.py#L40-L71 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/saved_model/builder_impl.py | python | SavedModelBuilder._tag_and_add_meta_graph | (self, meta_graph_def, tags, signature_def_map) | Tags the meta graph def and adds it to the SavedModel.
Tags the meta graph def with the supplied tags, adds signature defs to it if
provided and appends the meta graph def to the SavedModel proto.
Args:
meta_graph_def: The meta graph def to add to the SavedModel.
tags: The set of tags to annotate the meta graph def with.
signature_def_map: The map of signature defs to be added to the meta graph
def. | Tags the meta graph def and adds it to the SavedModel. | [
"Tags",
"the",
"meta",
"graph",
"def",
"and",
"adds",
"it",
"to",
"the",
"SavedModel",
"."
] | def _tag_and_add_meta_graph(self, meta_graph_def, tags, signature_def_map):
"""Tags the meta graph def and adds it to the SavedModel.
Tags the meta graph def with the supplied tags, adds signature defs to it if
provided and appends the meta graph def to the SavedModel proto.
Args:
meta_graph_def: The meta graph def to add to the SavedModel.
tags: The set of tags to annotate the meta graph def with.
signature_def_map: The map of signature defs to be added to the meta graph
def.
"""
for tag in tags:
meta_graph_def.meta_info_def.tags.append(tag)
if signature_def_map is not None:
for key in signature_def_map:
meta_graph_def.signature_def[key].CopyFrom(signature_def_map[key])
proto_meta_graph_def = self._saved_model.meta_graphs.add()
proto_meta_graph_def.CopyFrom(meta_graph_def) | [
"def",
"_tag_and_add_meta_graph",
"(",
"self",
",",
"meta_graph_def",
",",
"tags",
",",
"signature_def_map",
")",
":",
"for",
"tag",
"in",
"tags",
":",
"meta_graph_def",
".",
"meta_info_def",
".",
"tags",
".",
"append",
"(",
"tag",
")",
"if",
"signature_def_map",
"is",
"not",
"None",
":",
"for",
"key",
"in",
"signature_def_map",
":",
"meta_graph_def",
".",
"signature_def",
"[",
"key",
"]",
".",
"CopyFrom",
"(",
"signature_def_map",
"[",
"key",
"]",
")",
"proto_meta_graph_def",
"=",
"self",
".",
"_saved_model",
".",
"meta_graphs",
".",
"add",
"(",
")",
"proto_meta_graph_def",
".",
"CopyFrom",
"(",
"meta_graph_def",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/saved_model/builder_impl.py#L169-L189 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/platform/profiler/monsoon.py | python | Monsoon._ReadPacket | (self) | return result[:-1] | Read a single data record as a string (without length or checksum). | Read a single data record as a string (without length or checksum). | [
"Read",
"a",
"single",
"data",
"record",
"as",
"a",
"string",
"(",
"without",
"length",
"or",
"checksum",
")",
"."
] | def _ReadPacket(self):
"""Read a single data record as a string (without length or checksum)."""
len_char = self.ser.read(1)
if not len_char:
logging.error('timeout reading from serial port')
return None
data_len = struct.unpack('B', len_char)
data_len = ord(len_char)
if not data_len:
return ''
result = self.ser.read(data_len)
if len(result) != data_len:
return None
body = result[:-1]
checksum = (data_len + sum(struct.unpack('B' * len(body), body))) % 256
if result[-1] != struct.pack('B', checksum):
logging.error('invalid checksum from serial port')
return None
return result[:-1] | [
"def",
"_ReadPacket",
"(",
"self",
")",
":",
"len_char",
"=",
"self",
".",
"ser",
".",
"read",
"(",
"1",
")",
"if",
"not",
"len_char",
":",
"logging",
".",
"error",
"(",
"'timeout reading from serial port'",
")",
"return",
"None",
"data_len",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"len_char",
")",
"data_len",
"=",
"ord",
"(",
"len_char",
")",
"if",
"not",
"data_len",
":",
"return",
"''",
"result",
"=",
"self",
".",
"ser",
".",
"read",
"(",
"data_len",
")",
"if",
"len",
"(",
"result",
")",
"!=",
"data_len",
":",
"return",
"None",
"body",
"=",
"result",
"[",
":",
"-",
"1",
"]",
"checksum",
"=",
"(",
"data_len",
"+",
"sum",
"(",
"struct",
".",
"unpack",
"(",
"'B'",
"*",
"len",
"(",
"body",
")",
",",
"body",
")",
")",
")",
"%",
"256",
"if",
"result",
"[",
"-",
"1",
"]",
"!=",
"struct",
".",
"pack",
"(",
"'B'",
",",
"checksum",
")",
":",
"logging",
".",
"error",
"(",
"'invalid checksum from serial port'",
")",
"return",
"None",
"return",
"result",
"[",
":",
"-",
"1",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/platform/profiler/monsoon.py#L254-L274 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/utils/estimator_checks.py | python | check_clusterer_compute_labels_predict | (name, Clusterer) | Check that predict is invariant of compute_labels | Check that predict is invariant of compute_labels | [
"Check",
"that",
"predict",
"is",
"invariant",
"of",
"compute_labels"
] | def check_clusterer_compute_labels_predict(name, Clusterer):
"""Check that predict is invariant of compute_labels"""
X, y = make_blobs(n_samples=20, random_state=0)
clusterer = Clusterer()
if hasattr(clusterer, "compute_labels"):
# MiniBatchKMeans
if hasattr(clusterer, "random_state"):
clusterer.set_params(random_state=0)
X_pred1 = clusterer.fit(X).predict(X)
clusterer.set_params(compute_labels=False)
X_pred2 = clusterer.fit(X).predict(X)
assert_array_equal(X_pred1, X_pred2) | [
"def",
"check_clusterer_compute_labels_predict",
"(",
"name",
",",
"Clusterer",
")",
":",
"X",
",",
"y",
"=",
"make_blobs",
"(",
"n_samples",
"=",
"20",
",",
"random_state",
"=",
"0",
")",
"clusterer",
"=",
"Clusterer",
"(",
")",
"if",
"hasattr",
"(",
"clusterer",
",",
"\"compute_labels\"",
")",
":",
"# MiniBatchKMeans",
"if",
"hasattr",
"(",
"clusterer",
",",
"\"random_state\"",
")",
":",
"clusterer",
".",
"set_params",
"(",
"random_state",
"=",
"0",
")",
"X_pred1",
"=",
"clusterer",
".",
"fit",
"(",
"X",
")",
".",
"predict",
"(",
"X",
")",
"clusterer",
".",
"set_params",
"(",
"compute_labels",
"=",
"False",
")",
"X_pred2",
"=",
"clusterer",
".",
"fit",
"(",
"X",
")",
".",
"predict",
"(",
"X",
")",
"assert_array_equal",
"(",
"X_pred1",
",",
"X_pred2",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/estimator_checks.py#L958-L971 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py | python | Standard_Suite_Events.data_size | (self, _object, _attributes={}, **_arguments) | data size: (optional) Return the size in bytes of an object
Required argument: the object whose data size is to be returned
Keyword argument as: the data type for which the size is calculated
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the size of the object in bytes | data size: (optional) Return the size in bytes of an object
Required argument: the object whose data size is to be returned
Keyword argument as: the data type for which the size is calculated
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the size of the object in bytes | [
"data",
"size",
":",
"(",
"optional",
")",
"Return",
"the",
"size",
"in",
"bytes",
"of",
"an",
"object",
"Required",
"argument",
":",
"the",
"object",
"whose",
"data",
"size",
"is",
"to",
"be",
"returned",
"Keyword",
"argument",
"as",
":",
"the",
"data",
"type",
"for",
"which",
"the",
"size",
"is",
"calculated",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary",
"Returns",
":",
"the",
"size",
"of",
"the",
"object",
"in",
"bytes"
] | def data_size(self, _object, _attributes={}, **_arguments):
"""data size: (optional) Return the size in bytes of an object
Required argument: the object whose data size is to be returned
Keyword argument as: the data type for which the size is calculated
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the size of the object in bytes
"""
_code = 'core'
_subcode = 'dsiz'
aetools.keysubst(_arguments, self._argmap_data_size)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"data_size",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'core'",
"_subcode",
"=",
"'dsiz'",
"aetools",
".",
"keysubst",
"(",
"_arguments",
",",
"self",
".",
"_argmap_data_size",
")",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py#L100-L120 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/zone.py | python | Zone.add_record | (self, resource_type, name, value, ttl=60, identifier=None,
comment="") | return Status(self.route53connection, self._commit(changes)) | Add a new record to this Zone. See _new_record for parameter
documentation. Returns a Status object. | Add a new record to this Zone. See _new_record for parameter
documentation. Returns a Status object. | [
"Add",
"a",
"new",
"record",
"to",
"this",
"Zone",
".",
"See",
"_new_record",
"for",
"parameter",
"documentation",
".",
"Returns",
"a",
"Status",
"object",
"."
] | def add_record(self, resource_type, name, value, ttl=60, identifier=None,
comment=""):
"""
Add a new record to this Zone. See _new_record for parameter
documentation. Returns a Status object.
"""
changes = ResourceRecordSets(self.route53connection, self.id, comment)
self._new_record(changes, resource_type, name, value, ttl, identifier,
comment)
return Status(self.route53connection, self._commit(changes)) | [
"def",
"add_record",
"(",
"self",
",",
"resource_type",
",",
"name",
",",
"value",
",",
"ttl",
"=",
"60",
",",
"identifier",
"=",
"None",
",",
"comment",
"=",
"\"\"",
")",
":",
"changes",
"=",
"ResourceRecordSets",
"(",
"self",
".",
"route53connection",
",",
"self",
".",
"id",
",",
"comment",
")",
"self",
".",
"_new_record",
"(",
"changes",
",",
"resource_type",
",",
"name",
",",
"value",
",",
"ttl",
",",
"identifier",
",",
"comment",
")",
"return",
"Status",
"(",
"self",
".",
"route53connection",
",",
"self",
".",
"_commit",
"(",
"changes",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/zone.py#L111-L120 | |
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | utils/pylit/pylit.py | python | Code2Text.code_block_handler | (self, lines) | Covert code blocks to text format (indent or strip) | Covert code blocks to text format (indent or strip) | [
"Covert",
"code",
"blocks",
"to",
"text",
"format",
"(",
"indent",
"or",
"strip",
")"
] | def code_block_handler(self, lines):
"""Covert code blocks to text format (indent or strip)
"""
if self.strip == True:
return
# eventually insert transition marker
if self._add_code_block_marker:
self.state = "documentation"
yield self.code_block_marker + "\n"
yield "\n"
self._add_code_block_marker = False
self.state = "code_block"
for line in lines:
yield " "*self.codeindent + line | [
"def",
"code_block_handler",
"(",
"self",
",",
"lines",
")",
":",
"if",
"self",
".",
"strip",
"==",
"True",
":",
"return",
"# eventually insert transition marker",
"if",
"self",
".",
"_add_code_block_marker",
":",
"self",
".",
"state",
"=",
"\"documentation\"",
"yield",
"self",
".",
"code_block_marker",
"+",
"\"\\n\"",
"yield",
"\"\\n\"",
"self",
".",
"_add_code_block_marker",
"=",
"False",
"self",
".",
"state",
"=",
"\"code_block\"",
"for",
"line",
"in",
"lines",
":",
"yield",
"\" \"",
"*",
"self",
".",
"codeindent",
"+",
"line"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/utils/pylit/pylit.py#L984-L997 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/util.py | python | setenv | (name, value) | Set an environment variable in the C Runtime.
Parameters
----------
name : string type
The environment variable name
value : string type
The desired value to set the environment value to | Set an environment variable in the C Runtime. | [
"Set",
"an",
"environment",
"variable",
"in",
"the",
"C",
"Runtime",
"."
] | def setenv(name, value):
"""Set an environment variable in the C Runtime.
Parameters
----------
name : string type
The environment variable name
value : string type
The desired value to set the environment value to
"""
passed_value = None if value is None else c_str(value)
check_call(_LIB.MXSetEnv(c_str(name), passed_value)) | [
"def",
"setenv",
"(",
"name",
",",
"value",
")",
":",
"passed_value",
"=",
"None",
"if",
"value",
"is",
"None",
"else",
"c_str",
"(",
"value",
")",
"check_call",
"(",
"_LIB",
".",
"MXSetEnv",
"(",
"c_str",
"(",
"name",
")",
",",
"passed_value",
")",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/util.py#L1274-L1285 | ||
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | interfaces/cython/cantera/liquidvapor.py | python | Hydrogen | () | return PureFluid('liquidvapor.yaml', 'hydrogen') | Create a `PureFluid` object using the equation of state for hydrogen.
The object returned by this method implements an accurate equation of
state for hydrogen that can be used in the liquid, vapor, saturated
liquid/vapor, and supercritical regions of the phase diagram. The
equation of state is taken from
W. C. Reynolds, *Thermodynamic Properties in SI: graphs, tables, and
computational equations for forty substances* Stanford: Stanford
University, 1979. Print.
For more details, see classes :ct:PureFluid and tpx::hydrogen in the
Cantera C++ source code documentation. | Create a `PureFluid` object using the equation of state for hydrogen. | [
"Create",
"a",
"PureFluid",
"object",
"using",
"the",
"equation",
"of",
"state",
"for",
"hydrogen",
"."
] | def Hydrogen():
"""
Create a `PureFluid` object using the equation of state for hydrogen.
The object returned by this method implements an accurate equation of
state for hydrogen that can be used in the liquid, vapor, saturated
liquid/vapor, and supercritical regions of the phase diagram. The
equation of state is taken from
W. C. Reynolds, *Thermodynamic Properties in SI: graphs, tables, and
computational equations for forty substances* Stanford: Stanford
University, 1979. Print.
For more details, see classes :ct:PureFluid and tpx::hydrogen in the
Cantera C++ source code documentation.
"""
return PureFluid('liquidvapor.yaml', 'hydrogen') | [
"def",
"Hydrogen",
"(",
")",
":",
"return",
"PureFluid",
"(",
"'liquidvapor.yaml'",
",",
"'hydrogen'",
")"
] | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/liquidvapor.py#L95-L111 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/elementwise/log1p.py | python | log1p._grad | (self, values) | Gives the (sub/super)gradient of the atom w.r.t. each argument.
Matrix expressions are vectorized, so the gradient is a matrix.
Args:
values: A list of numeric values for the arguments.
Returns:
A list of SciPy CSC sparse matrices or None. | Gives the (sub/super)gradient of the atom w.r.t. each argument. | [
"Gives",
"the",
"(",
"sub",
"/",
"super",
")",
"gradient",
"of",
"the",
"atom",
"w",
".",
"r",
".",
"t",
".",
"each",
"argument",
"."
] | def _grad(self, values):
"""Gives the (sub/super)gradient of the atom w.r.t. each argument.
Matrix expressions are vectorized, so the gradient is a matrix.
Args:
values: A list of numeric values for the arguments.
Returns:
A list of SciPy CSC sparse matrices or None.
"""
rows = self.args[0].size
cols = self.size
# Outside domain or on boundary.
if np.min(values[0]) <= -1:
# Non-differentiable.
return [None]
else:
grad_vals = 1.0/(values[0]+1)
return [log1p.elemwise_grad_to_diag(grad_vals, rows, cols)] | [
"def",
"_grad",
"(",
"self",
",",
"values",
")",
":",
"rows",
"=",
"self",
".",
"args",
"[",
"0",
"]",
".",
"size",
"cols",
"=",
"self",
".",
"size",
"# Outside domain or on boundary.",
"if",
"np",
".",
"min",
"(",
"values",
"[",
"0",
"]",
")",
"<=",
"-",
"1",
":",
"# Non-differentiable.",
"return",
"[",
"None",
"]",
"else",
":",
"grad_vals",
"=",
"1.0",
"/",
"(",
"values",
"[",
"0",
"]",
"+",
"1",
")",
"return",
"[",
"log1p",
".",
"elemwise_grad_to_diag",
"(",
"grad_vals",
",",
"rows",
",",
"cols",
")",
"]"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/log1p.py#L43-L62 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | GenericProgressDialog.GetValue | (*args, **kwargs) | return _windows_.GenericProgressDialog_GetValue(*args, **kwargs) | GetValue(self) -> int | GetValue(self) -> int | [
"GetValue",
"(",
"self",
")",
"-",
">",
"int"
] | def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _windows_.GenericProgressDialog_GetValue(*args, **kwargs) | [
"def",
"GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"GenericProgressDialog_GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L3734-L3736 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/roslisp/rosbuild/scripts/genmsg_lisp.py | python | generate_srv | (srv_path) | Generate code from .srv file | Generate code from .srv file | [
"Generate",
"code",
"from",
".",
"srv",
"file"
] | def generate_srv(srv_path):
"Generate code from .srv file"
(pkg_dir, pkg) = roslib.packages.get_dir_pkg(srv_path)
(_, spec) = roslib.srvs.load_from_file(srv_path, pkg)
output_dir = '%s/srv_gen/lisp'%pkg_dir
if (not os.path.exists(output_dir)):
# if we're being run concurrently, the above test can report false but os.makedirs can still fail if
# another copy just created the directory
try:
os.makedirs(output_dir)
except OSError as e:
pass
########################################
# 1. Write the .lisp file
########################################
io = StringIO()
s = IndentedWriter(io)
write_begin(s, spec, srv_path, True)
spec.request.actual_name='%s-request'%spec.short_name
spec.response.actual_name='%s-response'%spec.short_name
write_srv_component(s, spec.request, spec)
s.newline()
write_srv_component(s, spec.response, spec)
write_service_specific_methods(s, spec)
with open('%s/%s.lisp'%(output_dir, spec.short_name), 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 2. Write the _package file
# for this service
########################################
io = StringIO()
s = IndentedWriter(io)
write_accessor_exports(s, spec)
with open('%s/_package_%s.lisp'%(output_dir, spec.short_name), 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 3. Write the _package.lisp file
########################################
io = StringIO()
s = IndentedWriter(io)
write_srv_exports(s, pkg)
with open('%s/_package.lisp'%output_dir, 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 4. Write the .asd file
########################################
io = StringIO()
s = IndentedWriter(io)
write_srv_asd(s, pkg)
with open('%s/%s-srv.asd'%(output_dir, pkg), 'w') as f:
f.write(io.getvalue())
io.close() | [
"def",
"generate_srv",
"(",
"srv_path",
")",
":",
"(",
"pkg_dir",
",",
"pkg",
")",
"=",
"roslib",
".",
"packages",
".",
"get_dir_pkg",
"(",
"srv_path",
")",
"(",
"_",
",",
"spec",
")",
"=",
"roslib",
".",
"srvs",
".",
"load_from_file",
"(",
"srv_path",
",",
"pkg",
")",
"output_dir",
"=",
"'%s/srv_gen/lisp'",
"%",
"pkg_dir",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_dir",
")",
")",
":",
"# if we're being run concurrently, the above test can report false but os.makedirs can still fail if",
"# another copy just created the directory",
"try",
":",
"os",
".",
"makedirs",
"(",
"output_dir",
")",
"except",
"OSError",
"as",
"e",
":",
"pass",
"########################################",
"# 1. Write the .lisp file",
"########################################",
"io",
"=",
"StringIO",
"(",
")",
"s",
"=",
"IndentedWriter",
"(",
"io",
")",
"write_begin",
"(",
"s",
",",
"spec",
",",
"srv_path",
",",
"True",
")",
"spec",
".",
"request",
".",
"actual_name",
"=",
"'%s-request'",
"%",
"spec",
".",
"short_name",
"spec",
".",
"response",
".",
"actual_name",
"=",
"'%s-response'",
"%",
"spec",
".",
"short_name",
"write_srv_component",
"(",
"s",
",",
"spec",
".",
"request",
",",
"spec",
")",
"s",
".",
"newline",
"(",
")",
"write_srv_component",
"(",
"s",
",",
"spec",
".",
"response",
",",
"spec",
")",
"write_service_specific_methods",
"(",
"s",
",",
"spec",
")",
"with",
"open",
"(",
"'%s/%s.lisp'",
"%",
"(",
"output_dir",
",",
"spec",
".",
"short_name",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"io",
".",
"getvalue",
"(",
")",
")",
"io",
".",
"close",
"(",
")",
"########################################",
"# 2. Write the _package file",
"# for this service",
"########################################",
"io",
"=",
"StringIO",
"(",
")",
"s",
"=",
"IndentedWriter",
"(",
"io",
")",
"write_accessor_exports",
"(",
"s",
",",
"spec",
")",
"with",
"open",
"(",
"'%s/_package_%s.lisp'",
"%",
"(",
"output_dir",
",",
"spec",
".",
"short_name",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"io",
".",
"getvalue",
"(",
")",
")",
"io",
".",
"close",
"(",
")",
"########################################",
"# 3. Write the _package.lisp file",
"########################################",
"io",
"=",
"StringIO",
"(",
")",
"s",
"=",
"IndentedWriter",
"(",
"io",
")",
"write_srv_exports",
"(",
"s",
",",
"pkg",
")",
"with",
"open",
"(",
"'%s/_package.lisp'",
"%",
"output_dir",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"io",
".",
"getvalue",
"(",
")",
")",
"io",
".",
"close",
"(",
")",
"########################################",
"# 4. Write the .asd file",
"########################################",
"io",
"=",
"StringIO",
"(",
")",
"s",
"=",
"IndentedWriter",
"(",
"io",
")",
"write_srv_asd",
"(",
"s",
",",
"pkg",
")",
"with",
"open",
"(",
"'%s/%s-srv.asd'",
"%",
"(",
"output_dir",
",",
"pkg",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"io",
".",
"getvalue",
"(",
")",
")",
"io",
".",
"close",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/roslisp/rosbuild/scripts/genmsg_lisp.py#L800-L863 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | Locale.GetSystemEncodingName | (*args, **kwargs) | return _gdi_.Locale_GetSystemEncodingName(*args, **kwargs) | GetSystemEncodingName() -> String | GetSystemEncodingName() -> String | [
"GetSystemEncodingName",
"()",
"-",
">",
"String"
] | def GetSystemEncodingName(*args, **kwargs):
"""GetSystemEncodingName() -> String"""
return _gdi_.Locale_GetSystemEncodingName(*args, **kwargs) | [
"def",
"GetSystemEncodingName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Locale_GetSystemEncodingName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L3099-L3101 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/tools/in_graph_batch_env.py | python | InGraphBatchEnv.simulate | (self, action) | Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation. | Step the batch of environments. | [
"Step",
"the",
"batch",
"of",
"environments",
"."
] | def simulate(self, action):
"""Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation.
"""
with tf.name_scope('environment/simulate'):
if action.dtype in (tf.float16, tf.float32, tf.float64):
action = tf.check_numerics(action, 'action')
observ_dtype = self._parse_dtype(self._batch_env.observation_space)
observ, reward, done = tf.py_func(lambda a: self._batch_env.step(a)[:3], [action],
[observ_dtype, tf.float32, tf.bool],
name='step')
observ = tf.check_numerics(observ, 'observ')
reward = tf.check_numerics(reward, 'reward')
return tf.group(self._observ.assign(observ), self._action.assign(action),
self._reward.assign(reward), self._done.assign(done)) | [
"def",
"simulate",
"(",
"self",
",",
"action",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'environment/simulate'",
")",
":",
"if",
"action",
".",
"dtype",
"in",
"(",
"tf",
".",
"float16",
",",
"tf",
".",
"float32",
",",
"tf",
".",
"float64",
")",
":",
"action",
"=",
"tf",
".",
"check_numerics",
"(",
"action",
",",
"'action'",
")",
"observ_dtype",
"=",
"self",
".",
"_parse_dtype",
"(",
"self",
".",
"_batch_env",
".",
"observation_space",
")",
"observ",
",",
"reward",
",",
"done",
"=",
"tf",
".",
"py_func",
"(",
"lambda",
"a",
":",
"self",
".",
"_batch_env",
".",
"step",
"(",
"a",
")",
"[",
":",
"3",
"]",
",",
"[",
"action",
"]",
",",
"[",
"observ_dtype",
",",
"tf",
".",
"float32",
",",
"tf",
".",
"bool",
"]",
",",
"name",
"=",
"'step'",
")",
"observ",
"=",
"tf",
".",
"check_numerics",
"(",
"observ",
",",
"'observ'",
")",
"reward",
"=",
"tf",
".",
"check_numerics",
"(",
"reward",
",",
"'reward'",
")",
"return",
"tf",
".",
"group",
"(",
"self",
".",
"_observ",
".",
"assign",
"(",
"observ",
")",
",",
"self",
".",
"_action",
".",
"assign",
"(",
"action",
")",
",",
"self",
".",
"_reward",
".",
"assign",
"(",
"reward",
")",
",",
"self",
".",
"_done",
".",
"assign",
"(",
"done",
")",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/tools/in_graph_batch_env.py#L79-L100 | ||
google/sling | f408a148a06bc2d62e853a292a8ba7266c642839 | python/task/wiki.py | python | WikiWorkflow.wikipedia_import | (self, input, name=None) | return articles, categories, redirects | Task for converting Wikipedia dump to SLING articles and redirects.
Returns article, categories, and redirect channels. | Task for converting Wikipedia dump to SLING articles and redirects.
Returns article, categories, and redirect channels. | [
"Task",
"for",
"converting",
"Wikipedia",
"dump",
"to",
"SLING",
"articles",
"and",
"redirects",
".",
"Returns",
"article",
"categories",
"and",
"redirect",
"channels",
"."
] | def wikipedia_import(self, input, name=None):
"""Task for converting Wikipedia dump to SLING articles and redirects.
Returns article, categories, and redirect channels."""
task = self.wf.task("wikipedia-importer", name=name)
task.attach_input("input", input)
articles = self.wf.channel(task, name="articles", format="message/frame")
categories = self.wf.channel(task, name="categories",
format="message/frame")
redirects = self.wf.channel(task, name="redirects", format="message/frame")
return articles, categories, redirects | [
"def",
"wikipedia_import",
"(",
"self",
",",
"input",
",",
"name",
"=",
"None",
")",
":",
"task",
"=",
"self",
".",
"wf",
".",
"task",
"(",
"\"wikipedia-importer\"",
",",
"name",
"=",
"name",
")",
"task",
".",
"attach_input",
"(",
"\"input\"",
",",
"input",
")",
"articles",
"=",
"self",
".",
"wf",
".",
"channel",
"(",
"task",
",",
"name",
"=",
"\"articles\"",
",",
"format",
"=",
"\"message/frame\"",
")",
"categories",
"=",
"self",
".",
"wf",
".",
"channel",
"(",
"task",
",",
"name",
"=",
"\"categories\"",
",",
"format",
"=",
"\"message/frame\"",
")",
"redirects",
"=",
"self",
".",
"wf",
".",
"channel",
"(",
"task",
",",
"name",
"=",
"\"redirects\"",
",",
"format",
"=",
"\"message/frame\"",
")",
"return",
"articles",
",",
"categories",
",",
"redirects"
] | https://github.com/google/sling/blob/f408a148a06bc2d62e853a292a8ba7266c642839/python/task/wiki.py#L287-L296 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/moosesqa/get_requirements.py | python | get_requirements_from_file | (filename, prefix=None, include_non_testable=False, root_dir=None) | return requirements | Opens hit file and extracts requirement items.
Input:
filename[str]: The HIT file to open and extract Requirements
Returns:
A list of Requirement objects. | Opens hit file and extracts requirement items. | [
"Opens",
"hit",
"file",
"and",
"extracts",
"requirement",
"items",
"."
] | def get_requirements_from_file(filename, prefix=None, include_non_testable=False, root_dir=None):
"""
Opens hit file and extracts requirement items.
Input:
filename[str]: The HIT file to open and extract Requirements
Returns:
A list of Requirement objects.
"""
if not os.path.isfile(filename):
raise FileNotFoundError("The supplied filename does not exist: {}".format(filename))
requirements = list()
root = pyhit.load(filename)
# Options available at the top-level
# [Tests]
# design = 'foo.md bar.md'
# issues = '#12345 ab23bd34'
design = root.children[0].get('design', None)
design_line = root.children[0].line('design', None)
issues = root.children[0].get('issues', None)
issues_line = root.children[0].line('issues', None)
deprecated = root.children[0].get('deprecated', False)
deprecated_line = root.children[0].line('deprecated', None)
collections = root.children[0].get('collections', None)
collections_line = root.children[0].line('collections', None)
for child in root.children[0]:
req = _create_requirement(child, filename,
design, design_line,
issues, issues_line,
collections, collections_line,
deprecated, deprecated_line)
req.prefix = prefix
# Get "detail" parameter from nested tests
for grandchild in child.children:
detail = _create_detail(grandchild, filename)
detail.specification = _create_specification(grandchild, '{}/{}'.format(child.name, grandchild.name), filename, root_dir)
req.details.append(detail)
if not req.details:
req.specification = _create_specification(child, child.name, filename, root_dir)
if req.testable or include_non_testable:
requirements.append(req)
return requirements | [
"def",
"get_requirements_from_file",
"(",
"filename",
",",
"prefix",
"=",
"None",
",",
"include_non_testable",
"=",
"False",
",",
"root_dir",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"raise",
"FileNotFoundError",
"(",
"\"The supplied filename does not exist: {}\"",
".",
"format",
"(",
"filename",
")",
")",
"requirements",
"=",
"list",
"(",
")",
"root",
"=",
"pyhit",
".",
"load",
"(",
"filename",
")",
"# Options available at the top-level",
"# [Tests]",
"# design = 'foo.md bar.md'",
"# issues = '#12345 ab23bd34'",
"design",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"get",
"(",
"'design'",
",",
"None",
")",
"design_line",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"line",
"(",
"'design'",
",",
"None",
")",
"issues",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"get",
"(",
"'issues'",
",",
"None",
")",
"issues_line",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"line",
"(",
"'issues'",
",",
"None",
")",
"deprecated",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"get",
"(",
"'deprecated'",
",",
"False",
")",
"deprecated_line",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"line",
"(",
"'deprecated'",
",",
"None",
")",
"collections",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"get",
"(",
"'collections'",
",",
"None",
")",
"collections_line",
"=",
"root",
".",
"children",
"[",
"0",
"]",
".",
"line",
"(",
"'collections'",
",",
"None",
")",
"for",
"child",
"in",
"root",
".",
"children",
"[",
"0",
"]",
":",
"req",
"=",
"_create_requirement",
"(",
"child",
",",
"filename",
",",
"design",
",",
"design_line",
",",
"issues",
",",
"issues_line",
",",
"collections",
",",
"collections_line",
",",
"deprecated",
",",
"deprecated_line",
")",
"req",
".",
"prefix",
"=",
"prefix",
"# Get \"detail\" parameter from nested tests",
"for",
"grandchild",
"in",
"child",
".",
"children",
":",
"detail",
"=",
"_create_detail",
"(",
"grandchild",
",",
"filename",
")",
"detail",
".",
"specification",
"=",
"_create_specification",
"(",
"grandchild",
",",
"'{}/{}'",
".",
"format",
"(",
"child",
".",
"name",
",",
"grandchild",
".",
"name",
")",
",",
"filename",
",",
"root_dir",
")",
"req",
".",
"details",
".",
"append",
"(",
"detail",
")",
"if",
"not",
"req",
".",
"details",
":",
"req",
".",
"specification",
"=",
"_create_specification",
"(",
"child",
",",
"child",
".",
"name",
",",
"filename",
",",
"root_dir",
")",
"if",
"req",
".",
"testable",
"or",
"include_non_testable",
":",
"requirements",
".",
"append",
"(",
"req",
")",
"return",
"requirements"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/moosesqa/get_requirements.py#L58-L106 | |
shogun-toolbox/shogun | 9b8d856971af5a295dd6ad70623ae45647a6334c | examples/undocumented/python/graphical/interactive_kmm_demo.py | python | DataHolder.series_len | (self) | return self.datalen | Length of a data series | Length of a data series | [
"Length",
"of",
"a",
"data",
"series"
] | def series_len(self):
""" Length of a data series
"""
return self.datalen | [
"def",
"series_len",
"(",
"self",
")",
":",
"return",
"self",
".",
"datalen"
] | https://github.com/shogun-toolbox/shogun/blob/9b8d856971af5a295dd6ad70623ae45647a6334c/examples/undocumented/python/graphical/interactive_kmm_demo.py#L358-L361 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/ext.py | python | babel_extract | (fileobj, keywords, comment_tags, options) | Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently) | Babel extraction method for Jinja templates. | [
"Babel",
"extraction",
"method",
"for",
"Jinja",
"templates",
"."
] | def babel_extract(fileobj, keywords, comment_tags, options):
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently)
"""
extensions = set()
for extension in options.get('extensions', '').split(','):
extension = extension.strip()
if not extension:
continue
extensions.add(import_string(extension))
if InternationalizationExtension not in extensions:
extensions.add(InternationalizationExtension)
def getbool(options, key, default=False):
return options.get(key, str(default)).lower() in \
('1', 'on', 'yes', 'true')
silent = getbool(options, 'silent', True)
environment = Environment(
options.get('block_start_string', BLOCK_START_STRING),
options.get('block_end_string', BLOCK_END_STRING),
options.get('variable_start_string', VARIABLE_START_STRING),
options.get('variable_end_string', VARIABLE_END_STRING),
options.get('comment_start_string', COMMENT_START_STRING),
options.get('comment_end_string', COMMENT_END_STRING),
options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
getbool(options, 'trim_blocks', TRIM_BLOCKS),
getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),
NEWLINE_SEQUENCE,
getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),
frozenset(extensions),
cache_size=0,
auto_reload=False
)
if getbool(options, 'trimmed'):
environment.policies['ext.i18n.trimmed'] = True
if getbool(options, 'newstyle_gettext'):
environment.newstyle_gettext = True
source = fileobj.read().decode(options.get('encoding', 'utf-8'))
try:
node = environment.parse(source)
tokens = list(environment.lex(environment.preprocess(source)))
except TemplateSyntaxError as e:
if not silent:
raise
# skip templates with syntax errors
return
finder = _CommentFinder(tokens, comment_tags)
for lineno, func, message in extract_from_ast(node, keywords):
yield lineno, func, message, finder.find_comments(lineno) | [
"def",
"babel_extract",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"extensions",
"=",
"set",
"(",
")",
"for",
"extension",
"in",
"options",
".",
"get",
"(",
"'extensions'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
":",
"extension",
"=",
"extension",
".",
"strip",
"(",
")",
"if",
"not",
"extension",
":",
"continue",
"extensions",
".",
"add",
"(",
"import_string",
"(",
"extension",
")",
")",
"if",
"InternationalizationExtension",
"not",
"in",
"extensions",
":",
"extensions",
".",
"add",
"(",
"InternationalizationExtension",
")",
"def",
"getbool",
"(",
"options",
",",
"key",
",",
"default",
"=",
"False",
")",
":",
"return",
"options",
".",
"get",
"(",
"key",
",",
"str",
"(",
"default",
")",
")",
".",
"lower",
"(",
")",
"in",
"(",
"'1'",
",",
"'on'",
",",
"'yes'",
",",
"'true'",
")",
"silent",
"=",
"getbool",
"(",
"options",
",",
"'silent'",
",",
"True",
")",
"environment",
"=",
"Environment",
"(",
"options",
".",
"get",
"(",
"'block_start_string'",
",",
"BLOCK_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'block_end_string'",
",",
"BLOCK_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'variable_start_string'",
",",
"VARIABLE_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'variable_end_string'",
",",
"VARIABLE_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'comment_start_string'",
",",
"COMMENT_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'comment_end_string'",
",",
"COMMENT_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'line_statement_prefix'",
")",
"or",
"LINE_STATEMENT_PREFIX",
",",
"options",
".",
"get",
"(",
"'line_comment_prefix'",
")",
"or",
"LINE_COMMENT_PREFIX",
",",
"getbool",
"(",
"options",
",",
"'trim_blocks'",
",",
"TRIM_BLOCKS",
")",
",",
"getbool",
"(",
"options",
",",
"'lstrip_blocks'",
",",
"LSTRIP_BLOCKS",
")",
",",
"NEWLINE_SEQUENCE",
",",
"getbool",
"(",
"options",
",",
"'keep_trailing_newline'",
",",
"KEEP_TRAILING_NEWLINE",
")",
",",
"frozenset",
"(",
"extensions",
")",
",",
"cache_size",
"=",
"0",
",",
"auto_reload",
"=",
"False",
")",
"if",
"getbool",
"(",
"options",
",",
"'trimmed'",
")",
":",
"environment",
".",
"policies",
"[",
"'ext.i18n.trimmed'",
"]",
"=",
"True",
"if",
"getbool",
"(",
"options",
",",
"'newstyle_gettext'",
")",
":",
"environment",
".",
"newstyle_gettext",
"=",
"True",
"source",
"=",
"fileobj",
".",
"read",
"(",
")",
".",
"decode",
"(",
"options",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
")",
"try",
":",
"node",
"=",
"environment",
".",
"parse",
"(",
"source",
")",
"tokens",
"=",
"list",
"(",
"environment",
".",
"lex",
"(",
"environment",
".",
"preprocess",
"(",
"source",
")",
")",
")",
"except",
"TemplateSyntaxError",
"as",
"e",
":",
"if",
"not",
"silent",
":",
"raise",
"# skip templates with syntax errors",
"return",
"finder",
"=",
"_CommentFinder",
"(",
"tokens",
",",
"comment_tags",
")",
"for",
"lineno",
",",
"func",
",",
"message",
"in",
"extract_from_ast",
"(",
"node",
",",
"keywords",
")",
":",
"yield",
"lineno",
",",
"func",
",",
"message",
",",
"finder",
".",
"find_comments",
"(",
"lineno",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/ext.py#L542-L619 | ||
mongodb/mongo-cxx-driver | eb86512b05be20d2f51d53ba9b860c709e0799b3 | etc/make_release.py | python | ensure_c_driver | (c_driver_install_dir, c_driver_build_ref, with_c_driver, quiet) | return build_c_driver(c_driver_install_dir, c_driver_build_ref, quiet) | Ensures that there is a properly installed C driver, returning the location
of the C driver installation. If the with_c_driver parameter is set and
points to a proper installation of the C driver, then this function simply
returns that directory. Otherwise, delegates to another function to build
the C driver and install it to the directory specified by the
c_driver_install_dir parameter. | Ensures that there is a properly installed C driver, returning the location
of the C driver installation. If the with_c_driver parameter is set and
points to a proper installation of the C driver, then this function simply
returns that directory. Otherwise, delegates to another function to build
the C driver and install it to the directory specified by the
c_driver_install_dir parameter. | [
"Ensures",
"that",
"there",
"is",
"a",
"properly",
"installed",
"C",
"driver",
"returning",
"the",
"location",
"of",
"the",
"C",
"driver",
"installation",
".",
"If",
"the",
"with_c_driver",
"parameter",
"is",
"set",
"and",
"points",
"to",
"a",
"proper",
"installation",
"of",
"the",
"C",
"driver",
"then",
"this",
"function",
"simply",
"returns",
"that",
"directory",
".",
"Otherwise",
"delegates",
"to",
"another",
"function",
"to",
"build",
"the",
"C",
"driver",
"and",
"install",
"it",
"to",
"the",
"directory",
"specified",
"by",
"the",
"c_driver_install_dir",
"parameter",
"."
] | def ensure_c_driver(c_driver_install_dir, c_driver_build_ref, with_c_driver, quiet):
"""
Ensures that there is a properly installed C driver, returning the location
of the C driver installation. If the with_c_driver parameter is set and
points to a proper installation of the C driver, then this function simply
returns that directory. Otherwise, delegates to another function to build
the C driver and install it to the directory specified by the
c_driver_install_dir parameter.
"""
if with_c_driver:
bson_h = os.path.join(with_c_driver, 'include/libbson-1.0/bson/bson.h')
mongoc_h = os.path.join(with_c_driver, 'include/libmongoc-1.0/mongoc/mongoc.h')
if os.path.exists(bson_h) and os.path.exists(mongoc_h):
return with_c_driver
if not quiet:
click.echo('A required component of the C driver is missing!', err=True)
return None
return build_c_driver(c_driver_install_dir, c_driver_build_ref, quiet) | [
"def",
"ensure_c_driver",
"(",
"c_driver_install_dir",
",",
"c_driver_build_ref",
",",
"with_c_driver",
",",
"quiet",
")",
":",
"if",
"with_c_driver",
":",
"bson_h",
"=",
"os",
".",
"path",
".",
"join",
"(",
"with_c_driver",
",",
"'include/libbson-1.0/bson/bson.h'",
")",
"mongoc_h",
"=",
"os",
".",
"path",
".",
"join",
"(",
"with_c_driver",
",",
"'include/libmongoc-1.0/mongoc/mongoc.h'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"bson_h",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"mongoc_h",
")",
":",
"return",
"with_c_driver",
"if",
"not",
"quiet",
":",
"click",
".",
"echo",
"(",
"'A required component of the C driver is missing!'",
",",
"err",
"=",
"True",
")",
"return",
"None",
"return",
"build_c_driver",
"(",
"c_driver_install_dir",
",",
"c_driver_build_ref",
",",
"quiet",
")"
] | https://github.com/mongodb/mongo-cxx-driver/blob/eb86512b05be20d2f51d53ba9b860c709e0799b3/etc/make_release.py#L330-L349 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextRange.__sub__ | (*args, **kwargs) | return _richtext.RichTextRange___sub__(*args, **kwargs) | __sub__(self, RichTextRange range) -> RichTextRange | __sub__(self, RichTextRange range) -> RichTextRange | [
"__sub__",
"(",
"self",
"RichTextRange",
"range",
")",
"-",
">",
"RichTextRange"
] | def __sub__(*args, **kwargs):
"""__sub__(self, RichTextRange range) -> RichTextRange"""
return _richtext.RichTextRange___sub__(*args, **kwargs) | [
"def",
"__sub__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextRange___sub__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L957-L959 | |
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert-gpu/utils/create_glue_data.py | python | _truncate_seq_pair | (tokens_a, tokens_b, max_length) | Truncates a sequence pair in place to the maximum length. | Truncates a sequence pair in place to the maximum length. | [
"Truncates",
"a",
"sequence",
"pair",
"in",
"place",
"to",
"the",
"maximum",
"length",
"."
] | def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop() | [
"def",
"_truncate_seq_pair",
"(",
"tokens_a",
",",
"tokens_b",
",",
"max_length",
")",
":",
"# This is a simple heuristic which will always truncate the longer sequence",
"# one token at a time. This makes more sense than truncating an equal percent",
"# of tokens from each, since if one sequence is very short then each token",
"# that's truncated likely contains more information than a longer sequence.",
"while",
"True",
":",
"total_length",
"=",
"len",
"(",
"tokens_a",
")",
"+",
"len",
"(",
"tokens_b",
")",
"if",
"total_length",
"<=",
"max_length",
":",
"break",
"if",
"len",
"(",
"tokens_a",
")",
">",
"len",
"(",
"tokens_b",
")",
":",
"tokens_a",
".",
"pop",
"(",
")",
"else",
":",
"tokens_b",
".",
"pop",
"(",
")"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/utils/create_glue_data.py#L303-L317 | ||
neo-ai/neo-ai-dlr | bf397aa0367a5207654c00d2985f900d94ad1543 | container/sagemaker-tensorflow-inferentia/build_artifacts/deep_learning_container.py | python | query_bucket | () | return response | GET request on an empty object from an Amazon S3 bucket | GET request on an empty object from an Amazon S3 bucket | [
"GET",
"request",
"on",
"an",
"empty",
"object",
"from",
"an",
"Amazon",
"S3",
"bucket"
] | def query_bucket():
"""
GET request on an empty object from an Amazon S3 bucket
"""
response = None
instance_id = _retrieve_instance_id()
region = _retrieve_instance_region()
if instance_id is not None and region is not None:
url = ("https://aws-deep-learning-containers-{0}.s3.{0}.amazonaws.com"
"/dlc-containers.txt?x-instance-id={1}".format(region, instance_id))
response = requests_helper(url, timeout=0.2)
logging.debug("Query bucket finished: {}".format(response))
return response | [
"def",
"query_bucket",
"(",
")",
":",
"response",
"=",
"None",
"instance_id",
"=",
"_retrieve_instance_id",
"(",
")",
"region",
"=",
"_retrieve_instance_region",
"(",
")",
"if",
"instance_id",
"is",
"not",
"None",
"and",
"region",
"is",
"not",
"None",
":",
"url",
"=",
"(",
"\"https://aws-deep-learning-containers-{0}.s3.{0}.amazonaws.com\"",
"\"/dlc-containers.txt?x-instance-id={1}\"",
".",
"format",
"(",
"region",
",",
"instance_id",
")",
")",
"response",
"=",
"requests_helper",
"(",
"url",
",",
"timeout",
"=",
"0.2",
")",
"logging",
".",
"debug",
"(",
"\"Query bucket finished: {}\"",
".",
"format",
"(",
"response",
")",
")",
"return",
"response"
] | https://github.com/neo-ai/neo-ai-dlr/blob/bf397aa0367a5207654c00d2985f900d94ad1543/container/sagemaker-tensorflow-inferentia/build_artifacts/deep_learning_container.py#L69-L84 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | PyApp_GetMacHelpMenuTitleName | (*args) | return _core_.PyApp_GetMacHelpMenuTitleName(*args) | PyApp_GetMacHelpMenuTitleName() -> String | PyApp_GetMacHelpMenuTitleName() -> String | [
"PyApp_GetMacHelpMenuTitleName",
"()",
"-",
">",
"String"
] | def PyApp_GetMacHelpMenuTitleName(*args):
"""PyApp_GetMacHelpMenuTitleName() -> String"""
return _core_.PyApp_GetMacHelpMenuTitleName(*args) | [
"def",
"PyApp_GetMacHelpMenuTitleName",
"(",
"*",
"args",
")",
":",
"return",
"_core_",
".",
"PyApp_GetMacHelpMenuTitleName",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L8290-L8292 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mailbox.py | python | MH.__init__ | (self, path, factory=None, create=True) | Initialize an MH instance. | Initialize an MH instance. | [
"Initialize",
"an",
"MH",
"instance",
"."
] | def __init__(self, path, factory=None, create=True):
"""Initialize an MH instance."""
Mailbox.__init__(self, path, factory, create)
if not os.path.exists(self._path):
if create:
os.mkdir(self._path, 0700)
os.close(os.open(os.path.join(self._path, '.mh_sequences'),
os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
else:
raise NoSuchMailboxError(self._path)
self._locked = False | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"factory",
"=",
"None",
",",
"create",
"=",
"True",
")",
":",
"Mailbox",
".",
"__init__",
"(",
"self",
",",
"path",
",",
"factory",
",",
"create",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_path",
")",
":",
"if",
"create",
":",
"os",
".",
"mkdir",
"(",
"self",
".",
"_path",
",",
"0700",
")",
"os",
".",
"close",
"(",
"os",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"'.mh_sequences'",
")",
",",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_EXCL",
"|",
"os",
".",
"O_WRONLY",
",",
"0600",
")",
")",
"else",
":",
"raise",
"NoSuchMailboxError",
"(",
"self",
".",
"_path",
")",
"self",
".",
"_locked",
"=",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L920-L930 | ||
deepmind/reverb | ef3c8f0be1b720a741d2dee335e15e44668c291a | reverb/structured_writer.py | python | StructuredWriter.step_is_open | (self) | return self._writer.step_is_open | True if `partial_step` was set in the most recent `append`. | True if `partial_step` was set in the most recent `append`. | [
"True",
"if",
"partial_step",
"was",
"set",
"in",
"the",
"most",
"recent",
"append",
"."
] | def step_is_open(self) -> bool:
"""True if `partial_step` was set in the most recent `append`."""
return self._writer.step_is_open | [
"def",
"step_is_open",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_writer",
".",
"step_is_open"
] | https://github.com/deepmind/reverb/blob/ef3c8f0be1b720a741d2dee335e15e44668c291a/reverb/structured_writer.py#L192-L194 | |
libLAS/libLAS | e6a1aaed412d638687b8aec44f7b12df7ca2bbbb | python/liblas/header.py | python | Header.set_guid | (self, value) | return core.las.LASHeader_SetGUID(self.handle, value.handle) | Sets the GUID for the file. It must be a :class:`liblas.guid.GUID`
instance | Sets the GUID for the file. It must be a :class:`liblas.guid.GUID`
instance | [
"Sets",
"the",
"GUID",
"for",
"the",
"file",
".",
"It",
"must",
"be",
"a",
":",
"class",
":",
"liblas",
".",
"guid",
".",
"GUID",
"instance"
] | def set_guid(self, value):
"""Sets the GUID for the file. It must be a :class:`liblas.guid.GUID`
instance"""
return core.las.LASHeader_SetGUID(self.handle, value.handle) | [
"def",
"set_guid",
"(",
"self",
",",
"value",
")",
":",
"return",
"core",
".",
"las",
".",
"LASHeader_SetGUID",
"(",
"self",
".",
"handle",
",",
"value",
".",
"handle",
")"
] | https://github.com/libLAS/libLAS/blob/e6a1aaed412d638687b8aec44f7b12df7ca2bbbb/python/liblas/header.py#L189-L192 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/algorithms/ddp_comm_hooks/default_hooks.py | python | fp16_compress_wrapper | (
hook: Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]
) | return fp16_compress_wrapper_hook | This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
floating point format (``torch.float16``), and casts the resulting tensor of the given hook back to
the input data type, such as ``float32``.
Therefore, ``fp16_compress_hook`` is equivalent to ``fp16_compress_wrapper(allreduce_hook)``.
Example::
>>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1, start_powerSGD_iter=10)
>>> ddp_model.register_comm_hook(state, fp16_compress_wrapper(powerSGD_hook)) | This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
floating point format (``torch.float16``), and casts the resulting tensor of the given hook back to
the input data type, such as ``float32``. | [
"This",
"wrapper",
"casts",
"the",
"input",
"gradient",
"tensor",
"of",
"a",
"given",
"DDP",
"communication",
"hook",
"to",
"half",
"-",
"precision",
"floating",
"point",
"format",
"(",
"torch",
".",
"float16",
")",
"and",
"casts",
"the",
"resulting",
"tensor",
"of",
"the",
"given",
"hook",
"back",
"to",
"the",
"input",
"data",
"type",
"such",
"as",
"float32",
"."
] | def fp16_compress_wrapper(
hook: Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]
) -> Callable[[Any, dist.GradBucket], torch.futures.Future[torch.Tensor]]:
"""
This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
floating point format (``torch.float16``), and casts the resulting tensor of the given hook back to
the input data type, such as ``float32``.
Therefore, ``fp16_compress_hook`` is equivalent to ``fp16_compress_wrapper(allreduce_hook)``.
Example::
>>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1, start_powerSGD_iter=10)
>>> ddp_model.register_comm_hook(state, fp16_compress_wrapper(powerSGD_hook))
"""
def fp16_compress_wrapper_hook(
hook_state, bucket: dist.GradBucket
) -> torch.futures.Future[torch.Tensor]:
# Cast bucket tensor to FP16.
bucket.set_buffer(bucket.buffer().to(torch.float16))
fut = hook(hook_state, bucket)
def decompress(fut):
decompressed_tensor = bucket.buffer()
# Decompress in place to reduce the peak memory.
# See: https://github.com/pytorch/pytorch/issues/45968
decompressed_tensor.copy_(fut.value())
return decompressed_tensor
# Decompress after hook has run.
return fut.then(decompress)
return fp16_compress_wrapper_hook | [
"def",
"fp16_compress_wrapper",
"(",
"hook",
":",
"Callable",
"[",
"[",
"Any",
",",
"dist",
".",
"GradBucket",
"]",
",",
"torch",
".",
"futures",
".",
"Future",
"[",
"torch",
".",
"Tensor",
"]",
"]",
")",
"->",
"Callable",
"[",
"[",
"Any",
",",
"dist",
".",
"GradBucket",
"]",
",",
"torch",
".",
"futures",
".",
"Future",
"[",
"torch",
".",
"Tensor",
"]",
"]",
":",
"def",
"fp16_compress_wrapper_hook",
"(",
"hook_state",
",",
"bucket",
":",
"dist",
".",
"GradBucket",
")",
"->",
"torch",
".",
"futures",
".",
"Future",
"[",
"torch",
".",
"Tensor",
"]",
":",
"# Cast bucket tensor to FP16.",
"bucket",
".",
"set_buffer",
"(",
"bucket",
".",
"buffer",
"(",
")",
".",
"to",
"(",
"torch",
".",
"float16",
")",
")",
"fut",
"=",
"hook",
"(",
"hook_state",
",",
"bucket",
")",
"def",
"decompress",
"(",
"fut",
")",
":",
"decompressed_tensor",
"=",
"bucket",
".",
"buffer",
"(",
")",
"# Decompress in place to reduce the peak memory.",
"# See: https://github.com/pytorch/pytorch/issues/45968",
"decompressed_tensor",
".",
"copy_",
"(",
"fut",
".",
"value",
"(",
")",
")",
"return",
"decompressed_tensor",
"# Decompress after hook has run.",
"return",
"fut",
".",
"then",
"(",
"decompress",
")",
"return",
"fp16_compress_wrapper_hook"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/algorithms/ddp_comm_hooks/default_hooks.py#L108-L141 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/special/basic.py | python | jnyn_zeros | (n, nt) | return specfun.jyzo(abs(n), nt) | Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
Returns 4 arrays of length `nt`, corresponding to the first `nt` zeros of
Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively.
Parameters
----------
n : int
Order of the Bessel functions
nt : int
Number (<=1200) of zeros to compute
See jn_zeros, jnp_zeros, yn_zeros, ynp_zeros to get separate arrays.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html | Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x). | [
"Compute",
"nt",
"zeros",
"of",
"Bessel",
"functions",
"Jn",
"(",
"x",
")",
"Jn",
"(",
"x",
")",
"Yn",
"(",
"x",
")",
"and",
"Yn",
"(",
"x",
")",
"."
] | def jnyn_zeros(n, nt):
"""Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
Returns 4 arrays of length `nt`, corresponding to the first `nt` zeros of
Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively.
Parameters
----------
n : int
Order of the Bessel functions
nt : int
Number (<=1200) of zeros to compute
See jn_zeros, jnp_zeros, yn_zeros, ynp_zeros to get separate arrays.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(nt) and isscalar(n)):
raise ValueError("Arguments must be scalars.")
if (floor(n) != n) or (floor(nt) != nt):
raise ValueError("Arguments must be integers.")
if (nt <= 0):
raise ValueError("nt > 0")
return specfun.jyzo(abs(n), nt) | [
"def",
"jnyn_zeros",
"(",
"n",
",",
"nt",
")",
":",
"if",
"not",
"(",
"isscalar",
"(",
"nt",
")",
"and",
"isscalar",
"(",
"n",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Arguments must be scalars.\"",
")",
"if",
"(",
"floor",
"(",
"n",
")",
"!=",
"n",
")",
"or",
"(",
"floor",
"(",
"nt",
")",
"!=",
"nt",
")",
":",
"raise",
"ValueError",
"(",
"\"Arguments must be integers.\"",
")",
"if",
"(",
"nt",
"<=",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"nt > 0\"",
")",
"return",
"specfun",
".",
"jyzo",
"(",
"abs",
"(",
"n",
")",
",",
"nt",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/special/basic.py#L230-L258 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | utils/lit/lit/util.py | python | executeCommand | (command, cwd=None, env=None, input=None, timeout=0) | return out, err, exitCode | Execute command ``command`` (list of arguments or string) with.
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
* Input to the command ``input`` (str), use string to pass
no input.
* Max execution time ``timeout`` (int) seconds. Use 0 for no timeout.
Returns a tuple (out, err, exitCode) where
* ``out`` (str) is the standard output of running the command
* ``err`` (str) is the standard error of running the command
* ``exitCode`` (int) is the exitCode of running the command
If the timeout is hit an ``ExecuteCommandTimeoutException``
is raised. | Execute command ``command`` (list of arguments or string) with. | [
"Execute",
"command",
"command",
"(",
"list",
"of",
"arguments",
"or",
"string",
")",
"with",
"."
] | def executeCommand(command, cwd=None, env=None, input=None, timeout=0):
"""Execute command ``command`` (list of arguments or string) with.
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
* Input to the command ``input`` (str), use string to pass
no input.
* Max execution time ``timeout`` (int) seconds. Use 0 for no timeout.
Returns a tuple (out, err, exitCode) where
* ``out`` (str) is the standard output of running the command
* ``err`` (str) is the standard error of running the command
* ``exitCode`` (int) is the exitCode of running the command
If the timeout is hit an ``ExecuteCommandTimeoutException``
is raised.
"""
if input is not None:
input = to_bytes(input)
p = subprocess.Popen(command, cwd=cwd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env, close_fds=kUseCloseFDs)
timerObject = None
# FIXME: Because of the way nested function scopes work in Python 2.x we
# need to use a reference to a mutable object rather than a plain
# bool. In Python 3 we could use the "nonlocal" keyword but we need
# to support Python 2 as well.
hitTimeOut = [False]
try:
if timeout > 0:
def killProcess():
# We may be invoking a shell so we need to kill the
# process and all its children.
hitTimeOut[0] = True
killProcessAndChildren(p.pid)
timerObject = threading.Timer(timeout, killProcess)
timerObject.start()
out, err = p.communicate(input=input)
exitCode = p.wait()
finally:
if timerObject != None:
timerObject.cancel()
# Ensure the resulting output is always of string type.
out = to_string(out)
err = to_string(err)
if hitTimeOut[0]:
raise ExecuteCommandTimeoutException(
msg='Reached timeout of {} seconds'.format(timeout),
out=out,
err=err,
exitCode=exitCode
)
# Detect Ctrl-C in subprocess.
if exitCode == -signal.SIGINT:
raise KeyboardInterrupt
return out, err, exitCode | [
"def",
"executeCommand",
"(",
"command",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"input",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"if",
"input",
"is",
"not",
"None",
":",
"input",
"=",
"to_bytes",
"(",
"input",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"cwd",
"=",
"cwd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"env",
"=",
"env",
",",
"close_fds",
"=",
"kUseCloseFDs",
")",
"timerObject",
"=",
"None",
"# FIXME: Because of the way nested function scopes work in Python 2.x we",
"# need to use a reference to a mutable object rather than a plain",
"# bool. In Python 3 we could use the \"nonlocal\" keyword but we need",
"# to support Python 2 as well.",
"hitTimeOut",
"=",
"[",
"False",
"]",
"try",
":",
"if",
"timeout",
">",
"0",
":",
"def",
"killProcess",
"(",
")",
":",
"# We may be invoking a shell so we need to kill the",
"# process and all its children.",
"hitTimeOut",
"[",
"0",
"]",
"=",
"True",
"killProcessAndChildren",
"(",
"p",
".",
"pid",
")",
"timerObject",
"=",
"threading",
".",
"Timer",
"(",
"timeout",
",",
"killProcess",
")",
"timerObject",
".",
"start",
"(",
")",
"out",
",",
"err",
"=",
"p",
".",
"communicate",
"(",
"input",
"=",
"input",
")",
"exitCode",
"=",
"p",
".",
"wait",
"(",
")",
"finally",
":",
"if",
"timerObject",
"!=",
"None",
":",
"timerObject",
".",
"cancel",
"(",
")",
"# Ensure the resulting output is always of string type.",
"out",
"=",
"to_string",
"(",
"out",
")",
"err",
"=",
"to_string",
"(",
"err",
")",
"if",
"hitTimeOut",
"[",
"0",
"]",
":",
"raise",
"ExecuteCommandTimeoutException",
"(",
"msg",
"=",
"'Reached timeout of {} seconds'",
".",
"format",
"(",
"timeout",
")",
",",
"out",
"=",
"out",
",",
"err",
"=",
"err",
",",
"exitCode",
"=",
"exitCode",
")",
"# Detect Ctrl-C in subprocess.",
"if",
"exitCode",
"==",
"-",
"signal",
".",
"SIGINT",
":",
"raise",
"KeyboardInterrupt",
"return",
"out",
",",
"err",
",",
"exitCode"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/utils/lit/lit/util.py#L297-L362 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | FontMapper.CharsetToEncoding | (*args, **kwargs) | return _gdi_.FontMapper_CharsetToEncoding(*args, **kwargs) | CharsetToEncoding(self, String charset, bool interactive=True) -> int | CharsetToEncoding(self, String charset, bool interactive=True) -> int | [
"CharsetToEncoding",
"(",
"self",
"String",
"charset",
"bool",
"interactive",
"=",
"True",
")",
"-",
">",
"int"
] | def CharsetToEncoding(*args, **kwargs):
"""CharsetToEncoding(self, String charset, bool interactive=True) -> int"""
return _gdi_.FontMapper_CharsetToEncoding(*args, **kwargs) | [
"def",
"CharsetToEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"FontMapper_CharsetToEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L2028-L2030 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | concat | (seq, axis=0, out=None) | return _mx_nd_np.concatenate(seq, axis=axis, out=out) | Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
Returns
-------
res : ndarray
The concatenated array.
Note
--------
`concate` is a alias for `concatante`. It is a standard API in
https://data-apis.org/array-api/latest/API_specification/manipulation_functions.html#concat-arrays-axis-0
instead of an official NumPy operator.
See Also
--------
split : Split array into a list of multiple sub-arrays of equal size.
hsplit : Split array into multiple sub-arrays horizontally (column wise)
vsplit : Split array into multiple sub-arrays vertically (row wise)
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
stack : Stack a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise)
vstack : Stack arrays in sequence vertically (row wise)
dstack : Stack arrays in sequence depth wise (along third dimension)
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concat((a, b), axis=0)
array([[1., 2.],
[3., 4.],
[5., 6.]])
>>> np.concat((a, b.T), axis=1)
array([[1., 2., 5.],
[3., 4., 6.]])
>>> np.concat((a, b), axis=None)
array([1., 2., 3., 4., 5., 6.]) | Join a sequence of arrays along an existing axis. | [
"Join",
"a",
"sequence",
"of",
"arrays",
"along",
"an",
"existing",
"axis",
"."
] | def concat(seq, axis=0, out=None):
"""Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
Returns
-------
res : ndarray
The concatenated array.
Note
--------
`concate` is a alias for `concatante`. It is a standard API in
https://data-apis.org/array-api/latest/API_specification/manipulation_functions.html#concat-arrays-axis-0
instead of an official NumPy operator.
See Also
--------
split : Split array into a list of multiple sub-arrays of equal size.
hsplit : Split array into multiple sub-arrays horizontally (column wise)
vsplit : Split array into multiple sub-arrays vertically (row wise)
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
stack : Stack a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise)
vstack : Stack arrays in sequence vertically (row wise)
dstack : Stack arrays in sequence depth wise (along third dimension)
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concat((a, b), axis=0)
array([[1., 2.],
[3., 4.],
[5., 6.]])
>>> np.concat((a, b.T), axis=1)
array([[1., 2., 5.],
[3., 4., 6.]])
>>> np.concat((a, b), axis=None)
array([1., 2., 3., 4., 5., 6.])
"""
return _mx_nd_np.concatenate(seq, axis=axis, out=out) | [
"def",
"concat",
"(",
"seq",
",",
"axis",
"=",
"0",
",",
"out",
"=",
"None",
")",
":",
"return",
"_mx_nd_np",
".",
"concatenate",
"(",
"seq",
",",
"axis",
"=",
"axis",
",",
"out",
"=",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L7304-L7358 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/math/symbolic_sympy.py | python | _make_sympy_adaptor | (func) | return type(func.name+"_sympy_adaptor",(sympy.Function,),attributes) | Adapts a symbolic Function to a sympy Function | Adapts a symbolic Function to a sympy Function | [
"Adapts",
"a",
"symbolic",
"Function",
"to",
"a",
"sympy",
"Function"
] | def _make_sympy_adaptor(func):
"""Adapts a symbolic Function to a sympy Function"""
assert isinstance(func,Function)
def _eval_evalf(self,prec):
fargs = [a._to_mpmath(prec) for a in self.args]
res = self._symbolic_func(*fargs).evalf()
return sympy.S(res)
def fdiff(self, argindex):
from sympy.core.function import ArgumentIndexError
f = self._symbolic_func
if f.deriv is None:
raise ArgumentIndexError(self, argindex)
if _is_exactly(f.deriv,0):
return sympy.S(0)
argindex -= 1
if f.jacobian is not None and f.jacobian[argindex] is not None:
assert isinstance(f.jacobian[argindex],Function)
return _make_sympy_adaptor(f.jacobian[argindex])(*self.args)
if callable(f.deriv):
raise NotImplementedError("Can't adapt a callable derivative to sympy yet")
assert argindex >= 0 and argindex < len(f.deriv),"Invalid derivative argument index? 0 <= %d < %d"%(argindex,len(f.deriv))
if _is_exactly(f.deriv[argindex],0):
return sympy.S(0)
if f.deriv[argindex] is None:
raise ArgumentIndexError(self, argindex)
return _make_sympy_adaptor(f.deriv[argindex])(*(self.args+(1,)))
attributes = {
'_symbolic_func':func,
'_eval_evalf':_eval_evalf,
'fdiff':fdiff
}
if func.argNames is not None:
attributes['nargs'] = len(func.argNames)
return type(func.name+"_sympy_adaptor",(sympy.Function,),attributes) | [
"def",
"_make_sympy_adaptor",
"(",
"func",
")",
":",
"assert",
"isinstance",
"(",
"func",
",",
"Function",
")",
"def",
"_eval_evalf",
"(",
"self",
",",
"prec",
")",
":",
"fargs",
"=",
"[",
"a",
".",
"_to_mpmath",
"(",
"prec",
")",
"for",
"a",
"in",
"self",
".",
"args",
"]",
"res",
"=",
"self",
".",
"_symbolic_func",
"(",
"*",
"fargs",
")",
".",
"evalf",
"(",
")",
"return",
"sympy",
".",
"S",
"(",
"res",
")",
"def",
"fdiff",
"(",
"self",
",",
"argindex",
")",
":",
"from",
"sympy",
".",
"core",
".",
"function",
"import",
"ArgumentIndexError",
"f",
"=",
"self",
".",
"_symbolic_func",
"if",
"f",
".",
"deriv",
"is",
"None",
":",
"raise",
"ArgumentIndexError",
"(",
"self",
",",
"argindex",
")",
"if",
"_is_exactly",
"(",
"f",
".",
"deriv",
",",
"0",
")",
":",
"return",
"sympy",
".",
"S",
"(",
"0",
")",
"argindex",
"-=",
"1",
"if",
"f",
".",
"jacobian",
"is",
"not",
"None",
"and",
"f",
".",
"jacobian",
"[",
"argindex",
"]",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"f",
".",
"jacobian",
"[",
"argindex",
"]",
",",
"Function",
")",
"return",
"_make_sympy_adaptor",
"(",
"f",
".",
"jacobian",
"[",
"argindex",
"]",
")",
"(",
"*",
"self",
".",
"args",
")",
"if",
"callable",
"(",
"f",
".",
"deriv",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Can't adapt a callable derivative to sympy yet\"",
")",
"assert",
"argindex",
">=",
"0",
"and",
"argindex",
"<",
"len",
"(",
"f",
".",
"deriv",
")",
",",
"\"Invalid derivative argument index? 0 <= %d < %d\"",
"%",
"(",
"argindex",
",",
"len",
"(",
"f",
".",
"deriv",
")",
")",
"if",
"_is_exactly",
"(",
"f",
".",
"deriv",
"[",
"argindex",
"]",
",",
"0",
")",
":",
"return",
"sympy",
".",
"S",
"(",
"0",
")",
"if",
"f",
".",
"deriv",
"[",
"argindex",
"]",
"is",
"None",
":",
"raise",
"ArgumentIndexError",
"(",
"self",
",",
"argindex",
")",
"return",
"_make_sympy_adaptor",
"(",
"f",
".",
"deriv",
"[",
"argindex",
"]",
")",
"(",
"*",
"(",
"self",
".",
"args",
"+",
"(",
"1",
",",
")",
")",
")",
"attributes",
"=",
"{",
"'_symbolic_func'",
":",
"func",
",",
"'_eval_evalf'",
":",
"_eval_evalf",
",",
"'fdiff'",
":",
"fdiff",
"}",
"if",
"func",
".",
"argNames",
"is",
"not",
"None",
":",
"attributes",
"[",
"'nargs'",
"]",
"=",
"len",
"(",
"func",
".",
"argNames",
")",
"return",
"type",
"(",
"func",
".",
"name",
"+",
"\"_sympy_adaptor\"",
",",
"(",
"sympy",
".",
"Function",
",",
")",
",",
"attributes",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic_sympy.py#L153-L187 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | SizerFlags.Centre | (*args, **kwargs) | return _core_.SizerFlags_Centre(*args, **kwargs) | Centre(self) -> SizerFlags
Same as `Center` for those with an alternate dialect of English. | Centre(self) -> SizerFlags | [
"Centre",
"(",
"self",
")",
"-",
">",
"SizerFlags"
] | def Centre(*args, **kwargs):
"""
Centre(self) -> SizerFlags
Same as `Center` for those with an alternate dialect of English.
"""
return _core_.SizerFlags_Centre(*args, **kwargs) | [
"def",
"Centre",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerFlags_Centre",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13798-L13804 | |
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | tools/infer/predict_det.py | python | TextDetector.order_points_clockwise | (self, pts) | return rect | reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
# sort the points based on their x-coordinates | reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
# sort the points based on their x-coordinates | [
"reference",
"from",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"jrosebr1",
"/",
"imutils",
"/",
"blob",
"/",
"master",
"/",
"imutils",
"/",
"perspective",
".",
"py",
"#",
"sort",
"the",
"points",
"based",
"on",
"their",
"x",
"-",
"coordinates"
] | def order_points_clockwise(self, pts):
"""
reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
# sort the points based on their x-coordinates
"""
xSorted = pts[np.argsort(pts[:, 0]), :]
# grab the left-most and right-most points from the sorted
# x-roodinate points
leftMost = xSorted[:2, :]
rightMost = xSorted[2:, :]
# now, sort the left-most coordinates according to their
# y-coordinates so we can grab the top-left and bottom-left
# points, respectively
leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
(tl, bl) = leftMost
rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
(tr, br) = rightMost
rect = np.array([tl, tr, br, bl], dtype="float32")
return rect | [
"def",
"order_points_clockwise",
"(",
"self",
",",
"pts",
")",
":",
"xSorted",
"=",
"pts",
"[",
"np",
".",
"argsort",
"(",
"pts",
"[",
":",
",",
"0",
"]",
")",
",",
":",
"]",
"# grab the left-most and right-most points from the sorted",
"# x-roodinate points",
"leftMost",
"=",
"xSorted",
"[",
":",
"2",
",",
":",
"]",
"rightMost",
"=",
"xSorted",
"[",
"2",
":",
",",
":",
"]",
"# now, sort the left-most coordinates according to their",
"# y-coordinates so we can grab the top-left and bottom-left",
"# points, respectively",
"leftMost",
"=",
"leftMost",
"[",
"np",
".",
"argsort",
"(",
"leftMost",
"[",
":",
",",
"1",
"]",
")",
",",
":",
"]",
"(",
"tl",
",",
"bl",
")",
"=",
"leftMost",
"rightMost",
"=",
"rightMost",
"[",
"np",
".",
"argsort",
"(",
"rightMost",
"[",
":",
",",
"1",
"]",
")",
",",
":",
"]",
"(",
"tr",
",",
"br",
")",
"=",
"rightMost",
"rect",
"=",
"np",
".",
"array",
"(",
"[",
"tl",
",",
"tr",
",",
"br",
",",
"bl",
"]",
",",
"dtype",
"=",
"\"float32\"",
")",
"return",
"rect"
] | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/tools/infer/predict_det.py#L139-L161 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/inspect_checkpoint.py | python | print_tensors_in_checkpoint_file | (file_name, tensor_name, all_tensors,
all_tensor_names=False,
count_exclude_pattern="") | Prints tensors in a checkpoint file.
If no `tensor_name` is provided, prints the tensor names and shapes
in the checkpoint file.
If `tensor_name` is provided, prints the content of the tensor.
Args:
file_name: Name of the checkpoint file.
tensor_name: Name of the tensor in the checkpoint file to print.
all_tensors: Boolean indicating whether to print all tensors.
all_tensor_names: Boolean indicating whether to print all tensor names.
count_exclude_pattern: Regex string, pattern to exclude tensors when count. | Prints tensors in a checkpoint file. | [
"Prints",
"tensors",
"in",
"a",
"checkpoint",
"file",
"."
] | def print_tensors_in_checkpoint_file(file_name, tensor_name, all_tensors,
all_tensor_names=False,
count_exclude_pattern=""):
"""Prints tensors in a checkpoint file.
If no `tensor_name` is provided, prints the tensor names and shapes
in the checkpoint file.
If `tensor_name` is provided, prints the content of the tensor.
Args:
file_name: Name of the checkpoint file.
tensor_name: Name of the tensor in the checkpoint file to print.
all_tensors: Boolean indicating whether to print all tensors.
all_tensor_names: Boolean indicating whether to print all tensor names.
count_exclude_pattern: Regex string, pattern to exclude tensors when count.
"""
try:
reader = pywrap_tensorflow.NewCheckpointReader(file_name)
if all_tensors or all_tensor_names:
var_to_shape_map = reader.get_variable_to_shape_map()
for key in sorted(var_to_shape_map):
print("tensor_name: ", key)
if all_tensors:
print(reader.get_tensor(key))
elif not tensor_name:
print(reader.debug_string().decode("utf-8"))
else:
print("tensor_name: ", tensor_name)
print(reader.get_tensor(tensor_name))
# Count total number of parameters
print("# Total number of params: %d" % _count_total_params(
reader, count_exclude_pattern=count_exclude_pattern))
except Exception as e: # pylint: disable=broad-except
print(str(e))
if "corrupted compressed block contents" in str(e):
print("It's likely that your checkpoint file has been compressed "
"with SNAPPY.")
if ("Data loss" in str(e) and
any(e in file_name for e in [".index", ".meta", ".data"])):
proposed_file = ".".join(file_name.split(".")[0:-1])
v2_file_error_template = """
It's likely that this is a V2 checkpoint and you need to provide the filename
*prefix*. Try removing the '.' and extension. Try:
inspect checkpoint --file_name = {}"""
print(v2_file_error_template.format(proposed_file)) | [
"def",
"print_tensors_in_checkpoint_file",
"(",
"file_name",
",",
"tensor_name",
",",
"all_tensors",
",",
"all_tensor_names",
"=",
"False",
",",
"count_exclude_pattern",
"=",
"\"\"",
")",
":",
"try",
":",
"reader",
"=",
"pywrap_tensorflow",
".",
"NewCheckpointReader",
"(",
"file_name",
")",
"if",
"all_tensors",
"or",
"all_tensor_names",
":",
"var_to_shape_map",
"=",
"reader",
".",
"get_variable_to_shape_map",
"(",
")",
"for",
"key",
"in",
"sorted",
"(",
"var_to_shape_map",
")",
":",
"print",
"(",
"\"tensor_name: \"",
",",
"key",
")",
"if",
"all_tensors",
":",
"print",
"(",
"reader",
".",
"get_tensor",
"(",
"key",
")",
")",
"elif",
"not",
"tensor_name",
":",
"print",
"(",
"reader",
".",
"debug_string",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"else",
":",
"print",
"(",
"\"tensor_name: \"",
",",
"tensor_name",
")",
"print",
"(",
"reader",
".",
"get_tensor",
"(",
"tensor_name",
")",
")",
"# Count total number of parameters",
"print",
"(",
"\"# Total number of params: %d\"",
"%",
"_count_total_params",
"(",
"reader",
",",
"count_exclude_pattern",
"=",
"count_exclude_pattern",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"print",
"(",
"str",
"(",
"e",
")",
")",
"if",
"\"corrupted compressed block contents\"",
"in",
"str",
"(",
"e",
")",
":",
"print",
"(",
"\"It's likely that your checkpoint file has been compressed \"",
"\"with SNAPPY.\"",
")",
"if",
"(",
"\"Data loss\"",
"in",
"str",
"(",
"e",
")",
"and",
"any",
"(",
"e",
"in",
"file_name",
"for",
"e",
"in",
"[",
"\".index\"",
",",
"\".meta\"",
",",
"\".data\"",
"]",
")",
")",
":",
"proposed_file",
"=",
"\".\"",
".",
"join",
"(",
"file_name",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
":",
"-",
"1",
"]",
")",
"v2_file_error_template",
"=",
"\"\"\"\nIt's likely that this is a V2 checkpoint and you need to provide the filename\n*prefix*. Try removing the '.' and extension. Try:\ninspect checkpoint --file_name = {}\"\"\"",
"print",
"(",
"v2_file_error_template",
".",
"format",
"(",
"proposed_file",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/inspect_checkpoint.py#L57-L103 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/protobuf/python/google/protobuf/internal/decoder.py | python | _FieldSkipper | () | return SkipField | Constructs the SkipField function. | Constructs the SkipField function. | [
"Constructs",
"the",
"SkipField",
"function",
"."
] | def _FieldSkipper():
"""Constructs the SkipField function."""
WIRETYPE_TO_SKIPPER = [
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
]
wiretype_mask = wire_format.TAG_TYPE_MASK
local_ord = ord
def SkipField(buffer, pos, end, tag_bytes):
"""Skips a field with the specified tag.
|pos| should point to the byte immediately after the tag.
Returns:
The new position (after the tag value), or -1 if the tag is an end-group
tag (in which case the calling loop should break).
"""
# The wire type is always in the first byte since varints are little-endian.
wire_type = local_ord(tag_bytes[0]) & wiretype_mask
return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)
return SkipField | [
"def",
"_FieldSkipper",
"(",
")",
":",
"WIRETYPE_TO_SKIPPER",
"=",
"[",
"_SkipVarint",
",",
"_SkipFixed64",
",",
"_SkipLengthDelimited",
",",
"_SkipGroup",
",",
"_EndGroup",
",",
"_SkipFixed32",
",",
"_RaiseInvalidWireType",
",",
"_RaiseInvalidWireType",
",",
"]",
"wiretype_mask",
"=",
"wire_format",
".",
"TAG_TYPE_MASK",
"local_ord",
"=",
"ord",
"def",
"SkipField",
"(",
"buffer",
",",
"pos",
",",
"end",
",",
"tag_bytes",
")",
":",
"\"\"\"Skips a field with the specified tag.\n\n |pos| should point to the byte immediately after the tag.\n\n Returns:\n The new position (after the tag value), or -1 if the tag is an end-group\n tag (in which case the calling loop should break).\n \"\"\"",
"# The wire type is always in the first byte since varints are little-endian.",
"wire_type",
"=",
"local_ord",
"(",
"tag_bytes",
"[",
"0",
"]",
")",
"&",
"wiretype_mask",
"return",
"WIRETYPE_TO_SKIPPER",
"[",
"wire_type",
"]",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
"return",
"SkipField"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/decoder.py#L687-L718 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/_gl_pickle.py | python | _is_not_pickle_safe_gl_model_class | (obj_class) | return False | Check if a GraphLab create model is pickle safe.
The function does it by checking that _CustomModel is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the GLC class is a model and is pickle safe. | Check if a GraphLab create model is pickle safe. | [
"Check",
"if",
"a",
"GraphLab",
"create",
"model",
"is",
"pickle",
"safe",
"."
] | def _is_not_pickle_safe_gl_model_class(obj_class):
"""
Check if a GraphLab create model is pickle safe.
The function does it by checking that _CustomModel is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the GLC class is a model and is pickle safe.
"""
if issubclass(obj_class, _toolkits._model.CustomModel):
return not obj_class._is_gl_pickle_safe()
return False | [
"def",
"_is_not_pickle_safe_gl_model_class",
"(",
"obj_class",
")",
":",
"if",
"issubclass",
"(",
"obj_class",
",",
"_toolkits",
".",
"_model",
".",
"CustomModel",
")",
":",
"return",
"not",
"obj_class",
".",
"_is_gl_pickle_safe",
"(",
")",
"return",
"False"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/_gl_pickle.py#L32-L49 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.IsRuleRunUnderCygwin | (self, rule) | return int(rule.get('msvs_cygwin_shell',
self.spec.get('msvs_cygwin_shell', 1))) != 0 | Determine if an action should be run under cygwin. If the variable is
unset, or set to 1 we use cygwin. | Determine if an action should be run under cygwin. If the variable is
unset, or set to 1 we use cygwin. | [
"Determine",
"if",
"an",
"action",
"should",
"be",
"run",
"under",
"cygwin",
".",
"If",
"the",
"variable",
"is",
"unset",
"or",
"set",
"to",
"1",
"we",
"use",
"cygwin",
"."
] | def IsRuleRunUnderCygwin(self, rule):
"""Determine if an action should be run under cygwin. If the variable is
unset, or set to 1 we use cygwin."""
return int(rule.get('msvs_cygwin_shell',
self.spec.get('msvs_cygwin_shell', 1))) != 0 | [
"def",
"IsRuleRunUnderCygwin",
"(",
"self",
",",
"rule",
")",
":",
"return",
"int",
"(",
"rule",
".",
"get",
"(",
"'msvs_cygwin_shell'",
",",
"self",
".",
"spec",
".",
"get",
"(",
"'msvs_cygwin_shell'",
",",
"1",
")",
")",
")",
"!=",
"0"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L811-L815 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/fispact.py | python | read_summary_data | (data) | return sum_data | Processes the summary block at the end of the file | Processes the summary block at the end of the file | [
"Processes",
"the",
"summary",
"block",
"at",
"the",
"end",
"of",
"the",
"file"
] | def read_summary_data(data):
""" Processes the summary block at the end of the file"""
if isFisII(data):
cool_str = " -----Irradiation Phase-----"
else:
cool_str = " COOLING STEPS"
start_ind = data.index(cool_str)
end_ind = [i for i, line in enumerate(data) if "0 Mass" in line]
sum_lines = data[start_ind+1:end_ind[0]]
sum_data = []
time_yrs = []
act = []
act_un = []
dr = []
dr_un = []
heat = []
heat_un = []
ing = []
ing_un = []
inhal = []
inhal_un = []
trit = []
to = 0
for l in sum_lines:
if isFisII(data):
if l[1] == "-":
to = time_yrs[-1]
else:
time_yrs.append(float(l[24:32]) + to)
act.append(l[35:43])
dr.append(l[58:66])
heat.append(l[81:89])
ing.append(l[104:112])
inhal.append(l[127:135])
trit.append(l[150:158])
else:
time_yrs.append(l[20:28])
act.append(l[31:39])
dr.append(l[54:62])
heat.append(l[77:85])
ing.append(l[100:108])
inhal.append(l[123:131])
trit.append(l[146:154])
sum_data.append(time_yrs)
sum_data.append(act)
sum_data.append(dr)
sum_data.append(heat)
sum_data.append(ing)
sum_data.append(inhal)
sum_data.append(trit)
sum_data.append(act_un)
sum_data.append(dr_un)
sum_data.append(heat_un)
sum_data.append(ing_un)
sum_data.append(inhal_un)
return sum_data | [
"def",
"read_summary_data",
"(",
"data",
")",
":",
"if",
"isFisII",
"(",
"data",
")",
":",
"cool_str",
"=",
"\" -----Irradiation Phase-----\"",
"else",
":",
"cool_str",
"=",
"\" COOLING STEPS\"",
"start_ind",
"=",
"data",
".",
"index",
"(",
"cool_str",
")",
"end_ind",
"=",
"[",
"i",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"data",
")",
"if",
"\"0 Mass\"",
"in",
"line",
"]",
"sum_lines",
"=",
"data",
"[",
"start_ind",
"+",
"1",
":",
"end_ind",
"[",
"0",
"]",
"]",
"sum_data",
"=",
"[",
"]",
"time_yrs",
"=",
"[",
"]",
"act",
"=",
"[",
"]",
"act_un",
"=",
"[",
"]",
"dr",
"=",
"[",
"]",
"dr_un",
"=",
"[",
"]",
"heat",
"=",
"[",
"]",
"heat_un",
"=",
"[",
"]",
"ing",
"=",
"[",
"]",
"ing_un",
"=",
"[",
"]",
"inhal",
"=",
"[",
"]",
"inhal_un",
"=",
"[",
"]",
"trit",
"=",
"[",
"]",
"to",
"=",
"0",
"for",
"l",
"in",
"sum_lines",
":",
"if",
"isFisII",
"(",
"data",
")",
":",
"if",
"l",
"[",
"1",
"]",
"==",
"\"-\"",
":",
"to",
"=",
"time_yrs",
"[",
"-",
"1",
"]",
"else",
":",
"time_yrs",
".",
"append",
"(",
"float",
"(",
"l",
"[",
"24",
":",
"32",
"]",
")",
"+",
"to",
")",
"act",
".",
"append",
"(",
"l",
"[",
"35",
":",
"43",
"]",
")",
"dr",
".",
"append",
"(",
"l",
"[",
"58",
":",
"66",
"]",
")",
"heat",
".",
"append",
"(",
"l",
"[",
"81",
":",
"89",
"]",
")",
"ing",
".",
"append",
"(",
"l",
"[",
"104",
":",
"112",
"]",
")",
"inhal",
".",
"append",
"(",
"l",
"[",
"127",
":",
"135",
"]",
")",
"trit",
".",
"append",
"(",
"l",
"[",
"150",
":",
"158",
"]",
")",
"else",
":",
"time_yrs",
".",
"append",
"(",
"l",
"[",
"20",
":",
"28",
"]",
")",
"act",
".",
"append",
"(",
"l",
"[",
"31",
":",
"39",
"]",
")",
"dr",
".",
"append",
"(",
"l",
"[",
"54",
":",
"62",
"]",
")",
"heat",
".",
"append",
"(",
"l",
"[",
"77",
":",
"85",
"]",
")",
"ing",
".",
"append",
"(",
"l",
"[",
"100",
":",
"108",
"]",
")",
"inhal",
".",
"append",
"(",
"l",
"[",
"123",
":",
"131",
"]",
")",
"trit",
".",
"append",
"(",
"l",
"[",
"146",
":",
"154",
"]",
")",
"sum_data",
".",
"append",
"(",
"time_yrs",
")",
"sum_data",
".",
"append",
"(",
"act",
")",
"sum_data",
".",
"append",
"(",
"dr",
")",
"sum_data",
".",
"append",
"(",
"heat",
")",
"sum_data",
".",
"append",
"(",
"ing",
")",
"sum_data",
".",
"append",
"(",
"inhal",
")",
"sum_data",
".",
"append",
"(",
"trit",
")",
"sum_data",
".",
"append",
"(",
"act_un",
")",
"sum_data",
".",
"append",
"(",
"dr_un",
")",
"sum_data",
".",
"append",
"(",
"heat_un",
")",
"sum_data",
".",
"append",
"(",
"ing_un",
")",
"sum_data",
".",
"append",
"(",
"inhal_un",
")",
"return",
"sum_data"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/fispact.py#L211-L272 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | GridSizer.CalcRowsCols | (self) | return (rows, cols) | CalcRowsCols() -> (rows, cols)
Calculates how many rows and columns will be in the sizer based
on the current number of items and also the rows, cols specified
in the constructor. | CalcRowsCols() -> (rows, cols) | [
"CalcRowsCols",
"()",
"-",
">",
"(",
"rows",
"cols",
")"
] | def CalcRowsCols(self):
"""
CalcRowsCols() -> (rows, cols)
Calculates how many rows and columns will be in the sizer based
on the current number of items and also the rows, cols specified
in the constructor.
"""
nitems = len(self.GetChildren())
rows = self.GetRows()
cols = self.GetCols()
assert rows != 0 or cols != 0, "Grid sizer must have either rows or columns fixed"
if cols != 0:
rows = (nitems + cols - 1) / cols
elif rows != 0:
cols = (nitems + rows - 1) / rows
return (rows, cols) | [
"def",
"CalcRowsCols",
"(",
"self",
")",
":",
"nitems",
"=",
"len",
"(",
"self",
".",
"GetChildren",
"(",
")",
")",
"rows",
"=",
"self",
".",
"GetRows",
"(",
")",
"cols",
"=",
"self",
".",
"GetCols",
"(",
")",
"assert",
"rows",
"!=",
"0",
"or",
"cols",
"!=",
"0",
",",
"\"Grid sizer must have either rows or columns fixed\"",
"if",
"cols",
"!=",
"0",
":",
"rows",
"=",
"(",
"nitems",
"+",
"cols",
"-",
"1",
")",
"/",
"cols",
"elif",
"rows",
"!=",
"0",
":",
"cols",
"=",
"(",
"nitems",
"+",
"rows",
"-",
"1",
")",
"/",
"rows",
"return",
"(",
"rows",
",",
"cols",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L15277-L15293 | |
apple/swift-clang | d7403439fc6641751840b723e7165fb02f52db95 | tools/scan-build-py/libscanbuild/__init__.py | python | wrapper_environment | (args) | return {
ENVIRONMENT_KEY: json.dumps({
'verbose': args.verbose,
'cc': shlex.split(args.cc),
'cxx': shlex.split(args.cxx)
})
} | Set up environment for interpose compiler wrapper. | Set up environment for interpose compiler wrapper. | [
"Set",
"up",
"environment",
"for",
"interpose",
"compiler",
"wrapper",
"."
] | def wrapper_environment(args):
""" Set up environment for interpose compiler wrapper."""
return {
ENVIRONMENT_KEY: json.dumps({
'verbose': args.verbose,
'cc': shlex.split(args.cc),
'cxx': shlex.split(args.cxx)
})
} | [
"def",
"wrapper_environment",
"(",
"args",
")",
":",
"return",
"{",
"ENVIRONMENT_KEY",
":",
"json",
".",
"dumps",
"(",
"{",
"'verbose'",
":",
"args",
".",
"verbose",
",",
"'cc'",
":",
"shlex",
".",
"split",
"(",
"args",
".",
"cc",
")",
",",
"'cxx'",
":",
"shlex",
".",
"split",
"(",
"args",
".",
"cxx",
")",
"}",
")",
"}"
] | https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/tools/scan-build-py/libscanbuild/__init__.py#L198-L207 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> RichTextCtrl | __init__(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> RichTextCtrl | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"String",
"value",
"=",
"EmptyString",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"RE_MULTILINE",
"Validator",
"validator",
"=",
"DefaultValidator",
"String",
"name",
"=",
"RichTextCtrlNameStr",
")",
"-",
">",
"RichTextCtrl"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String value=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=RE_MULTILINE, Validator validator=DefaultValidator,
String name=RichTextCtrlNameStr) -> RichTextCtrl
"""
_richtext.RichTextCtrl_swiginit(self,_richtext.new_RichTextCtrl(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_richtext",
".",
"RichTextCtrl_swiginit",
"(",
"self",
",",
"_richtext",
".",
"new_RichTextCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2904-L2912 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | RobotModelLink.getWorldDirection | (self, vlocal: Point) | return _robotsim.RobotModelLink_getWorldDirection(self, vlocal) | r"""
Converts direction from local to world coordinates.
Args:
vlocal (:obj:`list of 3 floats`)
Returns:
list of 3 floats: the world coordinates of the local direction
vlocal | r"""
Converts direction from local to world coordinates. | [
"r",
"Converts",
"direction",
"from",
"local",
"to",
"world",
"coordinates",
"."
] | def getWorldDirection(self, vlocal: Point) ->None:
r"""
Converts direction from local to world coordinates.
Args:
vlocal (:obj:`list of 3 floats`)
Returns:
list of 3 floats: the world coordinates of the local direction
vlocal
"""
return _robotsim.RobotModelLink_getWorldDirection(self, vlocal) | [
"def",
"getWorldDirection",
"(",
"self",
",",
"vlocal",
":",
"Point",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"RobotModelLink_getWorldDirection",
"(",
"self",
",",
"vlocal",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L4094-L4107 | |
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | scripts/cpp_lint.py | python | _IncludeState.CheckNextIncludeOrder | (self, header_type) | return '' | Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong. | Returns a non-empty error message if the next header is out of order. | [
"Returns",
"a",
"non",
"-",
"empty",
"error",
"message",
"if",
"the",
"next",
"header",
"is",
"out",
"of",
"order",
"."
] | def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return '' | [
"def",
"CheckNextIncludeOrder",
"(",
"self",
",",
"header_type",
")",
":",
"error_message",
"=",
"(",
"'Found %s after %s'",
"%",
"(",
"self",
".",
"_TYPE_NAMES",
"[",
"header_type",
"]",
",",
"self",
".",
"_SECTION_NAMES",
"[",
"self",
".",
"_section",
"]",
")",
")",
"last_section",
"=",
"self",
".",
"_section",
"if",
"header_type",
"==",
"_C_SYS_HEADER",
":",
"if",
"self",
".",
"_section",
"<=",
"self",
".",
"_C_SECTION",
":",
"self",
".",
"_section",
"=",
"self",
".",
"_C_SECTION",
"else",
":",
"self",
".",
"_last_header",
"=",
"''",
"return",
"error_message",
"elif",
"header_type",
"==",
"_CPP_SYS_HEADER",
":",
"if",
"self",
".",
"_section",
"<=",
"self",
".",
"_CPP_SECTION",
":",
"self",
".",
"_section",
"=",
"self",
".",
"_CPP_SECTION",
"else",
":",
"self",
".",
"_last_header",
"=",
"''",
"return",
"error_message",
"elif",
"header_type",
"==",
"_LIKELY_MY_HEADER",
":",
"if",
"self",
".",
"_section",
"<=",
"self",
".",
"_MY_H_SECTION",
":",
"self",
".",
"_section",
"=",
"self",
".",
"_MY_H_SECTION",
"else",
":",
"self",
".",
"_section",
"=",
"self",
".",
"_OTHER_H_SECTION",
"elif",
"header_type",
"==",
"_POSSIBLE_MY_HEADER",
":",
"if",
"self",
".",
"_section",
"<=",
"self",
".",
"_MY_H_SECTION",
":",
"self",
".",
"_section",
"=",
"self",
".",
"_MY_H_SECTION",
"else",
":",
"# This will always be the fallback because we're not sure",
"# enough that the header is associated with this file.",
"self",
".",
"_section",
"=",
"self",
".",
"_OTHER_H_SECTION",
"else",
":",
"assert",
"header_type",
"==",
"_OTHER_HEADER",
"self",
".",
"_section",
"=",
"self",
".",
"_OTHER_H_SECTION",
"if",
"last_section",
"!=",
"self",
".",
"_section",
":",
"self",
".",
"_last_header",
"=",
"''",
"return",
"''"
] | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L637-L688 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/function.py | python | ConcreteFunction._build_call_outputs | (self, result) | return ret | Maps the fdef output list to actual output structure.
Args:
result: Output lists defined by FunctionDef.
Returns:
The actual call output. | Maps the fdef output list to actual output structure. | [
"Maps",
"the",
"fdef",
"output",
"list",
"to",
"actual",
"output",
"structure",
"."
] | def _build_call_outputs(self, result):
"""Maps the fdef output list to actual output structure.
Args:
result: Output lists defined by FunctionDef.
Returns:
The actual call output.
"""
# TODO(jlchu): call C++ version in function.cc when speed is improved
if self._func_graph.structured_outputs is None:
return result
# Replace outputs with results, skipping over any 'None' values.
outputs_list = nest.flatten(
self._func_graph.structured_outputs, expand_composites=True)
j = 0
for i, o in enumerate(outputs_list):
if o is not None:
handle_data_util.copy_handle_data(self.outputs[j], result[j])
outputs_list[i] = result[j]
j += 1
ret = nest.pack_sequence_as(self._func_graph.structured_outputs,
outputs_list, expand_composites=True)
return ret | [
"def",
"_build_call_outputs",
"(",
"self",
",",
"result",
")",
":",
"# TODO(jlchu): call C++ version in function.cc when speed is improved",
"if",
"self",
".",
"_func_graph",
".",
"structured_outputs",
"is",
"None",
":",
"return",
"result",
"# Replace outputs with results, skipping over any 'None' values.",
"outputs_list",
"=",
"nest",
".",
"flatten",
"(",
"self",
".",
"_func_graph",
".",
"structured_outputs",
",",
"expand_composites",
"=",
"True",
")",
"j",
"=",
"0",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"outputs_list",
")",
":",
"if",
"o",
"is",
"not",
"None",
":",
"handle_data_util",
".",
"copy_handle_data",
"(",
"self",
".",
"outputs",
"[",
"j",
"]",
",",
"result",
"[",
"j",
"]",
")",
"outputs_list",
"[",
"i",
"]",
"=",
"result",
"[",
"j",
"]",
"j",
"+=",
"1",
"ret",
"=",
"nest",
".",
"pack_sequence_as",
"(",
"self",
".",
"_func_graph",
".",
"structured_outputs",
",",
"outputs_list",
",",
"expand_composites",
"=",
"True",
")",
"return",
"ret"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/function.py#L2204-L2227 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/symbols.py | python | Scope.force_global | (self, name) | Force name to be global in scope.
Some child of the current node had a free reference to name.
When the child was processed, it was labelled a free
variable. Now that all its enclosing scope have been
processed, the name is known to be a global or builtin. So
walk back down the child chain and set the name to be global
rather than free.
Be careful to stop if a child does not think the name is
free. | Force name to be global in scope. | [
"Force",
"name",
"to",
"be",
"global",
"in",
"scope",
"."
] | def force_global(self, name):
"""Force name to be global in scope.
Some child of the current node had a free reference to name.
When the child was processed, it was labelled a free
variable. Now that all its enclosing scope have been
processed, the name is known to be a global or builtin. So
walk back down the child chain and set the name to be global
rather than free.
Be careful to stop if a child does not think the name is
free.
"""
self.globals[name] = 1
if name in self.frees:
del self.frees[name]
for child in self.children:
if child.check_name(name) == SC_FREE:
child.force_global(name) | [
"def",
"force_global",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"globals",
"[",
"name",
"]",
"=",
"1",
"if",
"name",
"in",
"self",
".",
"frees",
":",
"del",
"self",
".",
"frees",
"[",
"name",
"]",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"child",
".",
"check_name",
"(",
"name",
")",
"==",
"SC_FREE",
":",
"child",
".",
"force_global",
"(",
"name",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/symbols.py#L122-L140 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextLine.Clone | (*args, **kwargs) | return _richtext.RichTextLine_Clone(*args, **kwargs) | Clone(self) -> RichTextLine | Clone(self) -> RichTextLine | [
"Clone",
"(",
"self",
")",
"-",
">",
"RichTextLine"
] | def Clone(*args, **kwargs):
"""Clone(self) -> RichTextLine"""
return _richtext.RichTextLine_Clone(*args, **kwargs) | [
"def",
"Clone",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextLine_Clone",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1959-L1961 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.