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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/tools/docs/py_guide_parser.py | python | PyGuideParser.process | (self, full_path) | return ret | Read and process the file at `full_path`. | Read and process the file at `full_path`. | [
"Read",
"and",
"process",
"the",
"file",
"at",
"full_path",
"."
] | def process(self, full_path):
"""Read and process the file at `full_path`."""
md_string = open(full_path).read()
self._lines = md_string.split('\n')
seen = set()
in_blockquote = False
for i, line in enumerate(self._lines):
if '```' in line:
in_blockquote = not in_blockquote
if not in_blockquote and line.startswith('# '):
self.process_title(i, line[2:])
elif not in_blockquote and line.startswith('## '):
section_title = line.strip()[3:]
existing_tag = re.search(' {([^}]+)} *$', line)
if existing_tag:
tag = existing_tag.group(1)
else:
tag = re.sub('[^a-zA-Z0-9]+', '_', section_title)
if tag in seen:
suffix = 0
while True:
candidate = '%s_%d' % (tag, suffix)
if candidate not in seen:
tag = candidate
break
seen.add(tag)
self.process_section(i, section_title, tag)
elif in_blockquote:
self.process_in_blockquote(i, line)
else:
self.process_line(i, line)
ret = '\n'.join(self._lines)
self._lines = None
return ret | [
"def",
"process",
"(",
"self",
",",
"full_path",
")",
":",
"md_string",
"=",
"open",
"(",
"full_path",
")",
".",
"read",
"(",
")",
"self",
".",
"_lines",
"=",
"md_string",
".",
"split",
"(",
"'\\n'",
")",
"seen",
"=",
"set",
"(",
")",
"in_blockquote",
"=",
"False",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"self",
".",
"_lines",
")",
":",
"if",
"'```'",
"in",
"line",
":",
"in_blockquote",
"=",
"not",
"in_blockquote",
"if",
"not",
"in_blockquote",
"and",
"line",
".",
"startswith",
"(",
"'# '",
")",
":",
"self",
".",
"process_title",
"(",
"i",
",",
"line",
"[",
"2",
":",
"]",
")",
"elif",
"not",
"in_blockquote",
"and",
"line",
".",
"startswith",
"(",
"'## '",
")",
":",
"section_title",
"=",
"line",
".",
"strip",
"(",
")",
"[",
"3",
":",
"]",
"existing_tag",
"=",
"re",
".",
"search",
"(",
"' {([^}]+)} *$'",
",",
"line",
")",
"if",
"existing_tag",
":",
"tag",
"=",
"existing_tag",
".",
"group",
"(",
"1",
")",
"else",
":",
"tag",
"=",
"re",
".",
"sub",
"(",
"'[^a-zA-Z0-9]+'",
",",
"'_'",
",",
"section_title",
")",
"if",
"tag",
"in",
"seen",
":",
"suffix",
"=",
"0",
"while",
"True",
":",
"candidate",
"=",
"'%s_%d'",
"%",
"(",
"tag",
",",
"suffix",
")",
"if",
"candidate",
"not",
"in",
"seen",
":",
"tag",
"=",
"candidate",
"break",
"seen",
".",
"add",
"(",
"tag",
")",
"self",
".",
"process_section",
"(",
"i",
",",
"section_title",
",",
"tag",
")",
"elif",
"in_blockquote",
":",
"self",
".",
"process_in_blockquote",
"(",
"i",
",",
"line",
")",
"else",
":",
"self",
".",
"process_line",
"(",
"i",
",",
"line",
")",
"ret",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"_lines",
")",
"self",
".",
"_lines",
"=",
"None",
"return",
"ret"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/tools/docs/py_guide_parser.py#L45-L82 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/database.py | python | InstalledDistribution.read_exports | (self) | return result | Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries. | Read exports data from a file in .ini format. | [
"Read",
"exports",
"data",
"from",
"a",
"file",
"in",
".",
"ini",
"format",
"."
] | def read_exports(self):
"""
Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries.
"""
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
with contextlib.closing(r.as_stream()) as stream:
result = read_exports(stream)
return result | [
"def",
"read_exports",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"r",
"=",
"self",
".",
"get_distinfo_resource",
"(",
"EXPORTS_FILENAME",
")",
"if",
"r",
":",
"with",
"contextlib",
".",
"closing",
"(",
"r",
".",
"as_stream",
"(",
")",
")",
"as",
"stream",
":",
"result",
"=",
"read_exports",
"(",
"stream",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/database.py#L617-L630 | |
gnina/gnina | b9ae032f52fc7a8153987bde09c0efa3620d8bb6 | caffe/scripts/cpp_lint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [ or <, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"or",
"<",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
startchar = line[pos]
if startchar not in '({[<':
return (line, clean_lines.NumLines(), -1)
if startchar == '(': endchar = ')'
if startchar == '[': endchar = ']'
if startchar == '{': endchar = '}'
if startchar == '<': endchar = '>'
# Check first line
(end_pos, num_open) = FindEndOfExpressionInLine(
line, pos, 0, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, num_open) = FindEndOfExpressionInLine(
line, 0, num_open, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find endchar before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"startchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"startchar",
"not",
"in",
"'({[<'",
":",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")",
"if",
"startchar",
"==",
"'('",
":",
"endchar",
"=",
"')'",
"if",
"startchar",
"==",
"'['",
":",
"endchar",
"=",
"']'",
"if",
"startchar",
"==",
"'{'",
":",
"endchar",
"=",
"'}'",
"if",
"startchar",
"==",
"'<'",
":",
"endchar",
"=",
"'>'",
"# Check first line",
"(",
"end_pos",
",",
"num_open",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"pos",
",",
"0",
",",
"startchar",
",",
"endchar",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Continue scanning forward",
"while",
"linenum",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
"-",
"1",
":",
"linenum",
"+=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"(",
"end_pos",
",",
"num_open",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"0",
",",
"num_open",
",",
"startchar",
",",
"endchar",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Did not find endchar before end of file, give up",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")"
] | https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/scripts/cpp_lint.py#L1258-L1301 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Platform/virtualenv.py | python | Virtualenv | () | return None | Returns path to the virtualenv home if scons is executing within a
virtualenv or None, if not. | Returns path to the virtualenv home if scons is executing within a
virtualenv or None, if not. | [
"Returns",
"path",
"to",
"the",
"virtualenv",
"home",
"if",
"scons",
"is",
"executing",
"within",
"a",
"virtualenv",
"or",
"None",
"if",
"not",
"."
] | def Virtualenv():
"""Returns path to the virtualenv home if scons is executing within a
virtualenv or None, if not."""
if _running_in_virtualenv():
return sys.prefix
return None | [
"def",
"Virtualenv",
"(",
")",
":",
"if",
"_running_in_virtualenv",
"(",
")",
":",
"return",
"sys",
".",
"prefix",
"return",
"None"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Platform/virtualenv.py#L97-L102 | |
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py | python | AbstractWriter.setGenerateEmptyFile | (self) | This method is used to set a flag indicating that an empty file
should be generated. This is just a flag. It is up to the derived
class to ensure an empty file is generated for the code snippet
producers. | This method is used to set a flag indicating that an empty file
should be generated. This is just a flag. It is up to the derived
class to ensure an empty file is generated for the code snippet
producers. | [
"This",
"method",
"is",
"used",
"to",
"set",
"a",
"flag",
"indicating",
"that",
"an",
"empty",
"file",
"should",
"be",
"generated",
".",
"This",
"is",
"just",
"a",
"flag",
".",
"It",
"is",
"up",
"to",
"the",
"derived",
"class",
"to",
"ensure",
"an",
"empty",
"file",
"is",
"generated",
"for",
"the",
"code",
"snippet",
"producers",
"."
] | def setGenerateEmptyFile(self):
"""
This method is used to set a flag indicating that an empty file
should be generated. This is just a flag. It is up to the derived
class to ensure an empty file is generated for the code snippet
producers.
"""
self.__generate_empty_file = True | [
"def",
"setGenerateEmptyFile",
"(",
"self",
")",
":",
"self",
".",
"__generate_empty_file",
"=",
"True"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py#L43-L50 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/tools/docs/generate_lib.py | python | _is_free_function | (py_object, full_name, index) | return True | Check if input is a free function (and not a class- or static method). | Check if input is a free function (and not a class- or static method). | [
"Check",
"if",
"input",
"is",
"a",
"free",
"function",
"(",
"and",
"not",
"a",
"class",
"-",
"or",
"static",
"method",
")",
"."
] | def _is_free_function(py_object, full_name, index):
"""Check if input is a free function (and not a class- or static method)."""
if not tf_inspect.isfunction(py_object):
return False
# Static methods are functions to tf_inspect (in 2.7), so check if the parent
# is a class. If there is no parent, it's not a function.
if '.' not in full_name:
return False
parent_name = full_name.rsplit('.', 1)[0]
if tf_inspect.isclass(index[parent_name]):
return False
return True | [
"def",
"_is_free_function",
"(",
"py_object",
",",
"full_name",
",",
"index",
")",
":",
"if",
"not",
"tf_inspect",
".",
"isfunction",
"(",
"py_object",
")",
":",
"return",
"False",
"# Static methods are functions to tf_inspect (in 2.7), so check if the parent",
"# is a class. If there is no parent, it's not a function.",
"if",
"'.'",
"not",
"in",
"full_name",
":",
"return",
"False",
"parent_name",
"=",
"full_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"tf_inspect",
".",
"isclass",
"(",
"index",
"[",
"parent_name",
"]",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/tools/docs/generate_lib.py#L36-L50 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | validateNameValue | (value) | return ret | Validate that the given value match Name production | Validate that the given value match Name production | [
"Validate",
"that",
"the",
"given",
"value",
"match",
"Name",
"production"
] | def validateNameValue(value):
"""Validate that the given value match Name production """
ret = libxml2mod.xmlValidateNameValue(value)
return ret | [
"def",
"validateNameValue",
"(",
"value",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateNameValue",
"(",
"value",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L1052-L1055 | |
mysql/mysql-workbench | 2f35f9034f015cbcd22139a60e1baa2e3e8e795c | ext/scintilla/scripts/Dependencies.py | python | ExtractDependencies | (input) | return deps | Create a list of dependencies from input list of lines
Each element contains the name of the object and a list of
files that it depends on.
Dependencies that contain "/usr/" are removed as they are system headers. | Create a list of dependencies from input list of lines
Each element contains the name of the object and a list of
files that it depends on.
Dependencies that contain "/usr/" are removed as they are system headers. | [
"Create",
"a",
"list",
"of",
"dependencies",
"from",
"input",
"list",
"of",
"lines",
"Each",
"element",
"contains",
"the",
"name",
"of",
"the",
"object",
"and",
"a",
"list",
"of",
"files",
"that",
"it",
"depends",
"on",
".",
"Dependencies",
"that",
"contain",
"/",
"usr",
"/",
"are",
"removed",
"as",
"they",
"are",
"system",
"headers",
"."
] | def ExtractDependencies(input):
""" Create a list of dependencies from input list of lines
Each element contains the name of the object and a list of
files that it depends on.
Dependencies that contain "/usr/" are removed as they are system headers. """
deps = []
for line in input:
headersLine = line.startswith(" ") or line.startswith("\t")
line = line.strip()
isContinued = line.endswith("\\")
line = line.rstrip("\\ ")
fileNames = line.strip().split(" ")
if not headersLine:
# its a source file line, there may be headers too
sourceLine = fileNames[0].rstrip(":")
fileNames = fileNames[1:]
deps.append([sourceLine, []])
deps[-1][1].extend(header for header in fileNames if "/usr/" not in header)
return deps | [
"def",
"ExtractDependencies",
"(",
"input",
")",
":",
"deps",
"=",
"[",
"]",
"for",
"line",
"in",
"input",
":",
"headersLine",
"=",
"line",
".",
"startswith",
"(",
"\" \"",
")",
"or",
"line",
".",
"startswith",
"(",
"\"\\t\"",
")",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"isContinued",
"=",
"line",
".",
"endswith",
"(",
"\"\\\\\"",
")",
"line",
"=",
"line",
".",
"rstrip",
"(",
"\"\\\\ \"",
")",
"fileNames",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
"if",
"not",
"headersLine",
":",
"# its a source file line, there may be headers too",
"sourceLine",
"=",
"fileNames",
"[",
"0",
"]",
".",
"rstrip",
"(",
"\":\"",
")",
"fileNames",
"=",
"fileNames",
"[",
"1",
":",
"]",
"deps",
".",
"append",
"(",
"[",
"sourceLine",
",",
"[",
"]",
"]",
")",
"deps",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
".",
"extend",
"(",
"header",
"for",
"header",
"in",
"fileNames",
"if",
"\"/usr/\"",
"not",
"in",
"header",
")",
"return",
"deps"
] | https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/ext/scintilla/scripts/Dependencies.py#L104-L123 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/genlisp/src/genlisp/generate.py | python | generate_msg_from_spec | (msg_context, spec, search_path, output_dir, package) | Generate a message
@param msg_path: The path to the .msg file
@type msg_path: str | Generate a message | [
"Generate",
"a",
"message"
] | def generate_msg_from_spec(msg_context, spec, search_path, output_dir, package):
"""
Generate a message
@param msg_path: The path to the .msg file
@type msg_path: str
"""
genmsg.msg_loader.load_depends(msg_context, spec, search_path)
spec.actual_name=spec.short_name
spec.component_type='message'
msgs = msg_list(package, search_path, '.msg')
for m in msgs:
genmsg.load_msg_by_type(msg_context, '%s/%s'%(package, m), search_path)
########################################
# 1. Write the .lisp file
########################################
io = StringIO()
s = IndentedWriter(io)
write_begin(s, spec)
write_html_include(s, spec)
write_defclass(s, spec)
write_deprecated_readers(s, spec)
write_constants(s, spec)
write_serialize(s, spec)
write_deserialize(s, spec)
write_ros_datatype(s, spec)
write_md5sum(s, msg_context, spec)
write_message_definition(s, msg_context, spec)
write_serialization_length(s, spec)
write_list_converter(s, spec)
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
with open('%s/%s.lisp'%(output_dir, spec.short_name), 'w') as f:
f.write(io.getvalue() + "\n")
io.close()
########################################
# 2. Write the _package file
# for this message
########################################
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
# This is being rewritten once per msg
# file, which is inefficient
########################################
io = StringIO()
s = IndentedWriter(io)
write_class_exports(s, msgs, package)
with open('%s/_package.lisp'%output_dir, 'w') as f:
f.write(io.getvalue())
io.close()
########################################
# 4. Write the .asd file
# This is being written once per msg
# file, which is inefficient
########################################
io = StringIO()
s = IndentedWriter(io)
write_asd(s, package, msgs, msg_context)
with open('%s/%s-msg.asd'%(output_dir, package), 'w') as f:
f.write(io.getvalue())
io.close() | [
"def",
"generate_msg_from_spec",
"(",
"msg_context",
",",
"spec",
",",
"search_path",
",",
"output_dir",
",",
"package",
")",
":",
"genmsg",
".",
"msg_loader",
".",
"load_depends",
"(",
"msg_context",
",",
"spec",
",",
"search_path",
")",
"spec",
".",
"actual_name",
"=",
"spec",
".",
"short_name",
"spec",
".",
"component_type",
"=",
"'message'",
"msgs",
"=",
"msg_list",
"(",
"package",
",",
"search_path",
",",
"'.msg'",
")",
"for",
"m",
"in",
"msgs",
":",
"genmsg",
".",
"load_msg_by_type",
"(",
"msg_context",
",",
"'%s/%s'",
"%",
"(",
"package",
",",
"m",
")",
",",
"search_path",
")",
"########################################",
"# 1. Write the .lisp file",
"########################################",
"io",
"=",
"StringIO",
"(",
")",
"s",
"=",
"IndentedWriter",
"(",
"io",
")",
"write_begin",
"(",
"s",
",",
"spec",
")",
"write_html_include",
"(",
"s",
",",
"spec",
")",
"write_defclass",
"(",
"s",
",",
"spec",
")",
"write_deprecated_readers",
"(",
"s",
",",
"spec",
")",
"write_constants",
"(",
"s",
",",
"spec",
")",
"write_serialize",
"(",
"s",
",",
"spec",
")",
"write_deserialize",
"(",
"s",
",",
"spec",
")",
"write_ros_datatype",
"(",
"s",
",",
"spec",
")",
"write_md5sum",
"(",
"s",
",",
"msg_context",
",",
"spec",
")",
"write_message_definition",
"(",
"s",
",",
"msg_context",
",",
"spec",
")",
"write_serialization_length",
"(",
"s",
",",
"spec",
")",
"write_list_converter",
"(",
"s",
",",
"spec",
")",
"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",
"with",
"open",
"(",
"'%s/%s.lisp'",
"%",
"(",
"output_dir",
",",
"spec",
".",
"short_name",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"io",
".",
"getvalue",
"(",
")",
"+",
"\"\\n\"",
")",
"io",
".",
"close",
"(",
")",
"########################################",
"# 2. Write the _package file",
"# for this message",
"########################################",
"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",
"# This is being rewritten once per msg",
"# file, which is inefficient",
"########################################",
"io",
"=",
"StringIO",
"(",
")",
"s",
"=",
"IndentedWriter",
"(",
"io",
")",
"write_class_exports",
"(",
"s",
",",
"msgs",
",",
"package",
")",
"with",
"open",
"(",
"'%s/_package.lisp'",
"%",
"output_dir",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"io",
".",
"getvalue",
"(",
")",
")",
"io",
".",
"close",
"(",
")",
"########################################",
"# 4. Write the .asd file",
"# This is being written once per msg",
"# file, which is inefficient",
"########################################",
"io",
"=",
"StringIO",
"(",
")",
"s",
"=",
"IndentedWriter",
"(",
"io",
")",
"write_asd",
"(",
"s",
",",
"package",
",",
"msgs",
",",
"msg_context",
")",
"with",
"open",
"(",
"'%s/%s-msg.asd'",
"%",
"(",
"output_dir",
",",
"package",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"io",
".",
"getvalue",
"(",
")",
")",
"io",
".",
"close",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/genlisp/src/genlisp/generate.py#L741-L823 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.newDocPI | (self, name, content) | return __tmp | Creation of a processing instruction element. | Creation of a processing instruction element. | [
"Creation",
"of",
"a",
"processing",
"instruction",
"element",
"."
] | def newDocPI(self, name, content):
"""Creation of a processing instruction element. """
ret = libxml2mod.xmlNewDocPI(self._o, name, content)
if ret is None:raise treeError('xmlNewDocPI() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newDocPI",
"(",
"self",
",",
"name",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocPI",
"(",
"self",
".",
"_o",
",",
"name",
",",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewDocPI() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4300-L4305 | |
bingwin/MicroChat | 81d9a71a212c1cbca5bba497ec42659a7d25dccf | mars/lint/cpplint.py | python | FileInfo.FullName | (self) | return os.path.abspath(self._filename).replace('\\', '/') | Make Windows paths like Unix. | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix",
"."
] | def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/') | [
"def",
"FullName",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L988-L990 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/adapters.py | python | HTTPAdapter.request_url | (self, request, proxies) | return url | Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
:rtype: str | Obtain the url to use when making the final request. | [
"Obtain",
"the",
"url",
"to",
"use",
"when",
"making",
"the",
"final",
"request",
"."
] | def request_url(self, request, proxies):
"""Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
:rtype: str
"""
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
is_proxied_http_request = (proxy and scheme != 'https')
using_socks_proxy = False
if proxy:
proxy_scheme = urlparse(proxy).scheme.lower()
using_socks_proxy = proxy_scheme.startswith('socks')
url = request.path_url
if is_proxied_http_request and not using_socks_proxy:
url = urldefragauth(request.url)
return url | [
"def",
"request_url",
"(",
"self",
",",
"request",
",",
"proxies",
")",
":",
"proxy",
"=",
"select_proxy",
"(",
"request",
".",
"url",
",",
"proxies",
")",
"scheme",
"=",
"urlparse",
"(",
"request",
".",
"url",
")",
".",
"scheme",
"is_proxied_http_request",
"=",
"(",
"proxy",
"and",
"scheme",
"!=",
"'https'",
")",
"using_socks_proxy",
"=",
"False",
"if",
"proxy",
":",
"proxy_scheme",
"=",
"urlparse",
"(",
"proxy",
")",
".",
"scheme",
".",
"lower",
"(",
")",
"using_socks_proxy",
"=",
"proxy_scheme",
".",
"startswith",
"(",
"'socks'",
")",
"url",
"=",
"request",
".",
"path_url",
"if",
"is_proxied_http_request",
"and",
"not",
"using_socks_proxy",
":",
"url",
"=",
"urldefragauth",
"(",
"request",
".",
"url",
")",
"return",
"url"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/adapters.py#L323-L350 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Node/FS.py | python | File.changed_timestamp_match | (self, target, prev_ni, repo_node=None) | Return True if the timestamps don't match or if there is no previous timestamp
:param target:
:param prev_ni: Information about the node from the previous build
:return: | Return True if the timestamps don't match or if there is no previous timestamp
:param target:
:param prev_ni: Information about the node from the previous build
:return: | [
"Return",
"True",
"if",
"the",
"timestamps",
"don",
"t",
"match",
"or",
"if",
"there",
"is",
"no",
"previous",
"timestamp",
":",
"param",
"target",
":",
":",
"param",
"prev_ni",
":",
"Information",
"about",
"the",
"node",
"from",
"the",
"previous",
"build",
":",
"return",
":"
] | def changed_timestamp_match(self, target, prev_ni, repo_node=None):
"""
Return True if the timestamps don't match or if there is no previous timestamp
:param target:
:param prev_ni: Information about the node from the previous build
:return:
"""
try:
return self.get_timestamp() != prev_ni.timestamp
except AttributeError:
return 1 | [
"def",
"changed_timestamp_match",
"(",
"self",
",",
"target",
",",
"prev_ni",
",",
"repo_node",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"get_timestamp",
"(",
")",
"!=",
"prev_ni",
".",
"timestamp",
"except",
"AttributeError",
":",
"return",
"1"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/FS.py#L3487-L3497 | ||
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/common/walterWidgets/itemStyle.py | python | ItemStyle.subElementRect | (self, element, option, widget=None) | return self.__parent.subElementRect(element, option, widget) | Return the sub-area for the given element as described in the provided
style option. The returned rectangle is defined in screen coordinates. | Return the sub-area for the given element as described in the provided
style option. The returned rectangle is defined in screen coordinates. | [
"Return",
"the",
"sub",
"-",
"area",
"for",
"the",
"given",
"element",
"as",
"described",
"in",
"the",
"provided",
"style",
"option",
".",
"The",
"returned",
"rectangle",
"is",
"defined",
"in",
"screen",
"coordinates",
"."
] | def subElementRect(self, element, option, widget=None):
"""
Return the sub-area for the given element as described in the provided
style option. The returned rectangle is defined in screen coordinates.
"""
return self.__parent.subElementRect(element, option, widget) | [
"def",
"subElementRect",
"(",
"self",
",",
"element",
",",
"option",
",",
"widget",
"=",
"None",
")",
":",
"return",
"self",
".",
"__parent",
".",
"subElementRect",
"(",
"element",
",",
"option",
",",
"widget",
")"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/itemStyle.py#L148-L153 | |
bilibili/biliobs | 573613dc3b2b63fe7c1506cc94717609a2c52c0c | base/android/jni_generator/jni_generator.py | python | InlHeaderFileGenerator.GetRegisterCalledByNativesImplString | (self) | return '\n'.join(ret) | Returns the code for registering the called by native methods. | Returns the code for registering the called by native methods. | [
"Returns",
"the",
"code",
"for",
"registering",
"the",
"called",
"by",
"native",
"methods",
"."
] | def GetRegisterCalledByNativesImplString(self):
"""Returns the code for registering the called by native methods."""
if not self.options.eager_called_by_natives:
return ''
template = Template("""\
g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} = ${GET_METHOD_ID_IMPL}
if (g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} == NULL) {
return false;
}
""")
ret = []
for called_by_native in self.called_by_natives:
values = {
'JAVA_CLASS': called_by_native.java_class_name or self.class_name,
'METHOD_ID_VAR_NAME': called_by_native.method_id_var_name,
'GET_METHOD_ID_IMPL': self.GetMethodIDImpl(called_by_native),
}
ret += [template.substitute(values)]
return '\n'.join(ret) | [
"def",
"GetRegisterCalledByNativesImplString",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"options",
".",
"eager_called_by_natives",
":",
"return",
"''",
"template",
"=",
"Template",
"(",
"\"\"\"\\\n g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} = ${GET_METHOD_ID_IMPL}\n if (g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} == NULL) {\n return false;\n }\n \"\"\"",
")",
"ret",
"=",
"[",
"]",
"for",
"called_by_native",
"in",
"self",
".",
"called_by_natives",
":",
"values",
"=",
"{",
"'JAVA_CLASS'",
":",
"called_by_native",
".",
"java_class_name",
"or",
"self",
".",
"class_name",
",",
"'METHOD_ID_VAR_NAME'",
":",
"called_by_native",
".",
"method_id_var_name",
",",
"'GET_METHOD_ID_IMPL'",
":",
"self",
".",
"GetMethodIDImpl",
"(",
"called_by_native",
")",
",",
"}",
"ret",
"+=",
"[",
"template",
".",
"substitute",
"(",
"values",
")",
"]",
"return",
"'\\n'",
".",
"join",
"(",
"ret",
")"
] | https://github.com/bilibili/biliobs/blob/573613dc3b2b63fe7c1506cc94717609a2c52c0c/base/android/jni_generator/jni_generator.py#L906-L924 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py | python | DocComment.__repr__ | (self) | return '<DocComment: %s, %s>' % (
str(self.ordered_params), str(self.__flags)) | Returns a string representation of this object.
Returns:
A string representation of this object. | Returns a string representation of this object. | [
"Returns",
"a",
"string",
"representation",
"of",
"this",
"object",
"."
] | def __repr__(self):
"""Returns a string representation of this object.
Returns:
A string representation of this object.
"""
return '<DocComment: %s, %s>' % (
str(self.ordered_params), str(self.__flags)) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'<DocComment: %s, %s>'",
"%",
"(",
"str",
"(",
"self",
".",
"ordered_params",
")",
",",
"str",
"(",
"self",
".",
"__flags",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py#L569-L576 | |
freesurfer/freesurfer | 6dbe527d43ffa611acb2cd112e9469f9bfec8e36 | python/freesurfer/subfields/thalamus.py | python | ThalamicNuclei.get_cheating_gaussians | (self, sameGaussianParameters) | return (means, variances) | Return a tuple of (means, variances) for the initial segmentation-fitting stage. | Return a tuple of (means, variances) for the initial segmentation-fitting stage. | [
"Return",
"a",
"tuple",
"of",
"(",
"means",
"variances",
")",
"for",
"the",
"initial",
"segmentation",
"-",
"fitting",
"stage",
"."
] | def get_cheating_gaussians(self, sameGaussianParameters):
"""
Return a tuple of (means, variances) for the initial segmentation-fitting stage.
"""
means = np.zeros(len(sameGaussianParameters))
variances = 0.01 * np.ones(len(sameGaussianParameters))
for i in range(len(sameGaussianParameters)):
label = sameGaussianParameters[i][0]
if label >= 8100 and label < 8200:
means[i] = self.THlabelLeft # left thalamic nuclei + DE -> left TH
elif label >= 8200:
means[i] = self.THlabelRight # right thalamic nuclei + DE -> left TH
elif label == 0:
means[i] = 1 # background is 1 instead of 0
else:
means[i] = label
return (means, variances) | [
"def",
"get_cheating_gaussians",
"(",
"self",
",",
"sameGaussianParameters",
")",
":",
"means",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"sameGaussianParameters",
")",
")",
"variances",
"=",
"0.01",
"*",
"np",
".",
"ones",
"(",
"len",
"(",
"sameGaussianParameters",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sameGaussianParameters",
")",
")",
":",
"label",
"=",
"sameGaussianParameters",
"[",
"i",
"]",
"[",
"0",
"]",
"if",
"label",
">=",
"8100",
"and",
"label",
"<",
"8200",
":",
"means",
"[",
"i",
"]",
"=",
"self",
".",
"THlabelLeft",
"# left thalamic nuclei + DE -> left TH",
"elif",
"label",
">=",
"8200",
":",
"means",
"[",
"i",
"]",
"=",
"self",
".",
"THlabelRight",
"# right thalamic nuclei + DE -> left TH",
"elif",
"label",
"==",
"0",
":",
"means",
"[",
"i",
"]",
"=",
"1",
"# background is 1 instead of 0",
"else",
":",
"means",
"[",
"i",
"]",
"=",
"label",
"return",
"(",
"means",
",",
"variances",
")"
] | https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/subfields/thalamus.py#L200-L216 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Main/glue/vboxapi.py | python | PlatformBase.waitForEvents | (self, cMsTimeout) | return 2 | Wait for events to arrive and process them.
The timeout (cMsTimeout) is in milliseconds for how long to wait for
events to arrive. A negative value means waiting for ever, while 0
does not wait at all.
Returns 0 if events was processed.
Returns 1 if timed out or interrupted in some way.
Returns 2 on error (like not supported for web services).
Raises an exception if the calling thread is not the main thread (the one
that initialized VirtualBoxManager) or if the time isn't an integer. | Wait for events to arrive and process them. | [
"Wait",
"for",
"events",
"to",
"arrive",
"and",
"process",
"them",
"."
] | def waitForEvents(self, cMsTimeout):
"""
Wait for events to arrive and process them.
The timeout (cMsTimeout) is in milliseconds for how long to wait for
events to arrive. A negative value means waiting for ever, while 0
does not wait at all.
Returns 0 if events was processed.
Returns 1 if timed out or interrupted in some way.
Returns 2 on error (like not supported for web services).
Raises an exception if the calling thread is not the main thread (the one
that initialized VirtualBoxManager) or if the time isn't an integer.
"""
_ = cMsTimeout
return 2 | [
"def",
"waitForEvents",
"(",
"self",
",",
"cMsTimeout",
")",
":",
"_",
"=",
"cMsTimeout",
"return",
"2"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Main/glue/vboxapi.py#L290-L306 | |
rprichard/CxxCodeBrowser | a2fa83d2fe06119f0a7a1827b8167fab88b53561 | third_party/libre2/lib/codereview/codereview.py | python | GetEmail | (prompt) | return email | Prompts the user for their email address and returns it.
The last used email address is saved to a file and offered up as a suggestion
to the user. If the user presses enter without typing in anything the last
used email address is used. If the user enters a new address, it is saved
for next time we prompt. | Prompts the user for their email address and returns it. | [
"Prompts",
"the",
"user",
"for",
"their",
"email",
"address",
"and",
"returns",
"it",
"."
] | def GetEmail(prompt):
"""Prompts the user for their email address and returns it.
The last used email address is saved to a file and offered up as a suggestion
to the user. If the user presses enter without typing in anything the last
used email address is used. If the user enters a new address, it is saved
for next time we prompt.
"""
last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
last_email = ""
if os.path.exists(last_email_file_name):
try:
last_email_file = open(last_email_file_name, "r")
last_email = last_email_file.readline().strip("\n")
last_email_file.close()
prompt += " [%s]" % last_email
except IOError, e:
pass
email = raw_input(prompt + ": ").strip()
if email:
try:
last_email_file = open(last_email_file_name, "w")
last_email_file.write(email)
last_email_file.close()
except IOError, e:
pass
else:
email = last_email
return email | [
"def",
"GetEmail",
"(",
"prompt",
")",
":",
"last_email_file_name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.last_codereview_email_address\"",
")",
"last_email",
"=",
"\"\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"last_email_file_name",
")",
":",
"try",
":",
"last_email_file",
"=",
"open",
"(",
"last_email_file_name",
",",
"\"r\"",
")",
"last_email",
"=",
"last_email_file",
".",
"readline",
"(",
")",
".",
"strip",
"(",
"\"\\n\"",
")",
"last_email_file",
".",
"close",
"(",
")",
"prompt",
"+=",
"\" [%s]\"",
"%",
"last_email",
"except",
"IOError",
",",
"e",
":",
"pass",
"email",
"=",
"raw_input",
"(",
"prompt",
"+",
"\": \"",
")",
".",
"strip",
"(",
")",
"if",
"email",
":",
"try",
":",
"last_email_file",
"=",
"open",
"(",
"last_email_file_name",
",",
"\"w\"",
")",
"last_email_file",
".",
"write",
"(",
"email",
")",
"last_email_file",
".",
"close",
"(",
")",
"except",
"IOError",
",",
"e",
":",
"pass",
"else",
":",
"email",
"=",
"last_email",
"return",
"email"
] | https://github.com/rprichard/CxxCodeBrowser/blob/a2fa83d2fe06119f0a7a1827b8167fab88b53561/third_party/libre2/lib/codereview/codereview.py#L2702-L2731 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | catboost/python-package/catboost/core.py | python | CatBoost.save_model | (self, fname, format="cbm", export_parameters=None, pool=None) | Save the model to a file.
Parameters
----------
fname : string
Output file name.
format : string
Possible values:
* 'cbm' for catboost binary format,
* 'coreml' to export into Apple CoreML format
* 'onnx' to export into ONNX-ML format
* 'pmml' to export into PMML format
* 'cpp' to export as C++ code
* 'python' to export as Python code.
export_parameters : dict
Parameters for CoreML export:
* prediction_type : string - either 'probability' or 'raw'
* coreml_description : string
* coreml_model_version : string
* coreml_model_author : string
* coreml_model_license: string
Parameters for PMML export:
* pmml_copyright : string
* pmml_description : string
* pmml_model_version : string
pool : catboost.Pool or list or numpy.ndarray or pandas.DataFrame or pandas.Series or catboost.FeaturesData
Training pool. | Save the model to a file. | [
"Save",
"the",
"model",
"to",
"a",
"file",
"."
] | def save_model(self, fname, format="cbm", export_parameters=None, pool=None):
"""
Save the model to a file.
Parameters
----------
fname : string
Output file name.
format : string
Possible values:
* 'cbm' for catboost binary format,
* 'coreml' to export into Apple CoreML format
* 'onnx' to export into ONNX-ML format
* 'pmml' to export into PMML format
* 'cpp' to export as C++ code
* 'python' to export as Python code.
export_parameters : dict
Parameters for CoreML export:
* prediction_type : string - either 'probability' or 'raw'
* coreml_description : string
* coreml_model_version : string
* coreml_model_author : string
* coreml_model_license: string
Parameters for PMML export:
* pmml_copyright : string
* pmml_description : string
* pmml_model_version : string
pool : catboost.Pool or list or numpy.ndarray or pandas.DataFrame or pandas.Series or catboost.FeaturesData
Training pool.
"""
if not self.is_fitted():
raise CatBoostError("There is no trained model to use save_model(). Use fit() to train model. Then use this method.")
if not isinstance(fname, PATH_TYPES):
raise CatBoostError("Invalid fname type={}: must be str() or pathlib.Path().".format(type(fname)))
if pool is not None and not isinstance(pool, Pool):
pool = Pool(
data=pool,
cat_features=self._get_cat_feature_indices() if not isinstance(pool, FeaturesData) else None,
text_features=self._get_text_feature_indices() if not isinstance(pool, FeaturesData) else None,
embedding_features=self._get_embedding_feature_indices() if not isinstance(pool, FeaturesData) else None
)
self._save_model(fname, format, export_parameters, pool) | [
"def",
"save_model",
"(",
"self",
",",
"fname",
",",
"format",
"=",
"\"cbm\"",
",",
"export_parameters",
"=",
"None",
",",
"pool",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_fitted",
"(",
")",
":",
"raise",
"CatBoostError",
"(",
"\"There is no trained model to use save_model(). Use fit() to train model. Then use this method.\"",
")",
"if",
"not",
"isinstance",
"(",
"fname",
",",
"PATH_TYPES",
")",
":",
"raise",
"CatBoostError",
"(",
"\"Invalid fname type={}: must be str() or pathlib.Path().\"",
".",
"format",
"(",
"type",
"(",
"fname",
")",
")",
")",
"if",
"pool",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"pool",
",",
"Pool",
")",
":",
"pool",
"=",
"Pool",
"(",
"data",
"=",
"pool",
",",
"cat_features",
"=",
"self",
".",
"_get_cat_feature_indices",
"(",
")",
"if",
"not",
"isinstance",
"(",
"pool",
",",
"FeaturesData",
")",
"else",
"None",
",",
"text_features",
"=",
"self",
".",
"_get_text_feature_indices",
"(",
")",
"if",
"not",
"isinstance",
"(",
"pool",
",",
"FeaturesData",
")",
"else",
"None",
",",
"embedding_features",
"=",
"self",
".",
"_get_embedding_feature_indices",
"(",
")",
"if",
"not",
"isinstance",
"(",
"pool",
",",
"FeaturesData",
")",
"else",
"None",
")",
"self",
".",
"_save_model",
"(",
"fname",
",",
"format",
",",
"export_parameters",
",",
"pool",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/core.py#L3114-L3155 | ||
alexozer/jankdrone | c4b403eb254b41b832ab2bdfade12ba59c99e5dc | shm/lib/pyratemp/pyratemp.py | python | EvalPseudoSandbox.f_setvar | (self, name, expr) | return "" | ``setvar()`` for the sandboxed code.
Set a variable.
:Example: see module-docstring | ``setvar()`` for the sandboxed code. | [
"setvar",
"()",
"for",
"the",
"sandboxed",
"code",
"."
] | def f_setvar(self, name, expr):
"""``setvar()`` for the sandboxed code.
Set a variable.
:Example: see module-docstring
"""
self.vars_ptr[name] = self.eval(expr, self.vars_ptr)
return "" | [
"def",
"f_setvar",
"(",
"self",
",",
"name",
",",
"expr",
")",
":",
"self",
".",
"vars_ptr",
"[",
"name",
"]",
"=",
"self",
".",
"eval",
"(",
"expr",
",",
"self",
".",
"vars_ptr",
")",
"return",
"\"\""
] | https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/shm/lib/pyratemp/pyratemp.py#L995-L1003 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntH.GetDatV | (self, *args) | return _snap.TIntH_GetDatV(self, *args) | GetDatV(TIntH self, TIntV DatV)
Parameters:
DatV: TVec< TInt > & | GetDatV(TIntH self, TIntV DatV) | [
"GetDatV",
"(",
"TIntH",
"self",
"TIntV",
"DatV",
")"
] | def GetDatV(self, *args):
"""
GetDatV(TIntH self, TIntV DatV)
Parameters:
DatV: TVec< TInt > &
"""
return _snap.TIntH_GetDatV(self, *args) | [
"def",
"GetDatV",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntH_GetDatV",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L18703-L18711 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/filecmp.py | python | cmpfiles | (a, b, common, shallow=1) | return res | Compare common files in two directories.
a, b -- directory names
common -- list of file names found in both directories
shallow -- if true, do comparison based solely on stat() information
Returns a tuple of three lists:
files that compare equal
files that are different
filenames that aren't regular files. | Compare common files in two directories. | [
"Compare",
"common",
"files",
"in",
"two",
"directories",
"."
] | def cmpfiles(a, b, common, shallow=1):
"""Compare common files in two directories.
a, b -- directory names
common -- list of file names found in both directories
shallow -- if true, do comparison based solely on stat() information
Returns a tuple of three lists:
files that compare equal
files that are different
filenames that aren't regular files.
"""
res = ([], [], [])
for x in common:
ax = os.path.join(a, x)
bx = os.path.join(b, x)
res[_cmp(ax, bx, shallow)].append(x)
return res | [
"def",
"cmpfiles",
"(",
"a",
",",
"b",
",",
"common",
",",
"shallow",
"=",
"1",
")",
":",
"res",
"=",
"(",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
"for",
"x",
"in",
"common",
":",
"ax",
"=",
"os",
".",
"path",
".",
"join",
"(",
"a",
",",
"x",
")",
"bx",
"=",
"os",
".",
"path",
".",
"join",
"(",
"b",
",",
"x",
")",
"res",
"[",
"_cmp",
"(",
"ax",
",",
"bx",
",",
"shallow",
")",
"]",
".",
"append",
"(",
"x",
")",
"return",
"res"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/filecmp.py#L241-L259 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | ListCtrl.SetColumnsOrder | (*args, **kwargs) | return _controls_.ListCtrl_SetColumnsOrder(*args, **kwargs) | SetColumnsOrder(self, wxArrayInt orders) -> bool | SetColumnsOrder(self, wxArrayInt orders) -> bool | [
"SetColumnsOrder",
"(",
"self",
"wxArrayInt",
"orders",
")",
"-",
">",
"bool"
] | def SetColumnsOrder(*args, **kwargs):
"""SetColumnsOrder(self, wxArrayInt orders) -> bool"""
return _controls_.ListCtrl_SetColumnsOrder(*args, **kwargs) | [
"def",
"SetColumnsOrder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_SetColumnsOrder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4493-L4495 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/inputs/forces.py | python | InputForces.fetch | (self) | return flist | Returns a list of the output objects included in this dynamic
container.
Returns:
A list of tuples, with each tuple being of the form ('type', 'object'),
where 'type' is the type of forcefield, and 'object' is a | Returns a list of the output objects included in this dynamic
container. | [
"Returns",
"a",
"list",
"of",
"the",
"output",
"objects",
"included",
"in",
"this",
"dynamic",
"container",
"."
] | def fetch(self):
"""Returns a list of the output objects included in this dynamic
container.
Returns:
A list of tuples, with each tuple being of the form ('type', 'object'),
where 'type' is the type of forcefield, and 'object' is a
"""
super(InputForces, self).fetch()
flist = [ (n, f.fetch()) for (n, f) in self.extra ]
return flist | [
"def",
"fetch",
"(",
"self",
")",
":",
"super",
"(",
"InputForces",
",",
"self",
")",
".",
"fetch",
"(",
")",
"flist",
"=",
"[",
"(",
"n",
",",
"f",
".",
"fetch",
"(",
")",
")",
"for",
"(",
"n",
",",
"f",
")",
"in",
"self",
".",
"extra",
"]",
"return",
"flist"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/forces.py#L145-L157 | |
learnforpractice/pyeos | 4f04eb982c86c1fdb413084af77c713a6fda3070 | libraries/vm/vm_cpython_ss/lib/codecs.py | python | StreamWriter.__init__ | (self, stream, errors='strict') | Creates a StreamWriter instance.
stream must be a file-like object open for writing.
The StreamWriter may use different error handling
schemes by providing the errors keyword argument. These
parameters are predefined:
'strict' - raise a ValueError (or a subclass)
'ignore' - ignore the character and continue with the next
'replace'- replace with a suitable replacement character
'xmlcharrefreplace' - Replace with the appropriate XML
character reference.
'backslashreplace' - Replace with backslashed escape
sequences.
'namereplace' - Replace with \\N{...} escape sequences.
The set of allowed parameter values can be extended via
register_error. | Creates a StreamWriter instance. | [
"Creates",
"a",
"StreamWriter",
"instance",
"."
] | def __init__(self, stream, errors='strict'):
""" Creates a StreamWriter instance.
stream must be a file-like object open for writing.
The StreamWriter may use different error handling
schemes by providing the errors keyword argument. These
parameters are predefined:
'strict' - raise a ValueError (or a subclass)
'ignore' - ignore the character and continue with the next
'replace'- replace with a suitable replacement character
'xmlcharrefreplace' - Replace with the appropriate XML
character reference.
'backslashreplace' - Replace with backslashed escape
sequences.
'namereplace' - Replace with \\N{...} escape sequences.
The set of allowed parameter values can be extended via
register_error.
"""
self.stream = stream
self.errors = errors | [
"def",
"__init__",
"(",
"self",
",",
"stream",
",",
"errors",
"=",
"'strict'",
")",
":",
"self",
".",
"stream",
"=",
"stream",
"self",
".",
"errors",
"=",
"errors"
] | https://github.com/learnforpractice/pyeos/blob/4f04eb982c86c1fdb413084af77c713a6fda3070/libraries/vm/vm_cpython_ss/lib/codecs.py#L347-L370 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm.scores | (self) | return (self._all_scores, self._scores) | Returns the distances to each class.
Returns:
A tuple with two Tensors. The first contains the distance to
each class. The second contains the distance to the assigned
class. | Returns the distances to each class. | [
"Returns",
"the",
"distances",
"to",
"each",
"class",
"."
] | def scores(self):
"""Returns the distances to each class.
Returns:
A tuple with two Tensors. The first contains the distance to
each class. The second contains the distance to the assigned
class.
"""
return (self._all_scores, self._scores) | [
"def",
"scores",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_all_scores",
",",
"self",
".",
"_scores",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L194-L202 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/misc.py | python | get_distribution | (req_name) | return _search_distribution(req_name) | Given a requirement name, return the installed Distribution object.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``. | Given a requirement name, return the installed Distribution object. | [
"Given",
"a",
"requirement",
"name",
"return",
"the",
"installed",
"Distribution",
"object",
"."
] | def get_distribution(req_name):
# type: (str) -> Optional[Distribution]
"""Given a requirement name, return the installed Distribution object.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``.
"""
# Search the distribution by looking through the working set
dist = _search_distribution(req_name)
# If distribution could not be found, call working_set.require
# to update the working set, and try to find the distribution
# again.
# This might happen for e.g. when you install a package
# twice, once using setup.py develop and again using setup.py install.
# Now when run pip uninstall twice, the package gets removed
# from the working set in the first uninstall, so we have to populate
# the working set again so that pip knows about it and the packages
# gets picked up and is successfully uninstalled the second time too.
if not dist:
try:
pkg_resources.working_set.require(req_name)
except pkg_resources.DistributionNotFound:
return None
return _search_distribution(req_name) | [
"def",
"get_distribution",
"(",
"req_name",
")",
":",
"# type: (str) -> Optional[Distribution]",
"# Search the distribution by looking through the working set",
"dist",
"=",
"_search_distribution",
"(",
"req_name",
")",
"# If distribution could not be found, call working_set.require",
"# to update the working set, and try to find the distribution",
"# again.",
"# This might happen for e.g. when you install a package",
"# twice, once using setup.py develop and again using setup.py install.",
"# Now when run pip uninstall twice, the package gets removed",
"# from the working set in the first uninstall, so we have to populate",
"# the working set again so that pip knows about it and the packages",
"# gets picked up and is successfully uninstalled the second time too.",
"if",
"not",
"dist",
":",
"try",
":",
"pkg_resources",
".",
"working_set",
".",
"require",
"(",
"req_name",
")",
"except",
"pkg_resources",
".",
"DistributionNotFound",
":",
"return",
"None",
"return",
"_search_distribution",
"(",
"req_name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/misc.py#L1007-L1057 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py | python | RawTurtle.dot | (self, size=None, *color) | Draw a dot with diameter size, using color.
Optional arguments:
size -- an integer >= 1 (if given)
color -- a colorstring or a numeric color tuple
Draw a circular dot with diameter size, using color.
If size is not given, the maximum of pensize+4 and 2*pensize is used.
Example (for a Turtle instance named turtle):
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) | Draw a dot with diameter size, using color. | [
"Draw",
"a",
"dot",
"with",
"diameter",
"size",
"using",
"color",
"."
] | def dot(self, size=None, *color):
"""Draw a dot with diameter size, using color.
Optional arguments:
size -- an integer >= 1 (if given)
color -- a colorstring or a numeric color tuple
Draw a circular dot with diameter size, using color.
If size is not given, the maximum of pensize+4 and 2*pensize is used.
Example (for a Turtle instance named turtle):
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
"""
#print "dot-1:", size, color
if not color:
if isinstance(size, (str, tuple)):
color = self._colorstr(size)
size = self._pensize + max(self._pensize, 4)
else:
color = self._pencolor
if not size:
size = self._pensize + max(self._pensize, 4)
else:
if size is None:
size = self._pensize + max(self._pensize, 4)
color = self._colorstr(color)
#print "dot-2:", size, color
if hasattr(self.screen, "_dot"):
item = self.screen._dot(self._position, size, color)
#print "dot:", size, color, "item:", item
self.items.append(item)
if self.undobuffer:
self.undobuffer.push(("dot", item))
else:
pen = self.pen()
if self.undobuffer:
self.undobuffer.push(["seq"])
self.undobuffer.cumulate = True
try:
if self.resizemode() == 'auto':
self.ht()
self.pendown()
self.pensize(size)
self.pencolor(color)
self.forward(0)
finally:
self.pen(pen)
if self.undobuffer:
self.undobuffer.cumulate = False | [
"def",
"dot",
"(",
"self",
",",
"size",
"=",
"None",
",",
"*",
"color",
")",
":",
"#print \"dot-1:\", size, color",
"if",
"not",
"color",
":",
"if",
"isinstance",
"(",
"size",
",",
"(",
"str",
",",
"tuple",
")",
")",
":",
"color",
"=",
"self",
".",
"_colorstr",
"(",
"size",
")",
"size",
"=",
"self",
".",
"_pensize",
"+",
"max",
"(",
"self",
".",
"_pensize",
",",
"4",
")",
"else",
":",
"color",
"=",
"self",
".",
"_pencolor",
"if",
"not",
"size",
":",
"size",
"=",
"self",
".",
"_pensize",
"+",
"max",
"(",
"self",
".",
"_pensize",
",",
"4",
")",
"else",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"self",
".",
"_pensize",
"+",
"max",
"(",
"self",
".",
"_pensize",
",",
"4",
")",
"color",
"=",
"self",
".",
"_colorstr",
"(",
"color",
")",
"#print \"dot-2:\", size, color",
"if",
"hasattr",
"(",
"self",
".",
"screen",
",",
"\"_dot\"",
")",
":",
"item",
"=",
"self",
".",
"screen",
".",
"_dot",
"(",
"self",
".",
"_position",
",",
"size",
",",
"color",
")",
"#print \"dot:\", size, color, \"item:\", item",
"self",
".",
"items",
".",
"append",
"(",
"item",
")",
"if",
"self",
".",
"undobuffer",
":",
"self",
".",
"undobuffer",
".",
"push",
"(",
"(",
"\"dot\"",
",",
"item",
")",
")",
"else",
":",
"pen",
"=",
"self",
".",
"pen",
"(",
")",
"if",
"self",
".",
"undobuffer",
":",
"self",
".",
"undobuffer",
".",
"push",
"(",
"[",
"\"seq\"",
"]",
")",
"self",
".",
"undobuffer",
".",
"cumulate",
"=",
"True",
"try",
":",
"if",
"self",
".",
"resizemode",
"(",
")",
"==",
"'auto'",
":",
"self",
".",
"ht",
"(",
")",
"self",
".",
"pendown",
"(",
")",
"self",
".",
"pensize",
"(",
"size",
")",
"self",
".",
"pencolor",
"(",
"color",
")",
"self",
".",
"forward",
"(",
"0",
")",
"finally",
":",
"self",
".",
"pen",
"(",
"pen",
")",
"if",
"self",
".",
"undobuffer",
":",
"self",
".",
"undobuffer",
".",
"cumulate",
"=",
"False"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L3215-L3264 | ||
DaFuCoding/MTCNN_Caffe | 09c30c3ff391bd9cb6b249c1910afaf147767ab3 | tools/extra/extract_seconds.py | python | get_start_time | (line_iterable, year) | return start_datetime | Find start time from group of lines | Find start time from group of lines | [
"Find",
"start",
"time",
"from",
"group",
"of",
"lines"
] | def get_start_time(line_iterable, year):
"""Find start time from group of lines
"""
start_datetime = None
for line in line_iterable:
line = line.strip()
if line.find('Solving') != -1:
start_datetime = extract_datetime_from_line(line, year)
break
return start_datetime | [
"def",
"get_start_time",
"(",
"line_iterable",
",",
"year",
")",
":",
"start_datetime",
"=",
"None",
"for",
"line",
"in",
"line_iterable",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"find",
"(",
"'Solving'",
")",
"!=",
"-",
"1",
":",
"start_datetime",
"=",
"extract_datetime_from_line",
"(",
"line",
",",
"year",
")",
"break",
"return",
"start_datetime"
] | https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/tools/extra/extract_seconds.py#L31-L41 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/package_index.py | python | find_external_links | (url, page) | Find rel="homepage" and rel="download" links in `page`, yielding URLs | Find rel="homepage" and rel="download" links in `page`, yielding URLs | [
"Find",
"rel",
"=",
"homepage",
"and",
"rel",
"=",
"download",
"links",
"in",
"page",
"yielding",
"URLs"
] | def find_external_links(url, page):
"""Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
for match in REL.finditer(page):
tag, rel = match.groups()
rels = set(map(str.strip, rel.lower().split(',')))
if 'homepage' in rels or 'download' in rels:
for match in HREF.finditer(tag):
yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
for tag in ("<th>Home Page", "<th>Download URL"):
pos = page.find(tag)
if pos != -1:
match = HREF.search(page, pos)
if match:
yield urllib.parse.urljoin(url, htmldecode(match.group(1))) | [
"def",
"find_external_links",
"(",
"url",
",",
"page",
")",
":",
"for",
"match",
"in",
"REL",
".",
"finditer",
"(",
"page",
")",
":",
"tag",
",",
"rel",
"=",
"match",
".",
"groups",
"(",
")",
"rels",
"=",
"set",
"(",
"map",
"(",
"str",
".",
"strip",
",",
"rel",
".",
"lower",
"(",
")",
".",
"split",
"(",
"','",
")",
")",
")",
"if",
"'homepage'",
"in",
"rels",
"or",
"'download'",
"in",
"rels",
":",
"for",
"match",
"in",
"HREF",
".",
"finditer",
"(",
"tag",
")",
":",
"yield",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"url",
",",
"htmldecode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"for",
"tag",
"in",
"(",
"\"<th>Home Page\"",
",",
"\"<th>Download URL\"",
")",
":",
"pos",
"=",
"page",
".",
"find",
"(",
"tag",
")",
"if",
"pos",
"!=",
"-",
"1",
":",
"match",
"=",
"HREF",
".",
"search",
"(",
"page",
",",
"pos",
")",
"if",
"match",
":",
"yield",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"url",
",",
"htmldecode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/package_index.py#L205-L220 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/macostools.py | python | copy | (src, dst, createpath=0, copydates=1, forcetype=None) | Copy a file, including finder info, resource fork, etc | Copy a file, including finder info, resource fork, etc | [
"Copy",
"a",
"file",
"including",
"finder",
"info",
"resource",
"fork",
"etc"
] | def copy(src, dst, createpath=0, copydates=1, forcetype=None):
"""Copy a file, including finder info, resource fork, etc"""
src = File.pathname(src)
dst = File.pathname(dst)
if createpath:
mkdirs(os.path.split(dst)[0])
ifp = open(src, 'rb')
ofp = open(dst, 'wb')
d = ifp.read(BUFSIZ)
while d:
ofp.write(d)
d = ifp.read(BUFSIZ)
ifp.close()
ofp.close()
ifp = openrf(src, '*rb')
ofp = openrf(dst, '*wb')
d = ifp.read(BUFSIZ)
while d:
ofp.write(d)
d = ifp.read(BUFSIZ)
ifp.close()
ofp.close()
srcfss = File.FSSpec(src)
dstfss = File.FSSpec(dst)
sf = srcfss.FSpGetFInfo()
df = dstfss.FSpGetFInfo()
df.Creator, df.Type = sf.Creator, sf.Type
if forcetype is not None:
df.Type = forcetype
df.Flags = (sf.Flags & COPY_FLAGS)
dstfss.FSpSetFInfo(df)
if copydates:
srcfsr = File.FSRef(src)
dstfsr = File.FSRef(dst)
catinfo, _, _, _ = srcfsr.FSGetCatalogInfo(Files.kFSCatInfoAllDates)
dstfsr.FSSetCatalogInfo(Files.kFSCatInfoAllDates, catinfo) | [
"def",
"copy",
"(",
"src",
",",
"dst",
",",
"createpath",
"=",
"0",
",",
"copydates",
"=",
"1",
",",
"forcetype",
"=",
"None",
")",
":",
"src",
"=",
"File",
".",
"pathname",
"(",
"src",
")",
"dst",
"=",
"File",
".",
"pathname",
"(",
"dst",
")",
"if",
"createpath",
":",
"mkdirs",
"(",
"os",
".",
"path",
".",
"split",
"(",
"dst",
")",
"[",
"0",
"]",
")",
"ifp",
"=",
"open",
"(",
"src",
",",
"'rb'",
")",
"ofp",
"=",
"open",
"(",
"dst",
",",
"'wb'",
")",
"d",
"=",
"ifp",
".",
"read",
"(",
"BUFSIZ",
")",
"while",
"d",
":",
"ofp",
".",
"write",
"(",
"d",
")",
"d",
"=",
"ifp",
".",
"read",
"(",
"BUFSIZ",
")",
"ifp",
".",
"close",
"(",
")",
"ofp",
".",
"close",
"(",
")",
"ifp",
"=",
"openrf",
"(",
"src",
",",
"'*rb'",
")",
"ofp",
"=",
"openrf",
"(",
"dst",
",",
"'*wb'",
")",
"d",
"=",
"ifp",
".",
"read",
"(",
"BUFSIZ",
")",
"while",
"d",
":",
"ofp",
".",
"write",
"(",
"d",
")",
"d",
"=",
"ifp",
".",
"read",
"(",
"BUFSIZ",
")",
"ifp",
".",
"close",
"(",
")",
"ofp",
".",
"close",
"(",
")",
"srcfss",
"=",
"File",
".",
"FSSpec",
"(",
"src",
")",
"dstfss",
"=",
"File",
".",
"FSSpec",
"(",
"dst",
")",
"sf",
"=",
"srcfss",
".",
"FSpGetFInfo",
"(",
")",
"df",
"=",
"dstfss",
".",
"FSpGetFInfo",
"(",
")",
"df",
".",
"Creator",
",",
"df",
".",
"Type",
"=",
"sf",
".",
"Creator",
",",
"sf",
".",
"Type",
"if",
"forcetype",
"is",
"not",
"None",
":",
"df",
".",
"Type",
"=",
"forcetype",
"df",
".",
"Flags",
"=",
"(",
"sf",
".",
"Flags",
"&",
"COPY_FLAGS",
")",
"dstfss",
".",
"FSpSetFInfo",
"(",
"df",
")",
"if",
"copydates",
":",
"srcfsr",
"=",
"File",
".",
"FSRef",
"(",
"src",
")",
"dstfsr",
"=",
"File",
".",
"FSRef",
"(",
"dst",
")",
"catinfo",
",",
"_",
",",
"_",
",",
"_",
"=",
"srcfsr",
".",
"FSGetCatalogInfo",
"(",
"Files",
".",
"kFSCatInfoAllDates",
")",
"dstfsr",
".",
"FSSetCatalogInfo",
"(",
"Files",
".",
"kFSCatInfoAllDates",
",",
"catinfo",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/macostools.py#L90-L128 | ||
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/unit_tree/html_output.py | python | cleanurl | (url) | return urllib.parse.quote(url, encoding='utf-8') | Encode the given URL to ensure it only contains valid URL characters
(also known as percent-encoding). | Encode the given URL to ensure it only contains valid URL characters
(also known as percent-encoding). | [
"Encode",
"the",
"given",
"URL",
"to",
"ensure",
"it",
"only",
"contains",
"valid",
"URL",
"characters",
"(",
"also",
"known",
"as",
"percent",
"-",
"encoding",
")",
"."
] | def cleanurl(url):
"""
Encode the given URL to ensure it only contains valid URL characters
(also known as percent-encoding).
"""
if url is None:
return url
return urllib.parse.quote(url, encoding='utf-8') | [
"def",
"cleanurl",
"(",
"url",
")",
":",
"if",
"url",
"is",
"None",
":",
"return",
"url",
"return",
"urllib",
".",
"parse",
".",
"quote",
"(",
"url",
",",
"encoding",
"=",
"'utf-8'",
")"
] | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/unit_tree/html_output.py#L181-L188 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/dbgen/cinder.py | python | grab_cinder_dat | (build_dir="", datapath='') | return rtn | Grabs the cinder.dat file from the DATAPATH directory if not already
present. | Grabs the cinder.dat file from the DATAPATH directory if not already
present. | [
"Grabs",
"the",
"cinder",
".",
"dat",
"file",
"from",
"the",
"DATAPATH",
"directory",
"if",
"not",
"already",
"present",
"."
] | def grab_cinder_dat(build_dir="", datapath=''):
"""Grabs the cinder.dat file from the DATAPATH directory if not already
present."""
build_filename = os.path.join(build_dir, 'cinder.dat')
if os.path.exists(build_filename):
return True
if isinstance(datapath, basestring) and 0 < len(datapath):
pass
elif 'DATAPATH' in os.environ:
datapath = os.environ['DATAPATH']
else:
print(warning("DATAPATH not defined in environment; cinder.dat not "
"found - skipping."))
return False
local_filename = os.path.join(datapath, "[Cc][Ii][Nn][Dd][Ee][Rr]."
"[Dd][Aa][Tt]")
local_filename = glob(local_filename)
if 0 < len(local_filename):
print("Grabbing cinder.dat from " + datapath)
print(warning("cinder.dat contains export controlled information "
"nuc_data.h5 is now export controlled!"))
shutil.copy(local_filename[0], build_filename)
rtn = True
else:
print(warning("cinder.dat file not found in DATAPATH dir - skipping."))
rtn = False
return rtn | [
"def",
"grab_cinder_dat",
"(",
"build_dir",
"=",
"\"\"",
",",
"datapath",
"=",
"''",
")",
":",
"build_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"'cinder.dat'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"build_filename",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"datapath",
",",
"basestring",
")",
"and",
"0",
"<",
"len",
"(",
"datapath",
")",
":",
"pass",
"elif",
"'DATAPATH'",
"in",
"os",
".",
"environ",
":",
"datapath",
"=",
"os",
".",
"environ",
"[",
"'DATAPATH'",
"]",
"else",
":",
"print",
"(",
"warning",
"(",
"\"DATAPATH not defined in environment; cinder.dat not \"",
"\"found - skipping.\"",
")",
")",
"return",
"False",
"local_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"datapath",
",",
"\"[Cc][Ii][Nn][Dd][Ee][Rr].\"",
"\"[Dd][Aa][Tt]\"",
")",
"local_filename",
"=",
"glob",
"(",
"local_filename",
")",
"if",
"0",
"<",
"len",
"(",
"local_filename",
")",
":",
"print",
"(",
"\"Grabbing cinder.dat from \"",
"+",
"datapath",
")",
"print",
"(",
"warning",
"(",
"\"cinder.dat contains export controlled information \"",
"\"nuc_data.h5 is now export controlled!\"",
")",
")",
"shutil",
".",
"copy",
"(",
"local_filename",
"[",
"0",
"]",
",",
"build_filename",
")",
"rtn",
"=",
"True",
"else",
":",
"print",
"(",
"warning",
"(",
"\"cinder.dat file not found in DATAPATH dir - skipping.\"",
")",
")",
"rtn",
"=",
"False",
"return",
"rtn"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/dbgen/cinder.py#L25-L53 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/req/req_set.py | python | RequirementSet.__init__ | (self, require_hashes=False, check_supported_wheels=True) | Create a RequirementSet. | Create a RequirementSet. | [
"Create",
"a",
"RequirementSet",
"."
] | def __init__(self, require_hashes=False, check_supported_wheels=True):
# type: (bool, bool) -> None
"""Create a RequirementSet.
"""
self.requirements = OrderedDict() # type: Dict[str, InstallRequirement] # noqa: E501
self.require_hashes = require_hashes
self.check_supported_wheels = check_supported_wheels
# Mapping of alias: real_name
self.requirement_aliases = {} # type: Dict[str, str]
self.unnamed_requirements = [] # type: List[InstallRequirement]
self.successfully_downloaded = [] # type: List[InstallRequirement]
self.reqs_to_cleanup = [] | [
"def",
"__init__",
"(",
"self",
",",
"require_hashes",
"=",
"False",
",",
"check_supported_wheels",
"=",
"True",
")",
":",
"# type: (bool, bool) -> None",
"self",
".",
"requirements",
"=",
"OrderedDict",
"(",
")",
"# type: Dict[str, InstallRequirement] # noqa: E501",
"self",
".",
"require_hashes",
"=",
"require_hashes",
"self",
".",
"check_supported_wheels",
"=",
"check_supported_wheels",
"# Mapping of alias: real_name",
"self",
".",
"requirement_aliases",
"=",
"{",
"}",
"# type: Dict[str, str]",
"self",
".",
"unnamed_requirements",
"=",
"[",
"]",
"# type: List[InstallRequirement]",
"self",
".",
"successfully_downloaded",
"=",
"[",
"]",
"# type: List[InstallRequirement]",
"self",
".",
"reqs_to_cleanup",
"=",
"[",
"]"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/req/req_set.py#L21-L34 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/distributions/python/ops/mvn.py | python | MultivariateNormalCholesky.__init__ | (self,
mu,
chol,
validate_args=False,
allow_nan_stats=True,
name="MultivariateNormalCholesky") | Multivariate Normal distributions on `R^k`.
User must provide means `mu` and `chol` which holds the (batch) Cholesky
factors, such that the covariance of each batch member is `chol chol^T`.
Args:
mu: `(N+1)-D` floating point tensor with shape `[N1,...,Nb, k]`,
`b >= 0`.
chol: `(N+2)-D` `Tensor` with same `dtype` as `mu` and shape
`[N1,...,Nb, k, k]`. The upper triangular part is ignored (treated as
though it is zero), and the diagonal must be positive.
validate_args: `Boolean`, default `False`. Whether to validate input
with asserts. If `validate_args` is `False`, and the inputs are
invalid, correct behavior is not guaranteed.
allow_nan_stats: `Boolean`, default `True`. If `False`, raise an
exception if a statistic (e.g. mean/mode/etc...) is undefined for any
batch member If `True`, batch members with valid parameters leading to
undefined statistics will return NaN for this statistic.
name: The name to give Ops created by the initializer.
Raises:
TypeError: If `mu` and `chol` are different dtypes. | Multivariate Normal distributions on `R^k`. | [
"Multivariate",
"Normal",
"distributions",
"on",
"R^k",
"."
] | def __init__(self,
mu,
chol,
validate_args=False,
allow_nan_stats=True,
name="MultivariateNormalCholesky"):
"""Multivariate Normal distributions on `R^k`.
User must provide means `mu` and `chol` which holds the (batch) Cholesky
factors, such that the covariance of each batch member is `chol chol^T`.
Args:
mu: `(N+1)-D` floating point tensor with shape `[N1,...,Nb, k]`,
`b >= 0`.
chol: `(N+2)-D` `Tensor` with same `dtype` as `mu` and shape
`[N1,...,Nb, k, k]`. The upper triangular part is ignored (treated as
though it is zero), and the diagonal must be positive.
validate_args: `Boolean`, default `False`. Whether to validate input
with asserts. If `validate_args` is `False`, and the inputs are
invalid, correct behavior is not guaranteed.
allow_nan_stats: `Boolean`, default `True`. If `False`, raise an
exception if a statistic (e.g. mean/mode/etc...) is undefined for any
batch member If `True`, batch members with valid parameters leading to
undefined statistics will return NaN for this statistic.
name: The name to give Ops created by the initializer.
Raises:
TypeError: If `mu` and `chol` are different dtypes.
"""
cov = operator_pd_cholesky.OperatorPDCholesky(chol, verify_pd=validate_args)
super(MultivariateNormalCholesky, self).__init__(
mu,
cov,
allow_nan_stats=allow_nan_stats,
validate_args=validate_args,
name=name) | [
"def",
"__init__",
"(",
"self",
",",
"mu",
",",
"chol",
",",
"validate_args",
"=",
"False",
",",
"allow_nan_stats",
"=",
"True",
",",
"name",
"=",
"\"MultivariateNormalCholesky\"",
")",
":",
"cov",
"=",
"operator_pd_cholesky",
".",
"OperatorPDCholesky",
"(",
"chol",
",",
"verify_pd",
"=",
"validate_args",
")",
"super",
"(",
"MultivariateNormalCholesky",
",",
"self",
")",
".",
"__init__",
"(",
"mu",
",",
"cov",
",",
"allow_nan_stats",
"=",
"allow_nan_stats",
",",
"validate_args",
"=",
"validate_args",
",",
"name",
"=",
"name",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/distributions/python/ops/mvn.py#L580-L615 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/tex.py | python | bibunitscan | (self) | return nodes | Parse the inputs and try to find the *bibunit* dependencies
:return: list of bibunit files
:rtype: list of :py:class:`waflib.Node.Node` | Parse the inputs and try to find the *bibunit* dependencies | [
"Parse",
"the",
"inputs",
"and",
"try",
"to",
"find",
"the",
"*",
"bibunit",
"*",
"dependencies"
] | def bibunitscan(self):
"""
Parse the inputs and try to find the *bibunit* dependencies
:return: list of bibunit files
:rtype: list of :py:class:`waflib.Node.Node`
"""
node = self.inputs[0]
nodes = []
if not node: return nodes
code = node.read()
for match in re_bibunit.finditer(code):
path = match.group('file')
if path:
for k in ['', '.bib']:
# add another loop for the tex include paths?
Logs.debug('tex: trying %s%s' % (path, k))
fi = node.parent.find_resource(path + k)
if fi:
nodes.append(fi)
# no break, people are crazy
else:
Logs.debug('tex: could not find %s' % path)
Logs.debug("tex: found the following bibunit files: %s" % nodes)
return nodes | [
"def",
"bibunitscan",
"(",
"self",
")",
":",
"node",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
"nodes",
"=",
"[",
"]",
"if",
"not",
"node",
":",
"return",
"nodes",
"code",
"=",
"node",
".",
"read",
"(",
")",
"for",
"match",
"in",
"re_bibunit",
".",
"finditer",
"(",
"code",
")",
":",
"path",
"=",
"match",
".",
"group",
"(",
"'file'",
")",
"if",
"path",
":",
"for",
"k",
"in",
"[",
"''",
",",
"'.bib'",
"]",
":",
"# add another loop for the tex include paths?",
"Logs",
".",
"debug",
"(",
"'tex: trying %s%s'",
"%",
"(",
"path",
",",
"k",
")",
")",
"fi",
"=",
"node",
".",
"parent",
".",
"find_resource",
"(",
"path",
"+",
"k",
")",
"if",
"fi",
":",
"nodes",
".",
"append",
"(",
"fi",
")",
"# no break, people are crazy",
"else",
":",
"Logs",
".",
"debug",
"(",
"'tex: could not find %s'",
"%",
"path",
")",
"Logs",
".",
"debug",
"(",
"\"tex: found the following bibunit files: %s\"",
"%",
"nodes",
")",
"return",
"nodes"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/tex.py#L35-L63 | |
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/jellyfish-2.2.0/swig/python/jellyfish.py | python | HashCounter.__getitem__ | (self, *args) | return _jellyfish.HashCounter___getitem__(self, *args) | Read a Jellyfish database sequentially | Read a Jellyfish database sequentially | [
"Read",
"a",
"Jellyfish",
"database",
"sequentially"
] | def __getitem__(self, *args):
"""Read a Jellyfish database sequentially"""
return _jellyfish.HashCounter___getitem__(self, *args) | [
"def",
"__getitem__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_jellyfish",
".",
"HashCounter___getitem__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/jellyfish-2.2.0/swig/python/jellyfish.py#L298-L300 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/io/pytables.py | python | Table.ncols | (self) | return sum(len(a.values) for a in self.values_axes) | the number of total columns in the values axes | the number of total columns in the values axes | [
"the",
"number",
"of",
"total",
"columns",
"in",
"the",
"values",
"axes"
] | def ncols(self):
""" the number of total columns in the values axes """
return sum(len(a.values) for a in self.values_axes) | [
"def",
"ncols",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"len",
"(",
"a",
".",
"values",
")",
"for",
"a",
"in",
"self",
".",
"values_axes",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L3202-L3204 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | libs/lv2/lv2specgen/lv2specgen.py | python | owlInfo | (term, m) | return res | Returns an extra information that is defined about a term using OWL. | Returns an extra information that is defined about a term using OWL. | [
"Returns",
"an",
"extra",
"information",
"that",
"is",
"defined",
"about",
"a",
"term",
"using",
"OWL",
"."
] | def owlInfo(term, m):
"""Returns an extra information that is defined about a term using OWL."""
res = ''
# Inverse properties ( owl:inverseOf )
first = True
for st in findStatements(m, term, owl.inverseOf, None):
res += getProperty(getTermLink(getObject(st)), first)
first = False
if res != "":
res += endProperties(first)
res = "<tr><th>Inverse:</th>\n" + res
def owlTypeInfo(term, propertyType, name):
if findOne(m, term, rdf.type, propertyType):
return "<tr><th>OWL Type</th><td>%s</td></tr>\n" % name
else:
return ""
res += owlTypeInfo(term, owl.DatatypeProperty, "Datatype Property")
res += owlTypeInfo(term, owl.ObjectProperty, "Object Property")
res += owlTypeInfo(term, owl.AnnotationProperty, "Annotation Property")
res += owlTypeInfo(term, owl.InverseFunctionalProperty, "Inverse Functional Property")
res += owlTypeInfo(term, owl.SymmetricProperty, "Symmetric Property")
return res | [
"def",
"owlInfo",
"(",
"term",
",",
"m",
")",
":",
"res",
"=",
"''",
"# Inverse properties ( owl:inverseOf )",
"first",
"=",
"True",
"for",
"st",
"in",
"findStatements",
"(",
"m",
",",
"term",
",",
"owl",
".",
"inverseOf",
",",
"None",
")",
":",
"res",
"+=",
"getProperty",
"(",
"getTermLink",
"(",
"getObject",
"(",
"st",
")",
")",
",",
"first",
")",
"first",
"=",
"False",
"if",
"res",
"!=",
"\"\"",
":",
"res",
"+=",
"endProperties",
"(",
"first",
")",
"res",
"=",
"\"<tr><th>Inverse:</th>\\n\"",
"+",
"res",
"def",
"owlTypeInfo",
"(",
"term",
",",
"propertyType",
",",
"name",
")",
":",
"if",
"findOne",
"(",
"m",
",",
"term",
",",
"rdf",
".",
"type",
",",
"propertyType",
")",
":",
"return",
"\"<tr><th>OWL Type</th><td>%s</td></tr>\\n\"",
"%",
"name",
"else",
":",
"return",
"\"\"",
"res",
"+=",
"owlTypeInfo",
"(",
"term",
",",
"owl",
".",
"DatatypeProperty",
",",
"\"Datatype Property\"",
")",
"res",
"+=",
"owlTypeInfo",
"(",
"term",
",",
"owl",
".",
"ObjectProperty",
",",
"\"Object Property\"",
")",
"res",
"+=",
"owlTypeInfo",
"(",
"term",
",",
"owl",
".",
"AnnotationProperty",
",",
"\"Annotation Property\"",
")",
"res",
"+=",
"owlTypeInfo",
"(",
"term",
",",
"owl",
".",
"InverseFunctionalProperty",
",",
"\"Inverse Functional Property\"",
")",
"res",
"+=",
"owlTypeInfo",
"(",
"term",
",",
"owl",
".",
"SymmetricProperty",
",",
"\"Symmetric Property\"",
")",
"return",
"res"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/libs/lv2/lv2specgen/lv2specgen.py#L624-L649 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FMRendererXP.__init__ | (self) | Default class constructor. | Default class constructor. | [
"Default",
"class",
"constructor",
"."
] | def __init__(self):
""" Default class constructor. """
FMRenderer.__init__(self)
self.drawLeftMargin = True
self.separatorHeight = 3
self.highlightCheckAndRadio = True
self.scrollBarButtons = True # Display scrollbar buttons if the menu doesn't fit on the screen
self.buttonBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self.buttonFaceColour = ArtManager.Get().LightColour(self.buttonBorderColour, 75)
self.buttonFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self.buttonFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self.buttonPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)
self.menuFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self.menuFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self.menuPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)
self.menuBarFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self.menuBarFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self.menuBarPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60) | [
"def",
"__init__",
"(",
"self",
")",
":",
"FMRenderer",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"drawLeftMargin",
"=",
"True",
"self",
".",
"separatorHeight",
"=",
"3",
"self",
".",
"highlightCheckAndRadio",
"=",
"True",
"self",
".",
"scrollBarButtons",
"=",
"True",
"# Display scrollbar buttons if the menu doesn't fit on the screen",
"self",
".",
"buttonBorderColour",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_ACTIVECAPTION",
")",
"self",
".",
"buttonFaceColour",
"=",
"ArtManager",
".",
"Get",
"(",
")",
".",
"LightColour",
"(",
"self",
".",
"buttonBorderColour",
",",
"75",
")",
"self",
".",
"buttonFocusBorderColour",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_ACTIVECAPTION",
")",
"self",
".",
"buttonFocusFaceColour",
"=",
"ArtManager",
".",
"Get",
"(",
")",
".",
"LightColour",
"(",
"self",
".",
"buttonFocusBorderColour",
",",
"75",
")",
"self",
".",
"buttonPressedBorderColour",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_ACTIVECAPTION",
")",
"self",
".",
"buttonPressedFaceColour",
"=",
"ArtManager",
".",
"Get",
"(",
")",
".",
"LightColour",
"(",
"self",
".",
"buttonPressedBorderColour",
",",
"60",
")",
"self",
".",
"menuFocusBorderColour",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_ACTIVECAPTION",
")",
"self",
".",
"menuFocusFaceColour",
"=",
"ArtManager",
".",
"Get",
"(",
")",
".",
"LightColour",
"(",
"self",
".",
"buttonFocusBorderColour",
",",
"75",
")",
"self",
".",
"menuPressedBorderColour",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_ACTIVECAPTION",
")",
"self",
".",
"menuPressedFaceColour",
"=",
"ArtManager",
".",
"Get",
"(",
")",
".",
"LightColour",
"(",
"self",
".",
"buttonPressedBorderColour",
",",
"60",
")",
"self",
".",
"menuBarFocusBorderColour",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_ACTIVECAPTION",
")",
"self",
".",
"menuBarFocusFaceColour",
"=",
"ArtManager",
".",
"Get",
"(",
")",
".",
"LightColour",
"(",
"self",
".",
"buttonFocusBorderColour",
",",
"75",
")",
"self",
".",
"menuBarPressedBorderColour",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_ACTIVECAPTION",
")",
"self",
".",
"menuBarPressedFaceColour",
"=",
"ArtManager",
".",
"Get",
"(",
")",
".",
"LightColour",
"(",
"self",
".",
"buttonPressedBorderColour",
",",
"60",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L1743-L1768 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/utils/data/_utils/collate.py | python | default_collate | (batch) | r"""
Function that takes in a batch of data and puts the elements within the batch
into a tensor with an additional outer dimension - batch size. The exact output type can be
a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a
Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type.
This is used as the default function for collation when
`batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`.
Here is the general input type (based on the type of the element within the batch) to output type mapping:
* :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size)
* NumPy Arrays -> :class:`torch.Tensor`
* `float` -> :class:`torch.Tensor`
* `int` -> :class:`torch.Tensor`
* `str` -> `str` (unchanged)
* `bytes` -> `bytes` (unchanged)
* `Mapping[K, V_i]` -> `Mapping[K, default_collate([V_1, V_2, ...])]`
* `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[default_collate([V1_1, V1_2, ...]), default_collate([V2_1, V2_2, ...]), ...]`
* `Sequence[V1_i, V2_i, ...]` -> `Sequence[default_collate([V1_1, V1_2, ...]), default_collate([V2_1, V2_2, ...]), ...]`
Args:
batch: a single batch to be collated
Examples:
>>> # Example with a batch of `int`s:
>>> default_collate([0, 1, 2, 3])
tensor([0, 1, 2, 3])
>>> # Example with a batch of `str`s:
>>> default_collate(['a', 'b', 'c'])
['a', 'b', 'c']
>>> # Example with `Map` inside the batch:
>>> default_collate([{'A': 0, 'B': 1}, {'A': 100, 'B': 100}])
{'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])}
>>> # Example with `NamedTuple` inside the batch:
>>> Point = namedtuple('Point', ['x', 'y'])
>>> default_collate([Point(0, 0), Point(1, 1)])
Point(x=tensor([0, 1]), y=tensor([0, 1]))
>>> # Example with `Tuple` inside the batch:
>>> default_collate([(0, 1), (2, 3)])
[tensor([0, 2]), tensor([1, 3])]
>>> # Example with `List` inside the batch:
>>> default_collate([[0, 1], [2, 3]])
[tensor([0, 2]), tensor([1, 3])] | r"""
Function that takes in a batch of data and puts the elements within the batch
into a tensor with an additional outer dimension - batch size. The exact output type can be
a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a
Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type.
This is used as the default function for collation when
`batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`. | [
"r",
"Function",
"that",
"takes",
"in",
"a",
"batch",
"of",
"data",
"and",
"puts",
"the",
"elements",
"within",
"the",
"batch",
"into",
"a",
"tensor",
"with",
"an",
"additional",
"outer",
"dimension",
"-",
"batch",
"size",
".",
"The",
"exact",
"output",
"type",
"can",
"be",
"a",
":",
"class",
":",
"torch",
".",
"Tensor",
"a",
"Sequence",
"of",
":",
"class",
":",
"torch",
".",
"Tensor",
"a",
"Collection",
"of",
":",
"class",
":",
"torch",
".",
"Tensor",
"or",
"left",
"unchanged",
"depending",
"on",
"the",
"input",
"type",
".",
"This",
"is",
"used",
"as",
"the",
"default",
"function",
"for",
"collation",
"when",
"batch_size",
"or",
"batch_sampler",
"is",
"defined",
"in",
":",
"class",
":",
"~torch",
".",
"utils",
".",
"data",
".",
"DataLoader",
"."
] | def default_collate(batch):
r"""
Function that takes in a batch of data and puts the elements within the batch
into a tensor with an additional outer dimension - batch size. The exact output type can be
a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a
Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type.
This is used as the default function for collation when
`batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`.
Here is the general input type (based on the type of the element within the batch) to output type mapping:
* :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size)
* NumPy Arrays -> :class:`torch.Tensor`
* `float` -> :class:`torch.Tensor`
* `int` -> :class:`torch.Tensor`
* `str` -> `str` (unchanged)
* `bytes` -> `bytes` (unchanged)
* `Mapping[K, V_i]` -> `Mapping[K, default_collate([V_1, V_2, ...])]`
* `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[default_collate([V1_1, V1_2, ...]), default_collate([V2_1, V2_2, ...]), ...]`
* `Sequence[V1_i, V2_i, ...]` -> `Sequence[default_collate([V1_1, V1_2, ...]), default_collate([V2_1, V2_2, ...]), ...]`
Args:
batch: a single batch to be collated
Examples:
>>> # Example with a batch of `int`s:
>>> default_collate([0, 1, 2, 3])
tensor([0, 1, 2, 3])
>>> # Example with a batch of `str`s:
>>> default_collate(['a', 'b', 'c'])
['a', 'b', 'c']
>>> # Example with `Map` inside the batch:
>>> default_collate([{'A': 0, 'B': 1}, {'A': 100, 'B': 100}])
{'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])}
>>> # Example with `NamedTuple` inside the batch:
>>> Point = namedtuple('Point', ['x', 'y'])
>>> default_collate([Point(0, 0), Point(1, 1)])
Point(x=tensor([0, 1]), y=tensor([0, 1]))
>>> # Example with `Tuple` inside the batch:
>>> default_collate([(0, 1), (2, 3)])
[tensor([0, 2]), tensor([1, 3])]
>>> # Example with `List` inside the batch:
>>> default_collate([[0, 1], [2, 3]])
[tensor([0, 2]), tensor([1, 3])]
"""
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, torch.Tensor):
out = None
if torch.utils.data.get_worker_info() is not None:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum(x.numel() for x in batch)
storage = elem.storage()._new_shared(numel)
out = elem.new(storage).resize_(len(batch), *list(elem.size()))
return torch.stack(batch, 0, out=out)
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
and elem_type.__name__ != 'string_':
if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap':
# array of string classes and object
if np_str_obj_array_pattern.search(elem.dtype.str) is not None:
raise TypeError(default_collate_err_msg_format.format(elem.dtype))
return default_collate([torch.as_tensor(b) for b in batch])
elif elem.shape == (): # scalars
return torch.as_tensor(batch)
elif isinstance(elem, float):
return torch.tensor(batch, dtype=torch.float64)
elif isinstance(elem, int):
return torch.tensor(batch)
elif isinstance(elem, string_classes):
return batch
elif isinstance(elem, collections.abc.Mapping):
try:
return elem_type({key: default_collate([d[key] for d in batch]) for key in elem})
except TypeError:
# The mapping type may not support `__init__(iterable)`.
return {key: default_collate([d[key] for d in batch]) for key in elem}
elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple
return elem_type(*(default_collate(samples) for samples in zip(*batch)))
elif isinstance(elem, collections.abc.Sequence):
# check to make sure that the elements in batch have consistent size
it = iter(batch)
elem_size = len(next(it))
if not all(len(elem) == elem_size for elem in it):
raise RuntimeError('each element in list of batch should be of equal size')
transposed = list(zip(*batch)) # It may be accessed twice, so we use a list.
if isinstance(elem, tuple):
return [default_collate(samples) for samples in transposed] # Backwards compatibility.
else:
try:
return elem_type([default_collate(samples) for samples in transposed])
except TypeError:
# The sequence type may not support `__init__(iterable)` (e.g., `range`).
return [default_collate(samples) for samples in transposed]
raise TypeError(default_collate_err_msg_format.format(elem_type)) | [
"def",
"default_collate",
"(",
"batch",
")",
":",
"elem",
"=",
"batch",
"[",
"0",
"]",
"elem_type",
"=",
"type",
"(",
"elem",
")",
"if",
"isinstance",
"(",
"elem",
",",
"torch",
".",
"Tensor",
")",
":",
"out",
"=",
"None",
"if",
"torch",
".",
"utils",
".",
"data",
".",
"get_worker_info",
"(",
")",
"is",
"not",
"None",
":",
"# If we're in a background process, concatenate directly into a",
"# shared memory tensor to avoid an extra copy",
"numel",
"=",
"sum",
"(",
"x",
".",
"numel",
"(",
")",
"for",
"x",
"in",
"batch",
")",
"storage",
"=",
"elem",
".",
"storage",
"(",
")",
".",
"_new_shared",
"(",
"numel",
")",
"out",
"=",
"elem",
".",
"new",
"(",
"storage",
")",
".",
"resize_",
"(",
"len",
"(",
"batch",
")",
",",
"*",
"list",
"(",
"elem",
".",
"size",
"(",
")",
")",
")",
"return",
"torch",
".",
"stack",
"(",
"batch",
",",
"0",
",",
"out",
"=",
"out",
")",
"elif",
"elem_type",
".",
"__module__",
"==",
"'numpy'",
"and",
"elem_type",
".",
"__name__",
"!=",
"'str_'",
"and",
"elem_type",
".",
"__name__",
"!=",
"'string_'",
":",
"if",
"elem_type",
".",
"__name__",
"==",
"'ndarray'",
"or",
"elem_type",
".",
"__name__",
"==",
"'memmap'",
":",
"# array of string classes and object",
"if",
"np_str_obj_array_pattern",
".",
"search",
"(",
"elem",
".",
"dtype",
".",
"str",
")",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"default_collate_err_msg_format",
".",
"format",
"(",
"elem",
".",
"dtype",
")",
")",
"return",
"default_collate",
"(",
"[",
"torch",
".",
"as_tensor",
"(",
"b",
")",
"for",
"b",
"in",
"batch",
"]",
")",
"elif",
"elem",
".",
"shape",
"==",
"(",
")",
":",
"# scalars",
"return",
"torch",
".",
"as_tensor",
"(",
"batch",
")",
"elif",
"isinstance",
"(",
"elem",
",",
"float",
")",
":",
"return",
"torch",
".",
"tensor",
"(",
"batch",
",",
"dtype",
"=",
"torch",
".",
"float64",
")",
"elif",
"isinstance",
"(",
"elem",
",",
"int",
")",
":",
"return",
"torch",
".",
"tensor",
"(",
"batch",
")",
"elif",
"isinstance",
"(",
"elem",
",",
"string_classes",
")",
":",
"return",
"batch",
"elif",
"isinstance",
"(",
"elem",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
":",
"try",
":",
"return",
"elem_type",
"(",
"{",
"key",
":",
"default_collate",
"(",
"[",
"d",
"[",
"key",
"]",
"for",
"d",
"in",
"batch",
"]",
")",
"for",
"key",
"in",
"elem",
"}",
")",
"except",
"TypeError",
":",
"# The mapping type may not support `__init__(iterable)`.",
"return",
"{",
"key",
":",
"default_collate",
"(",
"[",
"d",
"[",
"key",
"]",
"for",
"d",
"in",
"batch",
"]",
")",
"for",
"key",
"in",
"elem",
"}",
"elif",
"isinstance",
"(",
"elem",
",",
"tuple",
")",
"and",
"hasattr",
"(",
"elem",
",",
"'_fields'",
")",
":",
"# namedtuple",
"return",
"elem_type",
"(",
"*",
"(",
"default_collate",
"(",
"samples",
")",
"for",
"samples",
"in",
"zip",
"(",
"*",
"batch",
")",
")",
")",
"elif",
"isinstance",
"(",
"elem",
",",
"collections",
".",
"abc",
".",
"Sequence",
")",
":",
"# check to make sure that the elements in batch have consistent size",
"it",
"=",
"iter",
"(",
"batch",
")",
"elem_size",
"=",
"len",
"(",
"next",
"(",
"it",
")",
")",
"if",
"not",
"all",
"(",
"len",
"(",
"elem",
")",
"==",
"elem_size",
"for",
"elem",
"in",
"it",
")",
":",
"raise",
"RuntimeError",
"(",
"'each element in list of batch should be of equal size'",
")",
"transposed",
"=",
"list",
"(",
"zip",
"(",
"*",
"batch",
")",
")",
"# It may be accessed twice, so we use a list.",
"if",
"isinstance",
"(",
"elem",
",",
"tuple",
")",
":",
"return",
"[",
"default_collate",
"(",
"samples",
")",
"for",
"samples",
"in",
"transposed",
"]",
"# Backwards compatibility.",
"else",
":",
"try",
":",
"return",
"elem_type",
"(",
"[",
"default_collate",
"(",
"samples",
")",
"for",
"samples",
"in",
"transposed",
"]",
")",
"except",
"TypeError",
":",
"# The sequence type may not support `__init__(iterable)` (e.g., `range`).",
"return",
"[",
"default_collate",
"(",
"samples",
")",
"for",
"samples",
"in",
"transposed",
"]",
"raise",
"TypeError",
"(",
"default_collate_err_msg_format",
".",
"format",
"(",
"elem_type",
")",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/data/_utils/collate.py#L84-L180 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/keycloak.py | python | run_admin_cmds | (ctx,config) | Running Keycloak Admin commands(kcadm commands) in order to get the token, aud value, thumbprint and realm name. | Running Keycloak Admin commands(kcadm commands) in order to get the token, aud value, thumbprint and realm name. | [
"Running",
"Keycloak",
"Admin",
"commands",
"(",
"kcadm",
"commands",
")",
"in",
"order",
"to",
"get",
"the",
"token",
"aud",
"value",
"thumbprint",
"and",
"realm",
"name",
"."
] | def run_admin_cmds(ctx,config):
"""
Running Keycloak Admin commands(kcadm commands) in order to get the token, aud value, thumbprint and realm name.
"""
assert isinstance(config, dict)
log.info('Running admin commands...')
for (client,_) in config.items():
(remote,) = ctx.cluster.only(client).remotes.keys()
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'config', 'credentials',
'--server', 'http://localhost:8080/auth',
'--realm', 'master',
'--user', 'admin',
'--password', 'admin',
'--client', 'admin-cli',
],
)
realm_name='demorealm'
realm='realm={}'.format(realm_name)
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'create', 'realms',
'-s', realm,
'-s', 'enabled=true',
'-s', 'accessTokenLifespan=1800',
'-o',
],
)
client_name='my_client'
client='clientId={}'.format(client_name)
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'create', 'clients',
'-r', realm_name,
'-s', client,
'-s', 'directAccessGrantsEnabled=true',
'-s', 'redirectUris=["http://localhost:8080/myapp/*"]',
],
)
ans1= toxvenv_sh(ctx, remote,
[
'cd', '{tdir}/bin'.format(tdir=get_keycloak_dir(ctx,config)), run.Raw('&&'),
'./kcadm.sh', 'get', 'clients',
'-r', realm_name,
'-F', 'id,clientId', run.Raw('|'),
'jq', '-r', '.[] | select (.clientId == "my_client") | .id'
])
pre0=ans1.rstrip()
pre1="clients/{}".format(pre0)
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'update', pre1,
'-r', realm_name,
'-s', 'enabled=true',
'-s', 'serviceAccountsEnabled=true',
'-s', 'redirectUris=["http://localhost:8080/myapp/*"]',
],
)
ans2= pre1+'/client-secret'
out2= toxvenv_sh(ctx, remote,
[
'cd', '{tdir}/bin'.format(tdir=get_keycloak_dir(ctx,config)), run.Raw('&&'),
'./kcadm.sh', 'get', ans2,
'-r', realm_name,
'-F', 'value'
])
ans0= '{client}:{secret}'.format(client=client_name,secret=out2[15:51])
ans3= 'client_secret={}'.format(out2[15:51])
clientid='client_id={}'.format(client_name)
proto_map = pre1+"/protocol-mappers/models"
uname = "username=testuser"
upass = "password=testuser"
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'create', 'users',
'-s', uname,
'-s', 'enabled=true',
'-s', 'attributes.\"https://aws.amazon.com/tags\"=\"{"principal_tags":{"Department":["Engineering", "Marketing"]}}\"',
'-r', realm_name,
],
)
sample = 'testuser'
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'set-password',
'-r', realm_name,
'--username', sample,
'--new-password', sample,
],
)
file_path = '{tdir}/scripts/confi.py'.format(tdir=teuthology.get_testdir(ctx))
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'create', proto_map,
'-r', realm_name,
'-f', file_path,
],
)
remote.run(
args=[
'{tdir}/bin/kcadm.sh'.format(tdir=get_keycloak_dir(ctx,config)),
'config', 'credentials',
'--server', 'http://localhost:8080/auth',
'--realm', realm_name,
'--user', sample,
'--password', sample,
'--client', 'admin-cli',
],
)
out9= toxvenv_sh(ctx, remote,
[
'curl', '-k', '-v',
'-X', 'POST',
'-H', 'Content-Type:application/x-www-form-urlencoded',
'-d', 'scope=openid',
'-d', 'grant_type=password',
'-d', clientid,
'-d', ans3,
'-d', uname,
'-d', upass,
'http://localhost:8080/auth/realms/'+realm_name+'/protocol/openid-connect/token', run.Raw('|'),
'jq', '-r', '.access_token'
])
user_token_pre = out9.rstrip()
user_token = '{}'.format(user_token_pre)
out3= toxvenv_sh(ctx, remote,
[
'curl', '-k', '-v',
'-X', 'POST',
'-H', 'Content-Type:application/x-www-form-urlencoded',
'-d', 'scope=openid',
'-d', 'grant_type=client_credentials',
'-d', clientid,
'-d', ans3,
'http://localhost:8080/auth/realms/'+realm_name+'/protocol/openid-connect/token', run.Raw('|'),
'jq', '-r', '.access_token'
])
pre2=out3.rstrip()
acc_token= 'token={}'.format(pre2)
ans4= '{}'.format(pre2)
out4= toxvenv_sh(ctx, remote,
[
'curl', '-k', '-v',
'-X', 'GET',
'-H', 'Content-Type:application/x-www-form-urlencoded',
'http://localhost:8080/auth/realms/'+realm_name+'/protocol/openid-connect/certs', run.Raw('|'),
'jq', '-r', '.keys[].x5c[]'
])
pre3=out4.rstrip()
cert_value='{}'.format(pre3)
start_value= "-----BEGIN CERTIFICATE-----\n"
end_value= "\n-----END CERTIFICATE-----"
user_data=""
user_data+=start_value
user_data+=cert_value
user_data+=end_value
remote.write_file(
path='{tdir}/bin/certificate.crt'.format(tdir=get_keycloak_dir(ctx,config)),
data=user_data
)
out5= toxvenv_sh(ctx, remote,
[
'openssl', 'x509',
'-in', '{tdir}/bin/certificate.crt'.format(tdir=get_keycloak_dir(ctx,config)),
'--fingerprint', '--noout', '-sha1'
])
pre_ans= '{}'.format(out5[17:76])
ans5=""
for character in pre_ans:
if(character!=':'):
ans5+=character
str1 = 'curl'
str2 = '-k'
str3 = '-v'
str4 = '-X'
str5 = 'POST'
str6 = '-u'
str7 = '-d'
str8 = 'http://localhost:8080/auth/realms/'+realm_name+'/protocol/openid-connect/token/introspect'
out6= toxvenv_sh(ctx, remote,
[
str1, str2, str3, str4, str5, str6, ans0, str7, acc_token, str8, run.Raw('|'), 'jq', '-r', '.aud'
])
out7= toxvenv_sh(ctx, remote,
[
str1, str2, str3, str4, str5, str6, ans0, str7, acc_token, str8, run.Raw('|'), 'jq', '-r', '.sub'
])
out8= toxvenv_sh(ctx, remote,
[
str1, str2, str3, str4, str5, str6, ans0, str7, acc_token, str8, run.Raw('|'), 'jq', '-r', '.azp'
])
ans6=out6.rstrip()
ans7=out7.rstrip()
ans8=out8.rstrip()
os.environ['TOKEN']=ans4
os.environ['THUMBPRINT']=ans5
os.environ['AUD']=ans6
os.environ['SUB']=ans7
os.environ['AZP']=ans8
os.environ['USER_TOKEN']=user_token
os.environ['KC_REALM']=realm_name
try:
yield
finally:
log.info('Removing certificate.crt file...')
for (client,_) in config.items():
(remote,) = ctx.cluster.only(client).remotes.keys()
remote.run(
args=['rm', '-f',
'{tdir}/bin/certificate.crt'.format(tdir=get_keycloak_dir(ctx,config)),
],
)
remote.run(
args=['rm', '-f',
'{tdir}/confi.py'.format(tdir=teuthology.get_testdir(ctx)),
],
) | [
"def",
"run_admin_cmds",
"(",
"ctx",
",",
"config",
")",
":",
"assert",
"isinstance",
"(",
"config",
",",
"dict",
")",
"log",
".",
"info",
"(",
"'Running admin commands...'",
")",
"for",
"(",
"client",
",",
"_",
")",
"in",
"config",
".",
"items",
"(",
")",
":",
"(",
"remote",
",",
")",
"=",
"ctx",
".",
"cluster",
".",
"only",
"(",
"client",
")",
".",
"remotes",
".",
"keys",
"(",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'config'",
",",
"'credentials'",
",",
"'--server'",
",",
"'http://localhost:8080/auth'",
",",
"'--realm'",
",",
"'master'",
",",
"'--user'",
",",
"'admin'",
",",
"'--password'",
",",
"'admin'",
",",
"'--client'",
",",
"'admin-cli'",
",",
"]",
",",
")",
"realm_name",
"=",
"'demorealm'",
"realm",
"=",
"'realm={}'",
".",
"format",
"(",
"realm_name",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'create'",
",",
"'realms'",
",",
"'-s'",
",",
"realm",
",",
"'-s'",
",",
"'enabled=true'",
",",
"'-s'",
",",
"'accessTokenLifespan=1800'",
",",
"'-o'",
",",
"]",
",",
")",
"client_name",
"=",
"'my_client'",
"client",
"=",
"'clientId={}'",
".",
"format",
"(",
"client_name",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'create'",
",",
"'clients'",
",",
"'-r'",
",",
"realm_name",
",",
"'-s'",
",",
"client",
",",
"'-s'",
",",
"'directAccessGrantsEnabled=true'",
",",
"'-s'",
",",
"'redirectUris=[\"http://localhost:8080/myapp/*\"]'",
",",
"]",
",",
")",
"ans1",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"'cd'",
",",
"'{tdir}/bin'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"run",
".",
"Raw",
"(",
"'&&'",
")",
",",
"'./kcadm.sh'",
",",
"'get'",
",",
"'clients'",
",",
"'-r'",
",",
"realm_name",
",",
"'-F'",
",",
"'id,clientId'",
",",
"run",
".",
"Raw",
"(",
"'|'",
")",
",",
"'jq'",
",",
"'-r'",
",",
"'.[] | select (.clientId == \"my_client\") | .id'",
"]",
")",
"pre0",
"=",
"ans1",
".",
"rstrip",
"(",
")",
"pre1",
"=",
"\"clients/{}\"",
".",
"format",
"(",
"pre0",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'update'",
",",
"pre1",
",",
"'-r'",
",",
"realm_name",
",",
"'-s'",
",",
"'enabled=true'",
",",
"'-s'",
",",
"'serviceAccountsEnabled=true'",
",",
"'-s'",
",",
"'redirectUris=[\"http://localhost:8080/myapp/*\"]'",
",",
"]",
",",
")",
"ans2",
"=",
"pre1",
"+",
"'/client-secret'",
"out2",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"'cd'",
",",
"'{tdir}/bin'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"run",
".",
"Raw",
"(",
"'&&'",
")",
",",
"'./kcadm.sh'",
",",
"'get'",
",",
"ans2",
",",
"'-r'",
",",
"realm_name",
",",
"'-F'",
",",
"'value'",
"]",
")",
"ans0",
"=",
"'{client}:{secret}'",
".",
"format",
"(",
"client",
"=",
"client_name",
",",
"secret",
"=",
"out2",
"[",
"15",
":",
"51",
"]",
")",
"ans3",
"=",
"'client_secret={}'",
".",
"format",
"(",
"out2",
"[",
"15",
":",
"51",
"]",
")",
"clientid",
"=",
"'client_id={}'",
".",
"format",
"(",
"client_name",
")",
"proto_map",
"=",
"pre1",
"+",
"\"/protocol-mappers/models\"",
"uname",
"=",
"\"username=testuser\"",
"upass",
"=",
"\"password=testuser\"",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'create'",
",",
"'users'",
",",
"'-s'",
",",
"uname",
",",
"'-s'",
",",
"'enabled=true'",
",",
"'-s'",
",",
"'attributes.\\\"https://aws.amazon.com/tags\\\"=\\\"{\"principal_tags\":{\"Department\":[\"Engineering\", \"Marketing\"]}}\\\"'",
",",
"'-r'",
",",
"realm_name",
",",
"]",
",",
")",
"sample",
"=",
"'testuser'",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'set-password'",
",",
"'-r'",
",",
"realm_name",
",",
"'--username'",
",",
"sample",
",",
"'--new-password'",
",",
"sample",
",",
"]",
",",
")",
"file_path",
"=",
"'{tdir}/scripts/confi.py'",
".",
"format",
"(",
"tdir",
"=",
"teuthology",
".",
"get_testdir",
"(",
"ctx",
")",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'create'",
",",
"proto_map",
",",
"'-r'",
",",
"realm_name",
",",
"'-f'",
",",
"file_path",
",",
"]",
",",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'{tdir}/bin/kcadm.sh'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'config'",
",",
"'credentials'",
",",
"'--server'",
",",
"'http://localhost:8080/auth'",
",",
"'--realm'",
",",
"realm_name",
",",
"'--user'",
",",
"sample",
",",
"'--password'",
",",
"sample",
",",
"'--client'",
",",
"'admin-cli'",
",",
"]",
",",
")",
"out9",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"'curl'",
",",
"'-k'",
",",
"'-v'",
",",
"'-X'",
",",
"'POST'",
",",
"'-H'",
",",
"'Content-Type:application/x-www-form-urlencoded'",
",",
"'-d'",
",",
"'scope=openid'",
",",
"'-d'",
",",
"'grant_type=password'",
",",
"'-d'",
",",
"clientid",
",",
"'-d'",
",",
"ans3",
",",
"'-d'",
",",
"uname",
",",
"'-d'",
",",
"upass",
",",
"'http://localhost:8080/auth/realms/'",
"+",
"realm_name",
"+",
"'/protocol/openid-connect/token'",
",",
"run",
".",
"Raw",
"(",
"'|'",
")",
",",
"'jq'",
",",
"'-r'",
",",
"'.access_token'",
"]",
")",
"user_token_pre",
"=",
"out9",
".",
"rstrip",
"(",
")",
"user_token",
"=",
"'{}'",
".",
"format",
"(",
"user_token_pre",
")",
"out3",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"'curl'",
",",
"'-k'",
",",
"'-v'",
",",
"'-X'",
",",
"'POST'",
",",
"'-H'",
",",
"'Content-Type:application/x-www-form-urlencoded'",
",",
"'-d'",
",",
"'scope=openid'",
",",
"'-d'",
",",
"'grant_type=client_credentials'",
",",
"'-d'",
",",
"clientid",
",",
"'-d'",
",",
"ans3",
",",
"'http://localhost:8080/auth/realms/'",
"+",
"realm_name",
"+",
"'/protocol/openid-connect/token'",
",",
"run",
".",
"Raw",
"(",
"'|'",
")",
",",
"'jq'",
",",
"'-r'",
",",
"'.access_token'",
"]",
")",
"pre2",
"=",
"out3",
".",
"rstrip",
"(",
")",
"acc_token",
"=",
"'token={}'",
".",
"format",
"(",
"pre2",
")",
"ans4",
"=",
"'{}'",
".",
"format",
"(",
"pre2",
")",
"out4",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"'curl'",
",",
"'-k'",
",",
"'-v'",
",",
"'-X'",
",",
"'GET'",
",",
"'-H'",
",",
"'Content-Type:application/x-www-form-urlencoded'",
",",
"'http://localhost:8080/auth/realms/'",
"+",
"realm_name",
"+",
"'/protocol/openid-connect/certs'",
",",
"run",
".",
"Raw",
"(",
"'|'",
")",
",",
"'jq'",
",",
"'-r'",
",",
"'.keys[].x5c[]'",
"]",
")",
"pre3",
"=",
"out4",
".",
"rstrip",
"(",
")",
"cert_value",
"=",
"'{}'",
".",
"format",
"(",
"pre3",
")",
"start_value",
"=",
"\"-----BEGIN CERTIFICATE-----\\n\"",
"end_value",
"=",
"\"\\n-----END CERTIFICATE-----\"",
"user_data",
"=",
"\"\"",
"user_data",
"+=",
"start_value",
"user_data",
"+=",
"cert_value",
"user_data",
"+=",
"end_value",
"remote",
".",
"write_file",
"(",
"path",
"=",
"'{tdir}/bin/certificate.crt'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"data",
"=",
"user_data",
")",
"out5",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"'openssl'",
",",
"'x509'",
",",
"'-in'",
",",
"'{tdir}/bin/certificate.crt'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"'--fingerprint'",
",",
"'--noout'",
",",
"'-sha1'",
"]",
")",
"pre_ans",
"=",
"'{}'",
".",
"format",
"(",
"out5",
"[",
"17",
":",
"76",
"]",
")",
"ans5",
"=",
"\"\"",
"for",
"character",
"in",
"pre_ans",
":",
"if",
"(",
"character",
"!=",
"':'",
")",
":",
"ans5",
"+=",
"character",
"str1",
"=",
"'curl'",
"str2",
"=",
"'-k'",
"str3",
"=",
"'-v'",
"str4",
"=",
"'-X'",
"str5",
"=",
"'POST'",
"str6",
"=",
"'-u'",
"str7",
"=",
"'-d'",
"str8",
"=",
"'http://localhost:8080/auth/realms/'",
"+",
"realm_name",
"+",
"'/protocol/openid-connect/token/introspect'",
"out6",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"str1",
",",
"str2",
",",
"str3",
",",
"str4",
",",
"str5",
",",
"str6",
",",
"ans0",
",",
"str7",
",",
"acc_token",
",",
"str8",
",",
"run",
".",
"Raw",
"(",
"'|'",
")",
",",
"'jq'",
",",
"'-r'",
",",
"'.aud'",
"]",
")",
"out7",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"str1",
",",
"str2",
",",
"str3",
",",
"str4",
",",
"str5",
",",
"str6",
",",
"ans0",
",",
"str7",
",",
"acc_token",
",",
"str8",
",",
"run",
".",
"Raw",
"(",
"'|'",
")",
",",
"'jq'",
",",
"'-r'",
",",
"'.sub'",
"]",
")",
"out8",
"=",
"toxvenv_sh",
"(",
"ctx",
",",
"remote",
",",
"[",
"str1",
",",
"str2",
",",
"str3",
",",
"str4",
",",
"str5",
",",
"str6",
",",
"ans0",
",",
"str7",
",",
"acc_token",
",",
"str8",
",",
"run",
".",
"Raw",
"(",
"'|'",
")",
",",
"'jq'",
",",
"'-r'",
",",
"'.azp'",
"]",
")",
"ans6",
"=",
"out6",
".",
"rstrip",
"(",
")",
"ans7",
"=",
"out7",
".",
"rstrip",
"(",
")",
"ans8",
"=",
"out8",
".",
"rstrip",
"(",
")",
"os",
".",
"environ",
"[",
"'TOKEN'",
"]",
"=",
"ans4",
"os",
".",
"environ",
"[",
"'THUMBPRINT'",
"]",
"=",
"ans5",
"os",
".",
"environ",
"[",
"'AUD'",
"]",
"=",
"ans6",
"os",
".",
"environ",
"[",
"'SUB'",
"]",
"=",
"ans7",
"os",
".",
"environ",
"[",
"'AZP'",
"]",
"=",
"ans8",
"os",
".",
"environ",
"[",
"'USER_TOKEN'",
"]",
"=",
"user_token",
"os",
".",
"environ",
"[",
"'KC_REALM'",
"]",
"=",
"realm_name",
"try",
":",
"yield",
"finally",
":",
"log",
".",
"info",
"(",
"'Removing certificate.crt file...'",
")",
"for",
"(",
"client",
",",
"_",
")",
"in",
"config",
".",
"items",
"(",
")",
":",
"(",
"remote",
",",
")",
"=",
"ctx",
".",
"cluster",
".",
"only",
"(",
"client",
")",
".",
"remotes",
".",
"keys",
"(",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'rm'",
",",
"'-f'",
",",
"'{tdir}/bin/certificate.crt'",
".",
"format",
"(",
"tdir",
"=",
"get_keycloak_dir",
"(",
"ctx",
",",
"config",
")",
")",
",",
"]",
",",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"'rm'",
",",
"'-f'",
",",
"'{tdir}/confi.py'",
".",
"format",
"(",
"tdir",
"=",
"teuthology",
".",
"get_testdir",
"(",
"ctx",
")",
")",
",",
"]",
",",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/keycloak.py#L158-L418 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/xml/sax/handler.py | python | ContentHandler.startPrefixMapping | (self, prefix, uri) | Begin the scope of a prefix-URI Namespace mapping.
The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the
default).
There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the
start/endPrefixMapping event supplies the information to the
application to expand prefixes in those contexts itself, if
necessary.
Note that start/endPrefixMapping events are not guaranteed to
be properly nested relative to each-other: all
startPrefixMapping events will occur before the corresponding
startElement event, and all endPrefixMapping events will occur
after the corresponding endElement event, but their order is
not guaranteed. | Begin the scope of a prefix-URI Namespace mapping. | [
"Begin",
"the",
"scope",
"of",
"a",
"prefix",
"-",
"URI",
"Namespace",
"mapping",
"."
] | def startPrefixMapping(self, prefix, uri):
"""Begin the scope of a prefix-URI Namespace mapping.
The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the
default).
There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the
start/endPrefixMapping event supplies the information to the
application to expand prefixes in those contexts itself, if
necessary.
Note that start/endPrefixMapping events are not guaranteed to
be properly nested relative to each-other: all
startPrefixMapping events will occur before the corresponding
startElement event, and all endPrefixMapping events will occur
after the corresponding endElement event, but their order is
not guaranteed.""" | [
"def",
"startPrefixMapping",
"(",
"self",
",",
"prefix",
",",
"uri",
")",
":"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/xml/sax/handler.py#L96-L117 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/tensorboard/backend/server.py | python | ParseEventFilesSpec | (logdir) | return files | Parses `logdir` into a map from paths to run group names.
The events files flag format is a comma-separated list of path specifications.
A path specification either looks like 'group_name:/path/to/directory' or
'/path/to/directory'; in the latter case, the group is unnamed. Group names
cannot start with a forward slash: /foo:bar/baz will be interpreted as a
spec with no name and path '/foo:bar/baz'.
Globs are not supported.
Args:
logdir: A comma-separated list of run specifications.
Returns:
A dict mapping directory paths to names like {'/path/to/directory': 'name'}.
Groups without an explicit name are named after their path. If logdir is
None, returns an empty dict, which is helpful for testing things that don't
require any valid runs. | Parses `logdir` into a map from paths to run group names. | [
"Parses",
"logdir",
"into",
"a",
"map",
"from",
"paths",
"to",
"run",
"group",
"names",
"."
] | def ParseEventFilesSpec(logdir):
"""Parses `logdir` into a map from paths to run group names.
The events files flag format is a comma-separated list of path specifications.
A path specification either looks like 'group_name:/path/to/directory' or
'/path/to/directory'; in the latter case, the group is unnamed. Group names
cannot start with a forward slash: /foo:bar/baz will be interpreted as a
spec with no name and path '/foo:bar/baz'.
Globs are not supported.
Args:
logdir: A comma-separated list of run specifications.
Returns:
A dict mapping directory paths to names like {'/path/to/directory': 'name'}.
Groups without an explicit name are named after their path. If logdir is
None, returns an empty dict, which is helpful for testing things that don't
require any valid runs.
"""
files = {}
if logdir is None:
return files
for specification in logdir.split(','):
# If it's a gcs path, don't split on colon
if gcs.IsGCSPath(specification):
run_name = None
path = specification
# If the spec looks like /foo:bar/baz, then we assume it's a path with a
# colon.
elif ':' in specification and specification[0] != '/':
# We split at most once so run_name:/path:with/a/colon will work.
run_name, _, path = specification.partition(':')
else:
run_name = None
path = specification
if not gcs.IsGCSPath(path):
path = os.path.realpath(path)
files[path] = run_name
return files | [
"def",
"ParseEventFilesSpec",
"(",
"logdir",
")",
":",
"files",
"=",
"{",
"}",
"if",
"logdir",
"is",
"None",
":",
"return",
"files",
"for",
"specification",
"in",
"logdir",
".",
"split",
"(",
"','",
")",
":",
"# If it's a gcs path, don't split on colon",
"if",
"gcs",
".",
"IsGCSPath",
"(",
"specification",
")",
":",
"run_name",
"=",
"None",
"path",
"=",
"specification",
"# If the spec looks like /foo:bar/baz, then we assume it's a path with a",
"# colon.",
"elif",
"':'",
"in",
"specification",
"and",
"specification",
"[",
"0",
"]",
"!=",
"'/'",
":",
"# We split at most once so run_name:/path:with/a/colon will work.",
"run_name",
",",
"_",
",",
"path",
"=",
"specification",
".",
"partition",
"(",
"':'",
")",
"else",
":",
"run_name",
"=",
"None",
"path",
"=",
"specification",
"if",
"not",
"gcs",
".",
"IsGCSPath",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"files",
"[",
"path",
"]",
"=",
"run_name",
"return",
"files"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/tensorboard/backend/server.py#L48-L86 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/framework/checkpoint_utils.py | python | list_variables | (checkpoint_dir) | return result | Returns list of all variables in the latest checkpoint.
Args:
checkpoint_dir: Directory with checkpoints file or path to checkpoint.
Returns:
List of tuples `(name, shape)`. | Returns list of all variables in the latest checkpoint. | [
"Returns",
"list",
"of",
"all",
"variables",
"in",
"the",
"latest",
"checkpoint",
"."
] | def list_variables(checkpoint_dir):
"""Returns list of all variables in the latest checkpoint.
Args:
checkpoint_dir: Directory with checkpoints file or path to checkpoint.
Returns:
List of tuples `(name, shape)`.
"""
reader = load_checkpoint(checkpoint_dir)
variable_map = reader.get_variable_to_shape_map()
names = sorted(variable_map.keys())
result = []
for name in names:
result.append((name, variable_map[name]))
return result | [
"def",
"list_variables",
"(",
"checkpoint_dir",
")",
":",
"reader",
"=",
"load_checkpoint",
"(",
"checkpoint_dir",
")",
"variable_map",
"=",
"reader",
".",
"get_variable_to_shape_map",
"(",
")",
"names",
"=",
"sorted",
"(",
"variable_map",
".",
"keys",
"(",
")",
")",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"result",
".",
"append",
"(",
"(",
"name",
",",
"variable_map",
"[",
"name",
"]",
")",
")",
"return",
"result"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/framework/checkpoint_utils.py#L84-L99 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/metrics/classification.py | python | matthews_corrcoef | (y_true, y_pred, sample_weight=None) | Compute the Matthews correlation coefficient (MCC) for binary classes
The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary (two-class) classifications. It takes into
account true and false positives and negatives and is generally regarded as
a balanced measure which can be used even if the classes are of very
different sizes. The MCC is in essence a correlation coefficient value
between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
an average random prediction and -1 an inverse prediction. The statistic
is also known as the phi coefficient. [source: Wikipedia]
Only in the binary case does this relate to information about true and
false positives and negatives. See references below.
Read more in the :ref:`User Guide <matthews_corrcoef>`.
Parameters
----------
y_true : array, shape = [n_samples]
Ground truth (correct) target values.
y_pred : array, shape = [n_samples]
Estimated targets as returned by a classifier.
sample_weight : array-like of shape = [n_samples], default None
Sample weights.
Returns
-------
mcc : float
The Matthews correlation coefficient (+1 represents a perfect
prediction, 0 an average random prediction and -1 and inverse
prediction).
References
----------
.. [1] `Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the
accuracy of prediction algorithms for classification: an overview
<http://dx.doi.org/10.1093/bioinformatics/16.5.412>`_
.. [2] `Wikipedia entry for the Matthews Correlation Coefficient
<https://en.wikipedia.org/wiki/Matthews_correlation_coefficient>`_
Examples
--------
>>> from sklearn.metrics import matthews_corrcoef
>>> y_true = [+1, +1, +1, -1]
>>> y_pred = [+1, -1, +1, +1]
>>> matthews_corrcoef(y_true, y_pred) # doctest: +ELLIPSIS
-0.33... | Compute the Matthews correlation coefficient (MCC) for binary classes | [
"Compute",
"the",
"Matthews",
"correlation",
"coefficient",
"(",
"MCC",
")",
"for",
"binary",
"classes"
] | def matthews_corrcoef(y_true, y_pred, sample_weight=None):
"""Compute the Matthews correlation coefficient (MCC) for binary classes
The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary (two-class) classifications. It takes into
account true and false positives and negatives and is generally regarded as
a balanced measure which can be used even if the classes are of very
different sizes. The MCC is in essence a correlation coefficient value
between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
an average random prediction and -1 an inverse prediction. The statistic
is also known as the phi coefficient. [source: Wikipedia]
Only in the binary case does this relate to information about true and
false positives and negatives. See references below.
Read more in the :ref:`User Guide <matthews_corrcoef>`.
Parameters
----------
y_true : array, shape = [n_samples]
Ground truth (correct) target values.
y_pred : array, shape = [n_samples]
Estimated targets as returned by a classifier.
sample_weight : array-like of shape = [n_samples], default None
Sample weights.
Returns
-------
mcc : float
The Matthews correlation coefficient (+1 represents a perfect
prediction, 0 an average random prediction and -1 and inverse
prediction).
References
----------
.. [1] `Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the
accuracy of prediction algorithms for classification: an overview
<http://dx.doi.org/10.1093/bioinformatics/16.5.412>`_
.. [2] `Wikipedia entry for the Matthews Correlation Coefficient
<https://en.wikipedia.org/wiki/Matthews_correlation_coefficient>`_
Examples
--------
>>> from sklearn.metrics import matthews_corrcoef
>>> y_true = [+1, +1, +1, -1]
>>> y_pred = [+1, -1, +1, +1]
>>> matthews_corrcoef(y_true, y_pred) # doctest: +ELLIPSIS
-0.33...
"""
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
if y_type != "binary":
raise ValueError("%s is not supported" % y_type)
lb = LabelEncoder()
lb.fit(np.hstack([y_true, y_pred]))
y_true = lb.transform(y_true)
y_pred = lb.transform(y_pred)
mean_yt = np.average(y_true, weights=sample_weight)
mean_yp = np.average(y_pred, weights=sample_weight)
y_true_u_cent = y_true - mean_yt
y_pred_u_cent = y_pred - mean_yp
cov_ytyp = np.average(y_true_u_cent * y_pred_u_cent, weights=sample_weight)
var_yt = np.average(y_true_u_cent ** 2, weights=sample_weight)
var_yp = np.average(y_pred_u_cent ** 2, weights=sample_weight)
mcc = cov_ytyp / np.sqrt(var_yt * var_yp)
if np.isnan(mcc):
return 0.
else:
return mcc | [
"def",
"matthews_corrcoef",
"(",
"y_true",
",",
"y_pred",
",",
"sample_weight",
"=",
"None",
")",
":",
"y_type",
",",
"y_true",
",",
"y_pred",
"=",
"_check_targets",
"(",
"y_true",
",",
"y_pred",
")",
"if",
"y_type",
"!=",
"\"binary\"",
":",
"raise",
"ValueError",
"(",
"\"%s is not supported\"",
"%",
"y_type",
")",
"lb",
"=",
"LabelEncoder",
"(",
")",
"lb",
".",
"fit",
"(",
"np",
".",
"hstack",
"(",
"[",
"y_true",
",",
"y_pred",
"]",
")",
")",
"y_true",
"=",
"lb",
".",
"transform",
"(",
"y_true",
")",
"y_pred",
"=",
"lb",
".",
"transform",
"(",
"y_pred",
")",
"mean_yt",
"=",
"np",
".",
"average",
"(",
"y_true",
",",
"weights",
"=",
"sample_weight",
")",
"mean_yp",
"=",
"np",
".",
"average",
"(",
"y_pred",
",",
"weights",
"=",
"sample_weight",
")",
"y_true_u_cent",
"=",
"y_true",
"-",
"mean_yt",
"y_pred_u_cent",
"=",
"y_pred",
"-",
"mean_yp",
"cov_ytyp",
"=",
"np",
".",
"average",
"(",
"y_true_u_cent",
"*",
"y_pred_u_cent",
",",
"weights",
"=",
"sample_weight",
")",
"var_yt",
"=",
"np",
".",
"average",
"(",
"y_true_u_cent",
"**",
"2",
",",
"weights",
"=",
"sample_weight",
")",
"var_yp",
"=",
"np",
".",
"average",
"(",
"y_pred_u_cent",
"**",
"2",
",",
"weights",
"=",
"sample_weight",
")",
"mcc",
"=",
"cov_ytyp",
"/",
"np",
".",
"sqrt",
"(",
"var_yt",
"*",
"var_yp",
")",
"if",
"np",
".",
"isnan",
"(",
"mcc",
")",
":",
"return",
"0.",
"else",
":",
"return",
"mcc"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/metrics/classification.py#L444-L521 | ||
thpatch/thcrap | 9a0ebc52ebc775d93a44ddfe19d1bed0c512958f | scripts/repo_update.py | python | patch_build | (patch_id, servers, f, t, ignored) | return patch_js['title'] | Updates the patch in the [f]/[patch_id] directory, ignoring the files
that match [ignored].
Ensures that patch.js contains all necessary keys and values, then updates
the checksums in files.js and, if [t] differs from [f], copies all patch
files from [f] to [t].
Returns the contents of the patch ID key in repo.js. | Updates the patch in the [f]/[patch_id] directory, ignoring the files
that match [ignored]. | [
"Updates",
"the",
"patch",
"in",
"the",
"[",
"f",
"]",
"/",
"[",
"patch_id",
"]",
"directory",
"ignoring",
"the",
"files",
"that",
"match",
"[",
"ignored",
"]",
"."
] | def patch_build(patch_id, servers, f, t, ignored):
"""Updates the patch in the [f]/[patch_id] directory, ignoring the files
that match [ignored].
Ensures that patch.js contains all necessary keys and values, then updates
the checksums in files.js and, if [t] differs from [f], copies all patch
files from [f] to [t].
Returns the contents of the patch ID key in repo.js."""
f_path, t_path = [os.path.join(i, patch_id) for i in [f, t]]
# Prepare patch.js.
f_patch_fn = os.path.join(f_path, 'patch.js')
patch_js = utils.json_load(f_patch_fn)
enter_missing(
patch_js, 'title', 'Enter a nice title for "{}": '.format(patch_id)
)
patch_js['id'] = patch_id
patch_js['servers'] = []
# Delete obsolete keys.
if 'files' in patch_js:
del(patch_js['files'])
for i in servers:
url = os.path.join(i, patch_id) + '/'
patch_js['servers'].append(str_slash_normalize(url))
utils.json_store(f_patch_fn, patch_js)
# Reset all old entries to a JSON null. This will delete any files on the
# client side that no longer exist in the patch.
try:
files_js = utils.json_load(os.path.join(f_path, 'files.js'))
for i in files_js:
files_js[i] = None
except FileNotFoundError:
files_js = {}
patch_size = 0
print(patch_id, end='')
for f_fn in patch_files_walk(f, f_path, ignored):
print('.', end='')
patch_fn = f_fn[len(f_path) + 1:]
t_fn = os.path.join(t_path, patch_fn)
with open(f_fn, 'rb') as f_file:
f_file_data = f_file.read()
# Ensure Unix line endings for JSON input
if f_fn.endswith(('.js', '.jdiff')) and b'\r\n' in f_file_data:
f_file_data = f_file_data.replace(b'\r\n', b'\n')
with open(f_fn, 'wb') as f_file:
f_file.write(f_file_data)
f_sum = zlib.crc32(f_file_data) & 0xffffffff
files_js[str_slash_normalize(patch_fn)] = f_sum
patch_size += len(f_file_data)
del(f_file_data)
os.makedirs(os.path.dirname(t_fn), exist_ok=True)
if f != t:
shutil.copy2(f_fn, t_fn)
utils.json_store('files.js', files_js, dirs=[f_path, t_path])
print(
'{num} files, {size}'.format(
num=len({k: v for k, v in files_js.items() if v is not None}),
size=sizeof_fmt(patch_size)
)
)
return patch_js['title'] | [
"def",
"patch_build",
"(",
"patch_id",
",",
"servers",
",",
"f",
",",
"t",
",",
"ignored",
")",
":",
"f_path",
",",
"t_path",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"i",
",",
"patch_id",
")",
"for",
"i",
"in",
"[",
"f",
",",
"t",
"]",
"]",
"# Prepare patch.js.",
"f_patch_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"f_path",
",",
"'patch.js'",
")",
"patch_js",
"=",
"utils",
".",
"json_load",
"(",
"f_patch_fn",
")",
"enter_missing",
"(",
"patch_js",
",",
"'title'",
",",
"'Enter a nice title for \"{}\": '",
".",
"format",
"(",
"patch_id",
")",
")",
"patch_js",
"[",
"'id'",
"]",
"=",
"patch_id",
"patch_js",
"[",
"'servers'",
"]",
"=",
"[",
"]",
"# Delete obsolete keys.",
"if",
"'files'",
"in",
"patch_js",
":",
"del",
"(",
"patch_js",
"[",
"'files'",
"]",
")",
"for",
"i",
"in",
"servers",
":",
"url",
"=",
"os",
".",
"path",
".",
"join",
"(",
"i",
",",
"patch_id",
")",
"+",
"'/'",
"patch_js",
"[",
"'servers'",
"]",
".",
"append",
"(",
"str_slash_normalize",
"(",
"url",
")",
")",
"utils",
".",
"json_store",
"(",
"f_patch_fn",
",",
"patch_js",
")",
"# Reset all old entries to a JSON null. This will delete any files on the",
"# client side that no longer exist in the patch.",
"try",
":",
"files_js",
"=",
"utils",
".",
"json_load",
"(",
"os",
".",
"path",
".",
"join",
"(",
"f_path",
",",
"'files.js'",
")",
")",
"for",
"i",
"in",
"files_js",
":",
"files_js",
"[",
"i",
"]",
"=",
"None",
"except",
"FileNotFoundError",
":",
"files_js",
"=",
"{",
"}",
"patch_size",
"=",
"0",
"print",
"(",
"patch_id",
",",
"end",
"=",
"''",
")",
"for",
"f_fn",
"in",
"patch_files_walk",
"(",
"f",
",",
"f_path",
",",
"ignored",
")",
":",
"print",
"(",
"'.'",
",",
"end",
"=",
"''",
")",
"patch_fn",
"=",
"f_fn",
"[",
"len",
"(",
"f_path",
")",
"+",
"1",
":",
"]",
"t_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"t_path",
",",
"patch_fn",
")",
"with",
"open",
"(",
"f_fn",
",",
"'rb'",
")",
"as",
"f_file",
":",
"f_file_data",
"=",
"f_file",
".",
"read",
"(",
")",
"# Ensure Unix line endings for JSON input",
"if",
"f_fn",
".",
"endswith",
"(",
"(",
"'.js'",
",",
"'.jdiff'",
")",
")",
"and",
"b'\\r\\n'",
"in",
"f_file_data",
":",
"f_file_data",
"=",
"f_file_data",
".",
"replace",
"(",
"b'\\r\\n'",
",",
"b'\\n'",
")",
"with",
"open",
"(",
"f_fn",
",",
"'wb'",
")",
"as",
"f_file",
":",
"f_file",
".",
"write",
"(",
"f_file_data",
")",
"f_sum",
"=",
"zlib",
".",
"crc32",
"(",
"f_file_data",
")",
"&",
"0xffffffff",
"files_js",
"[",
"str_slash_normalize",
"(",
"patch_fn",
")",
"]",
"=",
"f_sum",
"patch_size",
"+=",
"len",
"(",
"f_file_data",
")",
"del",
"(",
"f_file_data",
")",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"t_fn",
")",
",",
"exist_ok",
"=",
"True",
")",
"if",
"f",
"!=",
"t",
":",
"shutil",
".",
"copy2",
"(",
"f_fn",
",",
"t_fn",
")",
"utils",
".",
"json_store",
"(",
"'files.js'",
",",
"files_js",
",",
"dirs",
"=",
"[",
"f_path",
",",
"t_path",
"]",
")",
"print",
"(",
"'{num} files, {size}'",
".",
"format",
"(",
"num",
"=",
"len",
"(",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"files_js",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}",
")",
",",
"size",
"=",
"sizeof_fmt",
"(",
"patch_size",
")",
")",
")",
"return",
"patch_js",
"[",
"'title'",
"]"
] | https://github.com/thpatch/thcrap/blob/9a0ebc52ebc775d93a44ddfe19d1bed0c512958f/scripts/repo_update.py#L99-L169 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/turtle.py | python | TPen.isdown | (self) | return self._drawing | Return True if pen is down, False if it's up.
No argument.
Example (for a Turtle instance named turtle):
>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True | Return True if pen is down, False if it's up. | [
"Return",
"True",
"if",
"pen",
"is",
"down",
"False",
"if",
"it",
"s",
"up",
"."
] | def isdown(self):
"""Return True if pen is down, False if it's up.
No argument.
Example (for a Turtle instance named turtle):
>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True
"""
return self._drawing | [
"def",
"isdown",
"(",
"self",
")",
":",
"return",
"self",
".",
"_drawing"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L2038-L2051 | |
eomahony/Numberjack | 53fa9e994a36f881ffd320d8d04158097190aad8 | Numberjack/__init__.py | python | NBJ_STD_Solver.load_mps | (self, filename, extension) | Asks the underlying MIP solver to load an MPS file.
:param filename: the path to the file.
:param extension: the file's extension.
:raises UnsupportedSolverFunction: if called on a non MIP solver. | Asks the underlying MIP solver to load an MPS file. | [
"Asks",
"the",
"underlying",
"MIP",
"solver",
"to",
"load",
"an",
"MPS",
"file",
"."
] | def load_mps(self, filename, extension):
"""
Asks the underlying MIP solver to load an MPS file.
:param filename: the path to the file.
:param extension: the file's extension.
:raises UnsupportedSolverFunction: if called on a non MIP solver.
"""
if not hasattr(self.solver, 'load_mps'):
raise UnsupportedSolverFunction(
str(type(self)), "load_mps", "Please load the model using a "
"MIP solver to use this functionality.")
self.solver.load_mps(filename, extension) | [
"def",
"load_mps",
"(",
"self",
",",
"filename",
",",
"extension",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"solver",
",",
"'load_mps'",
")",
":",
"raise",
"UnsupportedSolverFunction",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
",",
"\"load_mps\"",
",",
"\"Please load the model using a \"",
"\"MIP solver to use this functionality.\"",
")",
"self",
".",
"solver",
".",
"load_mps",
"(",
"filename",
",",
"extension",
")"
] | https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L3845-L3857 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListItem.SetAlign | (self, align) | Sets the alignment for the item.
:param `align`: one of the following bits:
============================ ========= ==============================
Alignment Bits Hex Value Description
============================ ========= ==============================
``ULC_FORMAT_LEFT`` 0x0 The item is left-aligned
``ULC_FORMAT_RIGHT`` 0x1 The item is right-aligned
``ULC_FORMAT_CENTRE`` 0x2 The item is centre-aligned
``ULC_FORMAT_CENTER`` 0x2 The item is center-aligned
============================ ========= ============================== | Sets the alignment for the item. | [
"Sets",
"the",
"alignment",
"for",
"the",
"item",
"."
] | def SetAlign(self, align):
"""
Sets the alignment for the item.
:param `align`: one of the following bits:
============================ ========= ==============================
Alignment Bits Hex Value Description
============================ ========= ==============================
``ULC_FORMAT_LEFT`` 0x0 The item is left-aligned
``ULC_FORMAT_RIGHT`` 0x1 The item is right-aligned
``ULC_FORMAT_CENTRE`` 0x2 The item is centre-aligned
``ULC_FORMAT_CENTER`` 0x2 The item is center-aligned
============================ ========= ==============================
"""
self._mask |= ULC_MASK_FORMAT
self._format = align | [
"def",
"SetAlign",
"(",
"self",
",",
"align",
")",
":",
"self",
".",
"_mask",
"|=",
"ULC_MASK_FORMAT",
"self",
".",
"_format",
"=",
"align"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L1593-L1611 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.CaptureMouse | (*args, **kwargs) | return _core_.Window_CaptureMouse(*args, **kwargs) | CaptureMouse(self)
Directs all mouse input to this window. Call wx.Window.ReleaseMouse to
release the capture.
Note that wxWindows maintains the stack of windows having captured the
mouse and when the mouse is released the capture returns to the window
which had had captured it previously and it is only really released if
there were no previous window. In particular, this means that you must
release the mouse as many times as you capture it, unless the window
receives the `wx.MouseCaptureLostEvent` event.
Any application which captures the mouse in the beginning of some
operation *must* handle `wx.MouseCaptureLostEvent` and cancel this
operation when it receives the event. The event handler must not
recapture mouse. | CaptureMouse(self) | [
"CaptureMouse",
"(",
"self",
")"
] | def CaptureMouse(*args, **kwargs):
"""
CaptureMouse(self)
Directs all mouse input to this window. Call wx.Window.ReleaseMouse to
release the capture.
Note that wxWindows maintains the stack of windows having captured the
mouse and when the mouse is released the capture returns to the window
which had had captured it previously and it is only really released if
there were no previous window. In particular, this means that you must
release the mouse as many times as you capture it, unless the window
receives the `wx.MouseCaptureLostEvent` event.
Any application which captures the mouse in the beginning of some
operation *must* handle `wx.MouseCaptureLostEvent` and cancel this
operation when it receives the event. The event handler must not
recapture mouse.
"""
return _core_.Window_CaptureMouse(*args, **kwargs) | [
"def",
"CaptureMouse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_CaptureMouse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L10619-L10638 | |
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/serde.py | python | float_ | () | return Optional(FloatSerde()) | Return an optional float serde. | Return an optional float serde. | [
"Return",
"an",
"optional",
"float",
"serde",
"."
] | def float_():
"""
Return an optional float serde.
"""
return Optional(FloatSerde()) | [
"def",
"float_",
"(",
")",
":",
"return",
"Optional",
"(",
"FloatSerde",
"(",
")",
")"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/serde.py#L711-L715 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Misc.winfo_visual | (self) | return self.tk.call('winfo', 'visual', self._w) | Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the
colormodel of this widget. | Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the
colormodel of this widget. | [
"Return",
"one",
"of",
"the",
"strings",
"directcolor",
"grayscale",
"pseudocolor",
"staticcolor",
"staticgray",
"or",
"truecolor",
"for",
"the",
"colormodel",
"of",
"this",
"widget",
"."
] | def winfo_visual(self):
"""Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the
colormodel of this widget."""
return self.tk.call('winfo', 'visual', self._w) | [
"def",
"winfo_visual",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'visual'",
",",
"self",
".",
"_w",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L965-L969 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/session.py | python | Session.get_available_services | (self) | return self._session.get_available_services() | Get a list of available services that can be loaded as low-level
clients via :py:meth:`Session.client`.
:rtype: list
:return: List of service names | Get a list of available services that can be loaded as low-level
clients via :py:meth:`Session.client`. | [
"Get",
"a",
"list",
"of",
"available",
"services",
"that",
"can",
"be",
"loaded",
"as",
"low",
"-",
"level",
"clients",
"via",
":",
"py",
":",
"meth",
":",
"Session",
".",
"client",
"."
] | def get_available_services(self):
"""
Get a list of available services that can be loaded as low-level
clients via :py:meth:`Session.client`.
:rtype: list
:return: List of service names
"""
return self._session.get_available_services() | [
"def",
"get_available_services",
"(",
"self",
")",
":",
"return",
"self",
".",
"_session",
".",
"get_available_services",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/session.py#L124-L132 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextEvent.GetUpdated | (*args, **kwargs) | return _stc.StyledTextEvent_GetUpdated(*args, **kwargs) | GetUpdated(self) -> int | GetUpdated(self) -> int | [
"GetUpdated",
"(",
"self",
")",
"-",
">",
"int"
] | def GetUpdated(*args, **kwargs):
"""GetUpdated(self) -> int"""
return _stc.StyledTextEvent_GetUpdated(*args, **kwargs) | [
"def",
"GetUpdated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_GetUpdated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L7198-L7200 | |
KhronosGroup/Vulkan-Headers | b32da5329b50e3cb96229aaecba9ded032fe29cc | registry/vkconventions.py | python | VulkanConventions.valid_flag_bit | (self, bitpos) | return bitpos >= 0 and bitpos < 31 | Return True if bitpos is an allowed numeric bit position for
an API flag bit.
Vulkan uses 32 bit Vk*Flags types, and assumes C compilers may
cause Vk*FlagBits values with bit 31 set to result in a 64 bit
enumerated type, so disallows such flags. | Return True if bitpos is an allowed numeric bit position for
an API flag bit. | [
"Return",
"True",
"if",
"bitpos",
"is",
"an",
"allowed",
"numeric",
"bit",
"position",
"for",
"an",
"API",
"flag",
"bit",
"."
] | def valid_flag_bit(self, bitpos):
"""Return True if bitpos is an allowed numeric bit position for
an API flag bit.
Vulkan uses 32 bit Vk*Flags types, and assumes C compilers may
cause Vk*FlagBits values with bit 31 set to result in a 64 bit
enumerated type, so disallows such flags."""
return bitpos >= 0 and bitpos < 31 | [
"def",
"valid_flag_bit",
"(",
"self",
",",
"bitpos",
")",
":",
"return",
"bitpos",
">=",
"0",
"and",
"bitpos",
"<",
"31"
] | https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/vkconventions.py#L268-L275 | |
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/MSVSSettings.py | python | ValidateMSVSSettings | (settings, stderr=sys.stderr) | Validates that the names of the settings are valid for MSVS.
Args:
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages. | Validates that the names of the settings are valid for MSVS. | [
"Validates",
"that",
"the",
"names",
"of",
"the",
"settings",
"are",
"valid",
"for",
"MSVS",
"."
] | def ValidateMSVSSettings(settings, stderr=sys.stderr):
"""Validates that the names of the settings are valid for MSVS.
Args:
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
"""
_ValidateSettings(_msvs_validators, settings, stderr) | [
"def",
"ValidateMSVSSettings",
"(",
"settings",
",",
"stderr",
"=",
"sys",
".",
"stderr",
")",
":",
"_ValidateSettings",
"(",
"_msvs_validators",
",",
"settings",
",",
"stderr",
")"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/MSVSSettings.py#L480-L488 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/python/google/platform_utils_win.py | python | GetCygwinPath | (path) | return path.replace('\\', '/') | Convert a Windows path to a cygwin path.
The cygpath utility insists on converting paths that it thinks are Cygwin
root paths to what it thinks the correct roots are. So paths such as
"C:\b\slave\webkit-release-kjs\build\third_party\cygwin\bin" are converted to
plain "/usr/bin". To avoid this, we do the conversion manually.
The path is expected to be an absolute path, on any drive. | Convert a Windows path to a cygwin path. | [
"Convert",
"a",
"Windows",
"path",
"to",
"a",
"cygwin",
"path",
"."
] | def GetCygwinPath(path):
"""Convert a Windows path to a cygwin path.
The cygpath utility insists on converting paths that it thinks are Cygwin
root paths to what it thinks the correct roots are. So paths such as
"C:\b\slave\webkit-release-kjs\build\third_party\cygwin\bin" are converted to
plain "/usr/bin". To avoid this, we do the conversion manually.
The path is expected to be an absolute path, on any drive.
"""
drive_regexp = re.compile(r'([a-z]):[/\\]', re.IGNORECASE)
def LowerDrive(matchobj):
return '/cygdrive/%s/' % matchobj.group(1).lower()
path = drive_regexp.sub(LowerDrive, path)
return path.replace('\\', '/') | [
"def",
"GetCygwinPath",
"(",
"path",
")",
":",
"drive_regexp",
"=",
"re",
".",
"compile",
"(",
"r'([a-z]):[/\\\\]'",
",",
"re",
".",
"IGNORECASE",
")",
"def",
"LowerDrive",
"(",
"matchobj",
")",
":",
"return",
"'/cygdrive/%s/'",
"%",
"matchobj",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"path",
"=",
"drive_regexp",
".",
"sub",
"(",
"LowerDrive",
",",
"path",
")",
"return",
"path",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/python/google/platform_utils_win.py#L180-L194 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/base64.py | python | urlsafe_b64encode | (s) | return b64encode(s).translate(_urlsafe_encode_translation) | Encode bytes using the URL- and filesystem-safe Base64 alphabet.
Argument s is a bytes-like object to encode. The result is returned as a
bytes object. The alphabet uses '-' instead of '+' and '_' instead of
'/'. | Encode bytes using the URL- and filesystem-safe Base64 alphabet. | [
"Encode",
"bytes",
"using",
"the",
"URL",
"-",
"and",
"filesystem",
"-",
"safe",
"Base64",
"alphabet",
"."
] | def urlsafe_b64encode(s):
"""Encode bytes using the URL- and filesystem-safe Base64 alphabet.
Argument s is a bytes-like object to encode. The result is returned as a
bytes object. The alphabet uses '-' instead of '+' and '_' instead of
'/'.
"""
return b64encode(s).translate(_urlsafe_encode_translation) | [
"def",
"urlsafe_b64encode",
"(",
"s",
")",
":",
"return",
"b64encode",
"(",
"s",
")",
".",
"translate",
"(",
"_urlsafe_encode_translation",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/base64.py#L111-L118 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_shgo_lib/triangulation.py | python | Complex.n_cube | (self, dim, symmetry=False, printout=False) | Generate the simplicial triangulation of the n dimensional hypercube
containing 2**n vertices | Generate the simplicial triangulation of the n dimensional hypercube
containing 2**n vertices | [
"Generate",
"the",
"simplicial",
"triangulation",
"of",
"the",
"n",
"dimensional",
"hypercube",
"containing",
"2",
"**",
"n",
"vertices"
] | def n_cube(self, dim, symmetry=False, printout=False):
"""
Generate the simplicial triangulation of the n dimensional hypercube
containing 2**n vertices
"""
origin = list(np.zeros(dim, dtype=int))
self.origin = origin
supremum = list(np.ones(dim, dtype=int))
self.supremum = supremum
# tuple versions for indexing
origintuple = tuple(origin)
supremumtuple = tuple(supremum)
x_parents = [origintuple]
if symmetry:
self.C0 = Simplex(0, 0, 0, self.dim) # Initial cell object
self.C0.add_vertex(self.V[origintuple])
i_s = 0
self.perm_symmetry(i_s, x_parents, origin)
self.C0.add_vertex(self.V[supremumtuple])
else:
self.C0 = Cell(0, 0, origin, supremum) # Initial cell object
self.C0.add_vertex(self.V[origintuple])
self.C0.add_vertex(self.V[supremumtuple])
i_parents = []
self.perm(i_parents, x_parents, origin)
if printout:
print("Initial hyper cube:")
for v in self.C0():
v.print_out() | [
"def",
"n_cube",
"(",
"self",
",",
"dim",
",",
"symmetry",
"=",
"False",
",",
"printout",
"=",
"False",
")",
":",
"origin",
"=",
"list",
"(",
"np",
".",
"zeros",
"(",
"dim",
",",
"dtype",
"=",
"int",
")",
")",
"self",
".",
"origin",
"=",
"origin",
"supremum",
"=",
"list",
"(",
"np",
".",
"ones",
"(",
"dim",
",",
"dtype",
"=",
"int",
")",
")",
"self",
".",
"supremum",
"=",
"supremum",
"# tuple versions for indexing",
"origintuple",
"=",
"tuple",
"(",
"origin",
")",
"supremumtuple",
"=",
"tuple",
"(",
"supremum",
")",
"x_parents",
"=",
"[",
"origintuple",
"]",
"if",
"symmetry",
":",
"self",
".",
"C0",
"=",
"Simplex",
"(",
"0",
",",
"0",
",",
"0",
",",
"self",
".",
"dim",
")",
"# Initial cell object",
"self",
".",
"C0",
".",
"add_vertex",
"(",
"self",
".",
"V",
"[",
"origintuple",
"]",
")",
"i_s",
"=",
"0",
"self",
".",
"perm_symmetry",
"(",
"i_s",
",",
"x_parents",
",",
"origin",
")",
"self",
".",
"C0",
".",
"add_vertex",
"(",
"self",
".",
"V",
"[",
"supremumtuple",
"]",
")",
"else",
":",
"self",
".",
"C0",
"=",
"Cell",
"(",
"0",
",",
"0",
",",
"origin",
",",
"supremum",
")",
"# Initial cell object",
"self",
".",
"C0",
".",
"add_vertex",
"(",
"self",
".",
"V",
"[",
"origintuple",
"]",
")",
"self",
".",
"C0",
".",
"add_vertex",
"(",
"self",
".",
"V",
"[",
"supremumtuple",
"]",
")",
"i_parents",
"=",
"[",
"]",
"self",
".",
"perm",
"(",
"i_parents",
",",
"x_parents",
",",
"origin",
")",
"if",
"printout",
":",
"print",
"(",
"\"Initial hyper cube:\"",
")",
"for",
"v",
"in",
"self",
".",
"C0",
"(",
")",
":",
"v",
".",
"print_out",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_shgo_lib/triangulation.py#L147-L181 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PGProperty.GetValidator | (*args, **kwargs) | return _propgrid.PGProperty_GetValidator(*args, **kwargs) | GetValidator(self) -> Validator | GetValidator(self) -> Validator | [
"GetValidator",
"(",
"self",
")",
"-",
">",
"Validator"
] | def GetValidator(*args, **kwargs):
"""GetValidator(self) -> Validator"""
return _propgrid.PGProperty_GetValidator(*args, **kwargs) | [
"def",
"GetValidator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_GetValidator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L775-L777 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBDebugger.SetLoggingCallback | (self, *args) | return _lldb.SBDebugger_SetLoggingCallback(self, *args) | SetLoggingCallback(self, LogOutputCallback log_callback) | SetLoggingCallback(self, LogOutputCallback log_callback) | [
"SetLoggingCallback",
"(",
"self",
"LogOutputCallback",
"log_callback",
")"
] | def SetLoggingCallback(self, *args):
"""SetLoggingCallback(self, LogOutputCallback log_callback)"""
return _lldb.SBDebugger_SetLoggingCallback(self, *args) | [
"def",
"SetLoggingCallback",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_SetLoggingCallback",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3402-L3404 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | ControlFlowState.ExitGradWhileContext | (self, op, before) | Exit the WhileContext for gradient computation. | Exit the WhileContext for gradient computation. | [
"Exit",
"the",
"WhileContext",
"for",
"gradient",
"computation",
"."
] | def ExitGradWhileContext(self, op, before):
"""Exit the WhileContext for gradient computation."""
grad_state = self._GetGradState(op, before)
if grad_state:
grad_state.grad_context.Exit() | [
"def",
"ExitGradWhileContext",
"(",
"self",
",",
"op",
",",
"before",
")",
":",
"grad_state",
"=",
"self",
".",
"_GetGradState",
"(",
"op",
",",
"before",
")",
"if",
"grad_state",
":",
"grad_state",
".",
"grad_context",
".",
"Exit",
"(",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L836-L840 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_SCHEME_ECDAA.GetUnionSelector | (self) | return TPM_ALG_ID.ECDAA | TpmUnion method | TpmUnion method | [
"TpmUnion",
"method"
] | def GetUnionSelector(self): # TPM_ALG_ID
""" TpmUnion method """
return TPM_ALG_ID.ECDAA | [
"def",
"GetUnionSelector",
"(",
"self",
")",
":",
"# TPM_ALG_ID",
"return",
"TPM_ALG_ID",
".",
"ECDAA"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6233-L6235 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | HelpProvider.GetHelp | (*args, **kwargs) | return _controls_.HelpProvider_GetHelp(*args, **kwargs) | GetHelp(self, Window window) -> String
Gets the help string for this window. Its interpretation is dependent
on the help provider except that empty string always means that no
help is associated with the window. | GetHelp(self, Window window) -> String | [
"GetHelp",
"(",
"self",
"Window",
"window",
")",
"-",
">",
"String"
] | def GetHelp(*args, **kwargs):
"""
GetHelp(self, Window window) -> String
Gets the help string for this window. Its interpretation is dependent
on the help provider except that empty string always means that no
help is associated with the window.
"""
return _controls_.HelpProvider_GetHelp(*args, **kwargs) | [
"def",
"GetHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"HelpProvider_GetHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L6235-L6243 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/main.py | python | _TopImprovements | (recent_anomalies, num_to_show) | return improvements[:num_to_show] | Fills in the given template dictionary with top improvements.
Args:
recent_anomalies: A list of Anomaly entities sorted from large to small.
num_to_show: The number of improvements to return.
Returns:
A list of top improvement Anomaly entities, in decreasing order. | Fills in the given template dictionary with top improvements. | [
"Fills",
"in",
"the",
"given",
"template",
"dictionary",
"with",
"top",
"improvements",
"."
] | def _TopImprovements(recent_anomalies, num_to_show):
"""Fills in the given template dictionary with top improvements.
Args:
recent_anomalies: A list of Anomaly entities sorted from large to small.
num_to_show: The number of improvements to return.
Returns:
A list of top improvement Anomaly entities, in decreasing order.
"""
improvements = [a for a in recent_anomalies if a.is_improvement]
return improvements[:num_to_show] | [
"def",
"_TopImprovements",
"(",
"recent_anomalies",
",",
"num_to_show",
")",
":",
"improvements",
"=",
"[",
"a",
"for",
"a",
"in",
"recent_anomalies",
"if",
"a",
".",
"is_improvement",
"]",
"return",
"improvements",
"[",
":",
"num_to_show",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/main.py#L139-L150 | |
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Modules/Scripted/DICOMLib/DICOMBrowser.py | python | SlicerDICOMBrowser.checkForExtensions | (self) | return extensionsToOffer | Check to see if there
are any registered extensions that might be available to
help the user work with data in the database.
1) load extension json description
2) load info for each series
3) check if data matches
then return matches
See
http://www.na-mic.org/Bug/view.php?id=4146 | Check to see if there
are any registered extensions that might be available to
help the user work with data in the database. | [
"Check",
"to",
"see",
"if",
"there",
"are",
"any",
"registered",
"extensions",
"that",
"might",
"be",
"available",
"to",
"help",
"the",
"user",
"work",
"with",
"data",
"in",
"the",
"database",
"."
] | def checkForExtensions(self):
"""Check to see if there
are any registered extensions that might be available to
help the user work with data in the database.
1) load extension json description
2) load info for each series
3) check if data matches
then return matches
See
http://www.na-mic.org/Bug/view.php?id=4146
"""
# 1 - load json
import logging, os, json
logging.info('Imported a DICOM directory, checking for extensions')
modulePath = os.path.dirname(slicer.modules.dicom.path)
extensionDescriptorPath = os.path.join(modulePath, 'DICOMExtensions.json')
try:
with open(extensionDescriptorPath) as extensionDescriptorFP:
extensionDescriptor = extensionDescriptorFP.read()
dicomExtensions = json.loads(extensionDescriptor)
except:
logging.error('Cannot access DICOMExtensions.json file')
return
# 2 - get series info
# - iterate though metadata - should be fast even with large database
# - the fileValue call checks the tag cache so it's fast
modalityTag = "0008,0060"
sopClassUIDTag = "0008,0016"
sopClassUIDs = set()
modalities = set()
for patient in slicer.dicomDatabase.patients():
for study in slicer.dicomDatabase.studiesForPatient(patient):
for series in slicer.dicomDatabase.seriesForStudy(study):
instance0 = slicer.dicomDatabase.filesForSeries(series, 1)[0]
modality = slicer.dicomDatabase.fileValue(instance0, modalityTag)
sopClassUID = slicer.dicomDatabase.fileValue(instance0, sopClassUIDTag)
modalities.add(modality)
sopClassUIDs.add(sopClassUID)
# 3 - check if data matches
extensionsManagerModel = slicer.app.extensionsManagerModel()
installedExtensions = extensionsManagerModel.installedExtensions
extensionsToOffer = []
for extension in dicomExtensions['extensions']:
extensionName = extension['name']
if extensionName not in installedExtensions:
tagValues = extension['tagValues']
if 'Modality' in tagValues:
for modality in tagValues['Modality']:
if modality in modalities:
extensionsToOffer.append(extension)
if 'SOPClassUID' in tagValues:
for sopClassUID in tagValues['SOPClassUID']:
if sopClassUID in sopClassUIDs:
extensionsToOffer.append(extension)
return extensionsToOffer | [
"def",
"checkForExtensions",
"(",
"self",
")",
":",
"# 1 - load json",
"import",
"logging",
",",
"os",
",",
"json",
"logging",
".",
"info",
"(",
"'Imported a DICOM directory, checking for extensions'",
")",
"modulePath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"slicer",
".",
"modules",
".",
"dicom",
".",
"path",
")",
"extensionDescriptorPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"modulePath",
",",
"'DICOMExtensions.json'",
")",
"try",
":",
"with",
"open",
"(",
"extensionDescriptorPath",
")",
"as",
"extensionDescriptorFP",
":",
"extensionDescriptor",
"=",
"extensionDescriptorFP",
".",
"read",
"(",
")",
"dicomExtensions",
"=",
"json",
".",
"loads",
"(",
"extensionDescriptor",
")",
"except",
":",
"logging",
".",
"error",
"(",
"'Cannot access DICOMExtensions.json file'",
")",
"return",
"# 2 - get series info",
"# - iterate though metadata - should be fast even with large database",
"# - the fileValue call checks the tag cache so it's fast",
"modalityTag",
"=",
"\"0008,0060\"",
"sopClassUIDTag",
"=",
"\"0008,0016\"",
"sopClassUIDs",
"=",
"set",
"(",
")",
"modalities",
"=",
"set",
"(",
")",
"for",
"patient",
"in",
"slicer",
".",
"dicomDatabase",
".",
"patients",
"(",
")",
":",
"for",
"study",
"in",
"slicer",
".",
"dicomDatabase",
".",
"studiesForPatient",
"(",
"patient",
")",
":",
"for",
"series",
"in",
"slicer",
".",
"dicomDatabase",
".",
"seriesForStudy",
"(",
"study",
")",
":",
"instance0",
"=",
"slicer",
".",
"dicomDatabase",
".",
"filesForSeries",
"(",
"series",
",",
"1",
")",
"[",
"0",
"]",
"modality",
"=",
"slicer",
".",
"dicomDatabase",
".",
"fileValue",
"(",
"instance0",
",",
"modalityTag",
")",
"sopClassUID",
"=",
"slicer",
".",
"dicomDatabase",
".",
"fileValue",
"(",
"instance0",
",",
"sopClassUIDTag",
")",
"modalities",
".",
"add",
"(",
"modality",
")",
"sopClassUIDs",
".",
"add",
"(",
"sopClassUID",
")",
"# 3 - check if data matches",
"extensionsManagerModel",
"=",
"slicer",
".",
"app",
".",
"extensionsManagerModel",
"(",
")",
"installedExtensions",
"=",
"extensionsManagerModel",
".",
"installedExtensions",
"extensionsToOffer",
"=",
"[",
"]",
"for",
"extension",
"in",
"dicomExtensions",
"[",
"'extensions'",
"]",
":",
"extensionName",
"=",
"extension",
"[",
"'name'",
"]",
"if",
"extensionName",
"not",
"in",
"installedExtensions",
":",
"tagValues",
"=",
"extension",
"[",
"'tagValues'",
"]",
"if",
"'Modality'",
"in",
"tagValues",
":",
"for",
"modality",
"in",
"tagValues",
"[",
"'Modality'",
"]",
":",
"if",
"modality",
"in",
"modalities",
":",
"extensionsToOffer",
".",
"append",
"(",
"extension",
")",
"if",
"'SOPClassUID'",
"in",
"tagValues",
":",
"for",
"sopClassUID",
"in",
"tagValues",
"[",
"'SOPClassUID'",
"]",
":",
"if",
"sopClassUID",
"in",
"sopClassUIDs",
":",
"extensionsToOffer",
".",
"append",
"(",
"extension",
")",
"return",
"extensionsToOffer"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMLib/DICOMBrowser.py#L235-L295 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/msgpack/ext.py | python | Timestamp.__repr__ | (self) | return "Timestamp(seconds={0}, nanoseconds={1})".format(
self.seconds, self.nanoseconds
) | String representation of Timestamp. | String representation of Timestamp. | [
"String",
"representation",
"of",
"Timestamp",
"."
] | def __repr__(self):
"""String representation of Timestamp."""
return "Timestamp(seconds={0}, nanoseconds={1})".format(
self.seconds, self.nanoseconds
) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"Timestamp(seconds={0}, nanoseconds={1})\"",
".",
"format",
"(",
"self",
".",
"seconds",
",",
"self",
".",
"nanoseconds",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/msgpack/ext.py#L137-L145 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | utils/sort_includes.py | python | sort_includes | (f) | Sort the #include lines of a specific file. | Sort the #include lines of a specific file. | [
"Sort",
"the",
"#include",
"lines",
"of",
"a",
"specific",
"file",
"."
] | def sort_includes(f):
"""Sort the #include lines of a specific file."""
# Skip files which are under INPUTS trees or test trees.
if 'INPUTS/' in f.name or 'test/' in f.name:
return
ext = os.path.splitext(f.name)[1]
if ext not in ['.cpp', '.c', '.h', '.inc', '.def']:
return
lines = f.readlines()
look_for_api_header = ext in ['.cpp', '.c']
found_headers = False
headers_begin = 0
headers_end = 0
api_headers = []
local_headers = []
subproject_headers = []
llvm_headers = []
system_headers = []
for (i, l) in enumerate(lines):
if l.strip() == '':
continue
if l.startswith('#include'):
if not found_headers:
headers_begin = i
found_headers = True
headers_end = i
header = l[len('#include'):].lstrip()
if look_for_api_header and header.startswith('"'):
api_headers.append(header)
look_for_api_header = False
continue
if (header.startswith('<') or header.startswith('"gtest/') or
header.startswith('"isl/') or header.startswith('"json/')):
system_headers.append(header)
continue
if (header.startswith('"clang/') or header.startswith('"clang-c/') or
header.startswith('"polly/')):
subproject_headers.append(header)
continue
if (header.startswith('"llvm/') or header.startswith('"llvm-c/')):
llvm_headers.append(header)
continue
local_headers.append(header)
continue
# Only allow comments and #defines prior to any includes. If either are
# mixed with includes, the order might be sensitive.
if found_headers:
break
if l.startswith('//') or l.startswith('#define') or l.startswith('#ifndef'):
continue
break
if not found_headers:
return
local_headers = sorted(set(local_headers))
subproject_headers = sorted(set(subproject_headers))
llvm_headers = sorted(set(llvm_headers))
system_headers = sorted(set(system_headers))
headers = api_headers + local_headers + subproject_headers + llvm_headers + system_headers
header_lines = ['#include ' + h for h in headers]
lines = lines[:headers_begin] + header_lines + lines[headers_end + 1:]
f.seek(0)
f.truncate()
f.writelines(lines) | [
"def",
"sort_includes",
"(",
"f",
")",
":",
"# Skip files which are under INPUTS trees or test trees.",
"if",
"'INPUTS/'",
"in",
"f",
".",
"name",
"or",
"'test/'",
"in",
"f",
".",
"name",
":",
"return",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
".",
"name",
")",
"[",
"1",
"]",
"if",
"ext",
"not",
"in",
"[",
"'.cpp'",
",",
"'.c'",
",",
"'.h'",
",",
"'.inc'",
",",
"'.def'",
"]",
":",
"return",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"look_for_api_header",
"=",
"ext",
"in",
"[",
"'.cpp'",
",",
"'.c'",
"]",
"found_headers",
"=",
"False",
"headers_begin",
"=",
"0",
"headers_end",
"=",
"0",
"api_headers",
"=",
"[",
"]",
"local_headers",
"=",
"[",
"]",
"subproject_headers",
"=",
"[",
"]",
"llvm_headers",
"=",
"[",
"]",
"system_headers",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"l",
")",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"l",
".",
"strip",
"(",
")",
"==",
"''",
":",
"continue",
"if",
"l",
".",
"startswith",
"(",
"'#include'",
")",
":",
"if",
"not",
"found_headers",
":",
"headers_begin",
"=",
"i",
"found_headers",
"=",
"True",
"headers_end",
"=",
"i",
"header",
"=",
"l",
"[",
"len",
"(",
"'#include'",
")",
":",
"]",
".",
"lstrip",
"(",
")",
"if",
"look_for_api_header",
"and",
"header",
".",
"startswith",
"(",
"'\"'",
")",
":",
"api_headers",
".",
"append",
"(",
"header",
")",
"look_for_api_header",
"=",
"False",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'<'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"gtest/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"isl/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"json/'",
")",
")",
":",
"system_headers",
".",
"append",
"(",
"header",
")",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'\"clang/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"clang-c/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"polly/'",
")",
")",
":",
"subproject_headers",
".",
"append",
"(",
"header",
")",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'\"llvm/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"llvm-c/'",
")",
")",
":",
"llvm_headers",
".",
"append",
"(",
"header",
")",
"continue",
"local_headers",
".",
"append",
"(",
"header",
")",
"continue",
"# Only allow comments and #defines prior to any includes. If either are",
"# mixed with includes, the order might be sensitive.",
"if",
"found_headers",
":",
"break",
"if",
"l",
".",
"startswith",
"(",
"'//'",
")",
"or",
"l",
".",
"startswith",
"(",
"'#define'",
")",
"or",
"l",
".",
"startswith",
"(",
"'#ifndef'",
")",
":",
"continue",
"break",
"if",
"not",
"found_headers",
":",
"return",
"local_headers",
"=",
"sorted",
"(",
"set",
"(",
"local_headers",
")",
")",
"subproject_headers",
"=",
"sorted",
"(",
"set",
"(",
"subproject_headers",
")",
")",
"llvm_headers",
"=",
"sorted",
"(",
"set",
"(",
"llvm_headers",
")",
")",
"system_headers",
"=",
"sorted",
"(",
"set",
"(",
"system_headers",
")",
")",
"headers",
"=",
"api_headers",
"+",
"local_headers",
"+",
"subproject_headers",
"+",
"llvm_headers",
"+",
"system_headers",
"header_lines",
"=",
"[",
"'#include '",
"+",
"h",
"for",
"h",
"in",
"headers",
"]",
"lines",
"=",
"lines",
"[",
":",
"headers_begin",
"]",
"+",
"header_lines",
"+",
"lines",
"[",
"headers_end",
"+",
"1",
":",
"]",
"f",
".",
"seek",
"(",
"0",
")",
"f",
".",
"truncate",
"(",
")",
"f",
".",
"writelines",
"(",
"lines",
")"
] | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/utils/sort_includes.py#L14-L82 | ||
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | IsErrorSuppressedByNolint | (category, linenum) | return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment. | Returns true if the specified error category is suppressed on this line. | [
"Returns",
"true",
"if",
"the",
"specified",
"error",
"category",
"is",
"suppressed",
"on",
"this",
"line",
"."
] | def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.
"""
return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | [
"def",
"IsErrorSuppressedByNolint",
"(",
"category",
",",
"linenum",
")",
":",
"return",
"(",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"category",
",",
"set",
"(",
")",
")",
"or",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"None",
",",
"set",
"(",
")",
")",
")"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L394-L407 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeMemberFunction.GetReturnType | (self) | return _lldb.SBTypeMemberFunction_GetReturnType(self) | GetReturnType(self) -> SBType | GetReturnType(self) -> SBType | [
"GetReturnType",
"(",
"self",
")",
"-",
">",
"SBType"
] | def GetReturnType(self):
"""GetReturnType(self) -> SBType"""
return _lldb.SBTypeMemberFunction_GetReturnType(self) | [
"def",
"GetReturnType",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBTypeMemberFunction_GetReturnType",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L10228-L10230 | |
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/bindings-generator/generator.py | python | Generator.in_listed_extend_classed | (self, class_name) | return False | returns True if the class is in the list of required classes that need to extend | returns True if the class is in the list of required classes that need to extend | [
"returns",
"True",
"if",
"the",
"class",
"is",
"in",
"the",
"list",
"of",
"required",
"classes",
"that",
"need",
"to",
"extend"
] | def in_listed_extend_classed(self, class_name):
"""
returns True if the class is in the list of required classes that need to extend
"""
for key in self.classes_need_extend:
md = re.match("^" + key + "$", class_name)
if md:
return True
return False | [
"def",
"in_listed_extend_classed",
"(",
"self",
",",
"class_name",
")",
":",
"for",
"key",
"in",
"self",
".",
"classes_need_extend",
":",
"md",
"=",
"re",
".",
"match",
"(",
"\"^\"",
"+",
"key",
"+",
"\"$\"",
",",
"class_name",
")",
"if",
"md",
":",
"return",
"True",
"return",
"False"
] | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/generator.py#L820-L828 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatnotebook.py | python | FlatNotebook.EnableTab | (self, page, enabled=True) | Enables or disables a tab.
:param `page`: an integer specifying the page index;
:param `enabled`: ``True`` to enable a tab, ``False`` to disable it. | Enables or disables a tab. | [
"Enables",
"or",
"disables",
"a",
"tab",
"."
] | def EnableTab(self, page, enabled=True):
"""
Enables or disables a tab.
:param `page`: an integer specifying the page index;
:param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
"""
if page >= len(self._windows):
return
self._windows[page].Enable(enabled)
self._pages.EnableTab(page, enabled) | [
"def",
"EnableTab",
"(",
"self",
",",
"page",
",",
"enabled",
"=",
"True",
")",
":",
"if",
"page",
">=",
"len",
"(",
"self",
".",
"_windows",
")",
":",
"return",
"self",
".",
"_windows",
"[",
"page",
"]",
".",
"Enable",
"(",
"enabled",
")",
"self",
".",
"_pages",
".",
"EnableTab",
"(",
"page",
",",
"enabled",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L4975-L4987 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Distribution.requires | (self, extras=()) | return deps | List of Requirements needed for this distro if `extras` are used | List of Requirements needed for this distro if `extras` are used | [
"List",
"of",
"Requirements",
"needed",
"for",
"this",
"distro",
"if",
"extras",
"are",
"used"
] | def requires(self, extras=()):
"""List of Requirements needed for this distro if `extras` are used"""
dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(
"%s has no such extra feature %r" % (self, ext)
)
return deps | [
"def",
"requires",
"(",
"self",
",",
"extras",
"=",
"(",
")",
")",
":",
"dm",
"=",
"self",
".",
"_dep_map",
"deps",
"=",
"[",
"]",
"deps",
".",
"extend",
"(",
"dm",
".",
"get",
"(",
"None",
",",
"(",
")",
")",
")",
"for",
"ext",
"in",
"extras",
":",
"try",
":",
"deps",
".",
"extend",
"(",
"dm",
"[",
"safe_extra",
"(",
"ext",
")",
"]",
")",
"except",
"KeyError",
":",
"raise",
"UnknownExtra",
"(",
"\"%s has no such extra feature %r\"",
"%",
"(",
"self",
",",
"ext",
")",
")",
"return",
"deps"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L2734-L2746 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/weights_broadcast_ops.py | python | assert_broadcastable | (weights, values) | Asserts `weights` can be broadcast to `values`.
In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We
let weights be either scalar, or the same rank as the target values, with each
dimension either 1, or the same as the corresponding values dimension.
Args:
weights: `Tensor` of weights.
values: `Tensor` of values to which weights are applied.
Returns:
`Operation` raising `InvalidArgumentError` if `weights` has incorrect shape.
`no_op` if static checks determine `weights` has correct shape.
Raises:
ValueError: If static checks determine `weights` has incorrect shape. | Asserts `weights` can be broadcast to `values`. | [
"Asserts",
"weights",
"can",
"be",
"broadcast",
"to",
"values",
"."
] | def assert_broadcastable(weights, values):
"""Asserts `weights` can be broadcast to `values`.
In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We
let weights be either scalar, or the same rank as the target values, with each
dimension either 1, or the same as the corresponding values dimension.
Args:
weights: `Tensor` of weights.
values: `Tensor` of values to which weights are applied.
Returns:
`Operation` raising `InvalidArgumentError` if `weights` has incorrect shape.
`no_op` if static checks determine `weights` has correct shape.
Raises:
ValueError: If static checks determine `weights` has incorrect shape.
"""
with ops.name_scope(None, "assert_broadcastable", (weights, values)) as scope:
with ops.name_scope(None, "weights", (weights,)) as weights_scope:
weights = ops.convert_to_tensor(weights, name=weights_scope)
weights_shape = array_ops.shape(weights, name="shape")
weights_rank = array_ops.rank(weights, name="rank")
weights_rank_static = tensor_util.constant_value(weights_rank)
with ops.name_scope(None, "values", (values,)) as values_scope:
values = ops.convert_to_tensor(values, name=values_scope)
values_shape = array_ops.shape(values, name="shape")
values_rank = array_ops.rank(values, name="rank")
values_rank_static = tensor_util.constant_value(values_rank)
# Try static checks.
if weights_rank_static is not None and values_rank_static is not None:
if weights_rank_static == 0:
return control_flow_ops.no_op(name="static_scalar_check_success")
if weights_rank_static != values_rank_static:
raise ValueError(
"%s values.rank=%s. weights.rank=%s."
" values.shape=%s. weights.shape=%s." % (
_ASSERT_BROADCASTABLE_ERROR_PREFIX, values_rank_static,
weights_rank_static, values.shape, weights.shape))
weights_shape_static = tensor_util.constant_value(weights_shape)
values_shape_static = tensor_util.constant_value(values_shape)
if weights_shape_static is not None and values_shape_static is not None:
# Sanity check, this should always be true since we checked rank above.
ndims = len(values_shape_static)
assert ndims == len(weights_shape_static)
for i in range(ndims):
if weights_shape_static[i] not in (1, values_shape_static[i]):
raise ValueError(
"%s Mismatch at dim %s. values.shape=%s weights.shape=%s." % (
_ASSERT_BROADCASTABLE_ERROR_PREFIX, i, values_shape_static,
weights_shape_static))
return control_flow_ops.no_op(name="static_dims_check_success")
# Dynamic checks.
is_scalar = math_ops.equal(0, weights_rank, name="is_scalar")
data = (
_ASSERT_BROADCASTABLE_ERROR_PREFIX,
"weights.shape=", weights.name, weights_shape,
"values.shape=", values.name, values_shape,
"is_scalar=", is_scalar,
)
is_valid_shape = control_flow_ops.cond(
is_scalar,
lambda: is_scalar,
lambda: _has_valid_nonscalar_shape( # pylint: disable=g-long-lambda
weights_rank, weights_shape, values_rank, values_shape),
name="is_valid_shape")
return control_flow_ops.Assert(is_valid_shape, data, name=scope) | [
"def",
"assert_broadcastable",
"(",
"weights",
",",
"values",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"\"assert_broadcastable\"",
",",
"(",
"weights",
",",
"values",
")",
")",
"as",
"scope",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"\"weights\"",
",",
"(",
"weights",
",",
")",
")",
"as",
"weights_scope",
":",
"weights",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"weights",
",",
"name",
"=",
"weights_scope",
")",
"weights_shape",
"=",
"array_ops",
".",
"shape",
"(",
"weights",
",",
"name",
"=",
"\"shape\"",
")",
"weights_rank",
"=",
"array_ops",
".",
"rank",
"(",
"weights",
",",
"name",
"=",
"\"rank\"",
")",
"weights_rank_static",
"=",
"tensor_util",
".",
"constant_value",
"(",
"weights_rank",
")",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"\"values\"",
",",
"(",
"values",
",",
")",
")",
"as",
"values_scope",
":",
"values",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"values",
",",
"name",
"=",
"values_scope",
")",
"values_shape",
"=",
"array_ops",
".",
"shape",
"(",
"values",
",",
"name",
"=",
"\"shape\"",
")",
"values_rank",
"=",
"array_ops",
".",
"rank",
"(",
"values",
",",
"name",
"=",
"\"rank\"",
")",
"values_rank_static",
"=",
"tensor_util",
".",
"constant_value",
"(",
"values_rank",
")",
"# Try static checks.",
"if",
"weights_rank_static",
"is",
"not",
"None",
"and",
"values_rank_static",
"is",
"not",
"None",
":",
"if",
"weights_rank_static",
"==",
"0",
":",
"return",
"control_flow_ops",
".",
"no_op",
"(",
"name",
"=",
"\"static_scalar_check_success\"",
")",
"if",
"weights_rank_static",
"!=",
"values_rank_static",
":",
"raise",
"ValueError",
"(",
"\"%s values.rank=%s. weights.rank=%s.\"",
"\" values.shape=%s. weights.shape=%s.\"",
"%",
"(",
"_ASSERT_BROADCASTABLE_ERROR_PREFIX",
",",
"values_rank_static",
",",
"weights_rank_static",
",",
"values",
".",
"shape",
",",
"weights",
".",
"shape",
")",
")",
"weights_shape_static",
"=",
"tensor_util",
".",
"constant_value",
"(",
"weights_shape",
")",
"values_shape_static",
"=",
"tensor_util",
".",
"constant_value",
"(",
"values_shape",
")",
"if",
"weights_shape_static",
"is",
"not",
"None",
"and",
"values_shape_static",
"is",
"not",
"None",
":",
"# Sanity check, this should always be true since we checked rank above.",
"ndims",
"=",
"len",
"(",
"values_shape_static",
")",
"assert",
"ndims",
"==",
"len",
"(",
"weights_shape_static",
")",
"for",
"i",
"in",
"range",
"(",
"ndims",
")",
":",
"if",
"weights_shape_static",
"[",
"i",
"]",
"not",
"in",
"(",
"1",
",",
"values_shape_static",
"[",
"i",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"%s Mismatch at dim %s. values.shape=%s weights.shape=%s.\"",
"%",
"(",
"_ASSERT_BROADCASTABLE_ERROR_PREFIX",
",",
"i",
",",
"values_shape_static",
",",
"weights_shape_static",
")",
")",
"return",
"control_flow_ops",
".",
"no_op",
"(",
"name",
"=",
"\"static_dims_check_success\"",
")",
"# Dynamic checks.",
"is_scalar",
"=",
"math_ops",
".",
"equal",
"(",
"0",
",",
"weights_rank",
",",
"name",
"=",
"\"is_scalar\"",
")",
"data",
"=",
"(",
"_ASSERT_BROADCASTABLE_ERROR_PREFIX",
",",
"\"weights.shape=\"",
",",
"weights",
".",
"name",
",",
"weights_shape",
",",
"\"values.shape=\"",
",",
"values",
".",
"name",
",",
"values_shape",
",",
"\"is_scalar=\"",
",",
"is_scalar",
",",
")",
"is_valid_shape",
"=",
"control_flow_ops",
".",
"cond",
"(",
"is_scalar",
",",
"lambda",
":",
"is_scalar",
",",
"lambda",
":",
"_has_valid_nonscalar_shape",
"(",
"# pylint: disable=g-long-lambda",
"weights_rank",
",",
"weights_shape",
",",
"values_rank",
",",
"values_shape",
")",
",",
"name",
"=",
"\"is_valid_shape\"",
")",
"return",
"control_flow_ops",
".",
"Assert",
"(",
"is_valid_shape",
",",
"data",
",",
"name",
"=",
"scope",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/weights_broadcast_ops.py#L63-L133 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/dockart.py | python | AuiDefaultDockArt.GetFont | (self, id) | return wx.NullFont | Gets a font setting.
:param integer `id`: must be ``AUI_DOCKART_CAPTION_FONT``, otherwise :class:`NullFont` is returned. | Gets a font setting. | [
"Gets",
"a",
"font",
"setting",
"."
] | def GetFont(self, id):
"""
Gets a font setting.
:param integer `id`: must be ``AUI_DOCKART_CAPTION_FONT``, otherwise :class:`NullFont` is returned.
"""
if id == AUI_DOCKART_CAPTION_FONT:
return self._caption_font
return wx.NullFont | [
"def",
"GetFont",
"(",
"self",
",",
"id",
")",
":",
"if",
"id",
"==",
"AUI_DOCKART_CAPTION_FONT",
":",
"return",
"self",
".",
"_caption_font",
"return",
"wx",
".",
"NullFont"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/dockart.py#L392-L402 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/difflib.py | python | get_close_matches | (word, possibilities, n=3, cutoff=0.6) | return [x for score, x in result] | Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of strings).
Optional arg n (default 3) is the maximum number of close matches to
return. n must be > 0.
Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
that don't score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned
in a list, sorted by similarity score, most similar first.
>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except'] | Use SequenceMatcher to return list of the best "good enough" matches. | [
"Use",
"SequenceMatcher",
"to",
"return",
"list",
"of",
"the",
"best",
"good",
"enough",
"matches",
"."
] | def get_close_matches(word, possibilities, n=3, cutoff=0.6):
"""Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of strings).
Optional arg n (default 3) is the maximum number of close matches to
return. n must be > 0.
Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
that don't score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned
in a list, sorted by similarity score, most similar first.
>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except']
"""
if not n > 0:
raise ValueError("n must be > 0: %r" % (n,))
if not 0.0 <= cutoff <= 1.0:
raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
result = []
s = SequenceMatcher()
s.set_seq2(word)
for x in possibilities:
s.set_seq1(x)
if s.real_quick_ratio() >= cutoff and \
s.quick_ratio() >= cutoff and \
s.ratio() >= cutoff:
result.append((s.ratio(), x))
# Move the best scorers to head of list
result = heapq.nlargest(n, result)
# Strip scores for the best n matches
return [x for score, x in result] | [
"def",
"get_close_matches",
"(",
"word",
",",
"possibilities",
",",
"n",
"=",
"3",
",",
"cutoff",
"=",
"0.6",
")",
":",
"if",
"not",
"n",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"n must be > 0: %r\"",
"%",
"(",
"n",
",",
")",
")",
"if",
"not",
"0.0",
"<=",
"cutoff",
"<=",
"1.0",
":",
"raise",
"ValueError",
"(",
"\"cutoff must be in [0.0, 1.0]: %r\"",
"%",
"(",
"cutoff",
",",
")",
")",
"result",
"=",
"[",
"]",
"s",
"=",
"SequenceMatcher",
"(",
")",
"s",
".",
"set_seq2",
"(",
"word",
")",
"for",
"x",
"in",
"possibilities",
":",
"s",
".",
"set_seq1",
"(",
"x",
")",
"if",
"s",
".",
"real_quick_ratio",
"(",
")",
">=",
"cutoff",
"and",
"s",
".",
"quick_ratio",
"(",
")",
">=",
"cutoff",
"and",
"s",
".",
"ratio",
"(",
")",
">=",
"cutoff",
":",
"result",
".",
"append",
"(",
"(",
"s",
".",
"ratio",
"(",
")",
",",
"x",
")",
")",
"# Move the best scorers to head of list",
"result",
"=",
"heapq",
".",
"nlargest",
"(",
"n",
",",
"result",
")",
"# Strip scores for the best n matches",
"return",
"[",
"x",
"for",
"score",
",",
"x",
"in",
"result",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/difflib.py#L701-L747 | |
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/wesnoth/wmlparser3.py | python | TagNode.wml | (self) | return s | Returns a (binary) WML representation of the entire node.
All attribute values are enclosed in quotes and quotes are
escaped (as double quotes). Note that no other escaping is
performed (see the BinaryWML specification for additional
escaping you may require). | Returns a (binary) WML representation of the entire node.
All attribute values are enclosed in quotes and quotes are
escaped (as double quotes). Note that no other escaping is
performed (see the BinaryWML specification for additional
escaping you may require). | [
"Returns",
"a",
"(",
"binary",
")",
"WML",
"representation",
"of",
"the",
"entire",
"node",
".",
"All",
"attribute",
"values",
"are",
"enclosed",
"in",
"quotes",
"and",
"quotes",
"are",
"escaped",
"(",
"as",
"double",
"quotes",
")",
".",
"Note",
"that",
"no",
"other",
"escaping",
"is",
"performed",
"(",
"see",
"the",
"BinaryWML",
"specification",
"for",
"additional",
"escaping",
"you",
"may",
"require",
")",
"."
] | def wml(self) -> bytes:
"""
Returns a (binary) WML representation of the entire node.
All attribute values are enclosed in quotes and quotes are
escaped (as double quotes). Note that no other escaping is
performed (see the BinaryWML specification for additional
escaping you may require).
"""
s = b"[" + self.name + b"]\n"
for sub in self.data:
s += sub.wml() + b"\n"
s += b"[/" + self.name.lstrip(b'+') + b"]\n"
return s | [
"def",
"wml",
"(",
"self",
")",
"->",
"bytes",
":",
"s",
"=",
"b\"[\"",
"+",
"self",
".",
"name",
"+",
"b\"]\\n\"",
"for",
"sub",
"in",
"self",
".",
"data",
":",
"s",
"+=",
"sub",
".",
"wml",
"(",
")",
"+",
"b\"\\n\"",
"s",
"+=",
"b\"[/\"",
"+",
"self",
".",
"name",
".",
"lstrip",
"(",
"b'+'",
")",
"+",
"b\"]\\n\"",
"return",
"s"
] | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmlparser3.py#L187-L199 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | EvtHandler.QueueEvent | (*args, **kwargs) | return _core_.EvtHandler_QueueEvent(*args, **kwargs) | QueueEvent(self, Event event) | QueueEvent(self, Event event) | [
"QueueEvent",
"(",
"self",
"Event",
"event",
")"
] | def QueueEvent(*args, **kwargs):
"""QueueEvent(self, Event event)"""
return _core_.EvtHandler_QueueEvent(*args, **kwargs) | [
"def",
"QueueEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"EvtHandler_QueueEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L4164-L4166 | |
lhmRyan/deep-supervised-hashing-DSH | 631901f82e2ab031fbac33f914a5b08ef8e21d57 | scripts/cpp_lint.py | python | UpdateIncludeState | (filename, include_state, io=codecs) | return True | Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise. | Fill up the include_state with new includes found from the file. | [
"Fill",
"up",
"the",
"include_state",
"with",
"new",
"includes",
"found",
"from",
"the",
"file",
"."
] | def UpdateIncludeState(filename, include_state, io=codecs):
"""Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
# The value formatting is cute, but not really used right now.
# What matters here is that the key is in include_state.
include_state.setdefault(include, '%s:%d' % (filename, linenum))
return True | [
"def",
"UpdateIncludeState",
"(",
"filename",
",",
"include_state",
",",
"io",
"=",
"codecs",
")",
":",
"headerfile",
"=",
"None",
"try",
":",
"headerfile",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
"except",
"IOError",
":",
"return",
"False",
"linenum",
"=",
"0",
"for",
"line",
"in",
"headerfile",
":",
"linenum",
"+=",
"1",
"clean_line",
"=",
"CleanseComments",
"(",
"line",
")",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"search",
"(",
"clean_line",
")",
"if",
"match",
":",
"include",
"=",
"match",
".",
"group",
"(",
"2",
")",
"# The value formatting is cute, but not really used right now.",
"# What matters here is that the key is in include_state.",
"include_state",
".",
"setdefault",
"(",
"include",
",",
"'%s:%d'",
"%",
"(",
"filename",
",",
"linenum",
")",
")",
"return",
"True"
] | https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/scripts/cpp_lint.py#L4454-L4480 | |
nsnam/ns-3-dev-git | efdb2e21f45c0a87a60b47c547b68fa140a7b686 | src/visualizer/visualizer/ipython_view.py | python | IterableIPShell.shell | (self, cmd,verbose=0,debug=0,header='') | !
Replacement method to allow shell commands without them blocking.
@param cmd: Shell command to execute.
@param verbose: Verbosity
@param debug: Debug level
@param header: Header to be printed before output
@return none | !
Replacement method to allow shell commands without them blocking. | [
"!",
"Replacement",
"method",
"to",
"allow",
"shell",
"commands",
"without",
"them",
"blocking",
"."
] | def shell(self, cmd,verbose=0,debug=0,header=''):
"""!
Replacement method to allow shell commands without them blocking.
@param cmd: Shell command to execute.
@param verbose: Verbosity
@param debug: Debug level
@param header: Header to be printed before output
@return none
"""
stat = 0
if verbose or debug: print(header+cmd)
# flush stdout so we don't mangle python's buffering
if not debug:
input, output = os.popen4(cmd)
print(output.read())
output.close()
input.close() | [
"def",
"shell",
"(",
"self",
",",
"cmd",
",",
"verbose",
"=",
"0",
",",
"debug",
"=",
"0",
",",
"header",
"=",
"''",
")",
":",
"stat",
"=",
"0",
"if",
"verbose",
"or",
"debug",
":",
"print",
"(",
"header",
"+",
"cmd",
")",
"# flush stdout so we don't mangle python's buffering",
"if",
"not",
"debug",
":",
"input",
",",
"output",
"=",
"os",
".",
"popen4",
"(",
"cmd",
")",
"print",
"(",
"output",
".",
"read",
"(",
")",
")",
"output",
".",
"close",
"(",
")",
"input",
".",
"close",
"(",
")"
] | https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/src/visualizer/visualizer/ipython_view.py#L313-L330 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/SHA256.py | python | SHA256Hash.digest | (self) | return get_raw_buffer(bfr) | Return the **binary** (non-printable) digest of the message that has been hashed so far.
:return: The hash digest, computed over the data processed so far.
Binary form.
:rtype: byte string | Return the **binary** (non-printable) digest of the message that has been hashed so far. | [
"Return",
"the",
"**",
"binary",
"**",
"(",
"non",
"-",
"printable",
")",
"digest",
"of",
"the",
"message",
"that",
"has",
"been",
"hashed",
"so",
"far",
"."
] | def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
:return: The hash digest, computed over the data processed so far.
Binary form.
:rtype: byte string
"""
bfr = create_string_buffer(self.digest_size)
result = _raw_sha256_lib.SHA256_digest(self._state.get(),
bfr,
c_size_t(self.digest_size))
if result:
raise ValueError("Error %d while making SHA256 digest"
% result)
return get_raw_buffer(bfr) | [
"def",
"digest",
"(",
"self",
")",
":",
"bfr",
"=",
"create_string_buffer",
"(",
"self",
".",
"digest_size",
")",
"result",
"=",
"_raw_sha256_lib",
".",
"SHA256_digest",
"(",
"self",
".",
"_state",
".",
"get",
"(",
")",
",",
"bfr",
",",
"c_size_t",
"(",
"self",
".",
"digest_size",
")",
")",
"if",
"result",
":",
"raise",
"ValueError",
"(",
"\"Error %d while making SHA256 digest\"",
"%",
"result",
")",
"return",
"get_raw_buffer",
"(",
"bfr",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/SHA256.py#L96-L112 | |
bingwin/MicroChat | 81d9a71a212c1cbca5bba497ec42659a7d25dccf | mars/lint/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L1318-L1320 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/docbook/__init__.py | python | __detect_cl_tool | (env, chainkey, cdict) | Helper function, picks a command line tool from the list
and initializes its environment variables. | Helper function, picks a command line tool from the list
and initializes its environment variables. | [
"Helper",
"function",
"picks",
"a",
"command",
"line",
"tool",
"from",
"the",
"list",
"and",
"initializes",
"its",
"environment",
"variables",
"."
] | def __detect_cl_tool(env, chainkey, cdict):
"""
Helper function, picks a command line tool from the list
and initializes its environment variables.
"""
if env.get(chainkey,'') == '':
clpath = ''
for cltool in cdict:
clpath = env.WhereIs(cltool)
if clpath:
env[chainkey] = clpath
if not env[chainkey + 'COM']:
env[chainkey + 'COM'] = cdict[cltool] | [
"def",
"__detect_cl_tool",
"(",
"env",
",",
"chainkey",
",",
"cdict",
")",
":",
"if",
"env",
".",
"get",
"(",
"chainkey",
",",
"''",
")",
"==",
"''",
":",
"clpath",
"=",
"''",
"for",
"cltool",
"in",
"cdict",
":",
"clpath",
"=",
"env",
".",
"WhereIs",
"(",
"cltool",
")",
"if",
"clpath",
":",
"env",
"[",
"chainkey",
"]",
"=",
"clpath",
"if",
"not",
"env",
"[",
"chainkey",
"+",
"'COM'",
"]",
":",
"env",
"[",
"chainkey",
"+",
"'COM'",
"]",
"=",
"cdict",
"[",
"cltool",
"]"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/docbook/__init__.py#L169-L181 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/artmanager.py | python | ArtManager.GetMenuBarColourScheme | (self) | return self._menuBarColourScheme | Returns the current colour scheme.
:return: A string representing the current colour scheme. | Returns the current colour scheme. | [
"Returns",
"the",
"current",
"colour",
"scheme",
"."
] | def GetMenuBarColourScheme(self):
"""
Returns the current colour scheme.
:return: A string representing the current colour scheme.
"""
return self._menuBarColourScheme | [
"def",
"GetMenuBarColourScheme",
"(",
"self",
")",
":",
"return",
"self",
".",
"_menuBarColourScheme"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/artmanager.py#L2034-L2041 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/ObjectsFem.py | python | makeConstraintForce | (
doc,
name="ConstraintForce"
) | return obj | makeConstraintForce(document, [name]):
makes a Fem ConstraintForce object | makeConstraintForce(document, [name]):
makes a Fem ConstraintForce object | [
"makeConstraintForce",
"(",
"document",
"[",
"name",
"]",
")",
":",
"makes",
"a",
"Fem",
"ConstraintForce",
"object"
] | def makeConstraintForce(
doc,
name="ConstraintForce"
):
"""makeConstraintForce(document, [name]):
makes a Fem ConstraintForce object"""
obj = doc.addObject("Fem::ConstraintForce", name)
return obj | [
"def",
"makeConstraintForce",
"(",
"doc",
",",
"name",
"=",
"\"ConstraintForce\"",
")",
":",
"obj",
"=",
"doc",
".",
"addObject",
"(",
"\"Fem::ConstraintForce\"",
",",
"name",
")",
"return",
"obj"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/ObjectsFem.py#L186-L193 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Scripting.py | python | dist | (ctx) | makes a tarball for redistributing the sources | makes a tarball for redistributing the sources | [
"makes",
"a",
"tarball",
"for",
"redistributing",
"the",
"sources"
] | def dist(ctx):
'''makes a tarball for redistributing the sources'''
pass | [
"def",
"dist",
"(",
"ctx",
")",
":",
"pass"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Scripting.py#L521-L523 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_tensor_shape.py | python | RaggedTensorDynamicShape.from_tensor | (cls, rt_input, dim_size_dtype=None) | Constructs a ragged shape for a potentially ragged tensor. | Constructs a ragged shape for a potentially ragged tensor. | [
"Constructs",
"a",
"ragged",
"shape",
"for",
"a",
"potentially",
"ragged",
"tensor",
"."
] | def from_tensor(cls, rt_input, dim_size_dtype=None):
"""Constructs a ragged shape for a potentially ragged tensor."""
with ops.name_scope(None, 'RaggedTensorDynamicShapeFromTensor', [rt_input]):
rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt_input)
if not ragged_tensor.is_ragged(rt_input):
return cls([], array_ops.shape(rt_input), dim_size_dtype=dim_size_dtype)
else:
partitioned_dim_sizes = (
(rt_input.nrows(),) + rt_input.nested_row_lengths())
return RaggedTensorDynamicShape(
partitioned_dim_sizes,
array_ops.shape(rt_input.flat_values)[1:],
dim_size_dtype=dim_size_dtype) | [
"def",
"from_tensor",
"(",
"cls",
",",
"rt_input",
",",
"dim_size_dtype",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"'RaggedTensorDynamicShapeFromTensor'",
",",
"[",
"rt_input",
"]",
")",
":",
"rt_input",
"=",
"ragged_tensor",
".",
"convert_to_tensor_or_ragged_tensor",
"(",
"rt_input",
")",
"if",
"not",
"ragged_tensor",
".",
"is_ragged",
"(",
"rt_input",
")",
":",
"return",
"cls",
"(",
"[",
"]",
",",
"array_ops",
".",
"shape",
"(",
"rt_input",
")",
",",
"dim_size_dtype",
"=",
"dim_size_dtype",
")",
"else",
":",
"partitioned_dim_sizes",
"=",
"(",
"(",
"rt_input",
".",
"nrows",
"(",
")",
",",
")",
"+",
"rt_input",
".",
"nested_row_lengths",
"(",
")",
")",
"return",
"RaggedTensorDynamicShape",
"(",
"partitioned_dim_sizes",
",",
"array_ops",
".",
"shape",
"(",
"rt_input",
".",
"flat_values",
")",
"[",
"1",
":",
"]",
",",
"dim_size_dtype",
"=",
"dim_size_dtype",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_tensor_shape.py#L177-L189 | ||
perilouswithadollarsign/cstrike15_src | f82112a2388b841d72cb62ca48ab1846dfcc11c8 | thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py | python | _AddPropertiesForExtensions | (descriptor, cls) | Adds properties for all fields in this protocol message type. | Adds properties for all fields in this protocol message type. | [
"Adds",
"properties",
"for",
"all",
"fields",
"in",
"this",
"protocol",
"message",
"type",
"."
] | def _AddPropertiesForExtensions(descriptor, cls):
"""Adds properties for all fields in this protocol message type."""
extension_dict = descriptor.extensions_by_name
for extension_name, extension_field in extension_dict.iteritems():
constant_name = extension_name.upper() + "_FIELD_NUMBER"
setattr(cls, constant_name, extension_field.number) | [
"def",
"_AddPropertiesForExtensions",
"(",
"descriptor",
",",
"cls",
")",
":",
"extension_dict",
"=",
"descriptor",
".",
"extensions_by_name",
"for",
"extension_name",
",",
"extension_field",
"in",
"extension_dict",
".",
"iteritems",
"(",
")",
":",
"constant_name",
"=",
"extension_name",
".",
"upper",
"(",
")",
"+",
"\"_FIELD_NUMBER\"",
"setattr",
"(",
"cls",
",",
"constant_name",
",",
"extension_field",
".",
"number",
")"
] | https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L520-L525 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/agents/scripts/configs.py | python | walker | () | return locals() | Configuration for MuJoCo's walker task. | Configuration for MuJoCo's walker task. | [
"Configuration",
"for",
"MuJoCo",
"s",
"walker",
"task",
"."
] | def walker():
"""Configuration for MuJoCo's walker task."""
locals().update(default())
# Environment
env = 'Walker2d-v1'
max_length = 1000
steps = 1e7 # 10M
return locals() | [
"def",
"walker",
"(",
")",
":",
"locals",
"(",
")",
".",
"update",
"(",
"default",
"(",
")",
")",
"# Environment",
"env",
"=",
"'Walker2d-v1'",
"max_length",
"=",
"1000",
"steps",
"=",
"1e7",
"# 10M",
"return",
"locals",
"(",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/agents/scripts/configs.py#L77-L84 | |
ros2/demos | fb3ad7e7fc6548c30e77a6ed86a2bd108fce5d82 | quality_of_service_demo/rclpy/quality_of_service_demo_py/common_nodes.py | python | Talker.stop | (self) | Cancel publishing and any manual liveliness assertions. | Cancel publishing and any manual liveliness assertions. | [
"Cancel",
"publishing",
"and",
"any",
"manual",
"liveliness",
"assertions",
"."
] | def stop(self):
"""Cancel publishing and any manual liveliness assertions."""
if self.assert_topic_timer:
self.assert_topic_timer.cancel()
self.publish_timer.cancel()
self.assert_topic_timer = None | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"assert_topic_timer",
":",
"self",
".",
"assert_topic_timer",
".",
"cancel",
"(",
")",
"self",
".",
"publish_timer",
".",
"cancel",
"(",
")",
"self",
".",
"assert_topic_timer",
"=",
"None"
] | https://github.com/ros2/demos/blob/fb3ad7e7fc6548c30e77a6ed86a2bd108fce5d82/quality_of_service_demo/rclpy/quality_of_service_demo_py/common_nodes.py#L83-L88 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_calibrator.py | python | CalibratorDomain.getInserted | (self, calibratorID) | return self._getUniversal(tc.VAR_INSERTED, calibratorID) | getInserted(string) -> double
Returns the number of inserted vehicles in the current calibration interval | getInserted(string) -> double
Returns the number of inserted vehicles in the current calibration interval | [
"getInserted",
"(",
"string",
")",
"-",
">",
"double",
"Returns",
"the",
"number",
"of",
"inserted",
"vehicles",
"in",
"the",
"current",
"calibration",
"interval"
] | def getInserted(self, calibratorID):
"""getInserted(string) -> double
Returns the number of inserted vehicles in the current calibration interval
"""
return self._getUniversal(tc.VAR_INSERTED, calibratorID) | [
"def",
"getInserted",
"(",
"self",
",",
"calibratorID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_INSERTED",
",",
"calibratorID",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_calibrator.py#L97-L101 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/ndarray.py | python | NDArray.log_sigmoid | (self, *args, **kwargs) | return op.log_sigmoid(self, *args, **kwargs) | Convenience fluent method for :py:func:`log_sigmoid`.
The arguments are the same as for :py:func:`log_sigmoid`, with
this array as data. | Convenience fluent method for :py:func:`log_sigmoid`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"log_sigmoid",
"."
] | def log_sigmoid(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`log_sigmoid`.
The arguments are the same as for :py:func:`log_sigmoid`, with
this array as data.
"""
return op.log_sigmoid(self, *args, **kwargs) | [
"def",
"log_sigmoid",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"log_sigmoid",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L2174-L2180 | |
carla-simulator/carla | 8854804f4d7748e14d937ec763a2912823a7e5f5 | PythonAPI/carla/agents/navigation/basic_agent.py | python | BasicAgent.ignore_traffic_lights | (self, active=True) | (De)activates the checks for traffic lights | (De)activates the checks for traffic lights | [
"(",
"De",
")",
"activates",
"the",
"checks",
"for",
"traffic",
"lights"
] | def ignore_traffic_lights(self, active=True):
"""(De)activates the checks for traffic lights"""
self._ignore_traffic_lights = active | [
"def",
"ignore_traffic_lights",
"(",
"self",
",",
"active",
"=",
"True",
")",
":",
"self",
".",
"_ignore_traffic_lights",
"=",
"active"
] | https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/carla/agents/navigation/basic_agent.py#L190-L192 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | MH.get_folder | (self, folder) | return MH(os.path.join(self._path, folder),
factory=self._factory, create=False) | Return an MH instance for the named folder. | Return an MH instance for the named folder. | [
"Return",
"an",
"MH",
"instance",
"for",
"the",
"named",
"folder",
"."
] | def get_folder(self, folder):
"""Return an MH instance for the named folder."""
return MH(os.path.join(self._path, folder),
factory=self._factory, create=False) | [
"def",
"get_folder",
"(",
"self",
",",
"folder",
")",
":",
"return",
"MH",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"folder",
")",
",",
"factory",
"=",
"self",
".",
"_factory",
",",
"create",
"=",
"False",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L1100-L1103 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | src/atomicgen.py | python | generate_cpp | () | return cpp_file | Generates the source file. | Generates the source file. | [
"Generates",
"the",
"source",
"file",
"."
] | def generate_cpp():
"""Generates the source file."""
cpp_file = AUTOGEN_WARNING
cpp_file += "// Implements basic nuclear data functions.\n"
cpp_file += "#ifndef PYNE_IS_AMALGAMATED\n"
cpp_file += "#include \"atomic_data.h\"\n"
cpp_file += "#include \"nucname.h\"\n"
cpp_file += "#endif\n"
cpp_file += " \n"
cpp_file += "void pyne::_load_atomic_mass_map_memory() { \n"
cpp_file += " // header version of atomic weight table data \n"
cpp_file += " //see if the data table is already loaded\n"
cpp_file += " if(!atomic_mass_map.empty()) {\n"
cpp_file += " return;\n"
cpp_file += " } else { \n"
cpp_file += " _insert_atomic_mass_map();\n"
cpp_file += " }\n"
cpp_file += " //see if the data table is already loaded\n"
cpp_file += " if(!natural_abund_map.empty()) {\n"
cpp_file += " return;\n"
cpp_file += " } else { \n"
cpp_file += " _insert_abund_map();\n"
cpp_file += " }\n"
cpp_file += " // calculate the atomic_masses of the elements \n"
cpp_file += " std::map<int,double> :: iterator it;\n"
cpp_file += " \n"
cpp_file += " for (int z = 1; z <= 92 ; z++) {\n"
cpp_file += " // loop through the natural abundance map\n"
cpp_file += " double element_atomic_weight = 0.0;\n"
cpp_file += " for (it = natural_abund_map.begin(); it != natural_abund_map.end() ; ++it){\n"
cpp_file += " // if the atomic number of the abudance matches the\n"
cpp_file += " // that of index\n"
cpp_file += " if(pyne::nucname::znum(it->first) == z) {\n"
cpp_file += " // take atomic abundance and multiply by mass\n"
cpp_file += " // to get the mass of that nuclide / 100 since abundance is in %\n"
cpp_file += " element_atomic_weight += (it->second*atomic_mass_map[it->first]/100.0);\n"
cpp_file += " }\n"
cpp_file += " }\n"
cpp_file += " // insert the abundance of the element into the list\n"
cpp_file += " atomic_mass_map[z*10000000] = element_atomic_weight;\n"
cpp_file += " }\n"
cpp_file += "}\n"
cpp_file += "\n\n"
cpp_file += "void pyne::_insert_atomic_mass_map() { \n"
cpp_file += generate_atomic_mass()
cpp_file += "}\n"
cpp_file += "\n\n"
cpp_file += "void pyne::_insert_abund_map() { \n"
cpp_file += generate_abundances()
cpp_file += "}\n"
return cpp_file | [
"def",
"generate_cpp",
"(",
")",
":",
"cpp_file",
"=",
"AUTOGEN_WARNING",
"cpp_file",
"+=",
"\"// Implements basic nuclear data functions.\\n\"",
"cpp_file",
"+=",
"\"#ifndef PYNE_IS_AMALGAMATED\\n\"",
"cpp_file",
"+=",
"\"#include \\\"atomic_data.h\\\"\\n\"",
"cpp_file",
"+=",
"\"#include \\\"nucname.h\\\"\\n\"",
"cpp_file",
"+=",
"\"#endif\\n\"",
"cpp_file",
"+=",
"\" \\n\"",
"cpp_file",
"+=",
"\"void pyne::_load_atomic_mass_map_memory() { \\n\"",
"cpp_file",
"+=",
"\" // header version of atomic weight table data \\n\"",
"cpp_file",
"+=",
"\" //see if the data table is already loaded\\n\"",
"cpp_file",
"+=",
"\" if(!atomic_mass_map.empty()) {\\n\"",
"cpp_file",
"+=",
"\" return;\\n\"",
"cpp_file",
"+=",
"\" } else { \\n\"",
"cpp_file",
"+=",
"\" _insert_atomic_mass_map();\\n\"",
"cpp_file",
"+=",
"\" }\\n\"",
"cpp_file",
"+=",
"\" //see if the data table is already loaded\\n\"",
"cpp_file",
"+=",
"\" if(!natural_abund_map.empty()) {\\n\"",
"cpp_file",
"+=",
"\" return;\\n\"",
"cpp_file",
"+=",
"\" } else { \\n\"",
"cpp_file",
"+=",
"\" _insert_abund_map();\\n\"",
"cpp_file",
"+=",
"\" }\\n\"",
"cpp_file",
"+=",
"\" // calculate the atomic_masses of the elements \\n\"",
"cpp_file",
"+=",
"\" std::map<int,double> :: iterator it;\\n\"",
"cpp_file",
"+=",
"\" \\n\"",
"cpp_file",
"+=",
"\" for (int z = 1; z <= 92 ; z++) {\\n\"",
"cpp_file",
"+=",
"\" // loop through the natural abundance map\\n\"",
"cpp_file",
"+=",
"\" double element_atomic_weight = 0.0;\\n\"",
"cpp_file",
"+=",
"\" for (it = natural_abund_map.begin(); it != natural_abund_map.end() ; ++it){\\n\"",
"cpp_file",
"+=",
"\" // if the atomic number of the abudance matches the\\n\"",
"cpp_file",
"+=",
"\" // that of index\\n\"",
"cpp_file",
"+=",
"\" if(pyne::nucname::znum(it->first) == z) {\\n\"",
"cpp_file",
"+=",
"\" // take atomic abundance and multiply by mass\\n\"",
"cpp_file",
"+=",
"\" // to get the mass of that nuclide / 100 since abundance is in %\\n\"",
"cpp_file",
"+=",
"\" element_atomic_weight += (it->second*atomic_mass_map[it->first]/100.0);\\n\"",
"cpp_file",
"+=",
"\" }\\n\"",
"cpp_file",
"+=",
"\" }\\n\"",
"cpp_file",
"+=",
"\" // insert the abundance of the element into the list\\n\"",
"cpp_file",
"+=",
"\" atomic_mass_map[z*10000000] = element_atomic_weight;\\n\"",
"cpp_file",
"+=",
"\" }\\n\"",
"cpp_file",
"+=",
"\"}\\n\"",
"cpp_file",
"+=",
"\"\\n\\n\"",
"cpp_file",
"+=",
"\"void pyne::_insert_atomic_mass_map() { \\n\"",
"cpp_file",
"+=",
"generate_atomic_mass",
"(",
")",
"cpp_file",
"+=",
"\"}\\n\"",
"cpp_file",
"+=",
"\"\\n\\n\"",
"cpp_file",
"+=",
"\"void pyne::_insert_abund_map() { \\n\"",
"cpp_file",
"+=",
"generate_abundances",
"(",
")",
"cpp_file",
"+=",
"\"}\\n\"",
"return",
"cpp_file"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/src/atomicgen.py#L129-L179 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBAttachInfo.GroupIDIsValid | (self) | return _lldb.SBAttachInfo_GroupIDIsValid(self) | GroupIDIsValid(self) -> bool | GroupIDIsValid(self) -> bool | [
"GroupIDIsValid",
"(",
"self",
")",
"-",
">",
"bool"
] | def GroupIDIsValid(self):
"""GroupIDIsValid(self) -> bool"""
return _lldb.SBAttachInfo_GroupIDIsValid(self) | [
"def",
"GroupIDIsValid",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBAttachInfo_GroupIDIsValid",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1094-L1096 | |
baidu/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | src/sdk/python/TeraSdk.py | python | RowReader.Family | (self) | return copy_string_to_user(value, long(vallen.value)) | Returns:
(string) 当前cell对应的ColumnFamily | Returns:
(string) 当前cell对应的ColumnFamily | [
"Returns",
":",
"(",
"string",
")",
"当前cell对应的ColumnFamily"
] | def Family(self):
"""
Returns:
(string) 当前cell对应的ColumnFamily
"""
value = POINTER(c_ubyte)()
vallen = c_uint64()
lib.tera_row_reader_family(self.reader, byref(value), byref(vallen))
return copy_string_to_user(value, long(vallen.value)) | [
"def",
"Family",
"(",
"self",
")",
":",
"value",
"=",
"POINTER",
"(",
"c_ubyte",
")",
"(",
")",
"vallen",
"=",
"c_uint64",
"(",
")",
"lib",
".",
"tera_row_reader_family",
"(",
"self",
".",
"reader",
",",
"byref",
"(",
"value",
")",
",",
"byref",
"(",
"vallen",
")",
")",
"return",
"copy_string_to_user",
"(",
"value",
",",
"long",
"(",
"vallen",
".",
"value",
")",
")"
] | https://github.com/baidu/tera/blob/dbcd28af792d879d961bf9fc7eb60de81b437646/src/sdk/python/TeraSdk.py#L780-L788 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/runtime.py | python | make_logging_undefined | (logger=None, base=None) | return LoggingUndefined | Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created.
Example::
logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(
logger=logger,
base=Undefined
)
.. versionadded:: 2.8
:param logger: the logger to use. If not provided, a default logger
is created.
:param base: the base class to add logging functionality to. This
defaults to :class:`Undefined`. | Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created. | [
"Given",
"a",
"logger",
"object",
"this",
"returns",
"a",
"new",
"undefined",
"class",
"that",
"will",
"log",
"certain",
"failures",
".",
"It",
"will",
"log",
"iterations",
"and",
"printing",
".",
"If",
"no",
"logger",
"is",
"given",
"a",
"default",
"logger",
"is",
"created",
"."
] | def make_logging_undefined(logger=None, base=None):
"""Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created.
Example::
logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(
logger=logger,
base=Undefined
)
.. versionadded:: 2.8
:param logger: the logger to use. If not provided, a default logger
is created.
:param base: the base class to add logging functionality to. This
defaults to :class:`Undefined`.
"""
if logger is None:
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler(sys.stderr))
if base is None:
base = Undefined
def _log_message(undef):
if undef._undefined_hint is None:
if undef._undefined_obj is missing:
hint = '%s is undefined' % undef._undefined_name
elif not isinstance(undef._undefined_name, string_types):
hint = '%s has no element %s' % (
object_type_repr(undef._undefined_obj),
undef._undefined_name)
else:
hint = '%s has no attribute %s' % (
object_type_repr(undef._undefined_obj),
undef._undefined_name)
else:
hint = undef._undefined_hint
logger.warning('Template variable warning: %s', hint)
class LoggingUndefined(base):
def _fail_with_undefined_error(self, *args, **kwargs):
try:
return base._fail_with_undefined_error(self, *args, **kwargs)
except self._undefined_exception as e:
logger.error('Template variable error: %s', str(e))
raise e
def __str__(self):
rv = base.__str__(self)
_log_message(self)
return rv
def __iter__(self):
rv = base.__iter__(self)
_log_message(self)
return rv
if PY2:
def __nonzero__(self):
rv = base.__nonzero__(self)
_log_message(self)
return rv
def __unicode__(self):
rv = base.__unicode__(self)
_log_message(self)
return rv
else:
def __bool__(self):
rv = base.__bool__(self)
_log_message(self)
return rv
return LoggingUndefined | [
"def",
"make_logging_undefined",
"(",
"logger",
"=",
"None",
",",
"base",
"=",
"None",
")",
":",
"if",
"logger",
"is",
"None",
":",
"import",
"logging",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"addHandler",
"(",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stderr",
")",
")",
"if",
"base",
"is",
"None",
":",
"base",
"=",
"Undefined",
"def",
"_log_message",
"(",
"undef",
")",
":",
"if",
"undef",
".",
"_undefined_hint",
"is",
"None",
":",
"if",
"undef",
".",
"_undefined_obj",
"is",
"missing",
":",
"hint",
"=",
"'%s is undefined'",
"%",
"undef",
".",
"_undefined_name",
"elif",
"not",
"isinstance",
"(",
"undef",
".",
"_undefined_name",
",",
"string_types",
")",
":",
"hint",
"=",
"'%s has no element %s'",
"%",
"(",
"object_type_repr",
"(",
"undef",
".",
"_undefined_obj",
")",
",",
"undef",
".",
"_undefined_name",
")",
"else",
":",
"hint",
"=",
"'%s has no attribute %s'",
"%",
"(",
"object_type_repr",
"(",
"undef",
".",
"_undefined_obj",
")",
",",
"undef",
".",
"_undefined_name",
")",
"else",
":",
"hint",
"=",
"undef",
".",
"_undefined_hint",
"logger",
".",
"warning",
"(",
"'Template variable warning: %s'",
",",
"hint",
")",
"class",
"LoggingUndefined",
"(",
"base",
")",
":",
"def",
"_fail_with_undefined_error",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"base",
".",
"_fail_with_undefined_error",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"self",
".",
"_undefined_exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"'Template variable error: %s'",
",",
"str",
"(",
"e",
")",
")",
"raise",
"e",
"def",
"__str__",
"(",
"self",
")",
":",
"rv",
"=",
"base",
".",
"__str__",
"(",
"self",
")",
"_log_message",
"(",
"self",
")",
"return",
"rv",
"def",
"__iter__",
"(",
"self",
")",
":",
"rv",
"=",
"base",
".",
"__iter__",
"(",
"self",
")",
"_log_message",
"(",
"self",
")",
"return",
"rv",
"if",
"PY2",
":",
"def",
"__nonzero__",
"(",
"self",
")",
":",
"rv",
"=",
"base",
".",
"__nonzero__",
"(",
"self",
")",
"_log_message",
"(",
"self",
")",
"return",
"rv",
"def",
"__unicode__",
"(",
"self",
")",
":",
"rv",
"=",
"base",
".",
"__unicode__",
"(",
"self",
")",
"_log_message",
"(",
"self",
")",
"return",
"rv",
"else",
":",
"def",
"__bool__",
"(",
"self",
")",
":",
"rv",
"=",
"base",
".",
"__bool__",
"(",
"self",
")",
"_log_message",
"(",
"self",
")",
"return",
"rv",
"return",
"LoggingUndefined"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/runtime.py#L677-L755 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.