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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/framework/ops.py | python | add_to_collections | (names, value) | Wrapper for `Graph.add_to_collections()` using the default graph.
See [`Graph.add_to_collections()`](../../api_docs/python/framework.md#Graph.add_to_collections)
for more details.
Args:
names: The key for the collections. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collections. | Wrapper for `Graph.add_to_collections()` using the default graph. | [
"Wrapper",
"for",
"Graph",
".",
"add_to_collections",
"()",
"using",
"the",
"default",
"graph",
"."
] | def add_to_collections(names, value):
"""Wrapper for `Graph.add_to_collections()` using the default graph.
See [`Graph.add_to_collections()`](../../api_docs/python/framework.md#Graph.add_to_collections)
for more details.
Args:
names: The key for the collections. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collections.
"""
get_default_graph().add_to_collections(names, value) | [
"def",
"add_to_collections",
"(",
"names",
",",
"value",
")",
":",
"get_default_graph",
"(",
")",
".",
"add_to_collections",
"(",
"names",
",",
"value",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L4055-L4066 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/config/expandlibs.py | python | ensureParentDir | (file) | Ensures the directory parent to the given file exists | Ensures the directory parent to the given file exists | [
"Ensures",
"the",
"directory",
"parent",
"to",
"the",
"given",
"file",
"exists"
] | def ensureParentDir(file):
'''Ensures the directory parent to the given file exists'''
dir = os.path.dirname(file)
if dir and not os.path.exists(dir):
try:
os.makedirs(dir)
except OSError, error:
if error.errno != errno.EEXIST:
raise | [
"def",
"ensureParentDir",
"(",
"file",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
")",
"if",
"dir",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"dir",
")",
"except",
"OSError",
",",
"error",
":",
"if",
"error",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/config/expandlibs.py#L33-L41 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/lookup_ops.py | python | InitializableLookupTableBase.default_value | (self) | return self._default_value | The default value of the table. | The default value of the table. | [
"The",
"default",
"value",
"of",
"the",
"table",
"."
] | def default_value(self):
"""The default value of the table."""
return self._default_value | [
"def",
"default_value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_default_value"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/lookup_ops.py#L209-L211 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/profile_analyzer_cli.py | python | _list_profile_sort_key | (profile_datum, sort_by) | Get a profile_datum property to sort by in list_profile command.
Args:
profile_datum: A `ProfileDatum` object.
sort_by: (string) indicates a value to sort by.
Must be one of SORT_BY* constants.
Returns:
profile_datum property to sort by. | Get a profile_datum property to sort by in list_profile command. | [
"Get",
"a",
"profile_datum",
"property",
"to",
"sort",
"by",
"in",
"list_profile",
"command",
"."
] | def _list_profile_sort_key(profile_datum, sort_by):
"""Get a profile_datum property to sort by in list_profile command.
Args:
profile_datum: A `ProfileDatum` object.
sort_by: (string) indicates a value to sort by.
Must be one of SORT_BY* constants.
Returns:
profile_datum property to sort by.
"""
if sort_by == SORT_OPS_BY_OP_NAME:
return profile_datum.node_exec_stats.node_name
elif sort_by == SORT_OPS_BY_OP_TYPE:
return profile_datum.op_type
elif sort_by == SORT_OPS_BY_LINE:
return profile_datum.file_line_func
elif sort_by == SORT_OPS_BY_OP_TIME:
return profile_datum.op_time
elif sort_by == SORT_OPS_BY_EXEC_TIME:
return profile_datum.node_exec_stats.all_end_rel_micros
else: # sort by start time
return profile_datum.node_exec_stats.all_start_micros | [
"def",
"_list_profile_sort_key",
"(",
"profile_datum",
",",
"sort_by",
")",
":",
"if",
"sort_by",
"==",
"SORT_OPS_BY_OP_NAME",
":",
"return",
"profile_datum",
".",
"node_exec_stats",
".",
"node_name",
"elif",
"sort_by",
"==",
"SORT_OPS_BY_OP_TYPE",
":",
"return",
"profile_datum",
".",
"op_type",
"elif",
"sort_by",
"==",
"SORT_OPS_BY_LINE",
":",
"return",
"profile_datum",
".",
"file_line_func",
"elif",
"sort_by",
"==",
"SORT_OPS_BY_OP_TIME",
":",
"return",
"profile_datum",
".",
"op_time",
"elif",
"sort_by",
"==",
"SORT_OPS_BY_EXEC_TIME",
":",
"return",
"profile_datum",
".",
"node_exec_stats",
".",
"all_end_rel_micros",
"else",
":",
"# sort by start time",
"return",
"profile_datum",
".",
"node_exec_stats",
".",
"all_start_micros"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/profile_analyzer_cli.py#L198-L220 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/coordinates.py | python | Frame.name | (self) | return self._name | Returns the name of this frame | Returns the name of this frame | [
"Returns",
"the",
"name",
"of",
"this",
"frame"
] | def name(self):
"""Returns the name of this frame"""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/coordinates.py#L45-L47 | |
Evolving-AI-Lab/fooling | 66f097dd6bd2eb6794ade3e187a7adfdf1887688 | caffe/scripts/cpp_lint.py | python | CheckForFunctionLengths | (filename, clean_lines, linenum,
function_state, error) | Reports for long function bodies.
For an overview why this is done, see:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found. | Reports for long function bodies. | [
"Reports",
"for",
"long",
"function",
"bodies",
"."
] | def CheckForFunctionLengths(filename, clean_lines, linenum,
function_state, error):
"""Reports for long function bodies.
For an overview why this is done, see:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found.
"""
lines = clean_lines.lines
line = lines[linenum]
raw = clean_lines.raw_lines
raw_line = raw[linenum]
joined_line = ''
starting_func = False
regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
match_result = Match(regexp, line)
if match_result:
# If the name is all caps and underscores, figure it's a macro and
# ignore it, unless it's TEST or TEST_F.
function_name = match_result.group(1).split()[-1]
if function_name == 'TEST' or function_name == 'TEST_F' or (
not Match(r'[A-Z_]+$', function_name)):
starting_func = True
if starting_func:
body_found = False
for start_linenum in xrange(linenum, clean_lines.NumLines()):
start_line = lines[start_linenum]
joined_line += ' ' + start_line.lstrip()
if Search(r'(;|})', start_line): # Declarations and trivial functions
body_found = True
break # ... ignore
elif Search(r'{', start_line):
body_found = True
function = Search(r'((\w|:)*)\(', line).group(1)
if Match(r'TEST', function): # Handle TEST... macros
parameter_regexp = Search(r'(\(.*\))', joined_line)
if parameter_regexp: # Ignore bad syntax
function += parameter_regexp.group(1)
else:
function += '()'
function_state.Begin(function)
break
if not body_found:
# No body for the function (or evidence of a non-function) was found.
error(filename, linenum, 'readability/fn_size', 5,
'Lint failed to find start of function body.')
elif Match(r'^\}\s*$', line): # function end
function_state.Check(error, filename, linenum)
function_state.End()
elif not Match(r'^\s*$', line):
function_state.Count() | [
"def",
"CheckForFunctionLengths",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"function_state",
",",
"error",
")",
":",
"lines",
"=",
"clean_lines",
".",
"lines",
"line",
"=",
"lines",
"[",
"linenum",
"]",
"raw",
"=",
"clean_lines",
".",
"raw_lines",
"raw_line",
"=",
"raw",
"[",
"linenum",
"]",
"joined_line",
"=",
"''",
"starting_func",
"=",
"False",
"regexp",
"=",
"r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('",
"# decls * & space::name( ...",
"match_result",
"=",
"Match",
"(",
"regexp",
",",
"line",
")",
"if",
"match_result",
":",
"# If the name is all caps and underscores, figure it's a macro and",
"# ignore it, unless it's TEST or TEST_F.",
"function_name",
"=",
"match_result",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"if",
"function_name",
"==",
"'TEST'",
"or",
"function_name",
"==",
"'TEST_F'",
"or",
"(",
"not",
"Match",
"(",
"r'[A-Z_]+$'",
",",
"function_name",
")",
")",
":",
"starting_func",
"=",
"True",
"if",
"starting_func",
":",
"body_found",
"=",
"False",
"for",
"start_linenum",
"in",
"xrange",
"(",
"linenum",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"start_line",
"=",
"lines",
"[",
"start_linenum",
"]",
"joined_line",
"+=",
"' '",
"+",
"start_line",
".",
"lstrip",
"(",
")",
"if",
"Search",
"(",
"r'(;|})'",
",",
"start_line",
")",
":",
"# Declarations and trivial functions",
"body_found",
"=",
"True",
"break",
"# ... ignore",
"elif",
"Search",
"(",
"r'{'",
",",
"start_line",
")",
":",
"body_found",
"=",
"True",
"function",
"=",
"Search",
"(",
"r'((\\w|:)*)\\('",
",",
"line",
")",
".",
"group",
"(",
"1",
")",
"if",
"Match",
"(",
"r'TEST'",
",",
"function",
")",
":",
"# Handle TEST... macros",
"parameter_regexp",
"=",
"Search",
"(",
"r'(\\(.*\\))'",
",",
"joined_line",
")",
"if",
"parameter_regexp",
":",
"# Ignore bad syntax",
"function",
"+=",
"parameter_regexp",
".",
"group",
"(",
"1",
")",
"else",
":",
"function",
"+=",
"'()'",
"function_state",
".",
"Begin",
"(",
"function",
")",
"break",
"if",
"not",
"body_found",
":",
"# No body for the function (or evidence of a non-function) was found.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/fn_size'",
",",
"5",
",",
"'Lint failed to find start of function body.'",
")",
"elif",
"Match",
"(",
"r'^\\}\\s*$'",
",",
"line",
")",
":",
"# function end",
"function_state",
".",
"Check",
"(",
"error",
",",
"filename",
",",
"linenum",
")",
"function_state",
".",
"End",
"(",
")",
"elif",
"not",
"Match",
"(",
"r'^\\s*$'",
",",
"line",
")",
":",
"function_state",
".",
"Count",
"(",
")"
] | https://github.com/Evolving-AI-Lab/fooling/blob/66f097dd6bd2eb6794ade3e187a7adfdf1887688/caffe/scripts/cpp_lint.py#L2314-L2381 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/trajectory.py | python | Trajectory.deriv_state | (self, t: float, endBehavior: str = 'halt') | return self.difference_state(self.milestones[i+1],self.milestones[i],u,self.times[i+1]-self.times[i]) | Internal deriv, used on the underlying state representation | Internal deriv, used on the underlying state representation | [
"Internal",
"deriv",
"used",
"on",
"the",
"underlying",
"state",
"representation"
] | def deriv_state(self, t: float, endBehavior: str = 'halt') -> Vector:
"""Internal deriv, used on the underlying state representation"""
i,u = self.getSegment(t,endBehavior)
if i<0: return [0.0]*len(self.milestones[0])
elif i+1>=len(self.milestones): return [0.0]*len(self.milestones[-1])
return self.difference_state(self.milestones[i+1],self.milestones[i],u,self.times[i+1]-self.times[i]) | [
"def",
"deriv_state",
"(",
"self",
",",
"t",
":",
"float",
",",
"endBehavior",
":",
"str",
"=",
"'halt'",
")",
"->",
"Vector",
":",
"i",
",",
"u",
"=",
"self",
".",
"getSegment",
"(",
"t",
",",
"endBehavior",
")",
"if",
"i",
"<",
"0",
":",
"return",
"[",
"0.0",
"]",
"*",
"len",
"(",
"self",
".",
"milestones",
"[",
"0",
"]",
")",
"elif",
"i",
"+",
"1",
">=",
"len",
"(",
"self",
".",
"milestones",
")",
":",
"return",
"[",
"0.0",
"]",
"*",
"len",
"(",
"self",
".",
"milestones",
"[",
"-",
"1",
"]",
")",
"return",
"self",
".",
"difference_state",
"(",
"self",
".",
"milestones",
"[",
"i",
"+",
"1",
"]",
",",
"self",
".",
"milestones",
"[",
"i",
"]",
",",
"u",
",",
"self",
".",
"times",
"[",
"i",
"+",
"1",
"]",
"-",
"self",
".",
"times",
"[",
"i",
"]",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/trajectory.py#L203-L208 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/common/xml_parsing.py | python | get_named_elements_from_ipf_file | (ipf_file, names_to_search, value_type) | return output | Gets a named element from the IPF
This is useful for detector names etc.
:param ipf_file: the path to the IPF
:param names_to_search: the names we want to search for on the XML file.
:param value_type: the type we expect for the names.
:return: a ElementName vs Value map | Gets a named element from the IPF | [
"Gets",
"a",
"named",
"element",
"from",
"the",
"IPF"
] | def get_named_elements_from_ipf_file(ipf_file, names_to_search, value_type):
"""
Gets a named element from the IPF
This is useful for detector names etc.
:param ipf_file: the path to the IPF
:param names_to_search: the names we want to search for on the XML file.
:param value_type: the type we expect for the names.
:return: a ElementName vs Value map
"""
"""
Args:
ipf_file: The path to the IPF
names_to_search: A list of search names
value_type: the type of an item
Returns: A map of the search names and the found information
"""
output = {}
number_of_elements_to_search = len(names_to_search)
for _, element in eTree.iterparse(ipf_file):
if element.tag == "parameter" and "name" in list(element.keys()):
# Ideally we would break the for loop if we have found all the elements we are looking for.
# BUT: a not completed generator eTree.iterparse emits a ResourceWarning if we don't finish the generator.
# There is also no method to close the file manually, hence we run through the whole file. Note that there
# is an existing bug report here: https://bugs.python.org/issue25707
if number_of_elements_to_search != len(output) and element.get("name") in names_to_search:
sub_element = element.find("value")
value = sub_element.get("val")
output.update({element.get("name"): value_type(value)})
element.clear()
return output | [
"def",
"get_named_elements_from_ipf_file",
"(",
"ipf_file",
",",
"names_to_search",
",",
"value_type",
")",
":",
"\"\"\"\n Args:\n ipf_file: The path to the IPF\n names_to_search: A list of search names\n value_type: the type of an item\n Returns: A map of the search names and the found information\n \"\"\"",
"output",
"=",
"{",
"}",
"number_of_elements_to_search",
"=",
"len",
"(",
"names_to_search",
")",
"for",
"_",
",",
"element",
"in",
"eTree",
".",
"iterparse",
"(",
"ipf_file",
")",
":",
"if",
"element",
".",
"tag",
"==",
"\"parameter\"",
"and",
"\"name\"",
"in",
"list",
"(",
"element",
".",
"keys",
"(",
")",
")",
":",
"# Ideally we would break the for loop if we have found all the elements we are looking for.",
"# BUT: a not completed generator eTree.iterparse emits a ResourceWarning if we don't finish the generator.",
"# There is also no method to close the file manually, hence we run through the whole file. Note that there",
"# is an existing bug report here: https://bugs.python.org/issue25707",
"if",
"number_of_elements_to_search",
"!=",
"len",
"(",
"output",
")",
"and",
"element",
".",
"get",
"(",
"\"name\"",
")",
"in",
"names_to_search",
":",
"sub_element",
"=",
"element",
".",
"find",
"(",
"\"value\"",
")",
"value",
"=",
"sub_element",
".",
"get",
"(",
"\"val\"",
")",
"output",
".",
"update",
"(",
"{",
"element",
".",
"get",
"(",
"\"name\"",
")",
":",
"value_type",
"(",
"value",
")",
"}",
")",
"element",
".",
"clear",
"(",
")",
"return",
"output"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/common/xml_parsing.py#L18-L50 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/ops.py | python | Graph.as_graph_def | (self, from_version=None, add_shapes=False) | return result | Returns a serialized `GraphDef` representation of this graph.
The serialized `GraphDef` can be imported into another `Graph`
(using @{tf.import_graph_def}) or used with the
[C++ Session API](../../api_docs/cc/index.md).
This method is thread-safe.
Args:
from_version: Optional. If this is set, returns a `GraphDef`
containing only the nodes that were added to this graph since
its `version` property had the given value.
add_shapes: If true, adds an "_output_shapes" list attr to each
node with the inferred shapes of each of its outputs.
Returns:
A
[`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
protocol buffer.
Raises:
ValueError: If the `graph_def` would be too large. | Returns a serialized `GraphDef` representation of this graph. | [
"Returns",
"a",
"serialized",
"GraphDef",
"representation",
"of",
"this",
"graph",
"."
] | def as_graph_def(self, from_version=None, add_shapes=False):
# pylint: disable=line-too-long
"""Returns a serialized `GraphDef` representation of this graph.
The serialized `GraphDef` can be imported into another `Graph`
(using @{tf.import_graph_def}) or used with the
[C++ Session API](../../api_docs/cc/index.md).
This method is thread-safe.
Args:
from_version: Optional. If this is set, returns a `GraphDef`
containing only the nodes that were added to this graph since
its `version` property had the given value.
add_shapes: If true, adds an "_output_shapes" list attr to each
node with the inferred shapes of each of its outputs.
Returns:
A
[`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
protocol buffer.
Raises:
ValueError: If the `graph_def` would be too large.
"""
# pylint: enable=line-too-long
result, _ = self._as_graph_def(from_version, add_shapes)
return result | [
"def",
"as_graph_def",
"(",
"self",
",",
"from_version",
"=",
"None",
",",
"add_shapes",
"=",
"False",
")",
":",
"# pylint: disable=line-too-long",
"# pylint: enable=line-too-long",
"result",
",",
"_",
"=",
"self",
".",
"_as_graph_def",
"(",
"from_version",
",",
"add_shapes",
")",
"return",
"result"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L2796-L2823 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | ext/ply/example/BASIC/basparse.py | python | p_dimitem_single | (p) | dimitem : ID LPAREN INTEGER RPAREN | dimitem : ID LPAREN INTEGER RPAREN | [
"dimitem",
":",
"ID",
"LPAREN",
"INTEGER",
"RPAREN"
] | def p_dimitem_single(p):
'''dimitem : ID LPAREN INTEGER RPAREN'''
p[0] = (p[1],eval(p[3]),0) | [
"def",
"p_dimitem_single",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"1",
"]",
",",
"eval",
"(",
"p",
"[",
"3",
"]",
")",
",",
"0",
")"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/BASIC/basparse.py#L272-L274 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/femtools/ccxtools.py | python | FemToolsCcx.set_base_name | (self, base_name=None) | Set base_name
Parameters
----------
base_name : str, optional
base_name base name of .inp/.frd file (without extension).
It is used to construct .inp file path that is passed to CalculiX ccx | Set base_name | [
"Set",
"base_name"
] | def set_base_name(self, base_name=None):
"""
Set base_name
Parameters
----------
base_name : str, optional
base_name base name of .inp/.frd file (without extension).
It is used to construct .inp file path that is passed to CalculiX ccx
"""
if base_name is None:
self.base_name = ""
else:
self.base_name = base_name
# Update inp file name
self.set_inp_file_name() | [
"def",
"set_base_name",
"(",
"self",
",",
"base_name",
"=",
"None",
")",
":",
"if",
"base_name",
"is",
"None",
":",
"self",
".",
"base_name",
"=",
"\"\"",
"else",
":",
"self",
".",
"base_name",
"=",
"base_name",
"# Update inp file name",
"self",
".",
"set_inp_file_name",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/femtools/ccxtools.py#L276-L291 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/Tools/python/GenObject.py | python | GenObject.encodeNonAlphanumerics | (line) | return GenObject._nonAlphaRE.sub( GenObject.char2ascii, line ) | Use a web like encoding of characters that are non-alphanumeric | Use a web like encoding of characters that are non-alphanumeric | [
"Use",
"a",
"web",
"like",
"encoding",
"of",
"characters",
"that",
"are",
"non",
"-",
"alphanumeric"
] | def encodeNonAlphanumerics (line):
"""Use a web like encoding of characters that are non-alphanumeric"""
return GenObject._nonAlphaRE.sub( GenObject.char2ascii, line ) | [
"def",
"encodeNonAlphanumerics",
"(",
"line",
")",
":",
"return",
"GenObject",
".",
"_nonAlphaRE",
".",
"sub",
"(",
"GenObject",
".",
"char2ascii",
",",
"line",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/Tools/python/GenObject.py#L128-L130 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/affine/diag.py | python | diag_mat.is_atom_log_log_concave | (self) | return True | Is the atom log-log concave? | Is the atom log-log concave? | [
"Is",
"the",
"atom",
"log",
"-",
"log",
"concave?"
] | def is_atom_log_log_concave(self) -> bool:
"""Is the atom log-log concave?
"""
return True | [
"def",
"is_atom_log_log_concave",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/diag.py#L131-L134 | |
polyworld/polyworld | eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26 | scripts/agent/agent.py | python | Agent.alive_at_timestep | (self, step) | return self.birth < step <= self.death | returns whether the Agent is alive at a given timestep | returns whether the Agent is alive at a given timestep | [
"returns",
"whether",
"the",
"Agent",
"is",
"alive",
"at",
"a",
"given",
"timestep"
] | def alive_at_timestep(self, step):
''' returns whether the Agent is alive at a given timestep '''
return self.birth < step <= self.death | [
"def",
"alive_at_timestep",
"(",
"self",
",",
"step",
")",
":",
"return",
"self",
".",
"birth",
"<",
"step",
"<=",
"self",
".",
"death"
] | https://github.com/polyworld/polyworld/blob/eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26/scripts/agent/agent.py#L257-L259 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py | python | batch_gather_with_default | (params,
indices,
default_value='',
name=None) | Same as `batch_gather` but inserts `default_value` for invalid indices.
This operation is similar to `batch_gather` except that it will substitute
the value for invalid indices with `default_value` as the contents.
See `batch_gather` for more details.
Args:
params: A potentially ragged tensor with shape `[B1...BN, P1...PM]` (`N>=0`,
`M>0`).
indices: A potentially ragged tensor with shape `[B1...BN, I]` (`N>=0`).
default_value: A value to be inserted in places where `indices` are out of
bounds. Must be the same dtype as params and either a scalar or rank 1.
name: A name for the operation (optional).
Returns:
A potentially ragged tensor with shape `[B1...BN, I, P2...PM]`.
`result.ragged_rank = max(indices.ragged_rank, params.ragged_rank)`.
#### Example:
```python
>>> params = tf.ragged.constant([
['a', 'b', 'c'],
['d'],
[],
['e']])
>>> indices = tf.ragged.constant([[1, 2, -1], [], [], [0, 10]])
>>> batch_gather_with_default(params, indices, 'FOO')
[['b', 'c', 'FOO'], [], [], ['e', 'FOO']]
``` | Same as `batch_gather` but inserts `default_value` for invalid indices. | [
"Same",
"as",
"batch_gather",
"but",
"inserts",
"default_value",
"for",
"invalid",
"indices",
"."
] | def batch_gather_with_default(params,
indices,
default_value='',
name=None):
"""Same as `batch_gather` but inserts `default_value` for invalid indices.
This operation is similar to `batch_gather` except that it will substitute
the value for invalid indices with `default_value` as the contents.
See `batch_gather` for more details.
Args:
params: A potentially ragged tensor with shape `[B1...BN, P1...PM]` (`N>=0`,
`M>0`).
indices: A potentially ragged tensor with shape `[B1...BN, I]` (`N>=0`).
default_value: A value to be inserted in places where `indices` are out of
bounds. Must be the same dtype as params and either a scalar or rank 1.
name: A name for the operation (optional).
Returns:
A potentially ragged tensor with shape `[B1...BN, I, P2...PM]`.
`result.ragged_rank = max(indices.ragged_rank, params.ragged_rank)`.
#### Example:
```python
>>> params = tf.ragged.constant([
['a', 'b', 'c'],
['d'],
[],
['e']])
>>> indices = tf.ragged.constant([[1, 2, -1], [], [], [0, 10]])
>>> batch_gather_with_default(params, indices, 'FOO')
[['b', 'c', 'FOO'], [], [], ['e', 'FOO']]
```
"""
with ops.name_scope(name, 'RaggedBatchGatherWithDefault'):
params = ragged_tensor.convert_to_tensor_or_ragged_tensor(
params, name='params',
)
indices = ragged_tensor.convert_to_tensor_or_ragged_tensor(
indices, name='indices',
)
default_value = ragged_tensor.convert_to_tensor_or_ragged_tensor(
default_value, name='default_value',
)
row_splits_dtype, (params, indices, default_value) = (
ragged_tensor.match_row_splits_dtypes(params, indices, default_value,
return_dtype=True))
# TODO(hterry): lift this restriction and support default_values of
# of rank > 1
if (default_value.shape.ndims is not 0
and default_value.shape.ndims is not 1):
raise ValueError('"default_value" must be a scalar or vector')
upper_bounds = None
if indices.shape.ndims is None:
raise ValueError('Indices must have a known rank.')
if params.shape.ndims is None:
raise ValueError('Params must have a known rank.')
num_batch_dimensions = indices.shape.ndims - 1
pad = None
# The logic for this works as follows:
# - create a padded params, where:
# padded_params[b1...bn, 0] = default_value
# padded_params[b1...bn, i] = params[b1...bn, i-1] (i>0)
# - create an `upper_bounds` Tensor that contains the number of elements
# in each innermost rank. Broadcast `upper_bounds` to be the same shape
# as `indices`.
# - check to see which index in `indices` are out of bounds and substitute
# it with the index containing `default_value` (the first).
# - call batch_gather with the indices adjusted.
with ops.control_dependencies([
check_ops.assert_greater_equal(array_ops.rank(params),
array_ops.rank(indices))]):
if ragged_tensor.is_ragged(params):
row_lengths = ragged_array_ops.expand_dims(
params.row_lengths(axis=num_batch_dimensions),
axis=-1)
upper_bounds = math_ops.cast(row_lengths, indices.dtype)
pad_shape = _get_pad_shape(params, indices, row_splits_dtype)
pad = ragged_tensor_shape.broadcast_to(
default_value, pad_shape)
else:
params_shape = array_ops.shape(params)
pad_shape = array_ops.concat([
params_shape[:num_batch_dimensions],
[1],
params_shape[num_batch_dimensions + 1:params.shape.ndims]
], 0)
upper_bounds = params_shape[num_batch_dimensions]
pad = array_ops.broadcast_to(default_value, pad_shape)
# Add `default_value` as the first value in the innermost (ragged) rank.
pad = math_ops.cast(pad, params.dtype)
padded_params = array_ops.concat(
[pad, params], axis=num_batch_dimensions)
# Adjust the indices by substituting out-of-bound indices to the
# default-value index (which is the first element)
shifted_indices = indices + 1
is_out_of_bounds = (indices < 0) | (indices > upper_bounds)
adjusted_indices = ragged_where_op.where(
is_out_of_bounds,
x=array_ops.zeros_like(indices), y=shifted_indices,
)
return array_ops.batch_gather(
params=padded_params, indices=adjusted_indices, name=name) | [
"def",
"batch_gather_with_default",
"(",
"params",
",",
"indices",
",",
"default_value",
"=",
"''",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'RaggedBatchGatherWithDefault'",
")",
":",
"params",
"=",
"ragged_tensor",
".",
"convert_to_tensor_or_ragged_tensor",
"(",
"params",
",",
"name",
"=",
"'params'",
",",
")",
"indices",
"=",
"ragged_tensor",
".",
"convert_to_tensor_or_ragged_tensor",
"(",
"indices",
",",
"name",
"=",
"'indices'",
",",
")",
"default_value",
"=",
"ragged_tensor",
".",
"convert_to_tensor_or_ragged_tensor",
"(",
"default_value",
",",
"name",
"=",
"'default_value'",
",",
")",
"row_splits_dtype",
",",
"(",
"params",
",",
"indices",
",",
"default_value",
")",
"=",
"(",
"ragged_tensor",
".",
"match_row_splits_dtypes",
"(",
"params",
",",
"indices",
",",
"default_value",
",",
"return_dtype",
"=",
"True",
")",
")",
"# TODO(hterry): lift this restriction and support default_values of",
"# of rank > 1",
"if",
"(",
"default_value",
".",
"shape",
".",
"ndims",
"is",
"not",
"0",
"and",
"default_value",
".",
"shape",
".",
"ndims",
"is",
"not",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'\"default_value\" must be a scalar or vector'",
")",
"upper_bounds",
"=",
"None",
"if",
"indices",
".",
"shape",
".",
"ndims",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Indices must have a known rank.'",
")",
"if",
"params",
".",
"shape",
".",
"ndims",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Params must have a known rank.'",
")",
"num_batch_dimensions",
"=",
"indices",
".",
"shape",
".",
"ndims",
"-",
"1",
"pad",
"=",
"None",
"# The logic for this works as follows:",
"# - create a padded params, where:",
"# padded_params[b1...bn, 0] = default_value",
"# padded_params[b1...bn, i] = params[b1...bn, i-1] (i>0)",
"# - create an `upper_bounds` Tensor that contains the number of elements",
"# in each innermost rank. Broadcast `upper_bounds` to be the same shape",
"# as `indices`.",
"# - check to see which index in `indices` are out of bounds and substitute",
"# it with the index containing `default_value` (the first).",
"# - call batch_gather with the indices adjusted.",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"check_ops",
".",
"assert_greater_equal",
"(",
"array_ops",
".",
"rank",
"(",
"params",
")",
",",
"array_ops",
".",
"rank",
"(",
"indices",
")",
")",
"]",
")",
":",
"if",
"ragged_tensor",
".",
"is_ragged",
"(",
"params",
")",
":",
"row_lengths",
"=",
"ragged_array_ops",
".",
"expand_dims",
"(",
"params",
".",
"row_lengths",
"(",
"axis",
"=",
"num_batch_dimensions",
")",
",",
"axis",
"=",
"-",
"1",
")",
"upper_bounds",
"=",
"math_ops",
".",
"cast",
"(",
"row_lengths",
",",
"indices",
".",
"dtype",
")",
"pad_shape",
"=",
"_get_pad_shape",
"(",
"params",
",",
"indices",
",",
"row_splits_dtype",
")",
"pad",
"=",
"ragged_tensor_shape",
".",
"broadcast_to",
"(",
"default_value",
",",
"pad_shape",
")",
"else",
":",
"params_shape",
"=",
"array_ops",
".",
"shape",
"(",
"params",
")",
"pad_shape",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"params_shape",
"[",
":",
"num_batch_dimensions",
"]",
",",
"[",
"1",
"]",
",",
"params_shape",
"[",
"num_batch_dimensions",
"+",
"1",
":",
"params",
".",
"shape",
".",
"ndims",
"]",
"]",
",",
"0",
")",
"upper_bounds",
"=",
"params_shape",
"[",
"num_batch_dimensions",
"]",
"pad",
"=",
"array_ops",
".",
"broadcast_to",
"(",
"default_value",
",",
"pad_shape",
")",
"# Add `default_value` as the first value in the innermost (ragged) rank.",
"pad",
"=",
"math_ops",
".",
"cast",
"(",
"pad",
",",
"params",
".",
"dtype",
")",
"padded_params",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"pad",
",",
"params",
"]",
",",
"axis",
"=",
"num_batch_dimensions",
")",
"# Adjust the indices by substituting out-of-bound indices to the",
"# default-value index (which is the first element)",
"shifted_indices",
"=",
"indices",
"+",
"1",
"is_out_of_bounds",
"=",
"(",
"indices",
"<",
"0",
")",
"|",
"(",
"indices",
">",
"upper_bounds",
")",
"adjusted_indices",
"=",
"ragged_where_op",
".",
"where",
"(",
"is_out_of_bounds",
",",
"x",
"=",
"array_ops",
".",
"zeros_like",
"(",
"indices",
")",
",",
"y",
"=",
"shifted_indices",
",",
")",
"return",
"array_ops",
".",
"batch_gather",
"(",
"params",
"=",
"padded_params",
",",
"indices",
"=",
"adjusted_indices",
",",
"name",
"=",
"name",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py#L38-L146 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/tools/grokdump.py | python | InspectionShell.do_lm | (self, arg) | return self.do_list_modules(arg) | see list_modules | see list_modules | [
"see",
"list_modules"
] | def do_lm(self, arg):
""" see list_modules """
return self.do_list_modules(arg) | [
"def",
"do_lm",
"(",
"self",
",",
"arg",
")",
":",
"return",
"self",
".",
"do_list_modules",
"(",
"arg",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/tools/grokdump.py#L3686-L3688 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/blackduck_hub.py | python | BuildloggerServer.post_new_file | (self, build_id, test_name, lines) | return self.handler.make_url(endpoint) | Post a new file to the build logger server. | Post a new file to the build logger server. | [
"Post",
"a",
"new",
"file",
"to",
"the",
"build",
"logger",
"server",
"."
] | def post_new_file(self, build_id, test_name, lines):
"""Post a new file to the build logger server."""
test_id = self.new_test_id(build_id, test_name, "foo")
endpoint = BUILD_LOGGER_APPEND_TEST_LOGS_ENDPOINT % {
"build_id": build_id,
"test_id": test_id,
}
dt = time.time()
dlines = [(dt, line) for line in lines]
try:
self.handler.post(endpoint, data=dlines)
except requests.HTTPError as err:
# Handle the "Request Entity Too Large" error, set the max size and retry.
raise ValueError("Encountered an HTTP error: %s" % (err))
except requests.RequestException as err:
raise ValueError("Encountered a network error: %s" % (err))
except: # pylint: disable=bare-except
raise ValueError("Encountered an error.")
return self.handler.make_url(endpoint) | [
"def",
"post_new_file",
"(",
"self",
",",
"build_id",
",",
"test_name",
",",
"lines",
")",
":",
"test_id",
"=",
"self",
".",
"new_test_id",
"(",
"build_id",
",",
"test_name",
",",
"\"foo\"",
")",
"endpoint",
"=",
"BUILD_LOGGER_APPEND_TEST_LOGS_ENDPOINT",
"%",
"{",
"\"build_id\"",
":",
"build_id",
",",
"\"test_id\"",
":",
"test_id",
",",
"}",
"dt",
"=",
"time",
".",
"time",
"(",
")",
"dlines",
"=",
"[",
"(",
"dt",
",",
"line",
")",
"for",
"line",
"in",
"lines",
"]",
"try",
":",
"self",
".",
"handler",
".",
"post",
"(",
"endpoint",
",",
"data",
"=",
"dlines",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"err",
":",
"# Handle the \"Request Entity Too Large\" error, set the max size and retry.",
"raise",
"ValueError",
"(",
"\"Encountered an HTTP error: %s\"",
"%",
"(",
"err",
")",
")",
"except",
"requests",
".",
"RequestException",
"as",
"err",
":",
"raise",
"ValueError",
"(",
"\"Encountered a network error: %s\"",
"%",
"(",
"err",
")",
")",
"except",
":",
"# pylint: disable=bare-except",
"raise",
"ValueError",
"(",
"\"Encountered an error.\"",
")",
"return",
"self",
".",
"handler",
".",
"make_url",
"(",
"endpoint",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/blackduck_hub.py#L229-L251 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/framework/python/ops/arg_scope.py | python | add_arg_scope | (func) | return func_with_args | Decorates a function with args so it can be used within an arg_scope.
Args:
func: function to decorate.
Returns:
A tuple with the decorated function func_with_args(). | Decorates a function with args so it can be used within an arg_scope. | [
"Decorates",
"a",
"function",
"with",
"args",
"so",
"it",
"can",
"be",
"used",
"within",
"an",
"arg_scope",
"."
] | def add_arg_scope(func):
"""Decorates a function with args so it can be used within an arg_scope.
Args:
func: function to decorate.
Returns:
A tuple with the decorated function func_with_args().
"""
@functools.wraps(func)
def func_with_args(*args, **kwargs):
current_scope = _current_arg_scope()
current_args = kwargs
key_func = _key_op(func)
if key_func in current_scope:
current_args = current_scope[key_func].copy()
current_args.update(kwargs)
return func(*args, **current_args)
_add_op(func)
setattr(func_with_args, '_key_op', _key_op(func))
setattr(func_with_args, '__doc__', func.__doc__)
return func_with_args | [
"def",
"add_arg_scope",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"func_with_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"current_scope",
"=",
"_current_arg_scope",
"(",
")",
"current_args",
"=",
"kwargs",
"key_func",
"=",
"_key_op",
"(",
"func",
")",
"if",
"key_func",
"in",
"current_scope",
":",
"current_args",
"=",
"current_scope",
"[",
"key_func",
"]",
".",
"copy",
"(",
")",
"current_args",
".",
"update",
"(",
"kwargs",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"current_args",
")",
"_add_op",
"(",
"func",
")",
"setattr",
"(",
"func_with_args",
",",
"'_key_op'",
",",
"_key_op",
"(",
"func",
")",
")",
"setattr",
"(",
"func_with_args",
",",
"'__doc__'",
",",
"func",
".",
"__doc__",
")",
"return",
"func_with_args"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/framework/python/ops/arg_scope.py#L160-L181 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/SCons.py | python | TargetBase.full_product_name | (self) | return name | Returns the full name of the product being built:
* Uses 'product_name' if it's set, else prefix + 'target_name'.
* Prepends 'product_dir' if set.
* Appends SCons suffix variables for the target type (or
product_extension). | Returns the full name of the product being built: | [
"Returns",
"the",
"full",
"name",
"of",
"the",
"product",
"being",
"built",
":"
] | def full_product_name(self):
"""
Returns the full name of the product being built:
* Uses 'product_name' if it's set, else prefix + 'target_name'.
* Prepends 'product_dir' if set.
* Appends SCons suffix variables for the target type (or
product_extension).
"""
suffix = self.target_suffix
product_extension = self.spec.get('product_extension')
if product_extension:
suffix = '.' + product_extension
prefix = self.spec.get('product_prefix', self.target_prefix)
name = self.spec['target_name']
name = prefix + self.spec.get('product_name', name) + suffix
product_dir = self.spec.get('product_dir')
if product_dir:
name = os.path.join(product_dir, name)
else:
name = os.path.join(self.out_dir, name)
return name | [
"def",
"full_product_name",
"(",
"self",
")",
":",
"suffix",
"=",
"self",
".",
"target_suffix",
"product_extension",
"=",
"self",
".",
"spec",
".",
"get",
"(",
"'product_extension'",
")",
"if",
"product_extension",
":",
"suffix",
"=",
"'.'",
"+",
"product_extension",
"prefix",
"=",
"self",
".",
"spec",
".",
"get",
"(",
"'product_prefix'",
",",
"self",
".",
"target_prefix",
")",
"name",
"=",
"self",
".",
"spec",
"[",
"'target_name'",
"]",
"name",
"=",
"prefix",
"+",
"self",
".",
"spec",
".",
"get",
"(",
"'product_name'",
",",
"name",
")",
"+",
"suffix",
"product_dir",
"=",
"self",
".",
"spec",
".",
"get",
"(",
"'product_dir'",
")",
"if",
"product_dir",
":",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"product_dir",
",",
"name",
")",
"else",
":",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"out_dir",
",",
"name",
")",
"return",
"name"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/SCons.py#L33-L54 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Conv.py | python | TimeConv.free_term | (self) | return Blob.Blob(self._internal.get_free_term()) | Gets the free term. The blob size is filter_count. | Gets the free term. The blob size is filter_count. | [
"Gets",
"the",
"free",
"term",
".",
"The",
"blob",
"size",
"is",
"filter_count",
"."
] | def free_term(self):
"""Gets the free term. The blob size is filter_count.
"""
return Blob.Blob(self._internal.get_free_term()) | [
"def",
"free_term",
"(",
"self",
")",
":",
"return",
"Blob",
".",
"Blob",
"(",
"self",
".",
"_internal",
".",
"get_free_term",
"(",
")",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Conv.py#L1184-L1187 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/aio/_base_server.py | python | ServicerContext.time_remaining | (self) | Describes the length of allowed time remaining for the RPC.
Returns:
A nonnegative float indicating the length of allowed time in seconds
remaining for the RPC to complete before it is considered to have
timed out, or None if no deadline was specified for the RPC. | Describes the length of allowed time remaining for the RPC. | [
"Describes",
"the",
"length",
"of",
"allowed",
"time",
"remaining",
"for",
"the",
"RPC",
"."
] | def time_remaining(self) -> float:
"""Describes the length of allowed time remaining for the RPC.
Returns:
A nonnegative float indicating the length of allowed time in seconds
remaining for the RPC to complete before it is considered to have
timed out, or None if no deadline was specified for the RPC.
""" | [
"def",
"time_remaining",
"(",
"self",
")",
"->",
"float",
":"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_base_server.py#L304-L311 | ||
astra-toolbox/astra-toolbox | 1e7ec8af702e595b76654f2e500f4c00344b273f | python/astra/data3d.py | python | clear | () | return d.clear() | Clear all 3D data objects. | Clear all 3D data objects. | [
"Clear",
"all",
"3D",
"data",
"objects",
"."
] | def clear():
"""Clear all 3D data objects."""
return d.clear() | [
"def",
"clear",
"(",
")",
":",
"return",
"d",
".",
"clear",
"(",
")"
] | https://github.com/astra-toolbox/astra-toolbox/blob/1e7ec8af702e595b76654f2e500f4c00344b273f/python/astra/data3d.py#L145-L147 | |
ros-perception/image_pipeline | cd4aa7ab38726d88e8e0144aa0d45ad2f236535a | camera_calibration/src/camera_calibration/calibrator.py | python | MonoCalibrator.cal_fromcorners | (self, good) | :param good: Good corner positions and boards
:type good: [(corners, ChessboardInfo)] | :param good: Good corner positions and boards
:type good: [(corners, ChessboardInfo)] | [
":",
"param",
"good",
":",
"Good",
"corner",
"positions",
"and",
"boards",
":",
"type",
"good",
":",
"[",
"(",
"corners",
"ChessboardInfo",
")",
"]"
] | def cal_fromcorners(self, good):
"""
:param good: Good corner positions and boards
:type good: [(corners, ChessboardInfo)]
"""
(ipts, ids, boards) = zip(*good)
opts = self.mk_object_points(boards)
# If FIX_ASPECT_RATIO flag set, enforce focal lengths have 1/1 ratio
intrinsics_in = numpy.eye(3, dtype=numpy.float64)
if self.pattern == Patterns.ChArUco:
if self.camera_model == CAMERA_MODEL.FISHEYE:
raise NotImplemented("Can't perform fisheye calibration with ChArUco board")
reproj_err, self.intrinsics, self.distortion, rvecs, tvecs = cv2.aruco.calibrateCameraCharuco(
ipts, ids, boards[0].charuco_board, self.size, intrinsics_in, None)
elif self.camera_model == CAMERA_MODEL.PINHOLE:
print("mono pinhole calibration...")
reproj_err, self.intrinsics, dist_coeffs, rvecs, tvecs = cv2.calibrateCamera(
opts, ipts,
self.size,
intrinsics_in,
None,
flags = self.calib_flags)
# OpenCV returns more than 8 coefficients (the additional ones all zeros) when CALIB_RATIONAL_MODEL is set.
# The extra ones include e.g. thin prism coefficients, which we are not interested in.
self.distortion = dist_coeffs.flat[:8].reshape(-1, 1)
elif self.camera_model == CAMERA_MODEL.FISHEYE:
print("mono fisheye calibration...")
# WARNING: cv2.fisheye.calibrate wants float64 points
ipts64 = numpy.asarray(ipts, dtype=numpy.float64)
ipts = ipts64
opts64 = numpy.asarray(opts, dtype=numpy.float64)
opts = opts64
reproj_err, self.intrinsics, self.distortion, rvecs, tvecs = cv2.fisheye.calibrate(
opts, ipts, self.size,
intrinsics_in, None, flags = self.fisheye_calib_flags)
# R is identity matrix for monocular calibration
self.R = numpy.eye(3, dtype=numpy.float64)
self.P = numpy.zeros((3, 4), dtype=numpy.float64)
self.set_alpha(0.0) | [
"def",
"cal_fromcorners",
"(",
"self",
",",
"good",
")",
":",
"(",
"ipts",
",",
"ids",
",",
"boards",
")",
"=",
"zip",
"(",
"*",
"good",
")",
"opts",
"=",
"self",
".",
"mk_object_points",
"(",
"boards",
")",
"# If FIX_ASPECT_RATIO flag set, enforce focal lengths have 1/1 ratio",
"intrinsics_in",
"=",
"numpy",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"if",
"self",
".",
"pattern",
"==",
"Patterns",
".",
"ChArUco",
":",
"if",
"self",
".",
"camera_model",
"==",
"CAMERA_MODEL",
".",
"FISHEYE",
":",
"raise",
"NotImplemented",
"(",
"\"Can't perform fisheye calibration with ChArUco board\"",
")",
"reproj_err",
",",
"self",
".",
"intrinsics",
",",
"self",
".",
"distortion",
",",
"rvecs",
",",
"tvecs",
"=",
"cv2",
".",
"aruco",
".",
"calibrateCameraCharuco",
"(",
"ipts",
",",
"ids",
",",
"boards",
"[",
"0",
"]",
".",
"charuco_board",
",",
"self",
".",
"size",
",",
"intrinsics_in",
",",
"None",
")",
"elif",
"self",
".",
"camera_model",
"==",
"CAMERA_MODEL",
".",
"PINHOLE",
":",
"print",
"(",
"\"mono pinhole calibration...\"",
")",
"reproj_err",
",",
"self",
".",
"intrinsics",
",",
"dist_coeffs",
",",
"rvecs",
",",
"tvecs",
"=",
"cv2",
".",
"calibrateCamera",
"(",
"opts",
",",
"ipts",
",",
"self",
".",
"size",
",",
"intrinsics_in",
",",
"None",
",",
"flags",
"=",
"self",
".",
"calib_flags",
")",
"# OpenCV returns more than 8 coefficients (the additional ones all zeros) when CALIB_RATIONAL_MODEL is set.",
"# The extra ones include e.g. thin prism coefficients, which we are not interested in.",
"self",
".",
"distortion",
"=",
"dist_coeffs",
".",
"flat",
"[",
":",
"8",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"elif",
"self",
".",
"camera_model",
"==",
"CAMERA_MODEL",
".",
"FISHEYE",
":",
"print",
"(",
"\"mono fisheye calibration...\"",
")",
"# WARNING: cv2.fisheye.calibrate wants float64 points",
"ipts64",
"=",
"numpy",
".",
"asarray",
"(",
"ipts",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"ipts",
"=",
"ipts64",
"opts64",
"=",
"numpy",
".",
"asarray",
"(",
"opts",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"opts",
"=",
"opts64",
"reproj_err",
",",
"self",
".",
"intrinsics",
",",
"self",
".",
"distortion",
",",
"rvecs",
",",
"tvecs",
"=",
"cv2",
".",
"fisheye",
".",
"calibrate",
"(",
"opts",
",",
"ipts",
",",
"self",
".",
"size",
",",
"intrinsics_in",
",",
"None",
",",
"flags",
"=",
"self",
".",
"fisheye_calib_flags",
")",
"# R is identity matrix for monocular calibration",
"self",
".",
"R",
"=",
"numpy",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"self",
".",
"P",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"3",
",",
"4",
")",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"self",
".",
"set_alpha",
"(",
"0.0",
")"
] | https://github.com/ros-perception/image_pipeline/blob/cd4aa7ab38726d88e8e0144aa0d45ad2f236535a/camera_calibration/src/camera_calibration/calibrator.py#L752-L798 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/externals/funcsigs.py | python | Signature.from_function | (cls, func) | return cls(parameters,
return_annotation=annotations.get('return', _empty),
__validate_parameters__=False) | Constructs Signature for the given python function | Constructs Signature for the given python function | [
"Constructs",
"Signature",
"for",
"the",
"given",
"python",
"function"
] | def from_function(cls, func):
'''Constructs Signature for the given python function'''
if not isinstance(func, types.FunctionType):
raise TypeError('{0!r} is not a Python function'.format(func))
Parameter = cls._parameter_cls
# Parameter information.
func_code = func.__code__
pos_count = func_code.co_argcount
arg_names = func_code.co_varnames
positional = tuple(arg_names[:pos_count])
keyword_only_count = getattr(func_code, 'co_kwonlyargcount', 0)
keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
annotations = getattr(func, '__annotations__', {})
defaults = func.__defaults__
kwdefaults = getattr(func, '__kwdefaults__', None)
if defaults:
pos_default_count = len(defaults)
else:
pos_default_count = 0
parameters = []
# Non-keyword-only parameters w/o defaults.
non_default_count = pos_count - pos_default_count
for name in positional[:non_default_count]:
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD))
# ... w/ defaults.
for offset, name in enumerate(positional[non_default_count:]):
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD,
default=defaults[offset]))
# *args
if func_code.co_flags & 0x04:
name = arg_names[pos_count + keyword_only_count]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_POSITIONAL))
# Keyword-only parameters.
for name in keyword_only:
default = _empty
if kwdefaults is not None:
default = kwdefaults.get(name, _empty)
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_KEYWORD_ONLY,
default=default))
# **kwargs
if func_code.co_flags & 0x08:
index = pos_count + keyword_only_count
if func_code.co_flags & 0x04:
index += 1
name = arg_names[index]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_KEYWORD))
return cls(parameters,
return_annotation=annotations.get('return', _empty),
__validate_parameters__=False) | [
"def",
"from_function",
"(",
"cls",
",",
"func",
")",
":",
"if",
"not",
"isinstance",
"(",
"func",
",",
"types",
".",
"FunctionType",
")",
":",
"raise",
"TypeError",
"(",
"'{0!r} is not a Python function'",
".",
"format",
"(",
"func",
")",
")",
"Parameter",
"=",
"cls",
".",
"_parameter_cls",
"# Parameter information.",
"func_code",
"=",
"func",
".",
"__code__",
"pos_count",
"=",
"func_code",
".",
"co_argcount",
"arg_names",
"=",
"func_code",
".",
"co_varnames",
"positional",
"=",
"tuple",
"(",
"arg_names",
"[",
":",
"pos_count",
"]",
")",
"keyword_only_count",
"=",
"getattr",
"(",
"func_code",
",",
"'co_kwonlyargcount'",
",",
"0",
")",
"keyword_only",
"=",
"arg_names",
"[",
"pos_count",
":",
"(",
"pos_count",
"+",
"keyword_only_count",
")",
"]",
"annotations",
"=",
"getattr",
"(",
"func",
",",
"'__annotations__'",
",",
"{",
"}",
")",
"defaults",
"=",
"func",
".",
"__defaults__",
"kwdefaults",
"=",
"getattr",
"(",
"func",
",",
"'__kwdefaults__'",
",",
"None",
")",
"if",
"defaults",
":",
"pos_default_count",
"=",
"len",
"(",
"defaults",
")",
"else",
":",
"pos_default_count",
"=",
"0",
"parameters",
"=",
"[",
"]",
"# Non-keyword-only parameters w/o defaults.",
"non_default_count",
"=",
"pos_count",
"-",
"pos_default_count",
"for",
"name",
"in",
"positional",
"[",
":",
"non_default_count",
"]",
":",
"annotation",
"=",
"annotations",
".",
"get",
"(",
"name",
",",
"_empty",
")",
"parameters",
".",
"append",
"(",
"Parameter",
"(",
"name",
",",
"annotation",
"=",
"annotation",
",",
"kind",
"=",
"_POSITIONAL_OR_KEYWORD",
")",
")",
"# ... w/ defaults.",
"for",
"offset",
",",
"name",
"in",
"enumerate",
"(",
"positional",
"[",
"non_default_count",
":",
"]",
")",
":",
"annotation",
"=",
"annotations",
".",
"get",
"(",
"name",
",",
"_empty",
")",
"parameters",
".",
"append",
"(",
"Parameter",
"(",
"name",
",",
"annotation",
"=",
"annotation",
",",
"kind",
"=",
"_POSITIONAL_OR_KEYWORD",
",",
"default",
"=",
"defaults",
"[",
"offset",
"]",
")",
")",
"# *args",
"if",
"func_code",
".",
"co_flags",
"&",
"0x04",
":",
"name",
"=",
"arg_names",
"[",
"pos_count",
"+",
"keyword_only_count",
"]",
"annotation",
"=",
"annotations",
".",
"get",
"(",
"name",
",",
"_empty",
")",
"parameters",
".",
"append",
"(",
"Parameter",
"(",
"name",
",",
"annotation",
"=",
"annotation",
",",
"kind",
"=",
"_VAR_POSITIONAL",
")",
")",
"# Keyword-only parameters.",
"for",
"name",
"in",
"keyword_only",
":",
"default",
"=",
"_empty",
"if",
"kwdefaults",
"is",
"not",
"None",
":",
"default",
"=",
"kwdefaults",
".",
"get",
"(",
"name",
",",
"_empty",
")",
"annotation",
"=",
"annotations",
".",
"get",
"(",
"name",
",",
"_empty",
")",
"parameters",
".",
"append",
"(",
"Parameter",
"(",
"name",
",",
"annotation",
"=",
"annotation",
",",
"kind",
"=",
"_KEYWORD_ONLY",
",",
"default",
"=",
"default",
")",
")",
"# **kwargs",
"if",
"func_code",
".",
"co_flags",
"&",
"0x08",
":",
"index",
"=",
"pos_count",
"+",
"keyword_only_count",
"if",
"func_code",
".",
"co_flags",
"&",
"0x04",
":",
"index",
"+=",
"1",
"name",
"=",
"arg_names",
"[",
"index",
"]",
"annotation",
"=",
"annotations",
".",
"get",
"(",
"name",
",",
"_empty",
")",
"parameters",
".",
"append",
"(",
"Parameter",
"(",
"name",
",",
"annotation",
"=",
"annotation",
",",
"kind",
"=",
"_VAR_KEYWORD",
")",
")",
"return",
"cls",
"(",
"parameters",
",",
"return_annotation",
"=",
"annotations",
".",
"get",
"(",
"'return'",
",",
"_empty",
")",
",",
"__validate_parameters__",
"=",
"False",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/funcsigs.py#L513-L583 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | Distribution.activate | (self, path=None, replace=False) | Ensure distribution is importable on `path` (default=sys.path) | Ensure distribution is importable on `path` (default=sys.path) | [
"Ensure",
"distribution",
"is",
"importable",
"on",
"path",
"(",
"default",
"=",
"sys",
".",
"path",
")"
] | def activate(self, path=None, replace=False):
"""Ensure distribution is importable on `path` (default=sys.path)"""
if path is None:
path = sys.path
self.insert_on(path, replace=replace)
if path is sys.path:
fixup_namespace_packages(self.location)
for pkg in self._get_metadata('namespace_packages.txt'):
if pkg in sys.modules:
declare_namespace(pkg) | [
"def",
"activate",
"(",
"self",
",",
"path",
"=",
"None",
",",
"replace",
"=",
"False",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"sys",
".",
"path",
"self",
".",
"insert_on",
"(",
"path",
",",
"replace",
"=",
"replace",
")",
"if",
"path",
"is",
"sys",
".",
"path",
":",
"fixup_namespace_packages",
"(",
"self",
".",
"location",
")",
"for",
"pkg",
"in",
"self",
".",
"_get_metadata",
"(",
"'namespace_packages.txt'",
")",
":",
"if",
"pkg",
"in",
"sys",
".",
"modules",
":",
"declare_namespace",
"(",
"pkg",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L2692-L2701 | ||
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | platforms/nuttx/NuttX/tools/kconfiglib.py | python | Kconfig.disable_warnings | (self) | See Kconfig.__init__(). | See Kconfig.__init__(). | [
"See",
"Kconfig",
".",
"__init__",
"()",
"."
] | def disable_warnings(self):
"""
See Kconfig.__init__().
"""
self._warnings_enabled = False | [
"def",
"disable_warnings",
"(",
"self",
")",
":",
"self",
".",
"_warnings_enabled",
"=",
"False"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/platforms/nuttx/NuttX/tools/kconfiglib.py#L1717-L1721 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Image.type | (self) | return self.tk.call('image', 'type', self.name) | Return the type of the image, e.g. "photo" or "bitmap". | Return the type of the image, e.g. "photo" or "bitmap". | [
"Return",
"the",
"type",
"of",
"the",
"image",
"e",
".",
"g",
".",
"photo",
"or",
"bitmap",
"."
] | def type(self):
"""Return the type of the image, e.g. "photo" or "bitmap"."""
return self.tk.call('image', 'type', self.name) | [
"def",
"type",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'image'",
",",
"'type'",
",",
"self",
".",
"name",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L3362-L3364 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Context.py | python | load_tool | (tool, tooldir=None) | Import a Waf tool (python module), and store it in the dict :py:const:`waflib.Context.Context.tools`
:type tool: string
:param tool: Name of the tool
:type tooldir: list
:param tooldir: List of directories to search for the tool module | Import a Waf tool (python module), and store it in the dict :py:const:`waflib.Context.Context.tools` | [
"Import",
"a",
"Waf",
"tool",
"(",
"python",
"module",
")",
"and",
"store",
"it",
"in",
"the",
"dict",
":",
"py",
":",
"const",
":",
"waflib",
".",
"Context",
".",
"Context",
".",
"tools"
] | def load_tool(tool, tooldir=None):
"""
Import a Waf tool (python module), and store it in the dict :py:const:`waflib.Context.Context.tools`
:type tool: string
:param tool: Name of the tool
:type tooldir: list
:param tooldir: List of directories to search for the tool module
"""
if tool == 'java':
tool = 'javaw' # jython
elif tool == 'compiler_cc':
tool = 'compiler_c' # TODO remove in waf 1.8
else:
tool = tool.replace('++', 'xx')
if tooldir:
assert isinstance(tooldir, list)
sys.path = tooldir + sys.path
try:
__import__(tool)
ret = sys.modules[tool]
Context.tools[tool] = ret
return ret
finally:
for d in tooldir:
sys.path.remove(d)
else:
global waf_dir
try:
os.stat(os.path.join(waf_dir, 'waflib', 'extras', tool + '.py'))
except OSError:
try:
os.stat(os.path.join(waf_dir, 'waflib', 'Tools', tool + '.py'))
except OSError:
d = tool # user has messed with sys.path
else:
d = 'waflib.Tools.%s' % tool
else:
d = 'waflib.extras.%s' % tool
__import__(d)
ret = sys.modules[d]
Context.tools[tool] = ret
return ret | [
"def",
"load_tool",
"(",
"tool",
",",
"tooldir",
"=",
"None",
")",
":",
"if",
"tool",
"==",
"'java'",
":",
"tool",
"=",
"'javaw'",
"# jython",
"elif",
"tool",
"==",
"'compiler_cc'",
":",
"tool",
"=",
"'compiler_c'",
"# TODO remove in waf 1.8",
"else",
":",
"tool",
"=",
"tool",
".",
"replace",
"(",
"'++'",
",",
"'xx'",
")",
"if",
"tooldir",
":",
"assert",
"isinstance",
"(",
"tooldir",
",",
"list",
")",
"sys",
".",
"path",
"=",
"tooldir",
"+",
"sys",
".",
"path",
"try",
":",
"__import__",
"(",
"tool",
")",
"ret",
"=",
"sys",
".",
"modules",
"[",
"tool",
"]",
"Context",
".",
"tools",
"[",
"tool",
"]",
"=",
"ret",
"return",
"ret",
"finally",
":",
"for",
"d",
"in",
"tooldir",
":",
"sys",
".",
"path",
".",
"remove",
"(",
"d",
")",
"else",
":",
"global",
"waf_dir",
"try",
":",
"os",
".",
"stat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"waf_dir",
",",
"'waflib'",
",",
"'extras'",
",",
"tool",
"+",
"'.py'",
")",
")",
"except",
"OSError",
":",
"try",
":",
"os",
".",
"stat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"waf_dir",
",",
"'waflib'",
",",
"'Tools'",
",",
"tool",
"+",
"'.py'",
")",
")",
"except",
"OSError",
":",
"d",
"=",
"tool",
"# user has messed with sys.path",
"else",
":",
"d",
"=",
"'waflib.Tools.%s'",
"%",
"tool",
"else",
":",
"d",
"=",
"'waflib.extras.%s'",
"%",
"tool",
"__import__",
"(",
"d",
")",
"ret",
"=",
"sys",
".",
"modules",
"[",
"d",
"]",
"Context",
".",
"tools",
"[",
"tool",
"]",
"=",
"ret",
"return",
"ret"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Context.py#L635-L679 | ||
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/pycocotools/coco.py | python | COCO.download | ( self, tarDir = None, imgIds = [] ) | Download COCO images from mscoco.org server.
:param tarDir (str): COCO results directory name
imgIds (list): images to be downloaded
:return: | Download COCO images from mscoco.org server.
:param tarDir (str): COCO results directory name
imgIds (list): images to be downloaded
:return: | [
"Download",
"COCO",
"images",
"from",
"mscoco",
".",
"org",
"server",
".",
":",
"param",
"tarDir",
"(",
"str",
")",
":",
"COCO",
"results",
"directory",
"name",
"imgIds",
"(",
"list",
")",
":",
"images",
"to",
"be",
"downloaded",
":",
"return",
":"
] | def download( self, tarDir = None, imgIds = [] ):
'''
Download COCO images from mscoco.org server.
:param tarDir (str): COCO results directory name
imgIds (list): images to be downloaded
:return:
'''
if tarDir is None:
print 'Please specify target directory'
return -1
if len(imgIds) == 0:
imgs = self.imgs.values()
else:
imgs = self.loadImgs(imgIds)
N = len(imgs)
if not os.path.exists(tarDir):
os.makedirs(tarDir)
for i, img in enumerate(imgs):
tic = time.time()
fname = os.path.join(tarDir, img['file_name'])
if not os.path.exists(fname):
urllib.urlretrieve(img['coco_url'], fname)
print 'downloaded %d/%d images (t=%.1fs)'%(i, N, time.time()- tic) | [
"def",
"download",
"(",
"self",
",",
"tarDir",
"=",
"None",
",",
"imgIds",
"=",
"[",
"]",
")",
":",
"if",
"tarDir",
"is",
"None",
":",
"print",
"'Please specify target directory'",
"return",
"-",
"1",
"if",
"len",
"(",
"imgIds",
")",
"==",
"0",
":",
"imgs",
"=",
"self",
".",
"imgs",
".",
"values",
"(",
")",
"else",
":",
"imgs",
"=",
"self",
".",
"loadImgs",
"(",
"imgIds",
")",
"N",
"=",
"len",
"(",
"imgs",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tarDir",
")",
":",
"os",
".",
"makedirs",
"(",
"tarDir",
")",
"for",
"i",
",",
"img",
"in",
"enumerate",
"(",
"imgs",
")",
":",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tarDir",
",",
"img",
"[",
"'file_name'",
"]",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"urllib",
".",
"urlretrieve",
"(",
"img",
"[",
"'coco_url'",
"]",
",",
"fname",
")",
"print",
"'downloaded %d/%d images (t=%.1fs)'",
"%",
"(",
"i",
",",
"N",
",",
"time",
".",
"time",
"(",
")",
"-",
"tic",
")"
] | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/pycocotools/coco.py#L329-L351 | ||
9miao/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | tools/bindings-generator/clang/cindex.py | python | Type.is_pod | (self) | return conf.lib.clang_isPODType(self) | Determine whether this Type represents plain old data (POD). | Determine whether this Type represents plain old data (POD). | [
"Determine",
"whether",
"this",
"Type",
"represents",
"plain",
"old",
"data",
"(",
"POD",
")",
"."
] | def is_pod(self):
"""Determine whether this Type represents plain old data (POD)."""
return conf.lib.clang_isPODType(self) | [
"def",
"is_pod",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isPODType",
"(",
"self",
")"
] | https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/clang/cindex.py#L1770-L1772 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenuBar.ClearBitmaps | (self, start=0) | Restores a :class:`NullBitmap` for all the items in the menu.
:param integer `start`: the index at which to start resetting the bitmaps. | Restores a :class:`NullBitmap` for all the items in the menu. | [
"Restores",
"a",
":",
"class",
":",
"NullBitmap",
"for",
"all",
"the",
"items",
"in",
"the",
"menu",
"."
] | def ClearBitmaps(self, start=0):
"""
Restores a :class:`NullBitmap` for all the items in the menu.
:param integer `start`: the index at which to start resetting the bitmaps.
"""
if self._isLCD:
return
for item in self._items[start:]:
item.SetTextBitmap(wx.NullBitmap)
item.SetSelectedTextBitmap(wx.NullBitmap) | [
"def",
"ClearBitmaps",
"(",
"self",
",",
"start",
"=",
"0",
")",
":",
"if",
"self",
".",
"_isLCD",
":",
"return",
"for",
"item",
"in",
"self",
".",
"_items",
"[",
"start",
":",
"]",
":",
"item",
".",
"SetTextBitmap",
"(",
"wx",
".",
"NullBitmap",
")",
"item",
".",
"SetSelectedTextBitmap",
"(",
"wx",
".",
"NullBitmap",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L3472-L3484 | ||
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | dev/archery/archery/utils/source.py | python | ArrowSources.cpp | (self) | return self.path / "cpp" | Returns the cpp directory of an Arrow sources. | Returns the cpp directory of an Arrow sources. | [
"Returns",
"the",
"cpp",
"directory",
"of",
"an",
"Arrow",
"sources",
"."
] | def cpp(self):
""" Returns the cpp directory of an Arrow sources. """
return self.path / "cpp" | [
"def",
"cpp",
"(",
"self",
")",
":",
"return",
"self",
".",
"path",
"/",
"\"cpp\""
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/utils/source.py#L62-L64 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | GraphicsRenderer.CreateContextFromImage | (*args, **kwargs) | return _gdi_.GraphicsRenderer_CreateContextFromImage(*args, **kwargs) | CreateContextFromImage(self, Image image) -> GraphicsContext | CreateContextFromImage(self, Image image) -> GraphicsContext | [
"CreateContextFromImage",
"(",
"self",
"Image",
"image",
")",
"-",
">",
"GraphicsContext"
] | def CreateContextFromImage(*args, **kwargs):
"""CreateContextFromImage(self, Image image) -> GraphicsContext"""
return _gdi_.GraphicsRenderer_CreateContextFromImage(*args, **kwargs) | [
"def",
"CreateContextFromImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsRenderer_CreateContextFromImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L6573-L6575 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/polyutils.py | python | _fit | (vander_f, x, y, deg, rcond=None, full=False, w=None) | Helper function used to implement the ``<type>fit`` functions.
Parameters
----------
vander_f : function(array_like, int) -> ndarray
The 1d vander function, such as ``polyvander``
c1, c2
See the ``<type>fit`` functions for more detail | Helper function used to implement the ``<type>fit`` functions. | [
"Helper",
"function",
"used",
"to",
"implement",
"the",
"<type",
">",
"fit",
"functions",
"."
] | def _fit(vander_f, x, y, deg, rcond=None, full=False, w=None):
"""
Helper function used to implement the ``<type>fit`` functions.
Parameters
----------
vander_f : function(array_like, int) -> ndarray
The 1d vander function, such as ``polyvander``
c1, c2
See the ``<type>fit`` functions for more detail
"""
x = np.asarray(x) + 0.0
y = np.asarray(y) + 0.0
deg = np.asarray(deg)
# check arguments.
if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0:
raise TypeError("deg must be an int or non-empty 1-D array of int")
if deg.min() < 0:
raise ValueError("expected deg >= 0")
if x.ndim != 1:
raise TypeError("expected 1D vector for x")
if x.size == 0:
raise TypeError("expected non-empty vector for x")
if y.ndim < 1 or y.ndim > 2:
raise TypeError("expected 1D or 2D array for y")
if len(x) != len(y):
raise TypeError("expected x and y to have same length")
if deg.ndim == 0:
lmax = deg
order = lmax + 1
van = vander_f(x, lmax)
else:
deg = np.sort(deg)
lmax = deg[-1]
order = len(deg)
van = vander_f(x, lmax)[:, deg]
# set up the least squares matrices in transposed form
lhs = van.T
rhs = y.T
if w is not None:
w = np.asarray(w) + 0.0
if w.ndim != 1:
raise TypeError("expected 1D vector for w")
if len(x) != len(w):
raise TypeError("expected x and w to have same length")
# apply weights. Don't use inplace operations as they
# can cause problems with NA.
lhs = lhs * w
rhs = rhs * w
# set rcond
if rcond is None:
rcond = len(x)*np.finfo(x.dtype).eps
# Determine the norms of the design matrix columns.
if issubclass(lhs.dtype.type, np.complexfloating):
scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
else:
scl = np.sqrt(np.square(lhs).sum(1))
scl[scl == 0] = 1
# Solve the least squares problem.
c, resids, rank, s = np.linalg.lstsq(lhs.T/scl, rhs.T, rcond)
c = (c.T/scl).T
# Expand c to include non-fitted coefficients which are set to zero
if deg.ndim > 0:
if c.ndim == 2:
cc = np.zeros((lmax+1, c.shape[1]), dtype=c.dtype)
else:
cc = np.zeros(lmax+1, dtype=c.dtype)
cc[deg] = c
c = cc
# warn on rank reduction
if rank != order and not full:
msg = "The fit may be poorly conditioned"
warnings.warn(msg, RankWarning, stacklevel=2)
if full:
return c, [resids, rank, s, rcond]
else:
return c | [
"def",
"_fit",
"(",
"vander_f",
",",
"x",
",",
"y",
",",
"deg",
",",
"rcond",
"=",
"None",
",",
"full",
"=",
"False",
",",
"w",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"+",
"0.0",
"y",
"=",
"np",
".",
"asarray",
"(",
"y",
")",
"+",
"0.0",
"deg",
"=",
"np",
".",
"asarray",
"(",
"deg",
")",
"# check arguments.",
"if",
"deg",
".",
"ndim",
">",
"1",
"or",
"deg",
".",
"dtype",
".",
"kind",
"not",
"in",
"'iu'",
"or",
"deg",
".",
"size",
"==",
"0",
":",
"raise",
"TypeError",
"(",
"\"deg must be an int or non-empty 1-D array of int\"",
")",
"if",
"deg",
".",
"min",
"(",
")",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"expected deg >= 0\"",
")",
"if",
"x",
".",
"ndim",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"\"expected 1D vector for x\"",
")",
"if",
"x",
".",
"size",
"==",
"0",
":",
"raise",
"TypeError",
"(",
"\"expected non-empty vector for x\"",
")",
"if",
"y",
".",
"ndim",
"<",
"1",
"or",
"y",
".",
"ndim",
">",
"2",
":",
"raise",
"TypeError",
"(",
"\"expected 1D or 2D array for y\"",
")",
"if",
"len",
"(",
"x",
")",
"!=",
"len",
"(",
"y",
")",
":",
"raise",
"TypeError",
"(",
"\"expected x and y to have same length\"",
")",
"if",
"deg",
".",
"ndim",
"==",
"0",
":",
"lmax",
"=",
"deg",
"order",
"=",
"lmax",
"+",
"1",
"van",
"=",
"vander_f",
"(",
"x",
",",
"lmax",
")",
"else",
":",
"deg",
"=",
"np",
".",
"sort",
"(",
"deg",
")",
"lmax",
"=",
"deg",
"[",
"-",
"1",
"]",
"order",
"=",
"len",
"(",
"deg",
")",
"van",
"=",
"vander_f",
"(",
"x",
",",
"lmax",
")",
"[",
":",
",",
"deg",
"]",
"# set up the least squares matrices in transposed form",
"lhs",
"=",
"van",
".",
"T",
"rhs",
"=",
"y",
".",
"T",
"if",
"w",
"is",
"not",
"None",
":",
"w",
"=",
"np",
".",
"asarray",
"(",
"w",
")",
"+",
"0.0",
"if",
"w",
".",
"ndim",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"\"expected 1D vector for w\"",
")",
"if",
"len",
"(",
"x",
")",
"!=",
"len",
"(",
"w",
")",
":",
"raise",
"TypeError",
"(",
"\"expected x and w to have same length\"",
")",
"# apply weights. Don't use inplace operations as they",
"# can cause problems with NA.",
"lhs",
"=",
"lhs",
"*",
"w",
"rhs",
"=",
"rhs",
"*",
"w",
"# set rcond",
"if",
"rcond",
"is",
"None",
":",
"rcond",
"=",
"len",
"(",
"x",
")",
"*",
"np",
".",
"finfo",
"(",
"x",
".",
"dtype",
")",
".",
"eps",
"# Determine the norms of the design matrix columns.",
"if",
"issubclass",
"(",
"lhs",
".",
"dtype",
".",
"type",
",",
"np",
".",
"complexfloating",
")",
":",
"scl",
"=",
"np",
".",
"sqrt",
"(",
"(",
"np",
".",
"square",
"(",
"lhs",
".",
"real",
")",
"+",
"np",
".",
"square",
"(",
"lhs",
".",
"imag",
")",
")",
".",
"sum",
"(",
"1",
")",
")",
"else",
":",
"scl",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"square",
"(",
"lhs",
")",
".",
"sum",
"(",
"1",
")",
")",
"scl",
"[",
"scl",
"==",
"0",
"]",
"=",
"1",
"# Solve the least squares problem.",
"c",
",",
"resids",
",",
"rank",
",",
"s",
"=",
"np",
".",
"linalg",
".",
"lstsq",
"(",
"lhs",
".",
"T",
"/",
"scl",
",",
"rhs",
".",
"T",
",",
"rcond",
")",
"c",
"=",
"(",
"c",
".",
"T",
"/",
"scl",
")",
".",
"T",
"# Expand c to include non-fitted coefficients which are set to zero",
"if",
"deg",
".",
"ndim",
">",
"0",
":",
"if",
"c",
".",
"ndim",
"==",
"2",
":",
"cc",
"=",
"np",
".",
"zeros",
"(",
"(",
"lmax",
"+",
"1",
",",
"c",
".",
"shape",
"[",
"1",
"]",
")",
",",
"dtype",
"=",
"c",
".",
"dtype",
")",
"else",
":",
"cc",
"=",
"np",
".",
"zeros",
"(",
"lmax",
"+",
"1",
",",
"dtype",
"=",
"c",
".",
"dtype",
")",
"cc",
"[",
"deg",
"]",
"=",
"c",
"c",
"=",
"cc",
"# warn on rank reduction",
"if",
"rank",
"!=",
"order",
"and",
"not",
"full",
":",
"msg",
"=",
"\"The fit may be poorly conditioned\"",
"warnings",
".",
"warn",
"(",
"msg",
",",
"RankWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"full",
":",
"return",
"c",
",",
"[",
"resids",
",",
"rank",
",",
"s",
",",
"rcond",
"]",
"else",
":",
"return",
"c"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/polyutils.py#L595-L680 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py | python | fill_parallel_impl | (return_type, arr, val) | return fill_1 | Parallel implemention of ndarray.fill. The array on
which to operate is retrieved from get_call_name and
is passed along with the value to fill. | Parallel implemention of ndarray.fill. The array on
which to operate is retrieved from get_call_name and
is passed along with the value to fill. | [
"Parallel",
"implemention",
"of",
"ndarray",
".",
"fill",
".",
"The",
"array",
"on",
"which",
"to",
"operate",
"is",
"retrieved",
"from",
"get_call_name",
"and",
"is",
"passed",
"along",
"with",
"the",
"value",
"to",
"fill",
"."
] | def fill_parallel_impl(return_type, arr, val):
"""Parallel implemention of ndarray.fill. The array on
which to operate is retrieved from get_call_name and
is passed along with the value to fill.
"""
if arr.ndim == 1:
def fill_1(in_arr, val):
numba.parfor.init_prange()
for i in numba.parfor.internal_prange(len(in_arr)):
in_arr[i] = val
return None
else:
def fill_1(in_arr, val):
numba.parfor.init_prange()
for i in numba.pndindex(in_arr.shape):
in_arr[i] = val
return None
return fill_1 | [
"def",
"fill_parallel_impl",
"(",
"return_type",
",",
"arr",
",",
"val",
")",
":",
"if",
"arr",
".",
"ndim",
"==",
"1",
":",
"def",
"fill_1",
"(",
"in_arr",
",",
"val",
")",
":",
"numba",
".",
"parfor",
".",
"init_prange",
"(",
")",
"for",
"i",
"in",
"numba",
".",
"parfor",
".",
"internal_prange",
"(",
"len",
"(",
"in_arr",
")",
")",
":",
"in_arr",
"[",
"i",
"]",
"=",
"val",
"return",
"None",
"else",
":",
"def",
"fill_1",
"(",
"in_arr",
",",
"val",
")",
":",
"numba",
".",
"parfor",
".",
"init_prange",
"(",
")",
"for",
"i",
"in",
"numba",
".",
"pndindex",
"(",
"in_arr",
".",
"shape",
")",
":",
"in_arr",
"[",
"i",
"]",
"=",
"val",
"return",
"None",
"return",
"fill_1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py#L430-L447 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py | python | require_device_memory | (obj) | A sentry for methods that accept CUDA memory object. | A sentry for methods that accept CUDA memory object. | [
"A",
"sentry",
"for",
"methods",
"that",
"accept",
"CUDA",
"memory",
"object",
"."
] | def require_device_memory(obj):
"""A sentry for methods that accept CUDA memory object.
"""
if not is_device_memory(obj):
raise Exception("Not a CUDA memory object.") | [
"def",
"require_device_memory",
"(",
"obj",
")",
":",
"if",
"not",
"is_device_memory",
"(",
"obj",
")",
":",
"raise",
"Exception",
"(",
"\"Not a CUDA memory object.\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py#L1868-L1872 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | utils/cpplint.py | python | FilesBelongToSameModule | (filename_cc, filename_h) | return files_belong_to_same_module, common_path | Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file. | Check if these two filenames belong to the same module. | [
"Check",
"if",
"these",
"two",
"filenames",
"belong",
"to",
"the",
"same",
"module",
"."
] | def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file.
"""
if not filename_cc.endswith('.cc'):
return (False, '')
filename_cc = filename_cc[:-len('.cc')]
if filename_cc.endswith('_unittest'):
filename_cc = filename_cc[:-len('_unittest')]
elif filename_cc.endswith('_test'):
filename_cc = filename_cc[:-len('_test')]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
if not filename_h.endswith('.h'):
return (False, '')
filename_h = filename_h[:-len('.h')]
if filename_h.endswith('-inl'):
filename_h = filename_h[:-len('-inl')]
filename_h = filename_h.replace('/public/', '/')
filename_h = filename_h.replace('/internal/', '/')
files_belong_to_same_module = filename_cc.endswith(filename_h)
common_path = ''
if files_belong_to_same_module:
common_path = filename_cc[:-len(filename_h)]
return files_belong_to_same_module, common_path | [
"def",
"FilesBelongToSameModule",
"(",
"filename_cc",
",",
"filename_h",
")",
":",
"if",
"not",
"filename_cc",
".",
"endswith",
"(",
"'.cc'",
")",
":",
"return",
"(",
"False",
",",
"''",
")",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'.cc'",
")",
"]",
"if",
"filename_cc",
".",
"endswith",
"(",
"'_unittest'",
")",
":",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'_unittest'",
")",
"]",
"elif",
"filename_cc",
".",
"endswith",
"(",
"'_test'",
")",
":",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'_test'",
")",
"]",
"filename_cc",
"=",
"filename_cc",
".",
"replace",
"(",
"'/public/'",
",",
"'/'",
")",
"filename_cc",
"=",
"filename_cc",
".",
"replace",
"(",
"'/internal/'",
",",
"'/'",
")",
"if",
"not",
"filename_h",
".",
"endswith",
"(",
"'.h'",
")",
":",
"return",
"(",
"False",
",",
"''",
")",
"filename_h",
"=",
"filename_h",
"[",
":",
"-",
"len",
"(",
"'.h'",
")",
"]",
"if",
"filename_h",
".",
"endswith",
"(",
"'-inl'",
")",
":",
"filename_h",
"=",
"filename_h",
"[",
":",
"-",
"len",
"(",
"'-inl'",
")",
"]",
"filename_h",
"=",
"filename_h",
".",
"replace",
"(",
"'/public/'",
",",
"'/'",
")",
"filename_h",
"=",
"filename_h",
".",
"replace",
"(",
"'/internal/'",
",",
"'/'",
")",
"files_belong_to_same_module",
"=",
"filename_cc",
".",
"endswith",
"(",
"filename_h",
")",
"common_path",
"=",
"''",
"if",
"files_belong_to_same_module",
":",
"common_path",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"filename_h",
")",
"]",
"return",
"files_belong_to_same_module",
",",
"common_path"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/utils/cpplint.py#L5526-L5578 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TRnd.__init__ | (self, *args) | __init__(TRnd self, int const & _Seed=1, int const & Steps=0) -> TRnd
Parameters:
_Seed: int const &
Steps: int const &
__init__(TRnd self, int const & _Seed=1) -> TRnd
Parameters:
_Seed: int const &
__init__(TRnd self) -> TRnd
__init__(TRnd self, TSIn SIn) -> TRnd
Parameters:
SIn: TSIn & | __init__(TRnd self, int const & _Seed=1, int const & Steps=0) -> TRnd | [
"__init__",
"(",
"TRnd",
"self",
"int",
"const",
"&",
"_Seed",
"=",
"1",
"int",
"const",
"&",
"Steps",
"=",
"0",
")",
"-",
">",
"TRnd"
] | def __init__(self, *args):
"""
__init__(TRnd self, int const & _Seed=1, int const & Steps=0) -> TRnd
Parameters:
_Seed: int const &
Steps: int const &
__init__(TRnd self, int const & _Seed=1) -> TRnd
Parameters:
_Seed: int const &
__init__(TRnd self) -> TRnd
__init__(TRnd self, TSIn SIn) -> TRnd
Parameters:
SIn: TSIn &
"""
_snap.TRnd_swiginit(self,_snap.new_TRnd(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_snap",
".",
"TRnd_swiginit",
"(",
"self",
",",
"_snap",
".",
"new_TRnd",
"(",
"*",
"args",
")",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L7527-L7547 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/math_grad.py | python | _RsqrtGrad | (op, grad) | return gen_math_ops._rsqrt_grad(y, grad) | Returns -0.5 * grad * conj(y)^3. | Returns -0.5 * grad * conj(y)^3. | [
"Returns",
"-",
"0",
".",
"5",
"*",
"grad",
"*",
"conj",
"(",
"y",
")",
"^3",
"."
] | def _RsqrtGrad(op, grad):
"""Returns -0.5 * grad * conj(y)^3."""
y = op.outputs[0] # y = x^(-1/2)
return gen_math_ops._rsqrt_grad(y, grad) | [
"def",
"_RsqrtGrad",
"(",
"op",
",",
"grad",
")",
":",
"y",
"=",
"op",
".",
"outputs",
"[",
"0",
"]",
"# y = x^(-1/2)",
"return",
"gen_math_ops",
".",
"_rsqrt_grad",
"(",
"y",
",",
"grad",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/math_grad.py#L317-L320 | |
crankyoldgit/IRremoteESP8266 | 6bc095af80e5aec47d66f8c6263f3a943ea3b4d5 | tools/auto_analyse_raw_data.py | python | get_rawdata | (arg_options) | Return the rawdata string(s) as per the options. | Return the rawdata string(s) as per the options. | [
"Return",
"the",
"rawdata",
"string",
"(",
"s",
")",
"as",
"per",
"the",
"options",
"."
] | def get_rawdata(arg_options):
"""Return the rawdata string(s) as per the options."""
if arg_options.stdin:
return sys.stdin.read()
if arg_options.file:
with open(arg_options.file, encoding="utf8") as input_file:
return input_file.read()
else:
return arg_options.rawdata | [
"def",
"get_rawdata",
"(",
"arg_options",
")",
":",
"if",
"arg_options",
".",
"stdin",
":",
"return",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"if",
"arg_options",
".",
"file",
":",
"with",
"open",
"(",
"arg_options",
".",
"file",
",",
"encoding",
"=",
"\"utf8\"",
")",
"as",
"input_file",
":",
"return",
"input_file",
".",
"read",
"(",
")",
"else",
":",
"return",
"arg_options",
".",
"rawdata"
] | https://github.com/crankyoldgit/IRremoteESP8266/blob/6bc095af80e5aec47d66f8c6263f3a943ea3b4d5/tools/auto_analyse_raw_data.py#L724-L732 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | kratos/python_scripts/sub_model_part_entities_boolean_operation_process.py | python | SubModelPartEntitiesBooleanOperationProcess.GetDefaultParameters | () | return KM.Parameters("""{
"first_model_part_name" : "MODEL_PART_NAME",
"second_model_part_name" : "MODEL_PART_NAME",
"result_model_part_name" : "MODEL_PART_NAME",
"boolean_operation" : "Difference",
"entity_type" : "Nodes"
}""") | Return the default parameters. | Return the default parameters. | [
"Return",
"the",
"default",
"parameters",
"."
] | def GetDefaultParameters():
"""Return the default parameters."""
return KM.Parameters("""{
"first_model_part_name" : "MODEL_PART_NAME",
"second_model_part_name" : "MODEL_PART_NAME",
"result_model_part_name" : "MODEL_PART_NAME",
"boolean_operation" : "Difference",
"entity_type" : "Nodes"
}""") | [
"def",
"GetDefaultParameters",
"(",
")",
":",
"return",
"KM",
".",
"Parameters",
"(",
"\"\"\"{\n \"first_model_part_name\" : \"MODEL_PART_NAME\",\n \"second_model_part_name\" : \"MODEL_PART_NAME\",\n \"result_model_part_name\" : \"MODEL_PART_NAME\",\n \"boolean_operation\" : \"Difference\",\n \"entity_type\" : \"Nodes\"\n }\"\"\"",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/sub_model_part_entities_boolean_operation_process.py#L43-L51 | |
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/sessionoptions.py | python | TlsOptions.createFromFiles | (clientCredentialsFilename,
clientCredentialsPassword,
trustedCertificatesFilename) | return TlsOptions(handle) | Args:
clientCredentialsFilename (str): Path to the file with the client
credentials
clientCredentialsPassword (str): Password for the credentials
trustedCertificatesFilename (str): Path to the file with the
trusted certificates
Creates a :class:`TlsOptions` using a DER encoded client credentials in
PKCS#12 format and DER encoded trust material in PKCS#7 format from the
specified files. | Args:
clientCredentialsFilename (str): Path to the file with the client
credentials
clientCredentialsPassword (str): Password for the credentials
trustedCertificatesFilename (str): Path to the file with the
trusted certificates | [
"Args",
":",
"clientCredentialsFilename",
"(",
"str",
")",
":",
"Path",
"to",
"the",
"file",
"with",
"the",
"client",
"credentials",
"clientCredentialsPassword",
"(",
"str",
")",
":",
"Password",
"for",
"the",
"credentials",
"trustedCertificatesFilename",
"(",
"str",
")",
":",
"Path",
"to",
"the",
"file",
"with",
"the",
"trusted",
"certificates"
] | def createFromFiles(clientCredentialsFilename,
clientCredentialsPassword,
trustedCertificatesFilename):
"""
Args:
clientCredentialsFilename (str): Path to the file with the client
credentials
clientCredentialsPassword (str): Password for the credentials
trustedCertificatesFilename (str): Path to the file with the
trusted certificates
Creates a :class:`TlsOptions` using a DER encoded client credentials in
PKCS#12 format and DER encoded trust material in PKCS#7 format from the
specified files.
"""
handle = internals.blpapi_TlsOptions_createFromFiles(
clientCredentialsFilename,
clientCredentialsPassword,
trustedCertificatesFilename)
return TlsOptions(handle) | [
"def",
"createFromFiles",
"(",
"clientCredentialsFilename",
",",
"clientCredentialsPassword",
",",
"trustedCertificatesFilename",
")",
":",
"handle",
"=",
"internals",
".",
"blpapi_TlsOptions_createFromFiles",
"(",
"clientCredentialsFilename",
",",
"clientCredentialsPassword",
",",
"trustedCertificatesFilename",
")",
"return",
"TlsOptions",
"(",
"handle",
")"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/sessionoptions.py#L827-L846 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_shgo.py | python | SHGO.simplex_minimizers | (self) | return self.X_min | Returns the indexes of all minimizers | Returns the indexes of all minimizers | [
"Returns",
"the",
"indexes",
"of",
"all",
"minimizers"
] | def simplex_minimizers(self):
"""
Returns the indexes of all minimizers
"""
self.minimizer_pool = []
# Note: Can implement parallelization here
for x in self.HC.V.cache:
if self.HC.V[x].minimiser():
if self.disp:
logging.info('=' * 60)
logging.info(
'v.x = {} is minimiser'.format(self.HC.V[x].x_a))
logging.info('v.f = {} is minimiser'.format(self.HC.V[x].f))
logging.info('=' * 30)
if self.HC.V[x] not in self.minimizer_pool:
self.minimizer_pool.append(self.HC.V[x])
if self.disp:
logging.info('Neighbours:')
logging.info('=' * 30)
for vn in self.HC.V[x].nn:
logging.info('x = {} || f = {}'.format(vn.x, vn.f))
logging.info('=' * 60)
self.minimizer_pool_F = []
self.X_min = []
# normalized tuple in the Vertex cache
self.X_min_cache = {} # Cache used in hypercube sampling
for v in self.minimizer_pool:
self.X_min.append(v.x_a)
self.minimizer_pool_F.append(v.f)
self.X_min_cache[tuple(v.x_a)] = v.x
self.minimizer_pool_F = np.array(self.minimizer_pool_F)
self.X_min = np.array(self.X_min)
# TODO: Only do this if global mode
self.sort_min_pool()
return self.X_min | [
"def",
"simplex_minimizers",
"(",
"self",
")",
":",
"self",
".",
"minimizer_pool",
"=",
"[",
"]",
"# Note: Can implement parallelization here",
"for",
"x",
"in",
"self",
".",
"HC",
".",
"V",
".",
"cache",
":",
"if",
"self",
".",
"HC",
".",
"V",
"[",
"x",
"]",
".",
"minimiser",
"(",
")",
":",
"if",
"self",
".",
"disp",
":",
"logging",
".",
"info",
"(",
"'='",
"*",
"60",
")",
"logging",
".",
"info",
"(",
"'v.x = {} is minimiser'",
".",
"format",
"(",
"self",
".",
"HC",
".",
"V",
"[",
"x",
"]",
".",
"x_a",
")",
")",
"logging",
".",
"info",
"(",
"'v.f = {} is minimiser'",
".",
"format",
"(",
"self",
".",
"HC",
".",
"V",
"[",
"x",
"]",
".",
"f",
")",
")",
"logging",
".",
"info",
"(",
"'='",
"*",
"30",
")",
"if",
"self",
".",
"HC",
".",
"V",
"[",
"x",
"]",
"not",
"in",
"self",
".",
"minimizer_pool",
":",
"self",
".",
"minimizer_pool",
".",
"append",
"(",
"self",
".",
"HC",
".",
"V",
"[",
"x",
"]",
")",
"if",
"self",
".",
"disp",
":",
"logging",
".",
"info",
"(",
"'Neighbours:'",
")",
"logging",
".",
"info",
"(",
"'='",
"*",
"30",
")",
"for",
"vn",
"in",
"self",
".",
"HC",
".",
"V",
"[",
"x",
"]",
".",
"nn",
":",
"logging",
".",
"info",
"(",
"'x = {} || f = {}'",
".",
"format",
"(",
"vn",
".",
"x",
",",
"vn",
".",
"f",
")",
")",
"logging",
".",
"info",
"(",
"'='",
"*",
"60",
")",
"self",
".",
"minimizer_pool_F",
"=",
"[",
"]",
"self",
".",
"X_min",
"=",
"[",
"]",
"# normalized tuple in the Vertex cache",
"self",
".",
"X_min_cache",
"=",
"{",
"}",
"# Cache used in hypercube sampling",
"for",
"v",
"in",
"self",
".",
"minimizer_pool",
":",
"self",
".",
"X_min",
".",
"append",
"(",
"v",
".",
"x_a",
")",
"self",
".",
"minimizer_pool_F",
".",
"append",
"(",
"v",
".",
"f",
")",
"self",
".",
"X_min_cache",
"[",
"tuple",
"(",
"v",
".",
"x_a",
")",
"]",
"=",
"v",
".",
"x",
"self",
".",
"minimizer_pool_F",
"=",
"np",
".",
"array",
"(",
"self",
".",
"minimizer_pool_F",
")",
"self",
".",
"X_min",
"=",
"np",
".",
"array",
"(",
"self",
".",
"X_min",
")",
"# TODO: Only do this if global mode",
"self",
".",
"sort_min_pool",
"(",
")",
"return",
"self",
".",
"X_min"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_shgo.py#L911-L953 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.isMixedElement | (self, name) | return ret | Search in the DtDs whether an element accept Mixed content
(or ANY) basically if it is supposed to accept text childs | Search in the DtDs whether an element accept Mixed content
(or ANY) basically if it is supposed to accept text childs | [
"Search",
"in",
"the",
"DtDs",
"whether",
"an",
"element",
"accept",
"Mixed",
"content",
"(",
"or",
"ANY",
")",
"basically",
"if",
"it",
"is",
"supposed",
"to",
"accept",
"text",
"childs"
] | def isMixedElement(self, name):
"""Search in the DtDs whether an element accept Mixed content
(or ANY) basically if it is supposed to accept text childs """
ret = libxml2mod.xmlIsMixedElement(self._o, name)
return ret | [
"def",
"isMixedElement",
"(",
"self",
",",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlIsMixedElement",
"(",
"self",
".",
"_o",
",",
"name",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4556-L4560 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/uuid.py | python | _ipconfig_getnode | () | Get the hardware address on Windows by running ipconfig.exe. | Get the hardware address on Windows by running ipconfig.exe. | [
"Get",
"the",
"hardware",
"address",
"on",
"Windows",
"by",
"running",
"ipconfig",
".",
"exe",
"."
] | def _ipconfig_getnode():
"""Get the hardware address on Windows by running ipconfig.exe."""
import os, re
dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
try:
import ctypes
buffer = ctypes.create_string_buffer(300)
ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
dirs.insert(0, buffer.value.decode('mbcs'))
except:
pass
for dir in dirs:
try:
pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
except IOError:
continue
else:
for line in pipe:
value = line.split(':')[-1].strip().lower()
if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
return int(value.replace('-', ''), 16)
finally:
pipe.close() | [
"def",
"_ipconfig_getnode",
"(",
")",
":",
"import",
"os",
",",
"re",
"dirs",
"=",
"[",
"''",
",",
"r'c:\\windows\\system32'",
",",
"r'c:\\winnt\\system32'",
"]",
"try",
":",
"import",
"ctypes",
"buffer",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"300",
")",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"GetSystemDirectoryA",
"(",
"buffer",
",",
"300",
")",
"dirs",
".",
"insert",
"(",
"0",
",",
"buffer",
".",
"value",
".",
"decode",
"(",
"'mbcs'",
")",
")",
"except",
":",
"pass",
"for",
"dir",
"in",
"dirs",
":",
"try",
":",
"pipe",
"=",
"os",
".",
"popen",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"'ipconfig'",
")",
"+",
"' /all'",
")",
"except",
"IOError",
":",
"continue",
"else",
":",
"for",
"line",
"in",
"pipe",
":",
"value",
"=",
"line",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"re",
".",
"match",
"(",
"'([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]'",
",",
"value",
")",
":",
"return",
"int",
"(",
"value",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
",",
"16",
")",
"finally",
":",
"pipe",
".",
"close",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/uuid.py#L340-L362 | ||
kungfu-origin/kungfu | 90c84b2b590855654cb9a6395ed050e0f7763512 | core/deps/SQLiteCpp-2.3.0/cpplint.py | python | _NamespaceInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Check end of namespace comments. | Check end of namespace comments. | [
"Check",
"end",
"of",
"namespace",
"comments",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace"') | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
"# Check how many lines is enclosed in this namespace. Don't issue",
"# warning for missing namespace comments if there aren't enough",
"# lines. However, do apply checks if there is already an end of",
"# namespace comment and it's incorrect.",
"#",
"# TODO(unknown): We always want to check end of namespace comments",
"# if a namespace is large, but sometimes we also want to apply the",
"# check if a short namespace contained nontrivial things (something",
"# other than forward declarations). There is currently no logic on",
"# deciding what these nontrivial things are, so this check is",
"# triggered by namespace size only, which works most of the time.",
"if",
"(",
"linenum",
"-",
"self",
".",
"starting_linenum",
"<",
"10",
"and",
"not",
"Match",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace\\b'",
",",
"line",
")",
")",
":",
"return",
"# Look for matching comment at end of namespace.",
"#",
"# Note that we accept C style \"/* */\" comments for terminating",
"# namespaces, so that code that terminate namespaces inside",
"# preprocessor macros can be cpplint clean.",
"#",
"# We also accept stuff like \"// end of namespace <name>.\" with the",
"# period at the end.",
"#",
"# Besides these, we don't accept anything else, otherwise we might",
"# get false negatives when existing comment is a substring of the",
"# expected namespace.",
"if",
"self",
".",
"name",
":",
"# Named namespace",
"if",
"not",
"Match",
"(",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace\\s+'",
"+",
"re",
".",
"escape",
"(",
"self",
".",
"name",
")",
"+",
"r'[\\*/\\.\\\\\\s]*$'",
")",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/namespace'",
",",
"5",
",",
"'Namespace should be terminated with \"// namespace %s\"'",
"%",
"self",
".",
"name",
")",
"else",
":",
"# Anonymous namespace",
"if",
"not",
"Match",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/namespace'",
",",
"5",
",",
"'Namespace should be terminated with \"// namespace\"'",
")"
] | https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L1784-L1827 | ||
p4lang/PI | 38d87e81253feff9fff0660d662c885be78fb719 | tools/cpplint.py | python | FlagCxx14Features | (filename, clean_lines, linenum, error) | Flag those C++14 features that we restrict.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Flag those C++14 features that we restrict. | [
"Flag",
"those",
"C",
"++",
"14",
"features",
"that",
"we",
"restrict",
"."
] | def FlagCxx14Features(filename, clean_lines, linenum, error):
"""Flag those C++14 features that we restrict.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++14 headers.
if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
error(filename, linenum, 'build/c++14', 5,
('<%s> is an unapproved C++14 header.') % include.group(1)) | [
"def",
"FlagCxx14Features",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"include",
"=",
"Match",
"(",
"r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]'",
",",
"line",
")",
"# Flag unapproved C++14 headers.",
"if",
"include",
"and",
"include",
".",
"group",
"(",
"1",
")",
"in",
"(",
"'scoped_allocator'",
",",
"'shared_mutex'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/c++14'",
",",
"5",
",",
"(",
"'<%s> is an unapproved C++14 header.'",
")",
"%",
"include",
".",
"group",
"(",
"1",
")",
")"
] | https://github.com/p4lang/PI/blob/38d87e81253feff9fff0660d662c885be78fb719/tools/cpplint.py#L6432-L6448 | ||
sailing-pmls/pmls-caffe | 49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a | scripts/cpp_lint.py | python | CheckForIncludeWhatYouUse | (filename, clean_lines, include_state, error,
io=codecs) | Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection. | Reports for missing stl includes. | [
"Reports",
"for",
"missing",
"stl",
"includes",
"."
] | def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
io=codecs):
"""Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection.
"""
required = {} # A map of header name to linenumber and the template entity.
# Example of required: { '<functional>': (1219, 'less<>') }
for linenum in xrange(clean_lines.NumLines()):
line = clean_lines.elided[linenum]
if not line or line[0] == '#':
continue
# String is special -- it is a non-templatized type in STL.
matched = _RE_PATTERN_STRING.search(line)
if matched:
# Don't warn about strings in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required['<string>'] = (linenum, 'string')
for pattern, template, header in _re_pattern_algorithm_header:
if pattern.search(line):
required[header] = (linenum, template)
# The following function is just a speed up, no semantics are changed.
if not '<' in line: # Reduces the cpu time usage by skipping lines.
continue
for pattern, template, header in _re_pattern_templates:
if pattern.search(line):
required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.
# Let's copy the include_state so it is only messed up within this function.
include_state = include_state.copy()
# Did we find the header for this file (if any) and succesfully load it?
header_found = False
# Use the absolute path so that matching works properly.
abs_filename = FileInfo(filename).FullName()
# For Emacs's flymake.
# If cpplint is invoked from Emacs's flymake, a temporary file is generated
# by flymake and that file name might end with '_flymake.cc'. In that case,
# restore original file name here so that the corresponding header file can be
# found.
# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
# instead of 'foo_flymake.h'
abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
# include_state is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = include_state.keys()
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
if same_module and UpdateIncludeState(fullpath, include_state, io):
header_found = True
# If we can't find the header file for a .cc, assume it's because we don't
# know where to look. In that case we'll give up as we're not sure they
# didn't include it in the .h file.
# TODO(unknown): Do a better job of finding .h files so we are confident that
# not having the .h file means there isn't one.
if filename.endswith('.cc') and not header_found:
return
# All the lines have been processed, report the errors found.
for required_header_unstripped in required:
template = required[required_header_unstripped][1]
if required_header_unstripped.strip('<>"') not in include_state:
error(filename, required[required_header_unstripped][0],
'build/include_what_you_use', 4,
'Add #include ' + required_header_unstripped + ' for ' + template) | [
"def",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
",",
"io",
"=",
"codecs",
")",
":",
"required",
"=",
"{",
"}",
"# A map of header name to linenumber and the template entity.",
"# Example of required: { '<functional>': (1219, 'less<>') }",
"for",
"linenum",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"not",
"line",
"or",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"# String is special -- it is a non-templatized type in STL.",
"matched",
"=",
"_RE_PATTERN_STRING",
".",
"search",
"(",
"line",
")",
"if",
"matched",
":",
"# Don't warn about strings in non-STL namespaces:",
"# (We check only the first match per line; good enough.)",
"prefix",
"=",
"line",
"[",
":",
"matched",
".",
"start",
"(",
")",
"]",
"if",
"prefix",
".",
"endswith",
"(",
"'std::'",
")",
"or",
"not",
"prefix",
".",
"endswith",
"(",
"'::'",
")",
":",
"required",
"[",
"'<string>'",
"]",
"=",
"(",
"linenum",
",",
"'string'",
")",
"for",
"pattern",
",",
"template",
",",
"header",
"in",
"_re_pattern_algorithm_header",
":",
"if",
"pattern",
".",
"search",
"(",
"line",
")",
":",
"required",
"[",
"header",
"]",
"=",
"(",
"linenum",
",",
"template",
")",
"# The following function is just a speed up, no semantics are changed.",
"if",
"not",
"'<'",
"in",
"line",
":",
"# Reduces the cpu time usage by skipping lines.",
"continue",
"for",
"pattern",
",",
"template",
",",
"header",
"in",
"_re_pattern_templates",
":",
"if",
"pattern",
".",
"search",
"(",
"line",
")",
":",
"required",
"[",
"header",
"]",
"=",
"(",
"linenum",
",",
"template",
")",
"# The policy is that if you #include something in foo.h you don't need to",
"# include it again in foo.cc. Here, we will look at possible includes.",
"# Let's copy the include_state so it is only messed up within this function.",
"include_state",
"=",
"include_state",
".",
"copy",
"(",
")",
"# Did we find the header for this file (if any) and succesfully load it?",
"header_found",
"=",
"False",
"# Use the absolute path so that matching works properly.",
"abs_filename",
"=",
"FileInfo",
"(",
"filename",
")",
".",
"FullName",
"(",
")",
"# For Emacs's flymake.",
"# If cpplint is invoked from Emacs's flymake, a temporary file is generated",
"# by flymake and that file name might end with '_flymake.cc'. In that case,",
"# restore original file name here so that the corresponding header file can be",
"# found.",
"# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'",
"# instead of 'foo_flymake.h'",
"abs_filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.cc$'",
",",
"'.cc'",
",",
"abs_filename",
")",
"# include_state is modified during iteration, so we iterate over a copy of",
"# the keys.",
"header_keys",
"=",
"include_state",
".",
"keys",
"(",
")",
"for",
"header",
"in",
"header_keys",
":",
"(",
"same_module",
",",
"common_path",
")",
"=",
"FilesBelongToSameModule",
"(",
"abs_filename",
",",
"header",
")",
"fullpath",
"=",
"common_path",
"+",
"header",
"if",
"same_module",
"and",
"UpdateIncludeState",
"(",
"fullpath",
",",
"include_state",
",",
"io",
")",
":",
"header_found",
"=",
"True",
"# If we can't find the header file for a .cc, assume it's because we don't",
"# know where to look. In that case we'll give up as we're not sure they",
"# didn't include it in the .h file.",
"# TODO(unknown): Do a better job of finding .h files so we are confident that",
"# not having the .h file means there isn't one.",
"if",
"filename",
".",
"endswith",
"(",
"'.cc'",
")",
"and",
"not",
"header_found",
":",
"return",
"# All the lines have been processed, report the errors found.",
"for",
"required_header_unstripped",
"in",
"required",
":",
"template",
"=",
"required",
"[",
"required_header_unstripped",
"]",
"[",
"1",
"]",
"if",
"required_header_unstripped",
".",
"strip",
"(",
"'<>\"'",
")",
"not",
"in",
"include_state",
":",
"error",
"(",
"filename",
",",
"required",
"[",
"required_header_unstripped",
"]",
"[",
"0",
"]",
",",
"'build/include_what_you_use'",
",",
"4",
",",
"'Add #include '",
"+",
"required_header_unstripped",
"+",
"' for '",
"+",
"template",
")"
] | https://github.com/sailing-pmls/pmls-caffe/blob/49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a/scripts/cpp_lint.py#L4483-L4573 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/serial/serialposix.py | python | Serial._update_rts_state | (self) | Set terminal status line: Request To Send | Set terminal status line: Request To Send | [
"Set",
"terminal",
"status",
"line",
":",
"Request",
"To",
"Send"
] | def _update_rts_state(self):
"""Set terminal status line: Request To Send"""
if self._rts_state:
fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
else:
fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) | [
"def",
"_update_rts_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rts_state",
":",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"fd",
",",
"TIOCMBIS",
",",
"TIOCM_RTS_str",
")",
"else",
":",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"fd",
",",
"TIOCMBIC",
",",
"TIOCM_RTS_str",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialposix.py#L624-L629 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Validator.SetWindow | (*args, **kwargs) | return _core_.Validator_SetWindow(*args, **kwargs) | SetWindow(self, Window window) | SetWindow(self, Window window) | [
"SetWindow",
"(",
"self",
"Window",
"window",
")"
] | def SetWindow(*args, **kwargs):
"""SetWindow(self, Window window)"""
return _core_.Validator_SetWindow(*args, **kwargs) | [
"def",
"SetWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Validator_SetWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L11896-L11898 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py | python | Node.add_source | (self, source) | Adds sources. | Adds sources. | [
"Adds",
"sources",
"."
] | def add_source(self, source):
"""Adds sources."""
if self._specific_sources:
return
try:
self._add_child(self.sources, self.sources_set, source)
except TypeError, e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | [
"def",
"add_source",
"(",
"self",
",",
"source",
")",
":",
"if",
"self",
".",
"_specific_sources",
":",
"return",
"try",
":",
"self",
".",
"_add_child",
"(",
"self",
".",
"sources",
",",
"self",
".",
"sources_set",
",",
"source",
")",
"except",
"TypeError",
",",
"e",
":",
"e",
"=",
"e",
".",
"args",
"[",
"0",
"]",
"if",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"e",
")",
":",
"s",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"e",
")",
")",
"else",
":",
"s",
"=",
"str",
"(",
"e",
")",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"attempted to add a non-Node as source of %s:\\n\\t%s is a %s, not a Node\"",
"%",
"(",
"str",
"(",
"self",
")",
",",
"s",
",",
"type",
"(",
"e",
")",
")",
")"
] | 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/Node/__init__.py#L1269-L1281 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Context.py | python | Context.cmd_and_log | (self, cmd, **kw) | return out | Execute a command and return stdout if the execution is successful.
An exception is thrown when the exit status is non-0. In that case, both stderr and stdout
will be bound to the WafError object::
def configure(conf):
out = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.STDOUT, quiet=waflib.Context.BOTH)
(out, err) = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.BOTH)
try:
conf.cmd_and_log(['which', 'someapp'], output=waflib.Context.BOTH)
except Exception as e:
print(e.stdout, e.stderr)
:param cmd: args for subprocess.Popen
:param kw: keyword arguments for subprocess.Popen | Execute a command and return stdout if the execution is successful.
An exception is thrown when the exit status is non-0. In that case, both stderr and stdout
will be bound to the WafError object:: | [
"Execute",
"a",
"command",
"and",
"return",
"stdout",
"if",
"the",
"execution",
"is",
"successful",
".",
"An",
"exception",
"is",
"thrown",
"when",
"the",
"exit",
"status",
"is",
"non",
"-",
"0",
".",
"In",
"that",
"case",
"both",
"stderr",
"and",
"stdout",
"will",
"be",
"bound",
"to",
"the",
"WafError",
"object",
"::"
] | def cmd_and_log(self, cmd, **kw):
"""
Execute a command and return stdout if the execution is successful.
An exception is thrown when the exit status is non-0. In that case, both stderr and stdout
will be bound to the WafError object::
def configure(conf):
out = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.STDOUT, quiet=waflib.Context.BOTH)
(out, err) = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.BOTH)
try:
conf.cmd_and_log(['which', 'someapp'], output=waflib.Context.BOTH)
except Exception as e:
print(e.stdout, e.stderr)
:param cmd: args for subprocess.Popen
:param kw: keyword arguments for subprocess.Popen
"""
subprocess = Utils.subprocess
kw['shell'] = isinstance(cmd, str)
Logs.debug('runner: %r' % cmd)
if 'quiet' in kw:
quiet = kw['quiet']
del kw['quiet']
else:
quiet = None
if 'output' in kw:
to_ret = kw['output']
del kw['output']
else:
to_ret = STDOUT
kw['stdout'] = kw['stderr'] = subprocess.PIPE
if quiet is None:
self.to_log(cmd)
try:
p = subprocess.Popen(cmd, **kw)
(out, err) = p.communicate()
except Exception as e:
raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
if not isinstance(out, str):
out = out.decode(sys.stdout.encoding or 'iso8859-1', 'ignore')
if not isinstance(err, str):
err = err.decode(sys.stdout.encoding or 'iso8859-1', 'ignore')
if out and quiet != STDOUT and quiet != BOTH:
self.to_log('out: %s' % out)
if err and quiet != STDERR and quiet != BOTH:
self.to_log('err: %s' % err)
if p.returncode:
e = Errors.WafError('Command %r returned %r' % (cmd, p.returncode))
e.returncode = p.returncode
e.stderr = err
e.stdout = out
raise e
if to_ret == BOTH:
return (out, err)
elif to_ret == STDERR:
return err
return out | [
"def",
"cmd_and_log",
"(",
"self",
",",
"cmd",
",",
"*",
"*",
"kw",
")",
":",
"subprocess",
"=",
"Utils",
".",
"subprocess",
"kw",
"[",
"'shell'",
"]",
"=",
"isinstance",
"(",
"cmd",
",",
"str",
")",
"Logs",
".",
"debug",
"(",
"'runner: %r'",
"%",
"cmd",
")",
"if",
"'quiet'",
"in",
"kw",
":",
"quiet",
"=",
"kw",
"[",
"'quiet'",
"]",
"del",
"kw",
"[",
"'quiet'",
"]",
"else",
":",
"quiet",
"=",
"None",
"if",
"'output'",
"in",
"kw",
":",
"to_ret",
"=",
"kw",
"[",
"'output'",
"]",
"del",
"kw",
"[",
"'output'",
"]",
"else",
":",
"to_ret",
"=",
"STDOUT",
"kw",
"[",
"'stdout'",
"]",
"=",
"kw",
"[",
"'stderr'",
"]",
"=",
"subprocess",
".",
"PIPE",
"if",
"quiet",
"is",
"None",
":",
"self",
".",
"to_log",
"(",
"cmd",
")",
"try",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"*",
"*",
"kw",
")",
"(",
"out",
",",
"err",
")",
"=",
"p",
".",
"communicate",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"'Execution failure: %s'",
"%",
"str",
"(",
"e",
")",
",",
"ex",
"=",
"e",
")",
"if",
"not",
"isinstance",
"(",
"out",
",",
"str",
")",
":",
"out",
"=",
"out",
".",
"decode",
"(",
"sys",
".",
"stdout",
".",
"encoding",
"or",
"'iso8859-1'",
",",
"'ignore'",
")",
"if",
"not",
"isinstance",
"(",
"err",
",",
"str",
")",
":",
"err",
"=",
"err",
".",
"decode",
"(",
"sys",
".",
"stdout",
".",
"encoding",
"or",
"'iso8859-1'",
",",
"'ignore'",
")",
"if",
"out",
"and",
"quiet",
"!=",
"STDOUT",
"and",
"quiet",
"!=",
"BOTH",
":",
"self",
".",
"to_log",
"(",
"'out: %s'",
"%",
"out",
")",
"if",
"err",
"and",
"quiet",
"!=",
"STDERR",
"and",
"quiet",
"!=",
"BOTH",
":",
"self",
".",
"to_log",
"(",
"'err: %s'",
"%",
"err",
")",
"if",
"p",
".",
"returncode",
":",
"e",
"=",
"Errors",
".",
"WafError",
"(",
"'Command %r returned %r'",
"%",
"(",
"cmd",
",",
"p",
".",
"returncode",
")",
")",
"e",
".",
"returncode",
"=",
"p",
".",
"returncode",
"e",
".",
"stderr",
"=",
"err",
"e",
".",
"stdout",
"=",
"out",
"raise",
"e",
"if",
"to_ret",
"==",
"BOTH",
":",
"return",
"(",
"out",
",",
"err",
")",
"elif",
"to_ret",
"==",
"STDERR",
":",
"return",
"err",
"return",
"out"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Context.py#L395-L458 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/balloontip.py | python | BalloonTip.OnWidgetMotion | (self, event) | Handle the mouse motion inside the target.
This prevents the annoying behavior of :class:`BalloonTip` to display when the
user does something else inside the window. The :class:`BalloonTip` window is
displayed only when the mouse does *not* move for the start delay time.
:param `event`: a :class:`MouseEvent` event to be processed. | Handle the mouse motion inside the target. | [
"Handle",
"the",
"mouse",
"motion",
"inside",
"the",
"target",
"."
] | def OnWidgetMotion(self, event):
"""
Handle the mouse motion inside the target.
This prevents the annoying behavior of :class:`BalloonTip` to display when the
user does something else inside the window. The :class:`BalloonTip` window is
displayed only when the mouse does *not* move for the start delay time.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
if hasattr(self, "BalloonFrame"):
if self.BalloonFrame:
return
if hasattr(self, "showtime"):
if self.showtime:
self.showtime.Start(self._startdelaytime)
event.Skip() | [
"def",
"OnWidgetMotion",
"(",
"self",
",",
"event",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"BalloonFrame\"",
")",
":",
"if",
"self",
".",
"BalloonFrame",
":",
"return",
"if",
"hasattr",
"(",
"self",
",",
"\"showtime\"",
")",
":",
"if",
"self",
".",
"showtime",
":",
"self",
".",
"showtime",
".",
"Start",
"(",
"self",
".",
"_startdelaytime",
")",
"event",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/balloontip.py#L732-L751 | ||
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Memoize.py | python | CountDict.count | (self, *args, **kw) | Counts whether the computed key value is already present
in the memoization dictionary (a hit) or not (a miss). | Counts whether the computed key value is already present
in the memoization dictionary (a hit) or not (a miss). | [
"Counts",
"whether",
"the",
"computed",
"key",
"value",
"is",
"already",
"present",
"in",
"the",
"memoization",
"dictionary",
"(",
"a",
"hit",
")",
"or",
"not",
"(",
"a",
"miss",
")",
"."
] | def count(self, *args, **kw):
""" Counts whether the computed key value is already present
in the memoization dictionary (a hit) or not (a miss).
"""
obj = args[0]
try:
memo_dict = obj._memo[self.method_name]
except KeyError:
self.miss = self.miss + 1
else:
key = self.keymaker(*args, **kw)
if key in memo_dict:
self.hit = self.hit + 1
else:
self.miss = self.miss + 1 | [
"def",
"count",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"obj",
"=",
"args",
"[",
"0",
"]",
"try",
":",
"memo_dict",
"=",
"obj",
".",
"_memo",
"[",
"self",
".",
"method_name",
"]",
"except",
"KeyError",
":",
"self",
".",
"miss",
"=",
"self",
".",
"miss",
"+",
"1",
"else",
":",
"key",
"=",
"self",
".",
"keymaker",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"if",
"key",
"in",
"memo_dict",
":",
"self",
".",
"hit",
"=",
"self",
".",
"hit",
"+",
"1",
"else",
":",
"self",
".",
"miss",
"=",
"self",
".",
"miss",
"+",
"1"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Memoize.py#L164-L178 | ||
SmingHub/Sming | cde389ed030905694983121a32f9028976b57194 | Sming/Components/Storage/Tools/hwconfig/config.py | python | Config.load | (self, name) | Load a configuration recursively. | Load a configuration recursively. | [
"Load",
"a",
"configuration",
"recursively",
"."
] | def load(self, name):
"""Load a configuration recursively."""
filename = find_config(name)
self.depends.append(filename)
data = json_load(filename)
self.parse_dict(data) | [
"def",
"load",
"(",
"self",
",",
"name",
")",
":",
"filename",
"=",
"find_config",
"(",
"name",
")",
"self",
".",
"depends",
".",
"append",
"(",
"filename",
")",
"data",
"=",
"json_load",
"(",
"filename",
")",
"self",
".",
"parse_dict",
"(",
"data",
")"
] | https://github.com/SmingHub/Sming/blob/cde389ed030905694983121a32f9028976b57194/Sming/Components/Storage/Tools/hwconfig/config.py#L116-L121 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/masterslave.py | python | ROSHandler._shutdown | (self, reason='') | @param reason: human-readable debug string
@type reason: str | [] | def _shutdown(self, reason=''):
"""
@param reason: human-readable debug string
@type reason: str
"""
if not self.done:
self.done = True
if reason:
_logger.info(reason)
if self.protocol_handlers:
for handler in self.protocol_handlers:
handler.shutdown()
del self.protocol_handlers[:]
self.protocol_handlers = None
return True | [
"def",
"_shutdown",
"(",
"self",
",",
"reason",
"=",
"''",
")",
":",
"if",
"not",
"self",
".",
"done",
":",
"self",
".",
"done",
"=",
"True",
"if",
"reason",
":",
"_logger",
".",
"info",
"(",
"reason",
")",
"if",
"self",
".",
"protocol_handlers",
":",
"for",
"handler",
"in",
"self",
".",
"protocol_handlers",
":",
"handler",
".",
"shutdown",
"(",
")",
"del",
"self",
".",
"protocol_handlers",
"[",
":",
"]",
"self",
".",
"protocol_handlers",
"=",
"None",
"return",
"True"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/masterslave.py#L333-L347 | |||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/specs/python/summaries.py | python | tf_spec_summary | (spec,
inputs=None,
input_shape=None,
input_type=dtypes.float32) | Output a summary of the specification.
This prints a list of left-most tensor operations and summarized the
variables found in the right branches. This kind of representation
is particularly useful for networks that are generally structured
like pipelines.
Args:
spec: specification
inputs: input to the spec construction (usually a Tensor)
input_shape: optional shape of input
input_type: type of the input tensor | Output a summary of the specification. | [
"Output",
"a",
"summary",
"of",
"the",
"specification",
"."
] | def tf_spec_summary(spec,
inputs=None,
input_shape=None,
input_type=dtypes.float32):
"""Output a summary of the specification.
This prints a list of left-most tensor operations and summarized the
variables found in the right branches. This kind of representation
is particularly useful for networks that are generally structured
like pipelines.
Args:
spec: specification
inputs: input to the spec construction (usually a Tensor)
input_shape: optional shape of input
input_type: type of the input tensor
"""
if inputs is None:
inputs = array_ops.placeholder(input_type, input_shape)
outputs = specs.create_net(spec, inputs)
tf_parameter_summary(outputs) | [
"def",
"tf_spec_summary",
"(",
"spec",
",",
"inputs",
"=",
"None",
",",
"input_shape",
"=",
"None",
",",
"input_type",
"=",
"dtypes",
".",
"float32",
")",
":",
"if",
"inputs",
"is",
"None",
":",
"inputs",
"=",
"array_ops",
".",
"placeholder",
"(",
"input_type",
",",
"input_shape",
")",
"outputs",
"=",
"specs",
".",
"create_net",
"(",
"spec",
",",
"inputs",
")",
"tf_parameter_summary",
"(",
"outputs",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/specs/python/summaries.py#L273-L294 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py | python | FileStorageUri.names_object | (self) | return False | Returns True if this URI names an object. | Returns True if this URI names an object. | [
"Returns",
"True",
"if",
"this",
"URI",
"names",
"an",
"object",
"."
] | def names_object(self):
"""Returns True if this URI names an object."""
return False | [
"def",
"names_object",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py#L872-L874 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | support/apply-reviews.py | python | apply_patch | (options) | Applies patch locally. | Applies patch locally. | [
"Applies",
"patch",
"locally",
"."
] | def apply_patch(options):
"""Applies patch locally."""
cmd = 'git apply --index {review_id}.patch'.format(
review_id=patch_id(options))
if options['3way']:
cmd += ' --3way'
if platform.system() == 'Windows':
# NOTE: Depending on the Git settings, there may or may not be
# carriage returns in files and in the downloaded patch.
# We ignore these errors on Windows.
cmd += ' --ignore-whitespace'
shell(cmd, options['dry_run']) | [
"def",
"apply_patch",
"(",
"options",
")",
":",
"cmd",
"=",
"'git apply --index {review_id}.patch'",
".",
"format",
"(",
"review_id",
"=",
"patch_id",
"(",
"options",
")",
")",
"if",
"options",
"[",
"'3way'",
"]",
":",
"cmd",
"+=",
"' --3way'",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"# NOTE: Depending on the Git settings, there may or may not be",
"# carriage returns in files and in the downloaded patch.",
"# We ignore these errors on Windows.",
"cmd",
"+=",
"' --ignore-whitespace'",
"shell",
"(",
"cmd",
",",
"options",
"[",
"'dry_run'",
"]",
")"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/apply-reviews.py#L232-L246 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/function_base.py | python | disp | (mesg, device=None, linefeed=True) | return | Display a message on a device.
Parameters
----------
mesg : str
Message to display.
device : object
Device to write message. If None, defaults to ``sys.stdout`` which is
very similar to ``print``. `device` needs to have ``write()`` and
``flush()`` methods.
linefeed : bool, optional
Option whether to print a line feed or not. Defaults to True.
Raises
------
AttributeError
If `device` does not have a ``write()`` or ``flush()`` method.
Examples
--------
Besides ``sys.stdout``, a file-like object can also be used as it has
both required methods:
>>> from io import StringIO
>>> buf = StringIO()
>>> np.disp(u'"Display" in a file', device=buf)
>>> buf.getvalue()
'"Display" in a file\\n' | Display a message on a device. | [
"Display",
"a",
"message",
"on",
"a",
"device",
"."
] | def disp(mesg, device=None, linefeed=True):
"""
Display a message on a device.
Parameters
----------
mesg : str
Message to display.
device : object
Device to write message. If None, defaults to ``sys.stdout`` which is
very similar to ``print``. `device` needs to have ``write()`` and
``flush()`` methods.
linefeed : bool, optional
Option whether to print a line feed or not. Defaults to True.
Raises
------
AttributeError
If `device` does not have a ``write()`` or ``flush()`` method.
Examples
--------
Besides ``sys.stdout``, a file-like object can also be used as it has
both required methods:
>>> from io import StringIO
>>> buf = StringIO()
>>> np.disp(u'"Display" in a file', device=buf)
>>> buf.getvalue()
'"Display" in a file\\n'
"""
if device is None:
device = sys.stdout
if linefeed:
device.write('%s\n' % mesg)
else:
device.write('%s' % mesg)
device.flush()
return | [
"def",
"disp",
"(",
"mesg",
",",
"device",
"=",
"None",
",",
"linefeed",
"=",
"True",
")",
":",
"if",
"device",
"is",
"None",
":",
"device",
"=",
"sys",
".",
"stdout",
"if",
"linefeed",
":",
"device",
".",
"write",
"(",
"'%s\\n'",
"%",
"mesg",
")",
"else",
":",
"device",
".",
"write",
"(",
"'%s'",
"%",
"mesg",
")",
"device",
".",
"flush",
"(",
")",
"return"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/function_base.py#L1728-L1767 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/parameters/InputParameters.py | python | InputParameters.hasParameter | (self, name) | return name in self.__parameters | Test that the parameter exists.
Inputs:
name[str]: The name of the Parameter to check | Test that the parameter exists. | [
"Test",
"that",
"the",
"parameter",
"exists",
"."
] | def hasParameter(self, name):
"""
Test that the parameter exists.
Inputs:
name[str]: The name of the Parameter to check
"""
return name in self.__parameters | [
"def",
"hasParameter",
"(",
"self",
",",
"name",
")",
":",
"return",
"name",
"in",
"self",
".",
"__parameters"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/parameters/InputParameters.py#L209-L216 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_txt.py | python | EdFile.ReadLines | (self) | Get the contents of the file as a list of lines
@return: list of strings | Get the contents of the file as a list of lines
@return: list of strings | [
"Get",
"the",
"contents",
"of",
"the",
"file",
"as",
"a",
"list",
"of",
"lines",
"@return",
":",
"list",
"of",
"strings"
] | def ReadLines(self):
"""Get the contents of the file as a list of lines
@return: list of strings
"""
raise NotImplementedError | [
"def",
"ReadLines",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_txt.py#L500-L505 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/commands.py | python | InstallLib.finalize_options | (self) | Finalize options | Finalize options | [
"Finalize",
"options"
] | def finalize_options(self):
""" Finalize options """
_install_lib.install_lib.finalize_options(self)
if 'install_lib' in _option_inherits:
for parent, opt_name in _option_inherits['install_lib']:
self.set_undefined_options(parent, (opt_name, opt_name))
if 'install_lib' in _option_finalizers:
for func in list(_option_finalizers['install_lib'].values()):
func(self) | [
"def",
"finalize_options",
"(",
"self",
")",
":",
"_install_lib",
".",
"install_lib",
".",
"finalize_options",
"(",
"self",
")",
"if",
"'install_lib'",
"in",
"_option_inherits",
":",
"for",
"parent",
",",
"opt_name",
"in",
"_option_inherits",
"[",
"'install_lib'",
"]",
":",
"self",
".",
"set_undefined_options",
"(",
"parent",
",",
"(",
"opt_name",
",",
"opt_name",
")",
")",
"if",
"'install_lib'",
"in",
"_option_finalizers",
":",
"for",
"func",
"in",
"list",
"(",
"_option_finalizers",
"[",
"'install_lib'",
"]",
".",
"values",
"(",
")",
")",
":",
"func",
"(",
"self",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/commands.py#L160-L168 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/numbers.py | python | Real.__float__ | (self) | Any Real can be converted to a native float object.
Called for float(self). | Any Real can be converted to a native float object. | [
"Any",
"Real",
"can",
"be",
"converted",
"to",
"a",
"native",
"float",
"object",
"."
] | def __float__(self):
"""Any Real can be converted to a native float object.
Called for float(self)."""
raise NotImplementedError | [
"def",
"__float__",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/numbers.py#L159-L163 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_spectral.py | python | _wrap_result | (result, is_complex, shape=None) | return z | Convert from real to complex and reshape result arrays. | Convert from real to complex and reshape result arrays. | [
"Convert",
"from",
"real",
"to",
"complex",
"and",
"reshape",
"result",
"arrays",
"."
] | def _wrap_result(result, is_complex, shape=None):
"""
Convert from real to complex and reshape result arrays.
"""
if is_complex:
z = _real2complex(result)
else:
z = result
if shape is not None:
z = z.reshape(shape)
return z | [
"def",
"_wrap_result",
"(",
"result",
",",
"is_complex",
",",
"shape",
"=",
"None",
")",
":",
"if",
"is_complex",
":",
"z",
"=",
"_real2complex",
"(",
"result",
")",
"else",
":",
"z",
"=",
"result",
"if",
"shape",
"is",
"not",
"None",
":",
"z",
"=",
"z",
".",
"reshape",
"(",
"shape",
")",
"return",
"z"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_spectral.py#L241-L251 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | EndingList.checkin | (self, pos) | return False | Search for an ending | Search for an ending | [
"Search",
"for",
"an",
"ending"
] | def checkin(self, pos):
"Search for an ending"
if self.findending(pos):
return True
return False | [
"def",
"checkin",
"(",
"self",
",",
"pos",
")",
":",
"if",
"self",
".",
"findending",
"(",
"pos",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L1951-L1955 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozpack/packager/formats.py | python | JarFormatter._jarize | (self, entry, relpath) | return chromepath, entry | Transform a manifest entry in one pointing to chrome data in a jar.
Return the corresponding chrome path and the new entry. | Transform a manifest entry in one pointing to chrome data in a jar.
Return the corresponding chrome path and the new entry. | [
"Transform",
"a",
"manifest",
"entry",
"in",
"one",
"pointing",
"to",
"chrome",
"data",
"in",
"a",
"jar",
".",
"Return",
"the",
"corresponding",
"chrome",
"path",
"and",
"the",
"new",
"entry",
"."
] | def _jarize(self, entry, relpath):
'''
Transform a manifest entry in one pointing to chrome data in a jar.
Return the corresponding chrome path and the new entry.
'''
base = entry.base
basepath = mozpack.path.split(relpath)[0]
chromepath = mozpack.path.join(base, basepath)
entry = entry.rebase(chromepath) \
.move(mozpack.path.join(base, 'jar:%s.jar!' % basepath)) \
.rebase(base)
return chromepath, entry | [
"def",
"_jarize",
"(",
"self",
",",
"entry",
",",
"relpath",
")",
":",
"base",
"=",
"entry",
".",
"base",
"basepath",
"=",
"mozpack",
".",
"path",
".",
"split",
"(",
"relpath",
")",
"[",
"0",
"]",
"chromepath",
"=",
"mozpack",
".",
"path",
".",
"join",
"(",
"base",
",",
"basepath",
")",
"entry",
"=",
"entry",
".",
"rebase",
"(",
"chromepath",
")",
".",
"move",
"(",
"mozpack",
".",
"path",
".",
"join",
"(",
"base",
",",
"'jar:%s.jar!'",
"%",
"basepath",
")",
")",
".",
"rebase",
"(",
"base",
")",
"return",
"chromepath",
",",
"entry"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/packager/formats.py#L165-L176 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/combo.py | python | ComboCtrl.SetText | (*args, **kwargs) | return _combo.ComboCtrl_SetText(*args, **kwargs) | SetText(self, String value)
Sets the text for the text field without affecting the popup. Thus,
unlike `SetValue`, it works equally well with combo control using
wx.CB_READONLY style. | SetText(self, String value) | [
"SetText",
"(",
"self",
"String",
"value",
")"
] | def SetText(*args, **kwargs):
"""
SetText(self, String value)
Sets the text for the text field without affecting the popup. Thus,
unlike `SetValue`, it works equally well with combo control using
wx.CB_READONLY style.
"""
return _combo.ComboCtrl_SetText(*args, **kwargs) | [
"def",
"SetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"ComboCtrl_SetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/combo.py#L251-L259 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/cross_validation.py | python | _permutation_test_score | (estimator, X, y, cv, scorer) | return np.mean(avg_score) | Auxiliary function for permutation_test_score | Auxiliary function for permutation_test_score | [
"Auxiliary",
"function",
"for",
"permutation_test_score"
] | def _permutation_test_score(estimator, X, y, cv, scorer):
"""Auxiliary function for permutation_test_score"""
avg_score = []
for train, test in cv:
estimator.fit(X[train], y[train])
avg_score.append(scorer(estimator, X[test], y[test]))
return np.mean(avg_score) | [
"def",
"_permutation_test_score",
"(",
"estimator",
",",
"X",
",",
"y",
",",
"cv",
",",
"scorer",
")",
":",
"avg_score",
"=",
"[",
"]",
"for",
"train",
",",
"test",
"in",
"cv",
":",
"estimator",
".",
"fit",
"(",
"X",
"[",
"train",
"]",
",",
"y",
"[",
"train",
"]",
")",
"avg_score",
".",
"append",
"(",
"scorer",
"(",
"estimator",
",",
"X",
"[",
"test",
"]",
",",
"y",
"[",
"test",
"]",
")",
")",
"return",
"np",
".",
"mean",
"(",
"avg_score",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/cross_validation.py#L1755-L1761 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/build/project.py | python | ProjectRegistry.target | (self, project_module) | return self.module2target[project_module] | Returns the project target corresponding to the 'project-module'. | Returns the project target corresponding to the 'project-module'. | [
"Returns",
"the",
"project",
"target",
"corresponding",
"to",
"the",
"project",
"-",
"module",
"."
] | def target(self, project_module):
"""Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring)
if project_module not in self.module2target:
self.module2target[project_module] = \
b2.build.targets.ProjectTarget(project_module, project_module,
self.attribute(project_module, "requirements"))
return self.module2target[project_module] | [
"def",
"target",
"(",
"self",
",",
"project_module",
")",
":",
"assert",
"isinstance",
"(",
"project_module",
",",
"basestring",
")",
"if",
"project_module",
"not",
"in",
"self",
".",
"module2target",
":",
"self",
".",
"module2target",
"[",
"project_module",
"]",
"=",
"b2",
".",
"build",
".",
"targets",
".",
"ProjectTarget",
"(",
"project_module",
",",
"project_module",
",",
"self",
".",
"attribute",
"(",
"project_module",
",",
"\"requirements\"",
")",
")",
"return",
"self",
".",
"module2target",
"[",
"project_module",
"]"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/project.py#L611-L619 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py | python | _pad_sequence_fix | (attr, kernel_dim=None) | return new_attr | Changing onnx's pads sequence to match with mxnet's pad_width
mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)
onnx: (x1_begin, x2_begin, ... , xn_end, xn_end) | Changing onnx's pads sequence to match with mxnet's pad_width
mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)
onnx: (x1_begin, x2_begin, ... , xn_end, xn_end) | [
"Changing",
"onnx",
"s",
"pads",
"sequence",
"to",
"match",
"with",
"mxnet",
"s",
"pad_width",
"mxnet",
":",
"(",
"x1_begin",
"x1_end",
"...",
"xn_begin",
"xn_end",
")",
"onnx",
":",
"(",
"x1_begin",
"x2_begin",
"...",
"xn_end",
"xn_end",
")"
] | def _pad_sequence_fix(attr, kernel_dim=None):
"""Changing onnx's pads sequence to match with mxnet's pad_width
mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)
onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)"""
new_attr = ()
if len(attr) % 2 == 0:
for index in range(int(len(attr) / 2)):
new_attr = new_attr + attr[index::int(len(attr) / 2)]
# Making sure pad values are in the attr for all axes.
if kernel_dim is not None:
while len(new_attr) < kernel_dim*2:
new_attr = new_attr + (0, 0)
return new_attr | [
"def",
"_pad_sequence_fix",
"(",
"attr",
",",
"kernel_dim",
"=",
"None",
")",
":",
"new_attr",
"=",
"(",
")",
"if",
"len",
"(",
"attr",
")",
"%",
"2",
"==",
"0",
":",
"for",
"index",
"in",
"range",
"(",
"int",
"(",
"len",
"(",
"attr",
")",
"/",
"2",
")",
")",
":",
"new_attr",
"=",
"new_attr",
"+",
"attr",
"[",
"index",
":",
":",
"int",
"(",
"len",
"(",
"attr",
")",
"/",
"2",
")",
"]",
"# Making sure pad values are in the attr for all axes.",
"if",
"kernel_dim",
"is",
"not",
"None",
":",
"while",
"len",
"(",
"new_attr",
")",
"<",
"kernel_dim",
"*",
"2",
":",
"new_attr",
"=",
"new_attr",
"+",
"(",
"0",
",",
"0",
")",
"return",
"new_attr"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py#L75-L88 | |
harfbuzz/harfbuzz | c4cf5ddb272cb1c05a572db5b76629368f9054f5 | src/gen-tag-table.py | python | OpenTypeRegistryParser.inherit_from_macrolanguages | (self) | Copy mappings from macrolanguages to individual languages.
If a BCP 47 tag for an individual mapping has no OpenType
mapping but its macrolanguage does, the mapping is copied to
the individual language. For example, als (Tosk Albanian) has no
explicit mapping, so it inherits from sq (Albanian) the mapping
to SQI.
However, if an OpenType tag maps to a BCP 47 macrolanguage and
some but not all of its individual languages, the mapping is not
inherited from the macrolanguage to the missing individual
languages. For example, INUK (Nunavik Inuktitut) is mapped to
ike (Eastern Canadian Inuktitut) and iu (Inuktitut) but not to
ikt (Inuinnaqtun, which is an individual language of iu), so
this method does not add a mapping from ikt to INUK.
If a BCP 47 tag for a macrolanguage has no OpenType mapping but
some of its individual languages do, their mappings are copied
to the macrolanguage. | Copy mappings from macrolanguages to individual languages. | [
"Copy",
"mappings",
"from",
"macrolanguages",
"to",
"individual",
"languages",
"."
] | def inherit_from_macrolanguages (self):
"""Copy mappings from macrolanguages to individual languages.
If a BCP 47 tag for an individual mapping has no OpenType
mapping but its macrolanguage does, the mapping is copied to
the individual language. For example, als (Tosk Albanian) has no
explicit mapping, so it inherits from sq (Albanian) the mapping
to SQI.
However, if an OpenType tag maps to a BCP 47 macrolanguage and
some but not all of its individual languages, the mapping is not
inherited from the macrolanguage to the missing individual
languages. For example, INUK (Nunavik Inuktitut) is mapped to
ike (Eastern Canadian Inuktitut) and iu (Inuktitut) but not to
ikt (Inuinnaqtun, which is an individual language of iu), so
this method does not add a mapping from ikt to INUK.
If a BCP 47 tag for a macrolanguage has no OpenType mapping but
some of its individual languages do, their mappings are copied
to the macrolanguage.
"""
global bcp_47
first_time = self.from_bcp_47_uninherited is None
if first_time:
self.from_bcp_47_uninherited = dict (self.from_bcp_47)
for macrolanguage, languages in dict (bcp_47.macrolanguages).items ():
ot_macrolanguages = {
ot_macrolanguage for ot_macrolanguage in self.from_bcp_47_uninherited.get (macrolanguage, set ())
}
blocked_ot_macrolanguages = set ()
if 'retired code' not in bcp_47.scopes.get (macrolanguage, ''):
for ot_macrolanguage in ot_macrolanguages:
round_trip_macrolanguages = {
l for l in self.to_bcp_47[ot_macrolanguage]
if 'retired code' not in bcp_47.scopes.get (l, '')
}
round_trip_languages = {
l for l in languages
if 'retired code' not in bcp_47.scopes.get (l, '')
}
intersection = round_trip_macrolanguages & round_trip_languages
if intersection and intersection != round_trip_languages:
blocked_ot_macrolanguages.add (ot_macrolanguage)
if ot_macrolanguages:
for ot_macrolanguage in ot_macrolanguages:
if ot_macrolanguage not in blocked_ot_macrolanguages:
for language in languages:
self.add_language (language, ot_macrolanguage)
if not blocked_ot_macrolanguages:
self.ranks[ot_macrolanguage] += 1
elif first_time:
for language in languages:
if language in self.from_bcp_47_uninherited:
ot_macrolanguages |= self.from_bcp_47_uninherited[language]
else:
ot_macrolanguages.clear ()
if not ot_macrolanguages:
break
for ot_macrolanguage in ot_macrolanguages:
self.add_language (macrolanguage, ot_macrolanguage) | [
"def",
"inherit_from_macrolanguages",
"(",
"self",
")",
":",
"global",
"bcp_47",
"first_time",
"=",
"self",
".",
"from_bcp_47_uninherited",
"is",
"None",
"if",
"first_time",
":",
"self",
".",
"from_bcp_47_uninherited",
"=",
"dict",
"(",
"self",
".",
"from_bcp_47",
")",
"for",
"macrolanguage",
",",
"languages",
"in",
"dict",
"(",
"bcp_47",
".",
"macrolanguages",
")",
".",
"items",
"(",
")",
":",
"ot_macrolanguages",
"=",
"{",
"ot_macrolanguage",
"for",
"ot_macrolanguage",
"in",
"self",
".",
"from_bcp_47_uninherited",
".",
"get",
"(",
"macrolanguage",
",",
"set",
"(",
")",
")",
"}",
"blocked_ot_macrolanguages",
"=",
"set",
"(",
")",
"if",
"'retired code'",
"not",
"in",
"bcp_47",
".",
"scopes",
".",
"get",
"(",
"macrolanguage",
",",
"''",
")",
":",
"for",
"ot_macrolanguage",
"in",
"ot_macrolanguages",
":",
"round_trip_macrolanguages",
"=",
"{",
"l",
"for",
"l",
"in",
"self",
".",
"to_bcp_47",
"[",
"ot_macrolanguage",
"]",
"if",
"'retired code'",
"not",
"in",
"bcp_47",
".",
"scopes",
".",
"get",
"(",
"l",
",",
"''",
")",
"}",
"round_trip_languages",
"=",
"{",
"l",
"for",
"l",
"in",
"languages",
"if",
"'retired code'",
"not",
"in",
"bcp_47",
".",
"scopes",
".",
"get",
"(",
"l",
",",
"''",
")",
"}",
"intersection",
"=",
"round_trip_macrolanguages",
"&",
"round_trip_languages",
"if",
"intersection",
"and",
"intersection",
"!=",
"round_trip_languages",
":",
"blocked_ot_macrolanguages",
".",
"add",
"(",
"ot_macrolanguage",
")",
"if",
"ot_macrolanguages",
":",
"for",
"ot_macrolanguage",
"in",
"ot_macrolanguages",
":",
"if",
"ot_macrolanguage",
"not",
"in",
"blocked_ot_macrolanguages",
":",
"for",
"language",
"in",
"languages",
":",
"self",
".",
"add_language",
"(",
"language",
",",
"ot_macrolanguage",
")",
"if",
"not",
"blocked_ot_macrolanguages",
":",
"self",
".",
"ranks",
"[",
"ot_macrolanguage",
"]",
"+=",
"1",
"elif",
"first_time",
":",
"for",
"language",
"in",
"languages",
":",
"if",
"language",
"in",
"self",
".",
"from_bcp_47_uninherited",
":",
"ot_macrolanguages",
"|=",
"self",
".",
"from_bcp_47_uninherited",
"[",
"language",
"]",
"else",
":",
"ot_macrolanguages",
".",
"clear",
"(",
")",
"if",
"not",
"ot_macrolanguages",
":",
"break",
"for",
"ot_macrolanguage",
"in",
"ot_macrolanguages",
":",
"self",
".",
"add_language",
"(",
"macrolanguage",
",",
"ot_macrolanguage",
")"
] | https://github.com/harfbuzz/harfbuzz/blob/c4cf5ddb272cb1c05a572db5b76629368f9054f5/src/gen-tag-table.py#L461-L520 | ||
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/commands.py | python | try_cythonize | (extensions, linetracing=False, mandatory=True) | return Cython.Build.cythonize(
extensions,
include_path=[
include_dir for extension in extensions
for include_dir in extension.include_dirs
] + [CYTHON_STEM],
compiler_directives=cython_compiler_directives) | Attempt to cythonize the extensions.
Args:
extensions: A list of `distutils.extension.Extension`.
linetracing: A bool indicating whether or not to enable linetracing.
mandatory: Whether or not having Cython-generated files is mandatory. If it
is, extensions will be poisoned when they can't be fully generated. | Attempt to cythonize the extensions. | [
"Attempt",
"to",
"cythonize",
"the",
"extensions",
"."
] | def try_cythonize(extensions, linetracing=False, mandatory=True):
"""Attempt to cythonize the extensions.
Args:
extensions: A list of `distutils.extension.Extension`.
linetracing: A bool indicating whether or not to enable linetracing.
mandatory: Whether or not having Cython-generated files is mandatory. If it
is, extensions will be poisoned when they can't be fully generated.
"""
try:
# Break import style to ensure we have access to Cython post-setup_requires
import Cython.Build
except ImportError:
if mandatory:
sys.stderr.write(
"This package needs to generate C files with Cython but it cannot. "
"Poisoning extension sources to disallow extension commands...")
_poison_extensions(
extensions,
"Extensions have been poisoned due to missing Cython-generated code."
)
return extensions
cython_compiler_directives = {}
if linetracing:
additional_define_macros = [('CYTHON_TRACE_NOGIL', '1')]
cython_compiler_directives['linetrace'] = True
return Cython.Build.cythonize(
extensions,
include_path=[
include_dir for extension in extensions
for include_dir in extension.include_dirs
] + [CYTHON_STEM],
compiler_directives=cython_compiler_directives) | [
"def",
"try_cythonize",
"(",
"extensions",
",",
"linetracing",
"=",
"False",
",",
"mandatory",
"=",
"True",
")",
":",
"try",
":",
"# Break import style to ensure we have access to Cython post-setup_requires",
"import",
"Cython",
".",
"Build",
"except",
"ImportError",
":",
"if",
"mandatory",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"This package needs to generate C files with Cython but it cannot. \"",
"\"Poisoning extension sources to disallow extension commands...\"",
")",
"_poison_extensions",
"(",
"extensions",
",",
"\"Extensions have been poisoned due to missing Cython-generated code.\"",
")",
"return",
"extensions",
"cython_compiler_directives",
"=",
"{",
"}",
"if",
"linetracing",
":",
"additional_define_macros",
"=",
"[",
"(",
"'CYTHON_TRACE_NOGIL'",
",",
"'1'",
")",
"]",
"cython_compiler_directives",
"[",
"'linetrace'",
"]",
"=",
"True",
"return",
"Cython",
".",
"Build",
".",
"cythonize",
"(",
"extensions",
",",
"include_path",
"=",
"[",
"include_dir",
"for",
"extension",
"in",
"extensions",
"for",
"include_dir",
"in",
"extension",
".",
"include_dirs",
"]",
"+",
"[",
"CYTHON_STEM",
"]",
",",
"compiler_directives",
"=",
"cython_compiler_directives",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/commands.py#L165-L197 | |
google/sling | f408a148a06bc2d62e853a292a8ba7266c642839 | python/myelin/tf.py | python | attr_str | (value) | Convert attribute to string value. | Convert attribute to string value. | [
"Convert",
"attribute",
"to",
"string",
"value",
"."
] | def attr_str(value):
""" Convert attribute to string value."""
if isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, int):
return str(value)
elif isinstance(value, long):
return str(value)
elif isinstance(value, str):
return value
elif isinstance(value, list):
l = []
for v in value: l.append(attr_str(v))
return ",".join(l)
elif value.__class__.__name__ == "TensorShapeProto":
dims = []
for d in value.dim: dims.append(str(d.size))
return "x".join(dims)
elif value.__class__.__name__ == "TensorProto":
return str(value)
elif value.__class__.__name__ == "DType":
return value.name
else:
return str(type(value)) + ":" + str(value).replace('\n', ' ') | [
"def",
"attr_str",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"\"true\"",
"if",
"value",
"else",
"\"false\"",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"long",
")",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"l",
"=",
"[",
"]",
"for",
"v",
"in",
"value",
":",
"l",
".",
"append",
"(",
"attr_str",
"(",
"v",
")",
")",
"return",
"\",\"",
".",
"join",
"(",
"l",
")",
"elif",
"value",
".",
"__class__",
".",
"__name__",
"==",
"\"TensorShapeProto\"",
":",
"dims",
"=",
"[",
"]",
"for",
"d",
"in",
"value",
".",
"dim",
":",
"dims",
".",
"append",
"(",
"str",
"(",
"d",
".",
"size",
")",
")",
"return",
"\"x\"",
".",
"join",
"(",
"dims",
")",
"elif",
"value",
".",
"__class__",
".",
"__name__",
"==",
"\"TensorProto\"",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"value",
".",
"__class__",
".",
"__name__",
"==",
"\"DType\"",
":",
"return",
"value",
".",
"name",
"else",
":",
"return",
"str",
"(",
"type",
"(",
"value",
")",
")",
"+",
"\":\"",
"+",
"str",
"(",
"value",
")",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")"
] | https://github.com/google/sling/blob/f408a148a06bc2d62e853a292a8ba7266c642839/python/myelin/tf.py#L16-L39 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | IKObjective.setFreePosConstraint | (self) | return _robotsim.IKObjective_setFreePosConstraint(self) | r"""
setFreePosConstraint(IKObjective self)
Manual: Sets a free position constraint. | r"""
setFreePosConstraint(IKObjective self) | [
"r",
"setFreePosConstraint",
"(",
"IKObjective",
"self",
")"
] | def setFreePosConstraint(self) -> "void":
r"""
setFreePosConstraint(IKObjective self)
Manual: Sets a free position constraint.
"""
return _robotsim.IKObjective_setFreePosConstraint(self) | [
"def",
"setFreePosConstraint",
"(",
"self",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"IKObjective_setFreePosConstraint",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L6416-L6424 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/ext.py | python | InternationalizationExtension._make_node | (
self,
singular: str,
plural: t.Optional[str],
variables: t.Dict[str, nodes.Expr],
plural_expr: t.Optional[nodes.Expr],
vars_referenced: bool,
num_called_num: bool,
) | return nodes.Output([node]) | Generates a useful node from the data provided. | Generates a useful node from the data provided. | [
"Generates",
"a",
"useful",
"node",
"from",
"the",
"data",
"provided",
"."
] | def _make_node(
self,
singular: str,
plural: t.Optional[str],
variables: t.Dict[str, nodes.Expr],
plural_expr: t.Optional[nodes.Expr],
vars_referenced: bool,
num_called_num: bool,
) -> nodes.Output:
"""Generates a useful node from the data provided."""
newstyle = self.environment.newstyle_gettext # type: ignore
node: nodes.Expr
# no variables referenced? no need to escape for old style
# gettext invocations only if there are vars.
if not vars_referenced and not newstyle:
singular = singular.replace("%%", "%")
if plural:
plural = plural.replace("%%", "%")
# singular only:
if plural_expr is None:
gettext = nodes.Name("gettext", "load")
node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None)
# singular and plural
else:
ngettext = nodes.Name("ngettext", "load")
node = nodes.Call(
ngettext,
[nodes.Const(singular), nodes.Const(plural), plural_expr],
[],
None,
None,
)
# in case newstyle gettext is used, the method is powerful
# enough to handle the variable expansion and autoescape
# handling itself
if newstyle:
for key, value in variables.items():
# the function adds that later anyways in case num was
# called num, so just skip it.
if num_called_num and key == "num":
continue
node.kwargs.append(nodes.Keyword(key, value))
# otherwise do that here
else:
# mark the return value as safe if we are in an
# environment with autoescaping turned on
node = nodes.MarkSafeIfAutoescape(node)
if variables:
node = nodes.Mod(
node,
nodes.Dict(
[
nodes.Pair(nodes.Const(key), value)
for key, value in variables.items()
]
),
)
return nodes.Output([node]) | [
"def",
"_make_node",
"(",
"self",
",",
"singular",
":",
"str",
",",
"plural",
":",
"t",
".",
"Optional",
"[",
"str",
"]",
",",
"variables",
":",
"t",
".",
"Dict",
"[",
"str",
",",
"nodes",
".",
"Expr",
"]",
",",
"plural_expr",
":",
"t",
".",
"Optional",
"[",
"nodes",
".",
"Expr",
"]",
",",
"vars_referenced",
":",
"bool",
",",
"num_called_num",
":",
"bool",
",",
")",
"->",
"nodes",
".",
"Output",
":",
"newstyle",
"=",
"self",
".",
"environment",
".",
"newstyle_gettext",
"# type: ignore",
"node",
":",
"nodes",
".",
"Expr",
"# no variables referenced? no need to escape for old style",
"# gettext invocations only if there are vars.",
"if",
"not",
"vars_referenced",
"and",
"not",
"newstyle",
":",
"singular",
"=",
"singular",
".",
"replace",
"(",
"\"%%\"",
",",
"\"%\"",
")",
"if",
"plural",
":",
"plural",
"=",
"plural",
".",
"replace",
"(",
"\"%%\"",
",",
"\"%\"",
")",
"# singular only:",
"if",
"plural_expr",
"is",
"None",
":",
"gettext",
"=",
"nodes",
".",
"Name",
"(",
"\"gettext\"",
",",
"\"load\"",
")",
"node",
"=",
"nodes",
".",
"Call",
"(",
"gettext",
",",
"[",
"nodes",
".",
"Const",
"(",
"singular",
")",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")",
"# singular and plural",
"else",
":",
"ngettext",
"=",
"nodes",
".",
"Name",
"(",
"\"ngettext\"",
",",
"\"load\"",
")",
"node",
"=",
"nodes",
".",
"Call",
"(",
"ngettext",
",",
"[",
"nodes",
".",
"Const",
"(",
"singular",
")",
",",
"nodes",
".",
"Const",
"(",
"plural",
")",
",",
"plural_expr",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
",",
")",
"# in case newstyle gettext is used, the method is powerful",
"# enough to handle the variable expansion and autoescape",
"# handling itself",
"if",
"newstyle",
":",
"for",
"key",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
":",
"# the function adds that later anyways in case num was",
"# called num, so just skip it.",
"if",
"num_called_num",
"and",
"key",
"==",
"\"num\"",
":",
"continue",
"node",
".",
"kwargs",
".",
"append",
"(",
"nodes",
".",
"Keyword",
"(",
"key",
",",
"value",
")",
")",
"# otherwise do that here",
"else",
":",
"# mark the return value as safe if we are in an",
"# environment with autoescaping turned on",
"node",
"=",
"nodes",
".",
"MarkSafeIfAutoescape",
"(",
"node",
")",
"if",
"variables",
":",
"node",
"=",
"nodes",
".",
"Mod",
"(",
"node",
",",
"nodes",
".",
"Dict",
"(",
"[",
"nodes",
".",
"Pair",
"(",
"nodes",
".",
"Const",
"(",
"key",
")",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
"]",
")",
",",
")",
"return",
"nodes",
".",
"Output",
"(",
"[",
"node",
"]",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/ext.py#L510-L572 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/plugins/filebrowser/filebrowser/browser.py | python | FileBrowser2.OnCompareItems | (self, item1, item2) | Handle SortItems | Handle SortItems | [
"Handle",
"SortItems"
] | def OnCompareItems(self, item1, item2):
"""Handle SortItems"""
data = self.GetPyData(item1)
if data is not None:
path1 = int(not os.path.isdir(data))
else:
path1 = 0
tup1 = (path1, data.lower())
data2 = self.GetPyData(item2)
if data2 is not None:
path2 = int(not os.path.isdir(data2))
else:
path2 = 0
tup2 = (path2, data2.lower())
if tup1 < tup2:
return -1
elif tup1 == tup2:
return 0
else:
return 1 | [
"def",
"OnCompareItems",
"(",
"self",
",",
"item1",
",",
"item2",
")",
":",
"data",
"=",
"self",
".",
"GetPyData",
"(",
"item1",
")",
"if",
"data",
"is",
"not",
"None",
":",
"path1",
"=",
"int",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"data",
")",
")",
"else",
":",
"path1",
"=",
"0",
"tup1",
"=",
"(",
"path1",
",",
"data",
".",
"lower",
"(",
")",
")",
"data2",
"=",
"self",
".",
"GetPyData",
"(",
"item2",
")",
"if",
"data2",
"is",
"not",
"None",
":",
"path2",
"=",
"int",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"data2",
")",
")",
"else",
":",
"path2",
"=",
"0",
"tup2",
"=",
"(",
"path2",
",",
"data2",
".",
"lower",
"(",
")",
")",
"if",
"tup1",
"<",
"tup2",
":",
"return",
"-",
"1",
"elif",
"tup1",
"==",
"tup2",
":",
"return",
"0",
"else",
":",
"return",
"1"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/filebrowser/filebrowser/browser.py#L736-L757 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/sliceshell.py | python | SlicesShell.about | (self) | Display information about Py. | Display information about Py. | [
"Display",
"information",
"about",
"Py",
"."
] | def about(self):
"""Display information about Py."""
text = DISPLAY_TEXT % \
(__author__, VERSION, self.revision, self.interp.revision,
sys.version.split()[0], wx.VERSION_STRING, str(wx.PlatformInfo),
sys.platform)
self.write(text.strip(),type='Output') | [
"def",
"about",
"(",
"self",
")",
":",
"text",
"=",
"DISPLAY_TEXT",
"%",
"(",
"__author__",
",",
"VERSION",
",",
"self",
".",
"revision",
",",
"self",
".",
"interp",
".",
"revision",
",",
"sys",
".",
"version",
".",
"split",
"(",
")",
"[",
"0",
"]",
",",
"wx",
".",
"VERSION_STRING",
",",
"str",
"(",
"wx",
".",
"PlatformInfo",
")",
",",
"sys",
".",
"platform",
")",
"self",
".",
"write",
"(",
"text",
".",
"strip",
"(",
")",
",",
"type",
"=",
"'Output'",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/sliceshell.py#L1006-L1012 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/onnx2mx/_op_translations.py | python | maximum | (attrs, inputs, proto_obj) | return mxnet_op, attrs, inputs | Elementwise maximum of arrays.
MXNet maximum compares only two symbols at a time.
ONNX can send more than two to compare.
Breaking into multiple mxnet ops to compare two symbols at a time | Elementwise maximum of arrays.
MXNet maximum compares only two symbols at a time.
ONNX can send more than two to compare.
Breaking into multiple mxnet ops to compare two symbols at a time | [
"Elementwise",
"maximum",
"of",
"arrays",
".",
"MXNet",
"maximum",
"compares",
"only",
"two",
"symbols",
"at",
"a",
"time",
".",
"ONNX",
"can",
"send",
"more",
"than",
"two",
"to",
"compare",
".",
"Breaking",
"into",
"multiple",
"mxnet",
"ops",
"to",
"compare",
"two",
"symbols",
"at",
"a",
"time"
] | def maximum(attrs, inputs, proto_obj):
"""
Elementwise maximum of arrays.
MXNet maximum compares only two symbols at a time.
ONNX can send more than two to compare.
Breaking into multiple mxnet ops to compare two symbols at a time
"""
if len(inputs) > 1:
mxnet_op = symbol.maximum(inputs[0], inputs[1])
for op_input in inputs[2:]:
mxnet_op = symbol.maximum(mxnet_op, op_input)
else:
mxnet_op = symbol.maximum(inputs[0], inputs[0])
return mxnet_op, attrs, inputs | [
"def",
"maximum",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"if",
"len",
"(",
"inputs",
")",
">",
"1",
":",
"mxnet_op",
"=",
"symbol",
".",
"maximum",
"(",
"inputs",
"[",
"0",
"]",
",",
"inputs",
"[",
"1",
"]",
")",
"for",
"op_input",
"in",
"inputs",
"[",
"2",
":",
"]",
":",
"mxnet_op",
"=",
"symbol",
".",
"maximum",
"(",
"mxnet_op",
",",
"op_input",
")",
"else",
":",
"mxnet_op",
"=",
"symbol",
".",
"maximum",
"(",
"inputs",
"[",
"0",
"]",
",",
"inputs",
"[",
"0",
"]",
")",
"return",
"mxnet_op",
",",
"attrs",
",",
"inputs"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L164-L177 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py | python | find_files | (filenames, recursive, exclude) | Yield filenames. | Yield filenames. | [
"Yield",
"filenames",
"."
] | def find_files(filenames, recursive, exclude):
"""Yield filenames."""
while filenames:
name = filenames.pop(0)
if recursive and os.path.isdir(name):
for root, directories, children in os.walk(name):
filenames += [os.path.join(root, f) for f in children
if match_file(os.path.join(root, f),
exclude)]
directories[:] = [d for d in directories
if match_file(os.path.join(root, d),
exclude)]
else:
yield name | [
"def",
"find_files",
"(",
"filenames",
",",
"recursive",
",",
"exclude",
")",
":",
"while",
"filenames",
":",
"name",
"=",
"filenames",
".",
"pop",
"(",
"0",
")",
"if",
"recursive",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"name",
")",
":",
"for",
"root",
",",
"directories",
",",
"children",
"in",
"os",
".",
"walk",
"(",
"name",
")",
":",
"filenames",
"+=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"for",
"f",
"in",
"children",
"if",
"match_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
",",
"exclude",
")",
"]",
"directories",
"[",
":",
"]",
"=",
"[",
"d",
"for",
"d",
"in",
"directories",
"if",
"match_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"d",
")",
",",
"exclude",
")",
"]",
"else",
":",
"yield",
"name"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L3527-L3540 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/msw/gizmos.py | python | RemotelyScrolledTreeCtrl.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=TR_HAS_BUTTONS) -> RemotelyScrolledTreeCtrl | __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=TR_HAS_BUTTONS) -> RemotelyScrolledTreeCtrl | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"TR_HAS_BUTTONS",
")",
"-",
">",
"RemotelyScrolledTreeCtrl"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
long style=TR_HAS_BUTTONS) -> RemotelyScrolledTreeCtrl
"""
_gizmos.RemotelyScrolledTreeCtrl_swiginit(self,_gizmos.new_RemotelyScrolledTreeCtrl(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gizmos",
".",
"RemotelyScrolledTreeCtrl_swiginit",
"(",
"self",
",",
"_gizmos",
".",
"new_RemotelyScrolledTreeCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/msw/gizmos.py#L205-L211 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sarray.py | python | SArray.contains | (self, item) | return SArray(_proxy = self.__proxy__.left_scalar_operator(item, 'in')) | Performs an element-wise search of "item" in the SArray.
Conceptually equivalent to:
>>> sa.apply(lambda x: item in x)
If the current SArray contains strings and item is a string. Produces a 1
for each row if 'item' is a substring of the row and 0 otherwise.
If the current SArray contains list or arrays, this produces a 1
for each row if 'item' is an element of the list or array.
If the current SArray contains dictionaries, this produces a 1
for each row if 'item' is a key in the dictionary.
Parameters
----------
item : any type
The item to search for.
Returns
-------
out : SArray
A binary SArray where a non-zero value denotes that the item
was found in the row. And 0 if it is not found.
Examples
--------
>>> SArray(['abc','def','ghi']).contains('a')
dtype: int
Rows: 3
[1, 0, 0]
>>> SArray([['a','b'],['b','c'],['c','d']]).contains('b')
dtype: int
Rows: 3
[1, 1, 0]
>>> SArray([{'a':1},{'a':2,'b':1}, {'c':1}]).contains('a')
dtype: int
Rows: 3
[1, 1, 0]
See Also
--------
is_in | Performs an element-wise search of "item" in the SArray. | [
"Performs",
"an",
"element",
"-",
"wise",
"search",
"of",
"item",
"in",
"the",
"SArray",
"."
] | def contains(self, item):
"""
Performs an element-wise search of "item" in the SArray.
Conceptually equivalent to:
>>> sa.apply(lambda x: item in x)
If the current SArray contains strings and item is a string. Produces a 1
for each row if 'item' is a substring of the row and 0 otherwise.
If the current SArray contains list or arrays, this produces a 1
for each row if 'item' is an element of the list or array.
If the current SArray contains dictionaries, this produces a 1
for each row if 'item' is a key in the dictionary.
Parameters
----------
item : any type
The item to search for.
Returns
-------
out : SArray
A binary SArray where a non-zero value denotes that the item
was found in the row. And 0 if it is not found.
Examples
--------
>>> SArray(['abc','def','ghi']).contains('a')
dtype: int
Rows: 3
[1, 0, 0]
>>> SArray([['a','b'],['b','c'],['c','d']]).contains('b')
dtype: int
Rows: 3
[1, 1, 0]
>>> SArray([{'a':1},{'a':2,'b':1}, {'c':1}]).contains('a')
dtype: int
Rows: 3
[1, 1, 0]
See Also
--------
is_in
"""
return SArray(_proxy = self.__proxy__.left_scalar_operator(item, 'in')) | [
"def",
"contains",
"(",
"self",
",",
"item",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"left_scalar_operator",
"(",
"item",
",",
"'in'",
")",
")"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L818-L865 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridInterface.GetPropertyParent | (*args, **kwargs) | return _propgrid.PropertyGridInterface_GetPropertyParent(*args, **kwargs) | GetPropertyParent(self, PGPropArg id) -> PGProperty | GetPropertyParent(self, PGPropArg id) -> PGProperty | [
"GetPropertyParent",
"(",
"self",
"PGPropArg",
"id",
")",
"-",
">",
"PGProperty"
] | def GetPropertyParent(*args, **kwargs):
"""GetPropertyParent(self, PGPropArg id) -> PGProperty"""
return _propgrid.PropertyGridInterface_GetPropertyParent(*args, **kwargs) | [
"def",
"GetPropertyParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_GetPropertyParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1237-L1239 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/web.py | python | RequestHandler.decode_argument | (self, value: bytes, name: Optional[str] = None) | Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string.
By default, this method decodes the argument as utf-8 and returns
a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both `get_argument()` and for
values extracted from the url and passed to `get()`/`post()`/etc.
The name of the argument is provided if known, but may be None
(e.g. for unnamed groups in the url regex). | Decodes an argument from the request. | [
"Decodes",
"an",
"argument",
"from",
"the",
"request",
"."
] | def decode_argument(self, value: bytes, name: Optional[str] = None) -> str:
"""Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string.
By default, this method decodes the argument as utf-8 and returns
a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both `get_argument()` and for
values extracted from the url and passed to `get()`/`post()`/etc.
The name of the argument is provided if known, but may be None
(e.g. for unnamed groups in the url regex).
"""
try:
return _unicode(value)
except UnicodeDecodeError:
raise HTTPError(
400, "Invalid unicode in %s: %r" % (name or "url", value[:40])
) | [
"def",
"decode_argument",
"(",
"self",
",",
"value",
":",
"bytes",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"try",
":",
"return",
"_unicode",
"(",
"value",
")",
"except",
"UnicodeDecodeError",
":",
"raise",
"HTTPError",
"(",
"400",
",",
"\"Invalid unicode in %s: %r\"",
"%",
"(",
"name",
"or",
"\"url\"",
",",
"value",
"[",
":",
"40",
"]",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/web.py#L557-L575 | ||
mickem/nscp | 79f89fdbb6da63f91bc9dedb7aea202fe938f237 | scripts/python/lib/google/protobuf/internal/decoder.py | python | _SkipFixed32 | (buffer, pos, end) | return pos | Skip a fixed32 value. Returns the new position. | Skip a fixed32 value. Returns the new position. | [
"Skip",
"a",
"fixed32",
"value",
".",
"Returns",
"the",
"new",
"position",
"."
] | def _SkipFixed32(buffer, pos, end):
"""Skip a fixed32 value. Returns the new position."""
pos += 4
if pos > end:
raise _DecodeError('Truncated message.')
return pos | [
"def",
"_SkipFixed32",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"pos",
"+=",
"4",
"if",
"pos",
">",
"end",
":",
"raise",
"_DecodeError",
"(",
"'Truncated message.'",
")",
"return",
"pos"
] | https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/decoder.py#L668-L674 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/autograd.py | python | BinaryCrossEntropy.forward | (self, x) | return loss | Args:
x (CTensor): 1d or 2d tensor, the prediction data(output)
of current network.
t (CTensor): 1d or 2d tensor, the target data for training.
Returns:
loss (CTensor): scalar. | Args:
x (CTensor): 1d or 2d tensor, the prediction data(output)
of current network.
t (CTensor): 1d or 2d tensor, the target data for training.
Returns:
loss (CTensor): scalar. | [
"Args",
":",
"x",
"(",
"CTensor",
")",
":",
"1d",
"or",
"2d",
"tensor",
"the",
"prediction",
"data",
"(",
"output",
")",
"of",
"current",
"network",
".",
"t",
"(",
"CTensor",
")",
":",
"1d",
"or",
"2d",
"tensor",
"the",
"target",
"data",
"for",
"training",
".",
"Returns",
":",
"loss",
"(",
"CTensor",
")",
":",
"scalar",
"."
] | def forward(self, x):
"""
Args:
x (CTensor): 1d or 2d tensor, the prediction data(output)
of current network.
t (CTensor): 1d or 2d tensor, the target data for training.
Returns:
loss (CTensor): scalar.
"""
posx = singa.AddFloat(x, 0.0001)
loss = singa.SumAll(singa.__mul__(self.t, singa.Log(posx)))
negt = singa.AddFloat(singa.MultFloat(self.t, -1.0), 1.0)
negx = singa.AddFloat(singa.MultFloat(x, -1.0), 1.0001)
negLoss = singa.SumAll(singa.__mul__(negt, singa.Log(negx)))
loss += negLoss
loss /= -x.shape()[0]
self.x = singa.AddFloat(x, 0.0001)
return loss | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"posx",
"=",
"singa",
".",
"AddFloat",
"(",
"x",
",",
"0.0001",
")",
"loss",
"=",
"singa",
".",
"SumAll",
"(",
"singa",
".",
"__mul__",
"(",
"self",
".",
"t",
",",
"singa",
".",
"Log",
"(",
"posx",
")",
")",
")",
"negt",
"=",
"singa",
".",
"AddFloat",
"(",
"singa",
".",
"MultFloat",
"(",
"self",
".",
"t",
",",
"-",
"1.0",
")",
",",
"1.0",
")",
"negx",
"=",
"singa",
".",
"AddFloat",
"(",
"singa",
".",
"MultFloat",
"(",
"x",
",",
"-",
"1.0",
")",
",",
"1.0001",
")",
"negLoss",
"=",
"singa",
".",
"SumAll",
"(",
"singa",
".",
"__mul__",
"(",
"negt",
",",
"singa",
".",
"Log",
"(",
"negx",
")",
")",
")",
"loss",
"+=",
"negLoss",
"loss",
"/=",
"-",
"x",
".",
"shape",
"(",
")",
"[",
"0",
"]",
"self",
".",
"x",
"=",
"singa",
".",
"AddFloat",
"(",
"x",
",",
"0.0001",
")",
"return",
"loss"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L1165-L1182 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiDefaultDockArt.__init__ | (self, *args, **kwargs) | __init__(self) -> AuiDefaultDockArt | __init__(self) -> AuiDefaultDockArt | [
"__init__",
"(",
"self",
")",
"-",
">",
"AuiDefaultDockArt"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> AuiDefaultDockArt"""
_aui.AuiDefaultDockArt_swiginit(self,_aui.new_AuiDefaultDockArt(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_aui",
".",
"AuiDefaultDockArt_swiginit",
"(",
"self",
",",
"_aui",
".",
"new_AuiDefaultDockArt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1031-L1033 | ||
ValveSoftware/source-sdk-2013 | 0d8dceea4310fde5706b3ce1c70609d72a38efdf | mp/src/thirdparty/protobuf-2.3.0/python/mox.py | python | MockObject.__setitem__ | (self, key, value) | return self._CreateMockMethod('__setitem__')(key, value) | Provide custom logic for mocking classes that support item assignment.
Args:
key: Key to set the value for.
value: Value to set.
Returns:
Expected return value in replay mode. A MockMethod object for the
__setitem__ method that has already been called if not in replay mode.
Raises:
TypeError if the underlying class does not support item assignment.
UnexpectedMethodCallError if the object does not expect the call to
__setitem__. | Provide custom logic for mocking classes that support item assignment. | [
"Provide",
"custom",
"logic",
"for",
"mocking",
"classes",
"that",
"support",
"item",
"assignment",
"."
] | def __setitem__(self, key, value):
"""Provide custom logic for mocking classes that support item assignment.
Args:
key: Key to set the value for.
value: Value to set.
Returns:
Expected return value in replay mode. A MockMethod object for the
__setitem__ method that has already been called if not in replay mode.
Raises:
TypeError if the underlying class does not support item assignment.
UnexpectedMethodCallError if the object does not expect the call to
__setitem__.
"""
setitem = self._class_to_mock.__dict__.get('__setitem__', None)
# Verify the class supports item assignment.
if setitem is None:
raise TypeError('object does not support item assignment')
# If we are in replay mode then simply call the mock __setitem__ method.
if self._replay_mode:
return MockMethod('__setitem__', self._expected_calls_queue,
self._replay_mode)(key, value)
# Otherwise, create a mock method __setitem__.
return self._CreateMockMethod('__setitem__')(key, value) | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"setitem",
"=",
"self",
".",
"_class_to_mock",
".",
"__dict__",
".",
"get",
"(",
"'__setitem__'",
",",
"None",
")",
"# Verify the class supports item assignment.",
"if",
"setitem",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'object does not support item assignment'",
")",
"# If we are in replay mode then simply call the mock __setitem__ method.",
"if",
"self",
".",
"_replay_mode",
":",
"return",
"MockMethod",
"(",
"'__setitem__'",
",",
"self",
".",
"_expected_calls_queue",
",",
"self",
".",
"_replay_mode",
")",
"(",
"key",
",",
"value",
")",
"# Otherwise, create a mock method __setitem__.",
"return",
"self",
".",
"_CreateMockMethod",
"(",
"'__setitem__'",
")",
"(",
"key",
",",
"value",
")"
] | https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/mox.py#L427-L457 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | GraphicsContext.EndDoc | (*args, **kwargs) | return _gdi_.GraphicsContext_EndDoc(*args, **kwargs) | EndDoc(self)
Done with that document (relevant only for printing / pdf etc) | EndDoc(self) | [
"EndDoc",
"(",
"self",
")"
] | def EndDoc(*args, **kwargs):
"""
EndDoc(self)
Done with that document (relevant only for printing / pdf etc)
"""
return _gdi_.GraphicsContext_EndDoc(*args, **kwargs) | [
"def",
"EndDoc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsContext_EndDoc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L6038-L6044 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/contrib/layers/metric_op.py | python | ctr_metric_bundle | (input, label) | return local_sqrerr, local_abserr, local_prob, local_q, local_pos_num, local_ins_num | ctr related metric layer
This function help compute the ctr related metrics: RMSE, MAE, predicted_ctr, q_value.
To compute the final values of these metrics, we should do following computations using
total instance number:
MAE = local_abserr / instance number
RMSE = sqrt(local_sqrerr / instance number)
predicted_ctr = local_prob / instance number
q = local_q / instance number
Note that if you are doing distribute job, you should all reduce these metrics and instance
number first
Args:
input(Variable): A floating-point 2D Variable, values are in the range
[0, 1]. Each row is sorted in descending order. This
input should be the output of topk. Typically, this
Variable indicates the probability of each label.
label(Variable): A 2D int Variable indicating the label of the training
data. The height is batch size and width is always 1.
Returns:
local_sqrerr(Variable): Local sum of squared error
local_abserr(Variable): Local sum of abs error
local_prob(Variable): Local sum of predicted ctr
local_q(Variable): Local sum of q value
Examples:
.. code-block:: python
import paddle.fluid as fluid
data = fluid.layers.data(name="data", shape=[32, 32], dtype="float32")
label = fluid.layers.data(name="label", shape=[1], dtype="int32")
predict = fluid.layers.sigmoid(fluid.layers.fc(input=data, size=1))
auc_out = fluid.contrib.layers.ctr_metric_bundle(input=predict, label=label) | ctr related metric layer | [
"ctr",
"related",
"metric",
"layer"
] | def ctr_metric_bundle(input, label):
"""
ctr related metric layer
This function help compute the ctr related metrics: RMSE, MAE, predicted_ctr, q_value.
To compute the final values of these metrics, we should do following computations using
total instance number:
MAE = local_abserr / instance number
RMSE = sqrt(local_sqrerr / instance number)
predicted_ctr = local_prob / instance number
q = local_q / instance number
Note that if you are doing distribute job, you should all reduce these metrics and instance
number first
Args:
input(Variable): A floating-point 2D Variable, values are in the range
[0, 1]. Each row is sorted in descending order. This
input should be the output of topk. Typically, this
Variable indicates the probability of each label.
label(Variable): A 2D int Variable indicating the label of the training
data. The height is batch size and width is always 1.
Returns:
local_sqrerr(Variable): Local sum of squared error
local_abserr(Variable): Local sum of abs error
local_prob(Variable): Local sum of predicted ctr
local_q(Variable): Local sum of q value
Examples:
.. code-block:: python
import paddle.fluid as fluid
data = fluid.layers.data(name="data", shape=[32, 32], dtype="float32")
label = fluid.layers.data(name="label", shape=[1], dtype="int32")
predict = fluid.layers.sigmoid(fluid.layers.fc(input=data, size=1))
auc_out = fluid.contrib.layers.ctr_metric_bundle(input=predict, label=label)
"""
assert input.shape == label.shape
helper = LayerHelper("ctr_metric_bundle", **locals())
local_abserr = helper.create_global_variable(
persistable=True, dtype='float32', shape=[1])
local_sqrerr = helper.create_global_variable(
persistable=True, dtype='float32', shape=[1])
local_prob = helper.create_global_variable(
persistable=True, dtype='float32', shape=[1])
local_q = helper.create_global_variable(
persistable=True, dtype='float32', shape=[1])
local_pos_num = helper.create_global_variable(
persistable=True, dtype='float32', shape=[1])
local_ins_num = helper.create_global_variable(
persistable=True, dtype='float32', shape=[1])
tmp_res_elesub = helper.create_global_variable(
persistable=False, dtype='float32', shape=[-1])
tmp_res_sigmoid = helper.create_global_variable(
persistable=False, dtype='float32', shape=[-1])
tmp_ones = helper.create_global_variable(
persistable=False, dtype='float32', shape=[-1])
batch_prob = helper.create_global_variable(
persistable=False, dtype='float32', shape=[1])
batch_abserr = helper.create_global_variable(
persistable=False, dtype='float32', shape=[1])
batch_sqrerr = helper.create_global_variable(
persistable=False, dtype='float32', shape=[1])
batch_q = helper.create_global_variable(
persistable=False, dtype='float32', shape=[1])
batch_pos_num = helper.create_global_variable(
persistable=False, dtype='float32', shape=[1])
batch_ins_num = helper.create_global_variable(
persistable=False, dtype='float32', shape=[1])
for var in [
local_abserr, batch_abserr, local_sqrerr, batch_sqrerr, local_prob,
batch_prob, local_q, batch_q, batch_pos_num, batch_ins_num,
local_pos_num, local_ins_num
]:
helper.set_variable_initializer(
var, Constant(
value=0.0, force_cpu=True))
helper.append_op(
type="elementwise_sub",
inputs={"X": [input],
"Y": [label]},
outputs={"Out": [tmp_res_elesub]})
helper.append_op(
type="squared_l2_norm",
inputs={"X": [tmp_res_elesub]},
outputs={"Out": [batch_sqrerr]})
helper.append_op(
type="elementwise_add",
inputs={"X": [batch_sqrerr],
"Y": [local_sqrerr]},
outputs={"Out": [local_sqrerr]})
helper.append_op(
type="l1_norm",
inputs={"X": [tmp_res_elesub]},
outputs={"Out": [batch_abserr]})
helper.append_op(
type="elementwise_add",
inputs={"X": [batch_abserr],
"Y": [local_abserr]},
outputs={"Out": [local_abserr]})
helper.append_op(
type="reduce_sum", inputs={"X": [input]},
outputs={"Out": [batch_prob]})
helper.append_op(
type="elementwise_add",
inputs={"X": [batch_prob],
"Y": [local_prob]},
outputs={"Out": [local_prob]})
helper.append_op(
type="sigmoid",
inputs={"X": [input]},
outputs={"Out": [tmp_res_sigmoid]})
helper.append_op(
type="reduce_sum",
inputs={"X": [tmp_res_sigmoid]},
outputs={"Out": [batch_q]})
helper.append_op(
type="elementwise_add",
inputs={"X": [batch_q],
"Y": [local_q]},
outputs={"Out": [local_q]})
helper.append_op(
type="reduce_sum",
inputs={"X": [label]},
outputs={"Out": [batch_pos_num]})
helper.append_op(
type="elementwise_add",
inputs={"X": [batch_pos_num],
"Y": [local_pos_num]},
outputs={"Out": [local_pos_num]})
helper.append_op(
type='fill_constant_batch_size_like',
inputs={"Input": label},
outputs={'Out': [tmp_ones]},
attrs={
'shape': [-1, 1],
'dtype': tmp_ones.dtype,
'value': float(1.0),
})
helper.append_op(
type="reduce_sum",
inputs={"X": [tmp_ones]},
outputs={"Out": [batch_ins_num]})
helper.append_op(
type="elementwise_add",
inputs={"X": [batch_ins_num],
"Y": [local_ins_num]},
outputs={"Out": [local_ins_num]})
return local_sqrerr, local_abserr, local_prob, local_q, local_pos_num, local_ins_num | [
"def",
"ctr_metric_bundle",
"(",
"input",
",",
"label",
")",
":",
"assert",
"input",
".",
"shape",
"==",
"label",
".",
"shape",
"helper",
"=",
"LayerHelper",
"(",
"\"ctr_metric_bundle\"",
",",
"*",
"*",
"locals",
"(",
")",
")",
"local_abserr",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"True",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"local_sqrerr",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"True",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"local_prob",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"True",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"local_q",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"True",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"local_pos_num",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"True",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"local_ins_num",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"True",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"tmp_res_elesub",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"-",
"1",
"]",
")",
"tmp_res_sigmoid",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"-",
"1",
"]",
")",
"tmp_ones",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"-",
"1",
"]",
")",
"batch_prob",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"batch_abserr",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"batch_sqrerr",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"batch_q",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"batch_pos_num",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"batch_ins_num",
"=",
"helper",
".",
"create_global_variable",
"(",
"persistable",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"shape",
"=",
"[",
"1",
"]",
")",
"for",
"var",
"in",
"[",
"local_abserr",
",",
"batch_abserr",
",",
"local_sqrerr",
",",
"batch_sqrerr",
",",
"local_prob",
",",
"batch_prob",
",",
"local_q",
",",
"batch_q",
",",
"batch_pos_num",
",",
"batch_ins_num",
",",
"local_pos_num",
",",
"local_ins_num",
"]",
":",
"helper",
".",
"set_variable_initializer",
"(",
"var",
",",
"Constant",
"(",
"value",
"=",
"0.0",
",",
"force_cpu",
"=",
"True",
")",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"elementwise_sub\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"input",
"]",
",",
"\"Y\"",
":",
"[",
"label",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"tmp_res_elesub",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"squared_l2_norm\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"tmp_res_elesub",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"batch_sqrerr",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"elementwise_add\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"batch_sqrerr",
"]",
",",
"\"Y\"",
":",
"[",
"local_sqrerr",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"local_sqrerr",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"l1_norm\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"tmp_res_elesub",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"batch_abserr",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"elementwise_add\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"batch_abserr",
"]",
",",
"\"Y\"",
":",
"[",
"local_abserr",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"local_abserr",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"reduce_sum\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"input",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"batch_prob",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"elementwise_add\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"batch_prob",
"]",
",",
"\"Y\"",
":",
"[",
"local_prob",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"local_prob",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"sigmoid\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"input",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"tmp_res_sigmoid",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"reduce_sum\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"tmp_res_sigmoid",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"batch_q",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"elementwise_add\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"batch_q",
"]",
",",
"\"Y\"",
":",
"[",
"local_q",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"local_q",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"reduce_sum\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"label",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"batch_pos_num",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"elementwise_add\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"batch_pos_num",
"]",
",",
"\"Y\"",
":",
"[",
"local_pos_num",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"local_pos_num",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"'fill_constant_batch_size_like'",
",",
"inputs",
"=",
"{",
"\"Input\"",
":",
"label",
"}",
",",
"outputs",
"=",
"{",
"'Out'",
":",
"[",
"tmp_ones",
"]",
"}",
",",
"attrs",
"=",
"{",
"'shape'",
":",
"[",
"-",
"1",
",",
"1",
"]",
",",
"'dtype'",
":",
"tmp_ones",
".",
"dtype",
",",
"'value'",
":",
"float",
"(",
"1.0",
")",
",",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"reduce_sum\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"tmp_ones",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"batch_ins_num",
"]",
"}",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"elementwise_add\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"[",
"batch_ins_num",
"]",
",",
"\"Y\"",
":",
"[",
"local_ins_num",
"]",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"[",
"local_ins_num",
"]",
"}",
")",
"return",
"local_sqrerr",
",",
"local_abserr",
",",
"local_prob",
",",
"local_q",
",",
"local_pos_num",
",",
"local_ins_num"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/layers/metric_op.py#L30-L188 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/datasets/_species_distributions.py | python | _load_csv | (F) | return rec | Load csv file.
Parameters
----------
F : file object
CSV file open in byte mode.
Returns
-------
rec : np.ndarray
record array representing the data | Load csv file. | [
"Load",
"csv",
"file",
"."
] | def _load_csv(F):
"""Load csv file.
Parameters
----------
F : file object
CSV file open in byte mode.
Returns
-------
rec : np.ndarray
record array representing the data
"""
names = F.readline().decode('ascii').strip().split(',')
rec = np.loadtxt(F, skiprows=0, delimiter=',', dtype='a22,f4,f4')
rec.dtype.names = names
return rec | [
"def",
"_load_csv",
"(",
"F",
")",
":",
"names",
"=",
"F",
".",
"readline",
"(",
")",
".",
"decode",
"(",
"'ascii'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"','",
")",
"rec",
"=",
"np",
".",
"loadtxt",
"(",
"F",
",",
"skiprows",
"=",
"0",
",",
"delimiter",
"=",
"','",
",",
"dtype",
"=",
"'a22,f4,f4'",
")",
"rec",
".",
"dtype",
".",
"names",
"=",
"names",
"return",
"rec"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/datasets/_species_distributions.py#L94-L111 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/excel/_base.py | python | ExcelFile.parse | (
self,
sheet_name=0,
header=0,
names=None,
index_col=None,
usecols=None,
squeeze=False,
converters=None,
true_values=None,
false_values=None,
skiprows=None,
nrows=None,
na_values=None,
parse_dates=False,
date_parser=None,
thousands=None,
comment=None,
skipfooter=0,
convert_float=None,
mangle_dupe_cols=True,
**kwds,
) | return self._reader.parse(
sheet_name=sheet_name,
header=header,
names=names,
index_col=index_col,
usecols=usecols,
squeeze=squeeze,
converters=converters,
true_values=true_values,
false_values=false_values,
skiprows=skiprows,
nrows=nrows,
na_values=na_values,
parse_dates=parse_dates,
date_parser=date_parser,
thousands=thousands,
comment=comment,
skipfooter=skipfooter,
convert_float=convert_float,
mangle_dupe_cols=mangle_dupe_cols,
**kwds,
) | Parse specified sheet(s) into a DataFrame.
Equivalent to read_excel(ExcelFile, ...) See the read_excel
docstring for more info on accepted parameters.
Returns
-------
DataFrame or dict of DataFrames
DataFrame from the passed in Excel file. | Parse specified sheet(s) into a DataFrame. | [
"Parse",
"specified",
"sheet",
"(",
"s",
")",
"into",
"a",
"DataFrame",
"."
] | def parse(
self,
sheet_name=0,
header=0,
names=None,
index_col=None,
usecols=None,
squeeze=False,
converters=None,
true_values=None,
false_values=None,
skiprows=None,
nrows=None,
na_values=None,
parse_dates=False,
date_parser=None,
thousands=None,
comment=None,
skipfooter=0,
convert_float=None,
mangle_dupe_cols=True,
**kwds,
):
"""
Parse specified sheet(s) into a DataFrame.
Equivalent to read_excel(ExcelFile, ...) See the read_excel
docstring for more info on accepted parameters.
Returns
-------
DataFrame or dict of DataFrames
DataFrame from the passed in Excel file.
"""
return self._reader.parse(
sheet_name=sheet_name,
header=header,
names=names,
index_col=index_col,
usecols=usecols,
squeeze=squeeze,
converters=converters,
true_values=true_values,
false_values=false_values,
skiprows=skiprows,
nrows=nrows,
na_values=na_values,
parse_dates=parse_dates,
date_parser=date_parser,
thousands=thousands,
comment=comment,
skipfooter=skipfooter,
convert_float=convert_float,
mangle_dupe_cols=mangle_dupe_cols,
**kwds,
) | [
"def",
"parse",
"(",
"self",
",",
"sheet_name",
"=",
"0",
",",
"header",
"=",
"0",
",",
"names",
"=",
"None",
",",
"index_col",
"=",
"None",
",",
"usecols",
"=",
"None",
",",
"squeeze",
"=",
"False",
",",
"converters",
"=",
"None",
",",
"true_values",
"=",
"None",
",",
"false_values",
"=",
"None",
",",
"skiprows",
"=",
"None",
",",
"nrows",
"=",
"None",
",",
"na_values",
"=",
"None",
",",
"parse_dates",
"=",
"False",
",",
"date_parser",
"=",
"None",
",",
"thousands",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"skipfooter",
"=",
"0",
",",
"convert_float",
"=",
"None",
",",
"mangle_dupe_cols",
"=",
"True",
",",
"*",
"*",
"kwds",
",",
")",
":",
"return",
"self",
".",
"_reader",
".",
"parse",
"(",
"sheet_name",
"=",
"sheet_name",
",",
"header",
"=",
"header",
",",
"names",
"=",
"names",
",",
"index_col",
"=",
"index_col",
",",
"usecols",
"=",
"usecols",
",",
"squeeze",
"=",
"squeeze",
",",
"converters",
"=",
"converters",
",",
"true_values",
"=",
"true_values",
",",
"false_values",
"=",
"false_values",
",",
"skiprows",
"=",
"skiprows",
",",
"nrows",
"=",
"nrows",
",",
"na_values",
"=",
"na_values",
",",
"parse_dates",
"=",
"parse_dates",
",",
"date_parser",
"=",
"date_parser",
",",
"thousands",
"=",
"thousands",
",",
"comment",
"=",
"comment",
",",
"skipfooter",
"=",
"skipfooter",
",",
"convert_float",
"=",
"convert_float",
",",
"mangle_dupe_cols",
"=",
"mangle_dupe_cols",
",",
"*",
"*",
"kwds",
",",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/excel/_base.py#L1238-L1293 | |
yuxng/DA-RNN | 77fbb50b4272514588a10a9f90b7d5f8d46974fb | lib/datasets/shapenet_single.py | python | shapenet_single._load_image_set_index | (self) | return image_index | Load the indexes listed in this dataset's image set file. | Load the indexes listed in this dataset's image set file. | [
"Load",
"the",
"indexes",
"listed",
"in",
"this",
"dataset",
"s",
"image",
"set",
"file",
"."
] | def _load_image_set_index(self):
"""
Load the indexes listed in this dataset's image set file.
"""
image_set_file = os.path.join(self._shapenet_single_path, self._image_set + '.txt')
assert os.path.exists(image_set_file), \
'Path does not exist: {}'.format(image_set_file)
with open(image_set_file) as f:
image_index = [x.rstrip('\n') for x in f.readlines()]
return image_index | [
"def",
"_load_image_set_index",
"(",
"self",
")",
":",
"image_set_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_shapenet_single_path",
",",
"self",
".",
"_image_set",
"+",
"'.txt'",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"image_set_file",
")",
",",
"'Path does not exist: {}'",
".",
"format",
"(",
"image_set_file",
")",
"with",
"open",
"(",
"image_set_file",
")",
"as",
"f",
":",
"image_index",
"=",
"[",
"x",
".",
"rstrip",
"(",
"'\\n'",
")",
"for",
"x",
"in",
"f",
".",
"readlines",
"(",
")",
"]",
"return",
"image_index"
] | https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_single.py#L118-L128 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | _DomainGreaterEqual.__init__ | (self, critical_value) | DomainGreaterEqual(v)(x) = true where x < v | DomainGreaterEqual(v)(x) = true where x < v | [
"DomainGreaterEqual",
"(",
"v",
")",
"(",
"x",
")",
"=",
"true",
"where",
"x",
"<",
"v"
] | def __init__(self, critical_value):
"DomainGreaterEqual(v)(x) = true where x < v"
self.critical_value = critical_value | [
"def",
"__init__",
"(",
"self",
",",
"critical_value",
")",
":",
"self",
".",
"critical_value",
"=",
"critical_value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L889-L891 | ||
clMathLibraries/clBLAS | cf9113982fdfc994297d372785ce76eb80911af2 | src/scripts/perf/plotPerformance.py | python | plotFromDataFile | () | read in table(s) from file(s) | read in table(s) from file(s) | [
"read",
"in",
"table",
"(",
"s",
")",
"from",
"file",
"(",
"s",
")"
] | def plotFromDataFile():
data = []
"""
read in table(s) from file(s)
"""
for thisFile in args.datafile:
if not os.path.isfile(thisFile):
print 'No file with the name \'{}\' exists. Please indicate another filename.'.format(thisFile)
quit()
results = open(thisFile, 'r')
results_contents = results.read()
results_contents = results_contents.rstrip().split('\n')
firstRow = results_contents.pop(0)
print firstRow
print blas_table_header()
print firstRow.rstrip()==blas_table_header()
if firstRow.rstrip() != blas_table_header():
print 'ERROR: input file \'{}\' does not match expected format.'.format(thisFile)
quit()
for row in results_contents:
row = row.split(',')
row = TableRow(BlasTestCombination(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14], row[15], row[16], row[17][1:], row[17][0], row[18], row[19], row[20]), row[21])
data.append(BlasGraphPoint(row.parameters.sizem, row.parameters.sizen, row.parameters.sizek, row.parameters.lda, row.parameters.ldb, row.parameters.ldc, row.parameters.offa , row.parameters.offb , row.parameters.offc , row.parameters.device, row.parameters.order, row.parameters.transa, row.parameters.transb, row.parameters.precision + row.parameters.function, row.parameters.library, row.parameters.label, row.gflops))
"""
data sanity check
"""
# if multiple plotvalues have > 1 value among the data rows, the user must specify which to plot
multiplePlotValues = []
for option in plotvalues:
values = []
for point in data:
values.append(getattr(point, option))
multiplePlotValues.append(len(set(values)) > 1)
if multiplePlotValues.count(True) > 1 and args.plot == None:
print 'ERROR: more than one parameter of {} has multiple values. Please specify which parameter to plot with --plot'.format(plotvalues)
quit()
# if args.graphxaxis is not 'problemsize', the user should know that the results might be strange
#if args.graphxaxis != 'problemsize':
# xaxisvalueSet = []
# for option in xaxisvalues:
# if option != 'problemsize':
# values = []
# for point in data:
# values.append(getattr(point, option))
# xaxisvalueSet.append(len(set(values)) > 1)
# if xaxisvalueSet.count(True) > 1:
# print 'WARNING: more than one parameter of {} is varied. unexpected results may occur. please double check your graphs for accuracy.'.format(xaxisvalues)
# multiple rows should not have the same input values
#pointInputs = []
#for point in data:
# pointInputs.append(point.__str__().split(';')[0])
#if len(set(pointInputs)) != len(data):
# print 'ERROR: imported table has duplicate rows with identical input parameters'
# quit()
"""
figure out if we have multiple plots on this graph (and what they should be)
"""
if args.plot != None:
multiplePlots = args.plot
elif multiplePlotValues.count(True) == 1 and plotvalues[multiplePlotValues.index(True)] != 'sizek':
# we don't ever want to default to sizek, because it's probably going to vary for most plots
# we'll require the user to explicitly request multiple plots on sizek if necessary
multiplePlots = plotvalues[multiplePlotValues.index(True)]
else:
# default to device if none of the options to plot have multiple values
multiplePlots = 'device'
"""
assemble data for the graphs
"""
data.sort(key=lambda row: int(getattr(row, args.graphxaxis)))
# choose scale for x axis
if args.xaxisscale == None:
# user didn't specify. autodetect
if int(getattr(data[len(data)-1], args.graphxaxis)) > 2000: # big numbers on x-axis
args.xaxisscale = 'log2'
elif int(getattr(data[len(data)-1], args.graphxaxis)) > 10000: # bigger numbers on x-axis
args.xaxisscale = 'log10'
else: # small numbers on x-axis
args.xaxisscale = 'linear'
if args.xaxisscale == 'linear':
plotkwargs = {}
plottype = 'plot'
elif args.xaxisscale == 'log2':
plottype = 'semilogx'
plotkwargs = {'basex':2}
elif args.xaxisscale == 'log10':
plottype = 'semilogx'
plotkwargs = {'basex':10}
else:
print 'ERROR: invalid value for x-axis scale'
quit()
plots = set(getattr(row, multiplePlots) for row in data)
class DataForOnePlot:
def __init__(self, inlabel, inxdata, inydata):
self.label = inlabel
self.xdata = inxdata
self.ydata = inydata
dataForAllPlots = []
for plot in plots:
dataForThisPlot = itertools.ifilter( lambda x: getattr(x, multiplePlots) == plot, data)
dataForThisPlot = list(itertools.islice(dataForThisPlot, None))
#if args.graphxaxis == 'problemsize':
# xdata = [int(row.x) * int(row.y) * int(row.z) * int(row.batchsize) for row in dataForThisPlot]
#else:
xdata = [getattr(row, args.graphxaxis) for row in dataForThisPlot]
ydata = [getattr(row, args.graphyaxis) for row in dataForThisPlot]
dataForAllPlots.append(DataForOnePlot(plot,xdata,ydata))
"""
assemble labels for the graph or use the user-specified ones
"""
if args.graphtitle:
# use the user selection
title = args.graphtitle
else:
# autogen a lovely title
title = 'Performance vs. ' + args.graphxaxis.capitalize()
if args.xaxislabel:
# use the user selection
xaxislabel = args.xaxislabel
else:
# autogen a lovely x-axis label
if args.graphxaxis == 'cachesize':
units = '(bytes)'
else:
units = '(datapoints)'
xaxislabel = args.graphxaxis + ' ' + units
if args.yaxislabel:
# use the user selection
yaxislabel = args.yaxislabel
else:
# autogen a lovely y-axis label
if args.graphyaxis == 'gflops':
units = 'GFLOPS'
yaxislabel = 'Performance (' + units + ')'
"""
display a pretty graph
"""
colors = ['k','y','m','c','r','b','g']
for thisPlot in dataForAllPlots:
getattr(pylab, plottype)(thisPlot.xdata, thisPlot.ydata, '{}.-'.format(colors.pop()), label=thisPlot.label, **plotkwargs)
if len(dataForAllPlots) > 1:
pylab.legend(loc='best')
pylab.title(title)
pylab.xlabel(xaxislabel)
pylab.ylabel(yaxislabel)
pylab.grid(True)
if args.outputFilename == None:
# if no pdf output is requested, spit the graph to the screen . . .
pylab.show()
else:
# . . . otherwise, gimme gimme pdf
#pdf = PdfPages(args.outputFilename)
#pdf.savefig()
#pdf.close()
pylab.savefig(args.outputFilename,dpi=(1024/8)) | [
"def",
"plotFromDataFile",
"(",
")",
":",
"data",
"=",
"[",
"]",
"for",
"thisFile",
"in",
"args",
".",
"datafile",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"thisFile",
")",
":",
"print",
"'No file with the name \\'{}\\' exists. Please indicate another filename.'",
".",
"format",
"(",
"thisFile",
")",
"quit",
"(",
")",
"results",
"=",
"open",
"(",
"thisFile",
",",
"'r'",
")",
"results_contents",
"=",
"results",
".",
"read",
"(",
")",
"results_contents",
"=",
"results_contents",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"firstRow",
"=",
"results_contents",
".",
"pop",
"(",
"0",
")",
"print",
"firstRow",
"print",
"blas_table_header",
"(",
")",
"print",
"firstRow",
".",
"rstrip",
"(",
")",
"==",
"blas_table_header",
"(",
")",
"if",
"firstRow",
".",
"rstrip",
"(",
")",
"!=",
"blas_table_header",
"(",
")",
":",
"print",
"'ERROR: input file \\'{}\\' does not match expected format.'",
".",
"format",
"(",
"thisFile",
")",
"quit",
"(",
")",
"for",
"row",
"in",
"results_contents",
":",
"row",
"=",
"row",
".",
"split",
"(",
"','",
")",
"row",
"=",
"TableRow",
"(",
"BlasTestCombination",
"(",
"row",
"[",
"0",
"]",
",",
"row",
"[",
"1",
"]",
",",
"row",
"[",
"2",
"]",
",",
"row",
"[",
"3",
"]",
",",
"row",
"[",
"4",
"]",
",",
"row",
"[",
"5",
"]",
",",
"row",
"[",
"6",
"]",
",",
"row",
"[",
"7",
"]",
",",
"row",
"[",
"8",
"]",
",",
"row",
"[",
"9",
"]",
",",
"row",
"[",
"10",
"]",
",",
"row",
"[",
"11",
"]",
",",
"row",
"[",
"12",
"]",
",",
"row",
"[",
"13",
"]",
",",
"row",
"[",
"14",
"]",
",",
"row",
"[",
"15",
"]",
",",
"row",
"[",
"16",
"]",
",",
"row",
"[",
"17",
"]",
"[",
"1",
":",
"]",
",",
"row",
"[",
"17",
"]",
"[",
"0",
"]",
",",
"row",
"[",
"18",
"]",
",",
"row",
"[",
"19",
"]",
",",
"row",
"[",
"20",
"]",
")",
",",
"row",
"[",
"21",
"]",
")",
"data",
".",
"append",
"(",
"BlasGraphPoint",
"(",
"row",
".",
"parameters",
".",
"sizem",
",",
"row",
".",
"parameters",
".",
"sizen",
",",
"row",
".",
"parameters",
".",
"sizek",
",",
"row",
".",
"parameters",
".",
"lda",
",",
"row",
".",
"parameters",
".",
"ldb",
",",
"row",
".",
"parameters",
".",
"ldc",
",",
"row",
".",
"parameters",
".",
"offa",
",",
"row",
".",
"parameters",
".",
"offb",
",",
"row",
".",
"parameters",
".",
"offc",
",",
"row",
".",
"parameters",
".",
"device",
",",
"row",
".",
"parameters",
".",
"order",
",",
"row",
".",
"parameters",
".",
"transa",
",",
"row",
".",
"parameters",
".",
"transb",
",",
"row",
".",
"parameters",
".",
"precision",
"+",
"row",
".",
"parameters",
".",
"function",
",",
"row",
".",
"parameters",
".",
"library",
",",
"row",
".",
"parameters",
".",
"label",
",",
"row",
".",
"gflops",
")",
")",
"\"\"\"\n data sanity check\n \"\"\"",
"# if multiple plotvalues have > 1 value among the data rows, the user must specify which to plot",
"multiplePlotValues",
"=",
"[",
"]",
"for",
"option",
"in",
"plotvalues",
":",
"values",
"=",
"[",
"]",
"for",
"point",
"in",
"data",
":",
"values",
".",
"append",
"(",
"getattr",
"(",
"point",
",",
"option",
")",
")",
"multiplePlotValues",
".",
"append",
"(",
"len",
"(",
"set",
"(",
"values",
")",
")",
">",
"1",
")",
"if",
"multiplePlotValues",
".",
"count",
"(",
"True",
")",
">",
"1",
"and",
"args",
".",
"plot",
"==",
"None",
":",
"print",
"'ERROR: more than one parameter of {} has multiple values. Please specify which parameter to plot with --plot'",
".",
"format",
"(",
"plotvalues",
")",
"quit",
"(",
")",
"# if args.graphxaxis is not 'problemsize', the user should know that the results might be strange",
"#if args.graphxaxis != 'problemsize':",
"# xaxisvalueSet = []",
"# for option in xaxisvalues:",
"# if option != 'problemsize':",
"# values = []",
"# for point in data:",
"# values.append(getattr(point, option)) ",
"# xaxisvalueSet.append(len(set(values)) > 1)",
"# if xaxisvalueSet.count(True) > 1:",
"# print 'WARNING: more than one parameter of {} is varied. unexpected results may occur. please double check your graphs for accuracy.'.format(xaxisvalues)",
"# multiple rows should not have the same input values",
"#pointInputs = []",
"#for point in data:",
"# pointInputs.append(point.__str__().split(';')[0])",
"#if len(set(pointInputs)) != len(data):",
"# print 'ERROR: imported table has duplicate rows with identical input parameters'",
"# quit()",
"\"\"\"\n figure out if we have multiple plots on this graph (and what they should be)\n \"\"\"",
"if",
"args",
".",
"plot",
"!=",
"None",
":",
"multiplePlots",
"=",
"args",
".",
"plot",
"elif",
"multiplePlotValues",
".",
"count",
"(",
"True",
")",
"==",
"1",
"and",
"plotvalues",
"[",
"multiplePlotValues",
".",
"index",
"(",
"True",
")",
"]",
"!=",
"'sizek'",
":",
"# we don't ever want to default to sizek, because it's probably going to vary for most plots",
"# we'll require the user to explicitly request multiple plots on sizek if necessary",
"multiplePlots",
"=",
"plotvalues",
"[",
"multiplePlotValues",
".",
"index",
"(",
"True",
")",
"]",
"else",
":",
"# default to device if none of the options to plot have multiple values",
"multiplePlots",
"=",
"'device'",
"\"\"\"\n assemble data for the graphs\n \"\"\"",
"data",
".",
"sort",
"(",
"key",
"=",
"lambda",
"row",
":",
"int",
"(",
"getattr",
"(",
"row",
",",
"args",
".",
"graphxaxis",
")",
")",
")",
"# choose scale for x axis",
"if",
"args",
".",
"xaxisscale",
"==",
"None",
":",
"# user didn't specify. autodetect",
"if",
"int",
"(",
"getattr",
"(",
"data",
"[",
"len",
"(",
"data",
")",
"-",
"1",
"]",
",",
"args",
".",
"graphxaxis",
")",
")",
">",
"2000",
":",
"# big numbers on x-axis",
"args",
".",
"xaxisscale",
"=",
"'log2'",
"elif",
"int",
"(",
"getattr",
"(",
"data",
"[",
"len",
"(",
"data",
")",
"-",
"1",
"]",
",",
"args",
".",
"graphxaxis",
")",
")",
">",
"10000",
":",
"# bigger numbers on x-axis",
"args",
".",
"xaxisscale",
"=",
"'log10'",
"else",
":",
"# small numbers on x-axis",
"args",
".",
"xaxisscale",
"=",
"'linear'",
"if",
"args",
".",
"xaxisscale",
"==",
"'linear'",
":",
"plotkwargs",
"=",
"{",
"}",
"plottype",
"=",
"'plot'",
"elif",
"args",
".",
"xaxisscale",
"==",
"'log2'",
":",
"plottype",
"=",
"'semilogx'",
"plotkwargs",
"=",
"{",
"'basex'",
":",
"2",
"}",
"elif",
"args",
".",
"xaxisscale",
"==",
"'log10'",
":",
"plottype",
"=",
"'semilogx'",
"plotkwargs",
"=",
"{",
"'basex'",
":",
"10",
"}",
"else",
":",
"print",
"'ERROR: invalid value for x-axis scale'",
"quit",
"(",
")",
"plots",
"=",
"set",
"(",
"getattr",
"(",
"row",
",",
"multiplePlots",
")",
"for",
"row",
"in",
"data",
")",
"class",
"DataForOnePlot",
":",
"def",
"__init__",
"(",
"self",
",",
"inlabel",
",",
"inxdata",
",",
"inydata",
")",
":",
"self",
".",
"label",
"=",
"inlabel",
"self",
".",
"xdata",
"=",
"inxdata",
"self",
".",
"ydata",
"=",
"inydata",
"dataForAllPlots",
"=",
"[",
"]",
"for",
"plot",
"in",
"plots",
":",
"dataForThisPlot",
"=",
"itertools",
".",
"ifilter",
"(",
"lambda",
"x",
":",
"getattr",
"(",
"x",
",",
"multiplePlots",
")",
"==",
"plot",
",",
"data",
")",
"dataForThisPlot",
"=",
"list",
"(",
"itertools",
".",
"islice",
"(",
"dataForThisPlot",
",",
"None",
")",
")",
"#if args.graphxaxis == 'problemsize':",
"# xdata = [int(row.x) * int(row.y) * int(row.z) * int(row.batchsize) for row in dataForThisPlot]",
"#else:",
"xdata",
"=",
"[",
"getattr",
"(",
"row",
",",
"args",
".",
"graphxaxis",
")",
"for",
"row",
"in",
"dataForThisPlot",
"]",
"ydata",
"=",
"[",
"getattr",
"(",
"row",
",",
"args",
".",
"graphyaxis",
")",
"for",
"row",
"in",
"dataForThisPlot",
"]",
"dataForAllPlots",
".",
"append",
"(",
"DataForOnePlot",
"(",
"plot",
",",
"xdata",
",",
"ydata",
")",
")",
"\"\"\"\n assemble labels for the graph or use the user-specified ones\n \"\"\"",
"if",
"args",
".",
"graphtitle",
":",
"# use the user selection",
"title",
"=",
"args",
".",
"graphtitle",
"else",
":",
"# autogen a lovely title",
"title",
"=",
"'Performance vs. '",
"+",
"args",
".",
"graphxaxis",
".",
"capitalize",
"(",
")",
"if",
"args",
".",
"xaxislabel",
":",
"# use the user selection",
"xaxislabel",
"=",
"args",
".",
"xaxislabel",
"else",
":",
"# autogen a lovely x-axis label",
"if",
"args",
".",
"graphxaxis",
"==",
"'cachesize'",
":",
"units",
"=",
"'(bytes)'",
"else",
":",
"units",
"=",
"'(datapoints)'",
"xaxislabel",
"=",
"args",
".",
"graphxaxis",
"+",
"' '",
"+",
"units",
"if",
"args",
".",
"yaxislabel",
":",
"# use the user selection",
"yaxislabel",
"=",
"args",
".",
"yaxislabel",
"else",
":",
"# autogen a lovely y-axis label",
"if",
"args",
".",
"graphyaxis",
"==",
"'gflops'",
":",
"units",
"=",
"'GFLOPS'",
"yaxislabel",
"=",
"'Performance ('",
"+",
"units",
"+",
"')'",
"\"\"\"\n display a pretty graph\n \"\"\"",
"colors",
"=",
"[",
"'k'",
",",
"'y'",
",",
"'m'",
",",
"'c'",
",",
"'r'",
",",
"'b'",
",",
"'g'",
"]",
"for",
"thisPlot",
"in",
"dataForAllPlots",
":",
"getattr",
"(",
"pylab",
",",
"plottype",
")",
"(",
"thisPlot",
".",
"xdata",
",",
"thisPlot",
".",
"ydata",
",",
"'{}.-'",
".",
"format",
"(",
"colors",
".",
"pop",
"(",
")",
")",
",",
"label",
"=",
"thisPlot",
".",
"label",
",",
"*",
"*",
"plotkwargs",
")",
"if",
"len",
"(",
"dataForAllPlots",
")",
">",
"1",
":",
"pylab",
".",
"legend",
"(",
"loc",
"=",
"'best'",
")",
"pylab",
".",
"title",
"(",
"title",
")",
"pylab",
".",
"xlabel",
"(",
"xaxislabel",
")",
"pylab",
".",
"ylabel",
"(",
"yaxislabel",
")",
"pylab",
".",
"grid",
"(",
"True",
")",
"if",
"args",
".",
"outputFilename",
"==",
"None",
":",
"# if no pdf output is requested, spit the graph to the screen . . .",
"pylab",
".",
"show",
"(",
")",
"else",
":",
"# . . . otherwise, gimme gimme pdf",
"#pdf = PdfPages(args.outputFilename)",
"#pdf.savefig()",
"#pdf.close()",
"pylab",
".",
"savefig",
"(",
"args",
".",
"outputFilename",
",",
"dpi",
"=",
"(",
"1024",
"/",
"8",
")",
")"
] | https://github.com/clMathLibraries/clBLAS/blob/cf9113982fdfc994297d372785ce76eb80911af2/src/scripts/perf/plotPerformance.py#L68-L244 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/distributions/python/ops/independent.py | python | Independent.__init__ | (
self, distribution, reduce_batch_ndims=1, validate_args=False, name=None) | Construct a `Independent` distribution.
Args:
distribution: The base distribution instance to transform. Typically an
instance of `Distribution`.
reduce_batch_ndims: Scalar, integer number of rightmost batch dims which
will be regard as event dims.
validate_args: Python `bool`. Whether to validate input with asserts.
If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
name: The name for ops managed by the distribution.
Default value: `Independent + distribution.name`.
Raises:
ValueError: if `reduce_batch_ndims` exceeds `distribution.batch_ndims` | Construct a `Independent` distribution. | [
"Construct",
"a",
"Independent",
"distribution",
"."
] | def __init__(
self, distribution, reduce_batch_ndims=1, validate_args=False, name=None):
"""Construct a `Independent` distribution.
Args:
distribution: The base distribution instance to transform. Typically an
instance of `Distribution`.
reduce_batch_ndims: Scalar, integer number of rightmost batch dims which
will be regard as event dims.
validate_args: Python `bool`. Whether to validate input with asserts.
If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
name: The name for ops managed by the distribution.
Default value: `Independent + distribution.name`.
Raises:
ValueError: if `reduce_batch_ndims` exceeds `distribution.batch_ndims`
"""
parameters = locals()
name = name or "Independent" + distribution.name
self._distribution = distribution
with ops.name_scope(name):
reduce_batch_ndims = ops.convert_to_tensor(
reduce_batch_ndims, dtype=dtypes.int32, name="reduce_batch_ndims")
self._reduce_batch_ndims = reduce_batch_ndims
self._static_reduce_batch_ndims = tensor_util.constant_value(
reduce_batch_ndims)
if self._static_reduce_batch_ndims is not None:
self._reduce_batch_ndims = self._static_reduce_batch_ndims
super(Independent, self).__init__(
dtype=self._distribution.dtype,
reparameterization_type=self._distribution.reparameterization_type,
validate_args=validate_args,
allow_nan_stats=self._distribution.allow_nan_stats,
parameters=parameters,
graph_parents=(
[reduce_batch_ndims] +
distribution._graph_parents), # pylint: disable=protected-access
name=name)
self._runtime_assertions = self._make_runtime_assertions(
distribution, reduce_batch_ndims, validate_args) | [
"def",
"__init__",
"(",
"self",
",",
"distribution",
",",
"reduce_batch_ndims",
"=",
"1",
",",
"validate_args",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"parameters",
"=",
"locals",
"(",
")",
"name",
"=",
"name",
"or",
"\"Independent\"",
"+",
"distribution",
".",
"name",
"self",
".",
"_distribution",
"=",
"distribution",
"with",
"ops",
".",
"name_scope",
"(",
"name",
")",
":",
"reduce_batch_ndims",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"reduce_batch_ndims",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"\"reduce_batch_ndims\"",
")",
"self",
".",
"_reduce_batch_ndims",
"=",
"reduce_batch_ndims",
"self",
".",
"_static_reduce_batch_ndims",
"=",
"tensor_util",
".",
"constant_value",
"(",
"reduce_batch_ndims",
")",
"if",
"self",
".",
"_static_reduce_batch_ndims",
"is",
"not",
"None",
":",
"self",
".",
"_reduce_batch_ndims",
"=",
"self",
".",
"_static_reduce_batch_ndims",
"super",
"(",
"Independent",
",",
"self",
")",
".",
"__init__",
"(",
"dtype",
"=",
"self",
".",
"_distribution",
".",
"dtype",
",",
"reparameterization_type",
"=",
"self",
".",
"_distribution",
".",
"reparameterization_type",
",",
"validate_args",
"=",
"validate_args",
",",
"allow_nan_stats",
"=",
"self",
".",
"_distribution",
".",
"allow_nan_stats",
",",
"parameters",
"=",
"parameters",
",",
"graph_parents",
"=",
"(",
"[",
"reduce_batch_ndims",
"]",
"+",
"distribution",
".",
"_graph_parents",
")",
",",
"# pylint: disable=protected-access",
"name",
"=",
"name",
")",
"self",
".",
"_runtime_assertions",
"=",
"self",
".",
"_make_runtime_assertions",
"(",
"distribution",
",",
"reduce_batch_ndims",
",",
"validate_args",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/independent.py#L96-L136 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/utils/io_utils.py | python | ask_to_proceed_with_overwrite | (filepath) | return True | Produces a prompt asking about overwriting a file.
Args:
filepath: the path to the file to be overwritten.
Returns:
True if we can proceed with overwrite, False otherwise. | Produces a prompt asking about overwriting a file. | [
"Produces",
"a",
"prompt",
"asking",
"about",
"overwriting",
"a",
"file",
"."
] | def ask_to_proceed_with_overwrite(filepath):
"""Produces a prompt asking about overwriting a file.
Args:
filepath: the path to the file to be overwritten.
Returns:
True if we can proceed with overwrite, False otherwise.
"""
overwrite = input('[WARNING] %s already exists - overwrite? '
'[y/n]' % (filepath)).strip().lower()
while overwrite not in ('y', 'n'):
overwrite = input('Enter "y" (overwrite) or "n" '
'(cancel).').strip().lower()
if overwrite == 'n':
return False
print('[TIP] Next time specify overwrite=True!')
return True | [
"def",
"ask_to_proceed_with_overwrite",
"(",
"filepath",
")",
":",
"overwrite",
"=",
"input",
"(",
"'[WARNING] %s already exists - overwrite? '",
"'[y/n]'",
"%",
"(",
"filepath",
")",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"while",
"overwrite",
"not",
"in",
"(",
"'y'",
",",
"'n'",
")",
":",
"overwrite",
"=",
"input",
"(",
"'Enter \"y\" (overwrite) or \"n\" '",
"'(cancel).'",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"overwrite",
"==",
"'n'",
":",
"return",
"False",
"print",
"(",
"'[TIP] Next time specify overwrite=True!'",
")",
"return",
"True"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/io_utils.py#L42-L59 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py | python | ParserElement.setDefaultWhitespaceChars | ( chars ) | r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] | r"""
Overrides the default whitespace chars | [
"r",
"Overrides",
"the",
"default",
"whitespace",
"chars"
] | def setDefaultWhitespaceChars( chars ):
r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
"""
ParserElement.DEFAULT_WHITE_CHARS = chars | [
"def",
"setDefaultWhitespaceChars",
"(",
"chars",
")",
":",
"ParserElement",
".",
"DEFAULT_WHITE_CHARS",
"=",
"chars"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py#L1109-L1121 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py | python | Finder_items_Events.add_to_favorites | (self, _object, _attributes={}, **_arguments) | add to favorites: (NOT AVAILABLE YET) Add the items to the user\xd5s Favorites
Required argument: the items to add to the collection of Favorites
Keyword argument _attributes: AppleEvent attribute dictionary | add to favorites: (NOT AVAILABLE YET) Add the items to the user\xd5s Favorites
Required argument: the items to add to the collection of Favorites
Keyword argument _attributes: AppleEvent attribute dictionary | [
"add",
"to",
"favorites",
":",
"(",
"NOT",
"AVAILABLE",
"YET",
")",
"Add",
"the",
"items",
"to",
"the",
"user",
"\\",
"xd5s",
"Favorites",
"Required",
"argument",
":",
"the",
"items",
"to",
"add",
"to",
"the",
"collection",
"of",
"Favorites",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary"
] | def add_to_favorites(self, _object, _attributes={}, **_arguments):
"""add to favorites: (NOT AVAILABLE YET) Add the items to the user\xd5s Favorites
Required argument: the items to add to the collection of Favorites
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'fndr'
_subcode = 'ffav'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"add_to_favorites",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'fndr'",
"_subcode",
"=",
"'ffav'",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py#L15-L33 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Calibration/tube_spec.py | python | TubeSpec.setTubeSpecByStringArray | ( self, tubeSpecArray ) | Define the sets of tube from the workspace with an array of strings.
Set tube specification like setTubeSpecByString, but with an array of string
to enable multiple components to be calibrated.
This function allows you to calibrate a set of tubes that is not defined by a single component.
For example a set of windows. It takes an array of strings as its argument.
Each string specifies a component such as a window or a single tube in the same manner as for
:meth:`~tube_spec.TubeSpec.setTubeSpecByString`. The components must be disjoint.
:param tubeSpecArray: array of strings (ex. ['door1', 'door2']) | Define the sets of tube from the workspace with an array of strings. | [
"Define",
"the",
"sets",
"of",
"tube",
"from",
"the",
"workspace",
"with",
"an",
"array",
"of",
"strings",
"."
] | def setTubeSpecByStringArray( self, tubeSpecArray ):
"""
Define the sets of tube from the workspace with an array of strings.
Set tube specification like setTubeSpecByString, but with an array of string
to enable multiple components to be calibrated.
This function allows you to calibrate a set of tubes that is not defined by a single component.
For example a set of windows. It takes an array of strings as its argument.
Each string specifies a component such as a window or a single tube in the same manner as for
:meth:`~tube_spec.TubeSpec.setTubeSpecByString`. The components must be disjoint.
:param tubeSpecArray: array of strings (ex. ['door1', 'door2'])
"""
for i in range(len(tubeSpecArray)):
self.setTubeSpecByString(tubeSpecArray[i]) | [
"def",
"setTubeSpecByStringArray",
"(",
"self",
",",
"tubeSpecArray",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"tubeSpecArray",
")",
")",
":",
"self",
".",
"setTubeSpecByString",
"(",
"tubeSpecArray",
"[",
"i",
"]",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Calibration/tube_spec.py#L88-L104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.