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
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/packager-enterprise.py | python | tarfile | (build_os, arch, spec) | return "dl/mongodb-linux-%s-enterprise-%s-%s.tar.gz" % (spec.version(), build_os, arch) | Return the location where we store the downloaded tarball for
this package | Return the location where we store the downloaded tarball for
this package | [
"Return",
"the",
"location",
"where",
"we",
"store",
"the",
"downloaded",
"tarball",
"for",
"this",
"package"
] | def tarfile(build_os, arch, spec):
"""Return the location where we store the downloaded tarball for
this package"""
return "dl/mongodb-linux-%s-enterprise-%s-%s.tar.gz" % (spec.version(), build_os, arch) | [
"def",
"tarfile",
"(",
"build_os",
",",
"arch",
",",
"spec",
")",
":",
"return",
"\"dl/mongodb-linux-%s-enterprise-%s-%s.tar.gz\"",
"%",
"(",
"spec",
".",
"version",
"(",
")",
",",
"build_os",
",",
"arch",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/packager-enterprise.py#L183-L186 |
|
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/layers/blocks.py | python | _inject_name | (f, name) | return f | Call this at the end of any layer or block that takes an optional name argument. | Call this at the end of any layer or block that takes an optional name argument. | [
"Call",
"this",
"at",
"the",
"end",
"of",
"any",
"layer",
"or",
"block",
"that",
"takes",
"an",
"optional",
"name",
"argument",
"."
] | def _inject_name(f, name):
'''
Call this at the end of any layer or block that takes an optional name argument.
'''
if name:
if not isinstance(f, Function):
f = Function(f)
if len(f.outputs) == 1:
f = alias(f, name=name)
else:
f = combine(list(f.outputs), name=name) # BUGBUG: Does this actually name things?
return f | [
"def",
"_inject_name",
"(",
"f",
",",
"name",
")",
":",
"if",
"name",
":",
"if",
"not",
"isinstance",
"(",
"f",
",",
"Function",
")",
":",
"f",
"=",
"Function",
"(",
"f",
")",
"if",
"len",
"(",
"f",
".",
"outputs",
")",
"==",
"1",
":",
"f",
"=",
"alias",
"(",
"f",
",",
"name",
"=",
"name",
")",
"else",
":",
"f",
"=",
"combine",
"(",
"list",
"(",
"f",
".",
"outputs",
")",
",",
"name",
"=",
"name",
")",
"# BUGBUG: Does this actually name things?",
"return",
"f"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/layers/blocks.py#L70-L81 |
|
continental/ecal | 204dab80a24fe01abca62541133b311bf0c09608 | lang/python/core/ecal/core/publisher.py | python | MessagePublisher.__init__ | (self, name, topic_type="", topic_descriptor="") | Initialize a message publisher
:param name: subscription name of the publisher
:type name: string
:param topic_type: optional, type of the transported payload, eg a a string, a protobuf message
:type topic_type: string
:param topic_descriptor: optional, a string which can be registered with ecal to allow io
reflection features
:type topic_descriptor: string | Initialize a message publisher | [
"Initialize",
"a",
"message",
"publisher"
] | def __init__(self, name, topic_type="", topic_descriptor=""):
""" Initialize a message publisher
:param name: subscription name of the publisher
:type name: string
:param topic_type: optional, type of the transported payload, eg a a string, a protobuf message
:type topic_type: string
:param topic_descriptor: optional, a string which can be registered with ecal to allow io
reflection features
:type topic_descriptor: string
"""
self.c_publisher = ecal_core.publisher(name, topic_type, topic_descriptor) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"topic_type",
"=",
"\"\"",
",",
"topic_descriptor",
"=",
"\"\"",
")",
":",
"self",
".",
"c_publisher",
"=",
"ecal_core",
".",
"publisher",
"(",
"name",
",",
"topic_type",
",",
"topic_descriptor",
")"
] | https://github.com/continental/ecal/blob/204dab80a24fe01abca62541133b311bf0c09608/lang/python/core/ecal/core/publisher.py#L28-L40 |
||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/database.py | python | Distribution.__hash__ | (self) | return hash(self.name) + hash(self.version) + hash(self.source_url) | Compute hash in a way which matches the equality test. | Compute hash in a way which matches the equality test. | [
"Compute",
"hash",
"in",
"a",
"way",
"which",
"matches",
"the",
"equality",
"test",
"."
] | def __hash__(self):
"""
Compute hash in a way which matches the equality test.
"""
return hash(self.name) + hash(self.version) + hash(self.source_url) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"self",
".",
"name",
")",
"+",
"hash",
"(",
"self",
".",
"version",
")",
"+",
"hash",
"(",
"self",
".",
"source_url",
")"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/database.py#L467-L471 |
|
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/coprocessing.py | python | CoProcessor.RegisterView | (self, view, filename, freq, fittoscreen, magnification, width, height,
cinema=None, compression=None) | return view | Register a view for image capture with extra meta-data such
as magnification, size and frequency. | Register a view for image capture with extra meta-data such
as magnification, size and frequency. | [
"Register",
"a",
"view",
"for",
"image",
"capture",
"with",
"extra",
"meta",
"-",
"data",
"such",
"as",
"magnification",
"size",
"and",
"frequency",
"."
] | def RegisterView(self, view, filename, freq, fittoscreen, magnification, width, height,
cinema=None, compression=None):
"""Register a view for image capture with extra meta-data such
as magnification, size and frequency."""
if not isinstance(view, servermanager.Proxy):
raise RuntimeError ("Invalid 'view' argument passed to RegisterView.")
view.add_attribute("cpFileName", filename)
view.add_attribute("cpFrequency", freq)
view.add_attribute("cpFitToScreen", fittoscreen)
view.add_attribute("cpMagnification", magnification)
view.add_attribute("cpCinemaOptions", cinema)
view.add_attribute("cpCompression", compression)
view.ViewSize = [ width, height ]
self.__ViewsList.append(view)
return view | [
"def",
"RegisterView",
"(",
"self",
",",
"view",
",",
"filename",
",",
"freq",
",",
"fittoscreen",
",",
"magnification",
",",
"width",
",",
"height",
",",
"cinema",
"=",
"None",
",",
"compression",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"view",
",",
"servermanager",
".",
"Proxy",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid 'view' argument passed to RegisterView.\"",
")",
"view",
".",
"add_attribute",
"(",
"\"cpFileName\"",
",",
"filename",
")",
"view",
".",
"add_attribute",
"(",
"\"cpFrequency\"",
",",
"freq",
")",
"view",
".",
"add_attribute",
"(",
"\"cpFitToScreen\"",
",",
"fittoscreen",
")",
"view",
".",
"add_attribute",
"(",
"\"cpMagnification\"",
",",
"magnification",
")",
"view",
".",
"add_attribute",
"(",
"\"cpCinemaOptions\"",
",",
"cinema",
")",
"view",
".",
"add_attribute",
"(",
"\"cpCompression\"",
",",
"compression",
")",
"view",
".",
"ViewSize",
"=",
"[",
"width",
",",
"height",
"]",
"self",
".",
"__ViewsList",
".",
"append",
"(",
"view",
")",
"return",
"view"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/coprocessing.py#L587-L601 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/_polybase.py | python | ABCPolyBase.trim | (self, tol=0) | return self.__class__(coef, self.domain, self.window) | Remove trailing coefficients
Remove trailing coefficients until a coefficient is reached whose
absolute value greater than `tol` or the beginning of the series is
reached. If all the coefficients would be removed the series is set
to ``[0]``. A new series instance is returned with the new
coefficients. The current instance remains unchanged.
Parameters
----------
tol : non-negative number.
All trailing coefficients less than `tol` will be removed.
Returns
-------
new_series : series
Contains the new set of coefficients. | Remove trailing coefficients | [
"Remove",
"trailing",
"coefficients"
] | def trim(self, tol=0):
"""Remove trailing coefficients
Remove trailing coefficients until a coefficient is reached whose
absolute value greater than `tol` or the beginning of the series is
reached. If all the coefficients would be removed the series is set
to ``[0]``. A new series instance is returned with the new
coefficients. The current instance remains unchanged.
Parameters
----------
tol : non-negative number.
All trailing coefficients less than `tol` will be removed.
Returns
-------
new_series : series
Contains the new set of coefficients.
"""
coef = pu.trimcoef(self.coef, tol)
return self.__class__(coef, self.domain, self.window) | [
"def",
"trim",
"(",
"self",
",",
"tol",
"=",
"0",
")",
":",
"coef",
"=",
"pu",
".",
"trimcoef",
"(",
"self",
".",
"coef",
",",
"tol",
")",
"return",
"self",
".",
"__class__",
"(",
"coef",
",",
"self",
".",
"domain",
",",
"self",
".",
"window",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/_polybase.py#L587-L608 |
|
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/rabbits-in-forest.py | python | Solution.numRabbits | (self, answers) | return sum((((k+1)+v-1)//(k+1))*(k+1) for k, v in count.iteritems()) | :type answers: List[int]
:rtype: int | :type answers: List[int]
:rtype: int | [
":",
"type",
"answers",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def numRabbits(self, answers):
"""
:type answers: List[int]
:rtype: int
"""
count = collections.Counter(answers)
return sum((((k+1)+v-1)//(k+1))*(k+1) for k, v in count.iteritems()) | [
"def",
"numRabbits",
"(",
"self",
",",
"answers",
")",
":",
"count",
"=",
"collections",
".",
"Counter",
"(",
"answers",
")",
"return",
"sum",
"(",
"(",
"(",
"(",
"k",
"+",
"1",
")",
"+",
"v",
"-",
"1",
")",
"//",
"(",
"k",
"+",
"1",
")",
")",
"*",
"(",
"k",
"+",
"1",
")",
"for",
"k",
",",
"v",
"in",
"count",
".",
"iteritems",
"(",
")",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/rabbits-in-forest.py#L8-L14 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/compiler_machinery.py | python | PassManager.finalize | (self) | Finalize the PassManager, after which no more passes may be added
without re-finalization. | Finalize the PassManager, after which no more passes may be added
without re-finalization. | [
"Finalize",
"the",
"PassManager",
"after",
"which",
"no",
"more",
"passes",
"may",
"be",
"added",
"without",
"re",
"-",
"finalization",
"."
] | def finalize(self):
"""
Finalize the PassManager, after which no more passes may be added
without re-finalization.
"""
self._analysis = self.dependency_analysis()
self._print_after, self._print_before, self._print_wrap = \
self._debug_init()
self._finalized = True | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"_analysis",
"=",
"self",
".",
"dependency_analysis",
"(",
")",
"self",
".",
"_print_after",
",",
"self",
".",
"_print_before",
",",
"self",
".",
"_print_wrap",
"=",
"self",
".",
"_debug_init",
"(",
")",
"self",
".",
"_finalized",
"=",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/compiler_machinery.py#L239-L247 |
||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py | python | input_option | (message, default_value="", help=None, level=0, max_level=0) | return user_input | This is a fancy raw_input function.
If the user enters '?' then the contents of help is printed.
The 'level' and 'max_level' are used to adjust which advanced options
are printed. 'max_level' is the level of options that the user wants
to see. 'level' is the level of difficulty for this particular option.
If this level is <= the max_level the user wants then the
message is printed and user input is allowed; otherwise, the
default value is returned automatically without user input. | This is a fancy raw_input function.
If the user enters '?' then the contents of help is printed. | [
"This",
"is",
"a",
"fancy",
"raw_input",
"function",
".",
"If",
"the",
"user",
"enters",
"?",
"then",
"the",
"contents",
"of",
"help",
"is",
"printed",
"."
] | def input_option(message, default_value="", help=None, level=0, max_level=0):
"""This is a fancy raw_input function.
If the user enters '?' then the contents of help is printed.
The 'level' and 'max_level' are used to adjust which advanced options
are printed. 'max_level' is the level of options that the user wants
to see. 'level' is the level of difficulty for this particular option.
If this level is <= the max_level the user wants then the
message is printed and user input is allowed; otherwise, the
default value is returned automatically without user input.
"""
if default_value != '':
message = "%s [%s] " % (message, default_value)
if level > max_level:
return default_value
while True:
user_input = raw_input(message)
if user_input == '?':
print help
elif user_input == '':
return default_value
else:
break
return user_input | [
"def",
"input_option",
"(",
"message",
",",
"default_value",
"=",
"\"\"",
",",
"help",
"=",
"None",
",",
"level",
"=",
"0",
",",
"max_level",
"=",
"0",
")",
":",
"if",
"default_value",
"!=",
"''",
":",
"message",
"=",
"\"%s [%s] \"",
"%",
"(",
"message",
",",
"default_value",
")",
"if",
"level",
">",
"max_level",
":",
"return",
"default_value",
"while",
"True",
":",
"user_input",
"=",
"raw_input",
"(",
"message",
")",
"if",
"user_input",
"==",
"'?'",
":",
"print",
"help",
"elif",
"user_input",
"==",
"''",
":",
"return",
"default_value",
"else",
":",
"break",
"return",
"user_input"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py#L339-L362 |
|
lightvector/KataGo | 20d34784703c5b4000643d3ccc43bb37d418f3b5 | python/sgfmill/sgf.py | python | Node.has_property | (self, identifier) | return identifier in self._property_map | Check whether the node has the specified property. | Check whether the node has the specified property. | [
"Check",
"whether",
"the",
"node",
"has",
"the",
"specified",
"property",
"."
] | def has_property(self, identifier):
"""Check whether the node has the specified property."""
return identifier in self._property_map | [
"def",
"has_property",
"(",
"self",
",",
"identifier",
")",
":",
"return",
"identifier",
"in",
"self",
".",
"_property_map"
] | https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/sgfmill/sgf.py#L47-L49 |
|
RapidsAtHKUST/CommunityDetectionCodes | 23dbafd2e57ab0f5f0528b1322c4a409f21e5892 | Algorithms/2008-CliquePercolation/src_python/seq_clique_percolation.py | python | kcliquesByEdges | (edges, k) | Phase I in the SCP-algorithm.
Generator function that generates a list of cliques of size k in the order they
are formed when edges are added in the order defined by the 'edges' argument.
If many cliques is formed by adding one edge, the order of the cliques is
arbitrary.
This generator will pass through any EvaluationEvent objects that are passed to
it in the 'edges' generator. | Phase I in the SCP-algorithm. | [
"Phase",
"I",
"in",
"the",
"SCP",
"-",
"algorithm",
"."
] | def kcliquesByEdges(edges, k):
"""
Phase I in the SCP-algorithm.
Generator function that generates a list of cliques of size k in the order they
are formed when edges are added in the order defined by the 'edges' argument.
If many cliques is formed by adding one edge, the order of the cliques is
arbitrary.
This generator will pass through any EvaluationEvent objects that are passed to
it in the 'edges' generator.
"""
newNet = SymmNet() # Edges are added to a empty network one by one
for edge in edges:
if isinstance(edge, EvaluationEvent):
yield edge
else:
# First we find all new triangles that are born when the new edge is added
triangleEnds = set() # We keep track of the tip nodes of the new triangles
for adjacendNode in newNet[edge[0]]: # Neighbor of one node of the edge ...
if newNet[adjacendNode, edge[1]] != 0: # ...is a neighbor of the other node of the edge...
triangleEnds.add(adjacendNode) # ...then the neighbor is a tip of a new triangle
# New k-cliques are now (k-2)-cliques at the triangle end points plus
# the two nodes at the tips of the edge we are adding to the network
for kclique in kcliquesAtSubnet(triangleEnds, newNet, k - 2):
yield kclique + KClique([edge[0], edge[1]])
newNet[edge[0], edge[1]] = edge[2] | [
"def",
"kcliquesByEdges",
"(",
"edges",
",",
"k",
")",
":",
"newNet",
"=",
"SymmNet",
"(",
")",
"# Edges are added to a empty network one by one",
"for",
"edge",
"in",
"edges",
":",
"if",
"isinstance",
"(",
"edge",
",",
"EvaluationEvent",
")",
":",
"yield",
"edge",
"else",
":",
"# First we find all new triangles that are born when the new edge is added",
"triangleEnds",
"=",
"set",
"(",
")",
"# We keep track of the tip nodes of the new triangles",
"for",
"adjacendNode",
"in",
"newNet",
"[",
"edge",
"[",
"0",
"]",
"]",
":",
"# Neighbor of one node of the edge ...",
"if",
"newNet",
"[",
"adjacendNode",
",",
"edge",
"[",
"1",
"]",
"]",
"!=",
"0",
":",
"# ...is a neighbor of the other node of the edge...",
"triangleEnds",
".",
"add",
"(",
"adjacendNode",
")",
"# ...then the neighbor is a tip of a new triangle",
"# New k-cliques are now (k-2)-cliques at the triangle end points plus",
"# the two nodes at the tips of the edge we are adding to the network",
"for",
"kclique",
"in",
"kcliquesAtSubnet",
"(",
"triangleEnds",
",",
"newNet",
",",
"k",
"-",
"2",
")",
":",
"yield",
"kclique",
"+",
"KClique",
"(",
"[",
"edge",
"[",
"0",
"]",
",",
"edge",
"[",
"1",
"]",
"]",
")",
"newNet",
"[",
"edge",
"[",
"0",
"]",
",",
"edge",
"[",
"1",
"]",
"]",
"=",
"edge",
"[",
"2",
"]"
] | https://github.com/RapidsAtHKUST/CommunityDetectionCodes/blob/23dbafd2e57ab0f5f0528b1322c4a409f21e5892/Algorithms/2008-CliquePercolation/src_python/seq_clique_percolation.py#L727-L754 |
||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py | python | _CudnnRNNNoInputC.state_shape | (self, batch_size) | return [self.num_layers * self.num_dirs, batch_size, self.num_units], | Shape of the state of Cudnn RNN cells w/o. input_c.
Shape is a 1-element tuple,
[num_layers * num_dirs, batch_size, num_units]
Args:
batch_size: an int
Returns:
a tuple of python arrays. | Shape of the state of Cudnn RNN cells w/o. input_c. | [
"Shape",
"of",
"the",
"state",
"of",
"Cudnn",
"RNN",
"cells",
"w",
"/",
"o",
".",
"input_c",
"."
] | def state_shape(self, batch_size):
"""Shape of the state of Cudnn RNN cells w/o. input_c.
Shape is a 1-element tuple,
[num_layers * num_dirs, batch_size, num_units]
Args:
batch_size: an int
Returns:
a tuple of python arrays.
"""
return [self.num_layers * self.num_dirs, batch_size, self.num_units], | [
"def",
"state_shape",
"(",
"self",
",",
"batch_size",
")",
":",
"return",
"[",
"self",
".",
"num_layers",
"*",
"self",
".",
"num_dirs",
",",
"batch_size",
",",
"self",
".",
"num_units",
"]",
","
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py#L525-L535 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.winfo_width | (self) | return getint(
self.tk.call('winfo', 'width', self._w)) | Return the width of this widget. | Return the width of this widget. | [
"Return",
"the",
"width",
"of",
"this",
"widget",
"."
] | def winfo_width(self):
"""Return the width of this widget."""
return getint(
self.tk.call('winfo', 'width', self._w)) | [
"def",
"winfo_width",
"(",
"self",
")",
":",
"return",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'width'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L946-L949 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/serialposix.py | python | PosixSerial.sendBreak | (self, duration=0.25) | Send break condition. Timed, returns to idle state after given duration. | Send break condition. Timed, returns to idle state after given duration. | [
"Send",
"break",
"condition",
".",
"Timed",
"returns",
"to",
"idle",
"state",
"after",
"given",
"duration",
"."
] | def sendBreak(self, duration=0.25):
"""Send break condition. Timed, returns to idle state after given duration."""
if not self._isOpen: raise portNotOpenError
termios.tcsendbreak(self.fd, int(duration/0.25)) | [
"def",
"sendBreak",
"(",
"self",
",",
"duration",
"=",
"0.25",
")",
":",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"portNotOpenError",
"termios",
".",
"tcsendbreak",
"(",
"self",
".",
"fd",
",",
"int",
"(",
"duration",
"/",
"0.25",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/serialposix.py#L537-L540 |
||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/newclasscalc/calc.py | python | Calc.p_expression_uminus | (self, p) | expression : MINUS expression %prec UMINUS | expression : MINUS expression %prec UMINUS | [
"expression",
":",
"MINUS",
"expression",
"%prec",
"UMINUS"
] | def p_expression_uminus(self, p):
'expression : MINUS expression %prec UMINUS'
p[0] = -p[2] | [
"def",
"p_expression_uminus",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"-",
"p",
"[",
"2",
"]"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/newclasscalc/calc.py#L132-L134 |
||
VowpalWabbit/vowpal_wabbit | 866b8fa88ff85a957c7eb72065ea44518b9ba416 | python/vowpalwabbit/dftovw.py | python | MulticlassLabel.__init__ | (self, label: Hashable, weight: Optional[Hashable] = None) | Initialize a MulticlassLabel instance.
Args:
label: The column name with the multi class label.
weight: The column name with the (importance) weight of the multi class label. | Initialize a MulticlassLabel instance. | [
"Initialize",
"a",
"MulticlassLabel",
"instance",
"."
] | def __init__(self, label: Hashable, weight: Optional[Hashable] = None):
"""Initialize a MulticlassLabel instance.
Args:
label: The column name with the multi class label.
weight: The column name with the (importance) weight of the multi class label.
"""
self.label = label
self.weight = weight | [
"def",
"__init__",
"(",
"self",
",",
"label",
":",
"Hashable",
",",
"weight",
":",
"Optional",
"[",
"Hashable",
"]",
"=",
"None",
")",
":",
"self",
".",
"label",
"=",
"label",
"self",
".",
"weight",
"=",
"weight"
] | https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/dftovw.py#L256-L264 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | PlatformInformation.SetPortId | (*args, **kwargs) | return _misc_.PlatformInformation_SetPortId(*args, **kwargs) | SetPortId(self, int n) | SetPortId(self, int n) | [
"SetPortId",
"(",
"self",
"int",
"n",
")"
] | def SetPortId(*args, **kwargs):
"""SetPortId(self, int n)"""
return _misc_.PlatformInformation_SetPortId(*args, **kwargs) | [
"def",
"SetPortId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"PlatformInformation_SetPortId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1162-L1164 |
|
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftviewproviders/view_draft_annotation.py | python | ViewProviderDraftAnnotation.set_properties | (self, vobj) | Set the properties only if they don't already exist. | Set the properties only if they don't already exist. | [
"Set",
"the",
"properties",
"only",
"if",
"they",
"don",
"t",
"already",
"exist",
"."
] | def set_properties(self, vobj):
"""Set the properties only if they don't already exist."""
properties = vobj.PropertiesList
self.set_annotation_properties(vobj, properties)
self.set_graphics_properties(vobj, properties) | [
"def",
"set_properties",
"(",
"self",
",",
"vobj",
")",
":",
"properties",
"=",
"vobj",
".",
"PropertiesList",
"self",
".",
"set_annotation_properties",
"(",
"vobj",
",",
"properties",
")",
"self",
".",
"set_graphics_properties",
"(",
"vobj",
",",
"properties",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftviewproviders/view_draft_annotation.py#L67-L71 |
||
KhronosGroup/Vulkan-ValidationLayers | f9b894b68a712ba0f7880c176074ac9fbb67cc7d | scripts/thread_safety_generator.py | python | ThreadOutputGenerator.makeThreadUseBlock | (self, cmd, name, functionprefix) | Generate C function pointer typedef for <command> Element | Generate C function pointer typedef for <command> Element | [
"Generate",
"C",
"function",
"pointer",
"typedef",
"for",
"<command",
">",
"Element"
] | def makeThreadUseBlock(self, cmd, name, functionprefix):
"""Generate C function pointer typedef for <command> Element"""
paramdecl = ''
# Find and add any parameters that are thread unsafe
params = cmd.findall('param')
for param in params:
paramname = param.find('name')
if False: # self.paramIsPointer(param):
paramdecl += ' // not watching use of pointer ' + paramname.text + '\n'
else:
externsync = param.attrib.get('externsync')
if externsync == 'true':
if self.paramIsArray(param):
paramdecl += 'if (' + paramname.text + ') {\n'
paramdecl += ' for (uint32_t index=0; index < ' + param.attrib.get('len') + '; index++) {\n'
paramdecl += ' ' + functionprefix + 'WriteObject' + self.paramSuffix(param.find('type')) + '(' + paramname.text + '[index], "' + name + '");\n'
paramdecl += ' }\n'
paramdecl += '}\n'
else:
paramdecl += functionprefix + 'WriteObject' + self.paramSuffix(param.find('type')) + '(' + paramname.text + ', "' + name + '");\n'
if ('Destroy' in name or 'Free' in name or 'ReleasePerformanceConfigurationINTEL' in name) and functionprefix == 'Finish':
paramdecl += 'DestroyObject' + self.paramSuffix(param.find('type')) + '(' + paramname.text + ');\n'
elif (param.attrib.get('externsync')):
if self.paramIsArray(param):
# Externsync can list pointers to arrays of members to synchronize
paramdecl += 'if (' + paramname.text + ') {\n'
paramdecl += ' for (uint32_t index=0; index < ' + param.attrib.get('len') + '; index++) {\n'
second_indent = ' '
for member in externsync.split(","):
# Replace first empty [] in member name with index
element = member.replace('[]','[index]',1)
# XXX TODO: Can we do better to lookup types of externsync members?
suffix = ''
if 'surface' in member or 'swapchain' in member.lower():
suffix = 'ParentInstance'
if '[]' in element:
# TODO: These null checks can be removed if threading ends up behind parameter
# validation in layer order
element_ptr = element.split('[]')[0]
paramdecl += ' if (' + element_ptr + ') {\n'
# Replace any second empty [] in element name with inner array index based on mapping array
# names like "pSomeThings[]" to "someThingCount" array size. This could be more robust by
# mapping a param member name to a struct type and "len" attribute.
limit = element[0:element.find('s[]')] + 'Count'
dotp = limit.rfind('.p')
limit = limit[0:dotp+1] + limit[dotp+2:dotp+3].lower() + limit[dotp+3:]
paramdecl += ' for (uint32_t index2=0; index2 < '+limit+'; index2++) {\n'
element = element.replace('[]','[index2]')
second_indent = ' '
paramdecl += ' ' + second_indent + functionprefix + 'WriteObject' + suffix + '(' + element + ', "' + name + '");\n'
paramdecl += ' }\n'
paramdecl += ' }\n'
else:
paramdecl += ' ' + second_indent + functionprefix + 'WriteObject' + suffix + '(' + element + ', "' + name + '");\n'
paramdecl += ' }\n'
paramdecl += '}\n'
else:
# externsync can list members to synchronize
for member in externsync.split(","):
member = str(member).replace("::", "->")
member = str(member).replace(".", "->")
# XXX TODO: Can we do better to lookup types of externsync members?
suffix = ''
if 'surface' in member or 'swapchain' in member.lower():
suffix = 'ParentInstance'
paramdecl += ' ' + functionprefix + 'WriteObject' + suffix + '(' + member + ', "' + name + '");\n'
elif self.paramIsPointer(param) and ('Create' in name or 'Allocate' in name or 'AcquirePerformanceConfigurationINTEL' in name) and functionprefix == 'Finish':
paramtype = param.find('type')
if paramtype is not None:
paramtype = paramtype.text
else:
paramtype = 'None'
if paramtype in self.handle_types:
indent = ''
create_pipelines_call = True
# The CreateXxxPipelines APIs can return a list of partly created pipelines upon failure
if not ('Create' in name and 'Pipelines' in name):
paramdecl += 'if (result == VK_SUCCESS) {\n'
create_pipelines_call = False
indent = ' '
if self.paramIsArray(param):
# Add pointer dereference for array counts that are pointer values
dereference = ''
for candidate in params:
if param.attrib.get('len') == candidate.find('name').text:
if self.paramIsPointer(candidate):
dereference = '*'
param_len = str(param.attrib.get('len')).replace("::", "->")
paramdecl += indent + 'if (' + paramname.text + ') {\n'
paramdecl += indent + ' for (uint32_t index = 0; index < ' + dereference + param_len + '; index++) {\n'
if create_pipelines_call:
paramdecl += indent + ' if (!pPipelines[index]) continue;\n'
paramdecl += indent + ' CreateObject' + self.paramSuffix(param.find('type')) + '(' + paramname.text + '[index]);\n'
paramdecl += indent + ' }\n'
paramdecl += indent + '}\n'
else:
paramdecl += ' CreateObject' + self.paramSuffix(param.find('type')) + '(*' + paramname.text + ');\n'
if not create_pipelines_call:
paramdecl += '}\n'
else:
paramtype = param.find('type')
if paramtype is not None:
paramtype = paramtype.text
else:
paramtype = 'None'
if paramtype in self.handle_types and paramtype != 'VkPhysicalDevice':
if self.paramIsArray(param) and ('pPipelines' != paramname.text):
# Add pointer dereference for array counts that are pointer values
dereference = ''
for candidate in params:
if param.attrib.get('len') == candidate.find('name').text:
if self.paramIsPointer(candidate):
dereference = '*'
param_len = str(param.attrib.get('len')).replace("::", "->")
paramdecl += 'if (' + paramname.text + ') {\n'
paramdecl += ' for (uint32_t index = 0; index < ' + dereference + param_len + '; index++) {\n'
paramdecl += ' ' + functionprefix + 'ReadObject' + self.paramSuffix(param.find('type')) + '(' + paramname.text + '[index], "' + name + '");\n'
paramdecl += ' }\n'
paramdecl += '}\n'
elif not self.paramIsPointer(param):
# Pointer params are often being created.
# They are not being read from.
paramdecl += functionprefix + 'ReadObject' + self.paramSuffix(param.find('type')) + '(' + paramname.text + ', "' + name + '");\n'
explicitexternsyncparams = cmd.findall("param[@externsync]")
if (explicitexternsyncparams is not None):
for param in explicitexternsyncparams:
externsyncattrib = param.attrib.get('externsync')
paramname = param.find('name')
paramdecl += '// Host access to '
if externsyncattrib == 'true':
if self.paramIsArray(param):
paramdecl += 'each member of ' + paramname.text
elif self.paramIsPointer(param):
paramdecl += 'the object referenced by ' + paramname.text
else:
paramdecl += paramname.text
else:
paramdecl += externsyncattrib
paramdecl += ' must be externally synchronized\n'
# Find and add any "implicit" parameters that are thread unsafe
implicitexternsyncparams = cmd.find('implicitexternsyncparams')
if (implicitexternsyncparams is not None):
for elem in implicitexternsyncparams:
paramdecl += '// '
paramdecl += elem.text
paramdecl += ' must be externally synchronized between host accesses\n'
if (paramdecl == ''):
return None
else:
return paramdecl | [
"def",
"makeThreadUseBlock",
"(",
"self",
",",
"cmd",
",",
"name",
",",
"functionprefix",
")",
":",
"paramdecl",
"=",
"''",
"# Find and add any parameters that are thread unsafe",
"params",
"=",
"cmd",
".",
"findall",
"(",
"'param'",
")",
"for",
"param",
"in",
"params",
":",
"paramname",
"=",
"param",
".",
"find",
"(",
"'name'",
")",
"if",
"False",
":",
"# self.paramIsPointer(param):",
"paramdecl",
"+=",
"' // not watching use of pointer '",
"+",
"paramname",
".",
"text",
"+",
"'\\n'",
"else",
":",
"externsync",
"=",
"param",
".",
"attrib",
".",
"get",
"(",
"'externsync'",
")",
"if",
"externsync",
"==",
"'true'",
":",
"if",
"self",
".",
"paramIsArray",
"(",
"param",
")",
":",
"paramdecl",
"+=",
"'if ('",
"+",
"paramname",
".",
"text",
"+",
"') {\\n'",
"paramdecl",
"+=",
"' for (uint32_t index=0; index < '",
"+",
"param",
".",
"attrib",
".",
"get",
"(",
"'len'",
")",
"+",
"'; index++) {\\n'",
"paramdecl",
"+=",
"' '",
"+",
"functionprefix",
"+",
"'WriteObject'",
"+",
"self",
".",
"paramSuffix",
"(",
"param",
".",
"find",
"(",
"'type'",
")",
")",
"+",
"'('",
"+",
"paramname",
".",
"text",
"+",
"'[index], \"'",
"+",
"name",
"+",
"'\");\\n'",
"paramdecl",
"+=",
"' }\\n'",
"paramdecl",
"+=",
"'}\\n'",
"else",
":",
"paramdecl",
"+=",
"functionprefix",
"+",
"'WriteObject'",
"+",
"self",
".",
"paramSuffix",
"(",
"param",
".",
"find",
"(",
"'type'",
")",
")",
"+",
"'('",
"+",
"paramname",
".",
"text",
"+",
"', \"'",
"+",
"name",
"+",
"'\");\\n'",
"if",
"(",
"'Destroy'",
"in",
"name",
"or",
"'Free'",
"in",
"name",
"or",
"'ReleasePerformanceConfigurationINTEL'",
"in",
"name",
")",
"and",
"functionprefix",
"==",
"'Finish'",
":",
"paramdecl",
"+=",
"'DestroyObject'",
"+",
"self",
".",
"paramSuffix",
"(",
"param",
".",
"find",
"(",
"'type'",
")",
")",
"+",
"'('",
"+",
"paramname",
".",
"text",
"+",
"');\\n'",
"elif",
"(",
"param",
".",
"attrib",
".",
"get",
"(",
"'externsync'",
")",
")",
":",
"if",
"self",
".",
"paramIsArray",
"(",
"param",
")",
":",
"# Externsync can list pointers to arrays of members to synchronize",
"paramdecl",
"+=",
"'if ('",
"+",
"paramname",
".",
"text",
"+",
"') {\\n'",
"paramdecl",
"+=",
"' for (uint32_t index=0; index < '",
"+",
"param",
".",
"attrib",
".",
"get",
"(",
"'len'",
")",
"+",
"'; index++) {\\n'",
"second_indent",
"=",
"' '",
"for",
"member",
"in",
"externsync",
".",
"split",
"(",
"\",\"",
")",
":",
"# Replace first empty [] in member name with index",
"element",
"=",
"member",
".",
"replace",
"(",
"'[]'",
",",
"'[index]'",
",",
"1",
")",
"# XXX TODO: Can we do better to lookup types of externsync members?",
"suffix",
"=",
"''",
"if",
"'surface'",
"in",
"member",
"or",
"'swapchain'",
"in",
"member",
".",
"lower",
"(",
")",
":",
"suffix",
"=",
"'ParentInstance'",
"if",
"'[]'",
"in",
"element",
":",
"# TODO: These null checks can be removed if threading ends up behind parameter",
"# validation in layer order",
"element_ptr",
"=",
"element",
".",
"split",
"(",
"'[]'",
")",
"[",
"0",
"]",
"paramdecl",
"+=",
"' if ('",
"+",
"element_ptr",
"+",
"') {\\n'",
"# Replace any second empty [] in element name with inner array index based on mapping array",
"# names like \"pSomeThings[]\" to \"someThingCount\" array size. This could be more robust by",
"# mapping a param member name to a struct type and \"len\" attribute.",
"limit",
"=",
"element",
"[",
"0",
":",
"element",
".",
"find",
"(",
"'s[]'",
")",
"]",
"+",
"'Count'",
"dotp",
"=",
"limit",
".",
"rfind",
"(",
"'.p'",
")",
"limit",
"=",
"limit",
"[",
"0",
":",
"dotp",
"+",
"1",
"]",
"+",
"limit",
"[",
"dotp",
"+",
"2",
":",
"dotp",
"+",
"3",
"]",
".",
"lower",
"(",
")",
"+",
"limit",
"[",
"dotp",
"+",
"3",
":",
"]",
"paramdecl",
"+=",
"' for (uint32_t index2=0; index2 < '",
"+",
"limit",
"+",
"'; index2++) {\\n'",
"element",
"=",
"element",
".",
"replace",
"(",
"'[]'",
",",
"'[index2]'",
")",
"second_indent",
"=",
"' '",
"paramdecl",
"+=",
"' '",
"+",
"second_indent",
"+",
"functionprefix",
"+",
"'WriteObject'",
"+",
"suffix",
"+",
"'('",
"+",
"element",
"+",
"', \"'",
"+",
"name",
"+",
"'\");\\n'",
"paramdecl",
"+=",
"' }\\n'",
"paramdecl",
"+=",
"' }\\n'",
"else",
":",
"paramdecl",
"+=",
"' '",
"+",
"second_indent",
"+",
"functionprefix",
"+",
"'WriteObject'",
"+",
"suffix",
"+",
"'('",
"+",
"element",
"+",
"', \"'",
"+",
"name",
"+",
"'\");\\n'",
"paramdecl",
"+=",
"' }\\n'",
"paramdecl",
"+=",
"'}\\n'",
"else",
":",
"# externsync can list members to synchronize",
"for",
"member",
"in",
"externsync",
".",
"split",
"(",
"\",\"",
")",
":",
"member",
"=",
"str",
"(",
"member",
")",
".",
"replace",
"(",
"\"::\"",
",",
"\"->\"",
")",
"member",
"=",
"str",
"(",
"member",
")",
".",
"replace",
"(",
"\".\"",
",",
"\"->\"",
")",
"# XXX TODO: Can we do better to lookup types of externsync members?",
"suffix",
"=",
"''",
"if",
"'surface'",
"in",
"member",
"or",
"'swapchain'",
"in",
"member",
".",
"lower",
"(",
")",
":",
"suffix",
"=",
"'ParentInstance'",
"paramdecl",
"+=",
"' '",
"+",
"functionprefix",
"+",
"'WriteObject'",
"+",
"suffix",
"+",
"'('",
"+",
"member",
"+",
"', \"'",
"+",
"name",
"+",
"'\");\\n'",
"elif",
"self",
".",
"paramIsPointer",
"(",
"param",
")",
"and",
"(",
"'Create'",
"in",
"name",
"or",
"'Allocate'",
"in",
"name",
"or",
"'AcquirePerformanceConfigurationINTEL'",
"in",
"name",
")",
"and",
"functionprefix",
"==",
"'Finish'",
":",
"paramtype",
"=",
"param",
".",
"find",
"(",
"'type'",
")",
"if",
"paramtype",
"is",
"not",
"None",
":",
"paramtype",
"=",
"paramtype",
".",
"text",
"else",
":",
"paramtype",
"=",
"'None'",
"if",
"paramtype",
"in",
"self",
".",
"handle_types",
":",
"indent",
"=",
"''",
"create_pipelines_call",
"=",
"True",
"# The CreateXxxPipelines APIs can return a list of partly created pipelines upon failure",
"if",
"not",
"(",
"'Create'",
"in",
"name",
"and",
"'Pipelines'",
"in",
"name",
")",
":",
"paramdecl",
"+=",
"'if (result == VK_SUCCESS) {\\n'",
"create_pipelines_call",
"=",
"False",
"indent",
"=",
"' '",
"if",
"self",
".",
"paramIsArray",
"(",
"param",
")",
":",
"# Add pointer dereference for array counts that are pointer values",
"dereference",
"=",
"''",
"for",
"candidate",
"in",
"params",
":",
"if",
"param",
".",
"attrib",
".",
"get",
"(",
"'len'",
")",
"==",
"candidate",
".",
"find",
"(",
"'name'",
")",
".",
"text",
":",
"if",
"self",
".",
"paramIsPointer",
"(",
"candidate",
")",
":",
"dereference",
"=",
"'*'",
"param_len",
"=",
"str",
"(",
"param",
".",
"attrib",
".",
"get",
"(",
"'len'",
")",
")",
".",
"replace",
"(",
"\"::\"",
",",
"\"->\"",
")",
"paramdecl",
"+=",
"indent",
"+",
"'if ('",
"+",
"paramname",
".",
"text",
"+",
"') {\\n'",
"paramdecl",
"+=",
"indent",
"+",
"' for (uint32_t index = 0; index < '",
"+",
"dereference",
"+",
"param_len",
"+",
"'; index++) {\\n'",
"if",
"create_pipelines_call",
":",
"paramdecl",
"+=",
"indent",
"+",
"' if (!pPipelines[index]) continue;\\n'",
"paramdecl",
"+=",
"indent",
"+",
"' CreateObject'",
"+",
"self",
".",
"paramSuffix",
"(",
"param",
".",
"find",
"(",
"'type'",
")",
")",
"+",
"'('",
"+",
"paramname",
".",
"text",
"+",
"'[index]);\\n'",
"paramdecl",
"+=",
"indent",
"+",
"' }\\n'",
"paramdecl",
"+=",
"indent",
"+",
"'}\\n'",
"else",
":",
"paramdecl",
"+=",
"' CreateObject'",
"+",
"self",
".",
"paramSuffix",
"(",
"param",
".",
"find",
"(",
"'type'",
")",
")",
"+",
"'(*'",
"+",
"paramname",
".",
"text",
"+",
"');\\n'",
"if",
"not",
"create_pipelines_call",
":",
"paramdecl",
"+=",
"'}\\n'",
"else",
":",
"paramtype",
"=",
"param",
".",
"find",
"(",
"'type'",
")",
"if",
"paramtype",
"is",
"not",
"None",
":",
"paramtype",
"=",
"paramtype",
".",
"text",
"else",
":",
"paramtype",
"=",
"'None'",
"if",
"paramtype",
"in",
"self",
".",
"handle_types",
"and",
"paramtype",
"!=",
"'VkPhysicalDevice'",
":",
"if",
"self",
".",
"paramIsArray",
"(",
"param",
")",
"and",
"(",
"'pPipelines'",
"!=",
"paramname",
".",
"text",
")",
":",
"# Add pointer dereference for array counts that are pointer values",
"dereference",
"=",
"''",
"for",
"candidate",
"in",
"params",
":",
"if",
"param",
".",
"attrib",
".",
"get",
"(",
"'len'",
")",
"==",
"candidate",
".",
"find",
"(",
"'name'",
")",
".",
"text",
":",
"if",
"self",
".",
"paramIsPointer",
"(",
"candidate",
")",
":",
"dereference",
"=",
"'*'",
"param_len",
"=",
"str",
"(",
"param",
".",
"attrib",
".",
"get",
"(",
"'len'",
")",
")",
".",
"replace",
"(",
"\"::\"",
",",
"\"->\"",
")",
"paramdecl",
"+=",
"'if ('",
"+",
"paramname",
".",
"text",
"+",
"') {\\n'",
"paramdecl",
"+=",
"' for (uint32_t index = 0; index < '",
"+",
"dereference",
"+",
"param_len",
"+",
"'; index++) {\\n'",
"paramdecl",
"+=",
"' '",
"+",
"functionprefix",
"+",
"'ReadObject'",
"+",
"self",
".",
"paramSuffix",
"(",
"param",
".",
"find",
"(",
"'type'",
")",
")",
"+",
"'('",
"+",
"paramname",
".",
"text",
"+",
"'[index], \"'",
"+",
"name",
"+",
"'\");\\n'",
"paramdecl",
"+=",
"' }\\n'",
"paramdecl",
"+=",
"'}\\n'",
"elif",
"not",
"self",
".",
"paramIsPointer",
"(",
"param",
")",
":",
"# Pointer params are often being created.",
"# They are not being read from.",
"paramdecl",
"+=",
"functionprefix",
"+",
"'ReadObject'",
"+",
"self",
".",
"paramSuffix",
"(",
"param",
".",
"find",
"(",
"'type'",
")",
")",
"+",
"'('",
"+",
"paramname",
".",
"text",
"+",
"', \"'",
"+",
"name",
"+",
"'\");\\n'",
"explicitexternsyncparams",
"=",
"cmd",
".",
"findall",
"(",
"\"param[@externsync]\"",
")",
"if",
"(",
"explicitexternsyncparams",
"is",
"not",
"None",
")",
":",
"for",
"param",
"in",
"explicitexternsyncparams",
":",
"externsyncattrib",
"=",
"param",
".",
"attrib",
".",
"get",
"(",
"'externsync'",
")",
"paramname",
"=",
"param",
".",
"find",
"(",
"'name'",
")",
"paramdecl",
"+=",
"'// Host access to '",
"if",
"externsyncattrib",
"==",
"'true'",
":",
"if",
"self",
".",
"paramIsArray",
"(",
"param",
")",
":",
"paramdecl",
"+=",
"'each member of '",
"+",
"paramname",
".",
"text",
"elif",
"self",
".",
"paramIsPointer",
"(",
"param",
")",
":",
"paramdecl",
"+=",
"'the object referenced by '",
"+",
"paramname",
".",
"text",
"else",
":",
"paramdecl",
"+=",
"paramname",
".",
"text",
"else",
":",
"paramdecl",
"+=",
"externsyncattrib",
"paramdecl",
"+=",
"' must be externally synchronized\\n'",
"# Find and add any \"implicit\" parameters that are thread unsafe",
"implicitexternsyncparams",
"=",
"cmd",
".",
"find",
"(",
"'implicitexternsyncparams'",
")",
"if",
"(",
"implicitexternsyncparams",
"is",
"not",
"None",
")",
":",
"for",
"elem",
"in",
"implicitexternsyncparams",
":",
"paramdecl",
"+=",
"'// '",
"paramdecl",
"+=",
"elem",
".",
"text",
"paramdecl",
"+=",
"' must be externally synchronized between host accesses\\n'",
"if",
"(",
"paramdecl",
"==",
"''",
")",
":",
"return",
"None",
"else",
":",
"return",
"paramdecl"
] | https://github.com/KhronosGroup/Vulkan-ValidationLayers/blob/f9b894b68a712ba0f7880c176074ac9fbb67cc7d/scripts/thread_safety_generator.py#L1421-L1574 |
||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/globrelative.py | python | globpattern | (dir, pattern) | return leaves | Return leaf names in the specified directory which match the pattern. | Return leaf names in the specified directory which match the pattern. | [
"Return",
"leaf",
"names",
"in",
"the",
"specified",
"directory",
"which",
"match",
"the",
"pattern",
"."
] | def globpattern(dir, pattern):
"""
Return leaf names in the specified directory which match the pattern.
"""
if not hasglob(pattern):
if pattern == '':
if os.path.isdir(dir):
return ['']
return []
if os.path.exists(util.normaljoin(dir, pattern)):
return [pattern]
return []
leaves = os.listdir(dir) + ['.', '..']
# "hidden" filenames are a bit special
if not pattern.startswith('.'):
leaves = [leaf for leaf in leaves
if not leaf.startswith('.')]
leaves = fnmatch.filter(leaves, pattern)
leaves = filter(lambda l: os.path.exists(util.normaljoin(dir, l)), leaves)
leaves.sort()
return leaves | [
"def",
"globpattern",
"(",
"dir",
",",
"pattern",
")",
":",
"if",
"not",
"hasglob",
"(",
"pattern",
")",
":",
"if",
"pattern",
"==",
"''",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dir",
")",
":",
"return",
"[",
"''",
"]",
"return",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"util",
".",
"normaljoin",
"(",
"dir",
",",
"pattern",
")",
")",
":",
"return",
"[",
"pattern",
"]",
"return",
"[",
"]",
"leaves",
"=",
"os",
".",
"listdir",
"(",
"dir",
")",
"+",
"[",
"'.'",
",",
"'..'",
"]",
"# \"hidden\" filenames are a bit special",
"if",
"not",
"pattern",
".",
"startswith",
"(",
"'.'",
")",
":",
"leaves",
"=",
"[",
"leaf",
"for",
"leaf",
"in",
"leaves",
"if",
"not",
"leaf",
".",
"startswith",
"(",
"'.'",
")",
"]",
"leaves",
"=",
"fnmatch",
".",
"filter",
"(",
"leaves",
",",
"pattern",
")",
"leaves",
"=",
"filter",
"(",
"lambda",
"l",
":",
"os",
".",
"path",
".",
"exists",
"(",
"util",
".",
"normaljoin",
"(",
"dir",
",",
"l",
")",
")",
",",
"leaves",
")",
"leaves",
".",
"sort",
"(",
")",
"return",
"leaves"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/globrelative.py#L42-L68 |
|
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/google/protobuf/service.py | python | Service.GetDescriptor | () | Retrieves this service's descriptor. | Retrieves this service's descriptor. | [
"Retrieves",
"this",
"service",
"s",
"descriptor",
"."
] | def GetDescriptor():
"""Retrieves this service's descriptor."""
raise NotImplementedError | [
"def",
"GetDescriptor",
"(",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/service.py#L61-L63 |
||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter_interface.py | python | PlottingCanvasPresenterInterface.plot_guess_workspace | (self, guess_ws_name: str) | Plots the guess workspace from a fit | Plots the guess workspace from a fit | [
"Plots",
"the",
"guess",
"workspace",
"from",
"a",
"fit"
] | def plot_guess_workspace(self, guess_ws_name: str):
"""Plots the guess workspace from a fit"""
pass | [
"def",
"plot_guess_workspace",
"(",
"self",
",",
"guess_ws_name",
":",
"str",
")",
":",
"pass"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter_interface.py#L96-L98 |
||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py | python | FSM.reset | (self) | This sets the current_state to the initial_state and sets
input_symbol to None. The initial state was set by the constructor
__init__(). | This sets the current_state to the initial_state and sets
input_symbol to None. The initial state was set by the constructor
__init__(). | [
"This",
"sets",
"the",
"current_state",
"to",
"the",
"initial_state",
"and",
"sets",
"input_symbol",
"to",
"None",
".",
"The",
"initial",
"state",
"was",
"set",
"by",
"the",
"constructor",
"__init__",
"()",
"."
] | def reset (self):
'''This sets the current_state to the initial_state and sets
input_symbol to None. The initial state was set by the constructor
__init__(). '''
self.current_state = self.initial_state
self.input_symbol = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"current_state",
"=",
"self",
".",
"initial_state",
"self",
".",
"input_symbol",
"=",
"None"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py#L122-L129 |
||
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-sniffer/OT_Sniffer.py | python | OT_Sniffer.stopSniffer | (self) | Method for ending the sniffer capture.
Should stop background capturing, No further file I/O in capture file. | Method for ending the sniffer capture.
Should stop background capturing, No further file I/O in capture file. | [
"Method",
"for",
"ending",
"the",
"sniffer",
"capture",
".",
"Should",
"stop",
"background",
"capturing",
"No",
"further",
"file",
"I",
"/",
"O",
"in",
"capture",
"file",
"."
] | def stopSniffer(self):
"""
Method for ending the sniffer capture.
Should stop background capturing, No further file I/O in capture file.
"""
if self.is_active:
self.is_active = False
if self.subprocess:
self.subprocess.terminate()
self.subprocess.wait() | [
"def",
"stopSniffer",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_active",
":",
"self",
".",
"is_active",
"=",
"False",
"if",
"self",
".",
"subprocess",
":",
"self",
".",
"subprocess",
".",
"terminate",
"(",
")",
"self",
".",
"subprocess",
".",
"wait",
"(",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-sniffer/OT_Sniffer.py#L106-L115 |
||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py | python | StateTracker.InParentheses | (self) | return bool(self._paren_depth) | Returns true if the current token is within parentheses.
Returns:
True if the current token is within parentheses. | Returns true if the current token is within parentheses. | [
"Returns",
"true",
"if",
"the",
"current",
"token",
"is",
"within",
"parentheses",
"."
] | def InParentheses(self):
"""Returns true if the current token is within parentheses.
Returns:
True if the current token is within parentheses.
"""
return bool(self._paren_depth) | [
"def",
"InParentheses",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_paren_depth",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py#L901-L907 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/message.py | python | Message.get_param | (self, param, failobj=None, header='content-type',
unquote=True) | return failobj | Return the parameter value if found in the Content-Type header.
Optional failobj is the object to return if there is no Content-Type
header, or the Content-Type header has no such parameter. Optional
header is the header to search instead of Content-Type.
Parameter keys are always compared case insensitively. The return
value can either be a string, or a 3-tuple if the parameter was RFC
2231 encoded. When it's a 3-tuple, the elements of the value are of
the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
LANGUAGE can be None, in which case you should consider VALUE to be
encoded in the us-ascii charset. You can usually ignore LANGUAGE.
The parameter value (either the returned string, or the VALUE item in
the 3-tuple) is always unquoted, unless unquote is set to False.
If your application doesn't care whether the parameter was RFC 2231
encoded, it can turn the return value into a string as follows:
rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam) | Return the parameter value if found in the Content-Type header. | [
"Return",
"the",
"parameter",
"value",
"if",
"found",
"in",
"the",
"Content",
"-",
"Type",
"header",
"."
] | def get_param(self, param, failobj=None, header='content-type',
unquote=True):
"""Return the parameter value if found in the Content-Type header.
Optional failobj is the object to return if there is no Content-Type
header, or the Content-Type header has no such parameter. Optional
header is the header to search instead of Content-Type.
Parameter keys are always compared case insensitively. The return
value can either be a string, or a 3-tuple if the parameter was RFC
2231 encoded. When it's a 3-tuple, the elements of the value are of
the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and
LANGUAGE can be None, in which case you should consider VALUE to be
encoded in the us-ascii charset. You can usually ignore LANGUAGE.
The parameter value (either the returned string, or the VALUE item in
the 3-tuple) is always unquoted, unless unquote is set to False.
If your application doesn't care whether the parameter was RFC 2231
encoded, it can turn the return value into a string as follows:
rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam)
"""
if header not in self:
return failobj
for k, v in self._get_params_preserve(failobj, header):
if k.lower() == param.lower():
if unquote:
return _unquotevalue(v)
else:
return v
return failobj | [
"def",
"get_param",
"(",
"self",
",",
"param",
",",
"failobj",
"=",
"None",
",",
"header",
"=",
"'content-type'",
",",
"unquote",
"=",
"True",
")",
":",
"if",
"header",
"not",
"in",
"self",
":",
"return",
"failobj",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_get_params_preserve",
"(",
"failobj",
",",
"header",
")",
":",
"if",
"k",
".",
"lower",
"(",
")",
"==",
"param",
".",
"lower",
"(",
")",
":",
"if",
"unquote",
":",
"return",
"_unquotevalue",
"(",
"v",
")",
"else",
":",
"return",
"v",
"return",
"failobj"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/message.py#L667-L699 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap_external.py | python | _calc_mode | (path) | return mode | Calculate the mode permissions for a bytecode file. | Calculate the mode permissions for a bytecode file. | [
"Calculate",
"the",
"mode",
"permissions",
"for",
"a",
"bytecode",
"file",
"."
] | def _calc_mode(path):
"""Calculate the mode permissions for a bytecode file."""
try:
mode = _path_stat(path).st_mode
except OSError:
mode = 0o666
# We always ensure write access so we can update cached files
# later even when the source files are read-only on Windows (#6074)
mode |= 0o200
return mode | [
"def",
"_calc_mode",
"(",
"path",
")",
":",
"try",
":",
"mode",
"=",
"_path_stat",
"(",
"path",
")",
".",
"st_mode",
"except",
"OSError",
":",
"mode",
"=",
"0o666",
"# We always ensure write access so we can update cached files",
"# later even when the source files are read-only on Windows (#6074)",
"mode",
"|=",
"0o200",
"return",
"mode"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap_external.py#L381-L390 |
|
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | docs/doxygen/gmxtree.py | python | GromacsTree.report_unused_cycle_suppressions | (self, reporter) | Reports unused cycle suppressions. | Reports unused cycle suppressions. | [
"Reports",
"unused",
"cycle",
"suppressions",
"."
] | def report_unused_cycle_suppressions(self, reporter):
"""Reports unused cycle suppressions."""
for module in self.get_modules():
for dep in module.get_dependencies():
if not dep.suppression_used:
reporter.cyclic_issue("unused cycle suppression: {0} -> {1}".format(module.get_name()[7:], dep.get_other_module().get_name()[7:])) | [
"def",
"report_unused_cycle_suppressions",
"(",
"self",
",",
"reporter",
")",
":",
"for",
"module",
"in",
"self",
".",
"get_modules",
"(",
")",
":",
"for",
"dep",
"in",
"module",
".",
"get_dependencies",
"(",
")",
":",
"if",
"not",
"dep",
".",
"suppression_used",
":",
"reporter",
".",
"cyclic_issue",
"(",
"\"unused cycle suppression: {0} -> {1}\"",
".",
"format",
"(",
"module",
".",
"get_name",
"(",
")",
"[",
"7",
":",
"]",
",",
"dep",
".",
"get_other_module",
"(",
")",
".",
"get_name",
"(",
")",
"[",
"7",
":",
"]",
")",
")"
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/docs/doxygen/gmxtree.py#L1021-L1026 |
||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/openvino/runtime/opset8/ops.py | python | adaptive_avg_pool | (
data: NodeInput,
output_shape: NodeInput
) | return _get_node_factory_opset8().create("AdaptiveAvgPool", inputs) | Return a node which performs AdaptiveAvgPool operation.
@param data: The list of input nodes
@param output_shape: the shape of spatial dimentions after operation
@return: The new node performing AdaptiveAvgPool operation on the data | Return a node which performs AdaptiveAvgPool operation. | [
"Return",
"a",
"node",
"which",
"performs",
"AdaptiveAvgPool",
"operation",
"."
] | def adaptive_avg_pool(
data: NodeInput,
output_shape: NodeInput
) -> Node:
"""Return a node which performs AdaptiveAvgPool operation.
@param data: The list of input nodes
@param output_shape: the shape of spatial dimentions after operation
@return: The new node performing AdaptiveAvgPool operation on the data
"""
inputs = as_nodes(data, output_shape)
return _get_node_factory_opset8().create("AdaptiveAvgPool", inputs) | [
"def",
"adaptive_avg_pool",
"(",
"data",
":",
"NodeInput",
",",
"output_shape",
":",
"NodeInput",
")",
"->",
"Node",
":",
"inputs",
"=",
"as_nodes",
"(",
"data",
",",
"output_shape",
")",
"return",
"_get_node_factory_opset8",
"(",
")",
".",
"create",
"(",
"\"AdaptiveAvgPool\"",
",",
"inputs",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset8/ops.py#L89-L100 |
|
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _GetMSBuildPropertyGroup | (spec, label, properties) | return [group] | Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true. | Returns a PropertyGroup definition for the specified properties. | [
"Returns",
"a",
"PropertyGroup",
"definition",
"for",
"the",
"specified",
"properties",
"."
] | def _GetMSBuildPropertyGroup(spec, label, properties):
"""Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true.
"""
group = ["PropertyGroup"]
if label:
group.append({"Label": label})
num_configurations = len(spec["configurations"])
def GetEdges(node):
# Use a definition of edges such that user_of_variable -> used_varible.
# This happens to be easier in this case, since a variable's
# definition contains all variables it references in a single string.
edges = set()
for value in sorted(properties[node].keys()):
# Add to edges all $(...) references to variables.
#
# Variable references that refer to names not in properties are excluded
# These can exist for instance to refer built in definitions like
# $(SolutionDir).
#
# Self references are ignored. Self reference is used in a few places to
# append to the default value. I.e. PATH=$(PATH);other_path
edges.update(
{
v
for v in MSVS_VARIABLE_REFERENCE.findall(value)
if v in properties and v != node
}
)
return edges
properties_ordered = gyp.common.TopologicallySorted(properties.keys(), GetEdges)
# Walk properties in the reverse of a topological sort on
# user_of_variable -> used_variable as this ensures variables are
# defined before they are used.
# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
for name in reversed(properties_ordered):
values = properties[name]
for value, conditions in sorted(values.items()):
if len(conditions) == num_configurations:
# If the value is the same all configurations,
# just add one unconditional entry.
group.append([name, value])
else:
for condition in conditions:
group.append([name, {"Condition": condition}, value])
return [group] | [
"def",
"_GetMSBuildPropertyGroup",
"(",
"spec",
",",
"label",
",",
"properties",
")",
":",
"group",
"=",
"[",
"\"PropertyGroup\"",
"]",
"if",
"label",
":",
"group",
".",
"append",
"(",
"{",
"\"Label\"",
":",
"label",
"}",
")",
"num_configurations",
"=",
"len",
"(",
"spec",
"[",
"\"configurations\"",
"]",
")",
"def",
"GetEdges",
"(",
"node",
")",
":",
"# Use a definition of edges such that user_of_variable -> used_varible.",
"# This happens to be easier in this case, since a variable's",
"# definition contains all variables it references in a single string.",
"edges",
"=",
"set",
"(",
")",
"for",
"value",
"in",
"sorted",
"(",
"properties",
"[",
"node",
"]",
".",
"keys",
"(",
")",
")",
":",
"# Add to edges all $(...) references to variables.",
"#",
"# Variable references that refer to names not in properties are excluded",
"# These can exist for instance to refer built in definitions like",
"# $(SolutionDir).",
"#",
"# Self references are ignored. Self reference is used in a few places to",
"# append to the default value. I.e. PATH=$(PATH);other_path",
"edges",
".",
"update",
"(",
"{",
"v",
"for",
"v",
"in",
"MSVS_VARIABLE_REFERENCE",
".",
"findall",
"(",
"value",
")",
"if",
"v",
"in",
"properties",
"and",
"v",
"!=",
"node",
"}",
")",
"return",
"edges",
"properties_ordered",
"=",
"gyp",
".",
"common",
".",
"TopologicallySorted",
"(",
"properties",
".",
"keys",
"(",
")",
",",
"GetEdges",
")",
"# Walk properties in the reverse of a topological sort on",
"# user_of_variable -> used_variable as this ensures variables are",
"# defined before they are used.",
"# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))",
"for",
"name",
"in",
"reversed",
"(",
"properties_ordered",
")",
":",
"values",
"=",
"properties",
"[",
"name",
"]",
"for",
"value",
",",
"conditions",
"in",
"sorted",
"(",
"values",
".",
"items",
"(",
")",
")",
":",
"if",
"len",
"(",
"conditions",
")",
"==",
"num_configurations",
":",
"# If the value is the same all configurations,",
"# just add one unconditional entry.",
"group",
".",
"append",
"(",
"[",
"name",
",",
"value",
"]",
")",
"else",
":",
"for",
"condition",
"in",
"conditions",
":",
"group",
".",
"append",
"(",
"[",
"name",
",",
"{",
"\"Condition\"",
":",
"condition",
"}",
",",
"value",
"]",
")",
"return",
"[",
"group",
"]"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L3259-L3312 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | UpdateUIEvent.Enable | (*args, **kwargs) | return _core_.UpdateUIEvent_Enable(*args, **kwargs) | Enable(self, bool enable)
Enable or disable the UI element. | Enable(self, bool enable) | [
"Enable",
"(",
"self",
"bool",
"enable",
")"
] | def Enable(*args, **kwargs):
"""
Enable(self, bool enable)
Enable or disable the UI element.
"""
return _core_.UpdateUIEvent_Enable(*args, **kwargs) | [
"def",
"Enable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"UpdateUIEvent_Enable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L6825-L6831 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/play_services/update.py | python | AddBasicArguments | (parser) | Defines the common arguments on subparser rather than the main one. This
allows to put arguments after the command: `foo.py upload --debug --force`
instead of `foo.py --debug upload --force` | Defines the common arguments on subparser rather than the main one. This
allows to put arguments after the command: `foo.py upload --debug --force`
instead of `foo.py --debug upload --force` | [
"Defines",
"the",
"common",
"arguments",
"on",
"subparser",
"rather",
"than",
"the",
"main",
"one",
".",
"This",
"allows",
"to",
"put",
"arguments",
"after",
"the",
"command",
":",
"foo",
".",
"py",
"upload",
"--",
"debug",
"--",
"force",
"instead",
"of",
"foo",
".",
"py",
"--",
"debug",
"upload",
"--",
"force"
] | def AddBasicArguments(parser):
'''
Defines the common arguments on subparser rather than the main one. This
allows to put arguments after the command: `foo.py upload --debug --force`
instead of `foo.py --debug upload --force`
'''
parser.add_argument('--sdk-root',
help='base path to the Android SDK tools root',
default=constants.ANDROID_SDK_ROOT)
parser.add_argument('-v', '--verbose',
action='store_true',
help='print debug information') | [
"def",
"AddBasicArguments",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--sdk-root'",
",",
"help",
"=",
"'base path to the Android SDK tools root'",
",",
"default",
"=",
"constants",
".",
"ANDROID_SDK_ROOT",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'print debug information'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/play_services/update.py#L102-L115 |
||
citizenfx/fivem | 88276d40cc7baf8285d02754cc5ae42ec7a8563f | vendor/chromium/base/PRESUBMIT.py | python | _CheckNoInterfacesInBase | (input_api, output_api) | return [] | Checks to make sure no files in libbase.a have |@interface|. | Checks to make sure no files in libbase.a have | | [
"Checks",
"to",
"make",
"sure",
"no",
"files",
"in",
"libbase",
".",
"a",
"have",
"|"
] | def _CheckNoInterfacesInBase(input_api, output_api):
"""Checks to make sure no files in libbase.a have |@interface|."""
pattern = input_api.re.compile(r'^\s*@interface', input_api.re.MULTILINE)
files = []
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if (f.LocalPath().startswith('base/') and
not "/ios/" in f.LocalPath() and
not "/test/" in f.LocalPath() and
not f.LocalPath().endswith('_unittest.mm') and
not f.LocalPath().endswith('mac/sdk_forward_declarations.h')):
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if len(files):
return [ output_api.PresubmitError(
'Objective-C interfaces or categories are forbidden in libbase. ' +
'See http://groups.google.com/a/chromium.org/group/chromium-dev/' +
'browse_thread/thread/efb28c10435987fd',
files) ]
return [] | [
"def",
"_CheckNoInterfacesInBase",
"(",
"input_api",
",",
"output_api",
")",
":",
"pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'^\\s*@interface'",
",",
"input_api",
".",
"re",
".",
"MULTILINE",
")",
"files",
"=",
"[",
"]",
"for",
"f",
"in",
"input_api",
".",
"AffectedSourceFiles",
"(",
"input_api",
".",
"FilterSourceFile",
")",
":",
"if",
"(",
"f",
".",
"LocalPath",
"(",
")",
".",
"startswith",
"(",
"'base/'",
")",
"and",
"not",
"\"/ios/\"",
"in",
"f",
".",
"LocalPath",
"(",
")",
"and",
"not",
"\"/test/\"",
"in",
"f",
".",
"LocalPath",
"(",
")",
"and",
"not",
"f",
".",
"LocalPath",
"(",
")",
".",
"endswith",
"(",
"'_unittest.mm'",
")",
"and",
"not",
"f",
".",
"LocalPath",
"(",
")",
".",
"endswith",
"(",
"'mac/sdk_forward_declarations.h'",
")",
")",
":",
"contents",
"=",
"input_api",
".",
"ReadFile",
"(",
"f",
")",
"if",
"pattern",
".",
"search",
"(",
"contents",
")",
":",
"files",
".",
"append",
"(",
"f",
")",
"if",
"len",
"(",
"files",
")",
":",
"return",
"[",
"output_api",
".",
"PresubmitError",
"(",
"'Objective-C interfaces or categories are forbidden in libbase. '",
"+",
"'See http://groups.google.com/a/chromium.org/group/chromium-dev/'",
"+",
"'browse_thread/thread/efb28c10435987fd'",
",",
"files",
")",
"]",
"return",
"[",
"]"
] | https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/base/PRESUBMIT.py#L11-L31 |
|
tangjianpku/LINE | d5f840941e0f4026090d1b1feeaf15da38e2b24b | windows/evaluate/liblinear/python/liblinearutil.py | python | load_model | (model_file_name) | return model | load_model(model_file_name) -> model
Load a LIBLINEAR model from model_file_name and return. | load_model(model_file_name) -> model | [
"load_model",
"(",
"model_file_name",
")",
"-",
">",
"model"
] | def load_model(model_file_name):
"""
load_model(model_file_name) -> model
Load a LIBLINEAR model from model_file_name and return.
"""
model = liblinear.load_model(model_file_name.encode())
if not model:
print("can't open model file %s" % model_file_name)
return None
model = toPyModel(model)
return model | [
"def",
"load_model",
"(",
"model_file_name",
")",
":",
"model",
"=",
"liblinear",
".",
"load_model",
"(",
"model_file_name",
".",
"encode",
"(",
")",
")",
"if",
"not",
"model",
":",
"print",
"(",
"\"can't open model file %s\"",
"%",
"model_file_name",
")",
"return",
"None",
"model",
"=",
"toPyModel",
"(",
"model",
")",
"return",
"model"
] | https://github.com/tangjianpku/LINE/blob/d5f840941e0f4026090d1b1feeaf15da38e2b24b/windows/evaluate/liblinear/python/liblinearutil.py#L29-L40 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/logging/__init__.py | python | setLoggerClass | (klass) | Set the class to be used when instantiating a logger. The class should
define __init__() such that only a name argument is required, and the
__init__() should call Logger.__init__() | Set the class to be used when instantiating a logger. The class should
define __init__() such that only a name argument is required, and the
__init__() should call Logger.__init__() | [
"Set",
"the",
"class",
"to",
"be",
"used",
"when",
"instantiating",
"a",
"logger",
".",
"The",
"class",
"should",
"define",
"__init__",
"()",
"such",
"that",
"only",
"a",
"name",
"argument",
"is",
"required",
"and",
"the",
"__init__",
"()",
"should",
"call",
"Logger",
".",
"__init__",
"()"
] | def setLoggerClass(klass):
"""
Set the class to be used when instantiating a logger. The class should
define __init__() such that only a name argument is required, and the
__init__() should call Logger.__init__()
"""
if klass != Logger:
if not issubclass(klass, Logger):
raise TypeError("logger not derived from logging.Logger: "
+ klass.__name__)
global _loggerClass
_loggerClass = klass | [
"def",
"setLoggerClass",
"(",
"klass",
")",
":",
"if",
"klass",
"!=",
"Logger",
":",
"if",
"not",
"issubclass",
"(",
"klass",
",",
"Logger",
")",
":",
"raise",
"TypeError",
"(",
"\"logger not derived from logging.Logger: \"",
"+",
"klass",
".",
"__name__",
")",
"global",
"_loggerClass",
"_loggerClass",
"=",
"klass"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/__init__.py#L997-L1008 |
||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | in_range | (symbol, section) | Test whether a symbol is within the range of a section. | Test whether a symbol is within the range of a section. | [
"Test",
"whether",
"a",
"symbol",
"is",
"within",
"the",
"range",
"of",
"a",
"section",
"."
] | def in_range(symbol, section):
"""Test whether a symbol is within the range of a section."""
symSA = symbol.GetStartAddress().GetFileAddress()
symEA = symbol.GetEndAddress().GetFileAddress()
secSA = section.GetFileAddress()
secEA = secSA + section.GetByteSize()
if symEA != LLDB_INVALID_ADDRESS:
if secSA <= symSA and symEA <= secEA:
return True
else:
return False
else:
if secSA <= symSA and symSA < secEA:
return True
else:
return False | [
"def",
"in_range",
"(",
"symbol",
",",
"section",
")",
":",
"symSA",
"=",
"symbol",
".",
"GetStartAddress",
"(",
")",
".",
"GetFileAddress",
"(",
")",
"symEA",
"=",
"symbol",
".",
"GetEndAddress",
"(",
")",
".",
"GetFileAddress",
"(",
")",
"secSA",
"=",
"section",
".",
"GetFileAddress",
"(",
")",
"secEA",
"=",
"secSA",
"+",
"section",
".",
"GetByteSize",
"(",
")",
"if",
"symEA",
"!=",
"LLDB_INVALID_ADDRESS",
":",
"if",
"secSA",
"<=",
"symSA",
"and",
"symEA",
"<=",
"secEA",
":",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"if",
"secSA",
"<=",
"symSA",
"and",
"symSA",
"<",
"secEA",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L7042-L7058 |
||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | CommonTools/ParticleFlow/python/Tools/enablePileUpCorrection.py | python | enablePileUpCorrection | ( process, postfix, sequence='patPF2PATSequence') | Enables the pile-up correction for jets in a PF2PAT+PAT sequence
to be called after the usePF2PAT function. | Enables the pile-up correction for jets in a PF2PAT+PAT sequence
to be called after the usePF2PAT function. | [
"Enables",
"the",
"pile",
"-",
"up",
"correction",
"for",
"jets",
"in",
"a",
"PF2PAT",
"+",
"PAT",
"sequence",
"to",
"be",
"called",
"after",
"the",
"usePF2PAT",
"function",
"."
] | def enablePileUpCorrection( process, postfix, sequence='patPF2PATSequence'):
"""
Enables the pile-up correction for jets in a PF2PAT+PAT sequence
to be called after the usePF2PAT function.
"""
enablePileUpCorrectionInPF2PAT( process, postfix, sequence)
enablePileUpCorrectionInPAT( process, postfix, sequence) | [
"def",
"enablePileUpCorrection",
"(",
"process",
",",
"postfix",
",",
"sequence",
"=",
"'patPF2PATSequence'",
")",
":",
"enablePileUpCorrectionInPF2PAT",
"(",
"process",
",",
"postfix",
",",
"sequence",
")",
"enablePileUpCorrectionInPAT",
"(",
"process",
",",
"postfix",
",",
"sequence",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CommonTools/ParticleFlow/python/Tools/enablePileUpCorrection.py#L31-L38 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Variable.trace_vinfo | (self) | return map(self._tk.split, self._tk.splitlist(
self._tk.call("trace", "vinfo", self._name))) | Return all trace callback information. | Return all trace callback information. | [
"Return",
"all",
"trace",
"callback",
"information",
"."
] | def trace_vinfo(self):
"""Return all trace callback information."""
return map(self._tk.split, self._tk.splitlist(
self._tk.call("trace", "vinfo", self._name))) | [
"def",
"trace_vinfo",
"(",
"self",
")",
":",
"return",
"map",
"(",
"self",
".",
"_tk",
".",
"split",
",",
"self",
".",
"_tk",
".",
"splitlist",
"(",
"self",
".",
"_tk",
".",
"call",
"(",
"\"trace\"",
",",
"\"vinfo\"",
",",
"self",
".",
"_name",
")",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L261-L264 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/iterators.py | python | body_line_iterator | (msg, decode=False) | Iterate over the parts, returning string payloads line-by-line.
Optional decode (default False) is passed through to .get_payload(). | Iterate over the parts, returning string payloads line-by-line. | [
"Iterate",
"over",
"the",
"parts",
"returning",
"string",
"payloads",
"line",
"-",
"by",
"-",
"line",
"."
] | def body_line_iterator(msg, decode=False):
"""Iterate over the parts, returning string payloads line-by-line.
Optional decode (default False) is passed through to .get_payload().
"""
for subpart in msg.walk():
payload = subpart.get_payload(decode=decode)
if isinstance(payload, basestring):
for line in StringIO(payload):
yield line | [
"def",
"body_line_iterator",
"(",
"msg",
",",
"decode",
"=",
"False",
")",
":",
"for",
"subpart",
"in",
"msg",
".",
"walk",
"(",
")",
":",
"payload",
"=",
"subpart",
".",
"get_payload",
"(",
"decode",
"=",
"decode",
")",
"if",
"isinstance",
"(",
"payload",
",",
"basestring",
")",
":",
"for",
"line",
"in",
"StringIO",
"(",
"payload",
")",
":",
"yield",
"line"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/iterators.py#L35-L44 |
||
bundy-dns/bundy | 3d41934996b82b0cd2fe22dd74d2abc1daba835d | src/lib/python/bundy/config/ccsession.py | python | UIModuleCCSession.update_specs_and_config | (self) | Convenience function to both clear and update the known list of
module specifications, and update the current configuration on
the server side. There are a few cases where the caller might only
want to run one of these tasks, but often they are both needed. | Convenience function to both clear and update the known list of
module specifications, and update the current configuration on
the server side. There are a few cases where the caller might only
want to run one of these tasks, but often they are both needed. | [
"Convenience",
"function",
"to",
"both",
"clear",
"and",
"update",
"the",
"known",
"list",
"of",
"module",
"specifications",
"and",
"update",
"the",
"current",
"configuration",
"on",
"the",
"server",
"side",
".",
"There",
"are",
"a",
"few",
"cases",
"where",
"the",
"caller",
"might",
"only",
"want",
"to",
"run",
"one",
"of",
"these",
"tasks",
"but",
"often",
"they",
"are",
"both",
"needed",
"."
] | def update_specs_and_config(self):
"""Convenience function to both clear and update the known list of
module specifications, and update the current configuration on
the server side. There are a few cases where the caller might only
want to run one of these tasks, but often they are both needed."""
self.request_specifications()
self.request_current_config() | [
"def",
"update_specs_and_config",
"(",
"self",
")",
":",
"self",
".",
"request_specifications",
"(",
")",
"self",
".",
"request_current_config",
"(",
")"
] | https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/config/ccsession.py#L691-L697 |
||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | tools/linter/clang_tidy/run.py | python | get_all_files | (paths: List[str]) | return str(output).strip().splitlines() | Returns all files that are tracked by git in the given paths. | Returns all files that are tracked by git in the given paths. | [
"Returns",
"all",
"files",
"that",
"are",
"tracked",
"by",
"git",
"in",
"the",
"given",
"paths",
"."
] | async def get_all_files(paths: List[str]) -> List[str]:
"""Returns all files that are tracked by git in the given paths."""
output = await run_shell_command(["git", "ls-files"] + paths)
return str(output).strip().splitlines() | [
"async",
"def",
"get_all_files",
"(",
"paths",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"output",
"=",
"await",
"run_shell_command",
"(",
"[",
"\"git\"",
",",
"\"ls-files\"",
"]",
"+",
"paths",
")",
"return",
"str",
"(",
"output",
")",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/linter/clang_tidy/run.py#L389-L392 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/cygwinccompiler.py | python | CygwinCCompiler.link | (self, target_desc, objects, output_filename, output_dir=None,
libraries=None, library_dirs=None, runtime_library_dirs=None,
export_symbols=None, debug=0, extra_preargs=None,
extra_postargs=None, build_temp=None, target_lang=None) | Link the objects. | Link the objects. | [
"Link",
"the",
"objects",
"."
] | def link(self, target_desc, objects, output_filename, output_dir=None,
libraries=None, library_dirs=None, runtime_library_dirs=None,
export_symbols=None, debug=0, extra_preargs=None,
extra_postargs=None, build_temp=None, target_lang=None):
"""Link the objects."""
# use separate copies, so we can modify the lists
extra_preargs = copy.copy(extra_preargs or [])
libraries = copy.copy(libraries or [])
objects = copy.copy(objects or [])
# Additional libraries
libraries.extend(self.dll_libraries)
# handle export symbols by creating a def-file
# with executables this only works with gcc/ld as linker
if ((export_symbols is not None) and
(target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
# (The linker doesn't do anything if output is up-to-date.
# So it would probably better to check if we really need this,
# but for this we had to insert some unchanged parts of
# UnixCCompiler, and this is not what we want.)
# we want to put some files in the same directory as the
# object files are, build_temp doesn't help much
# where are the object files
temp_dir = os.path.dirname(objects[0])
# name of dll to give the helper files the same base name
(dll_name, dll_extension) = os.path.splitext(
os.path.basename(output_filename))
# generate the filenames for these files
def_file = os.path.join(temp_dir, dll_name + ".def")
lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
# Generate .def file
contents = [
"LIBRARY %s" % os.path.basename(output_filename),
"EXPORTS"]
for sym in export_symbols:
contents.append(sym)
self.execute(write_file, (def_file, contents),
"writing %s" % def_file)
# next add options for def-file and to creating import libraries
# dllwrap uses different options than gcc/ld
if self.linker_dll == "dllwrap":
extra_preargs.extend(["--output-lib", lib_file])
# for dllwrap we have to use a special option
extra_preargs.extend(["--def", def_file])
# we use gcc/ld here and can be sure ld is >= 2.9.10
else:
# doesn't work: bfd_close build\...\libfoo.a: Invalid operation
#extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
# for gcc/ld the def-file is specified as any object files
objects.append(def_file)
#end: if ((export_symbols is not None) and
# (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
# who wants symbols and a many times larger output file
# should explicitly switch the debug mode on
# otherwise we let dllwrap/ld strip the output file
# (On my machine: 10KiB < stripped_file < ??100KiB
# unstripped_file = stripped_file + XXX KiB
# ( XXX=254 for a typical python extension))
if not debug:
extra_preargs.append("-s")
UnixCCompiler.link(self, target_desc, objects, output_filename,
output_dir, libraries, library_dirs,
runtime_library_dirs,
None, # export_symbols, we do this in our def-file
debug, extra_preargs, extra_postargs, build_temp,
target_lang) | [
"def",
"link",
"(",
"self",
",",
"target_desc",
",",
"objects",
",",
"output_filename",
",",
"output_dir",
"=",
"None",
",",
"libraries",
"=",
"None",
",",
"library_dirs",
"=",
"None",
",",
"runtime_library_dirs",
"=",
"None",
",",
"export_symbols",
"=",
"None",
",",
"debug",
"=",
"0",
",",
"extra_preargs",
"=",
"None",
",",
"extra_postargs",
"=",
"None",
",",
"build_temp",
"=",
"None",
",",
"target_lang",
"=",
"None",
")",
":",
"# use separate copies, so we can modify the lists",
"extra_preargs",
"=",
"copy",
".",
"copy",
"(",
"extra_preargs",
"or",
"[",
"]",
")",
"libraries",
"=",
"copy",
".",
"copy",
"(",
"libraries",
"or",
"[",
"]",
")",
"objects",
"=",
"copy",
".",
"copy",
"(",
"objects",
"or",
"[",
"]",
")",
"# Additional libraries",
"libraries",
".",
"extend",
"(",
"self",
".",
"dll_libraries",
")",
"# handle export symbols by creating a def-file",
"# with executables this only works with gcc/ld as linker",
"if",
"(",
"(",
"export_symbols",
"is",
"not",
"None",
")",
"and",
"(",
"target_desc",
"!=",
"self",
".",
"EXECUTABLE",
"or",
"self",
".",
"linker_dll",
"==",
"\"gcc\"",
")",
")",
":",
"# (The linker doesn't do anything if output is up-to-date.",
"# So it would probably better to check if we really need this,",
"# but for this we had to insert some unchanged parts of",
"# UnixCCompiler, and this is not what we want.)",
"# we want to put some files in the same directory as the",
"# object files are, build_temp doesn't help much",
"# where are the object files",
"temp_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"objects",
"[",
"0",
"]",
")",
"# name of dll to give the helper files the same base name",
"(",
"dll_name",
",",
"dll_extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"output_filename",
")",
")",
"# generate the filenames for these files",
"def_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"dll_name",
"+",
"\".def\"",
")",
"lib_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"'lib'",
"+",
"dll_name",
"+",
"\".a\"",
")",
"# Generate .def file",
"contents",
"=",
"[",
"\"LIBRARY %s\"",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"output_filename",
")",
",",
"\"EXPORTS\"",
"]",
"for",
"sym",
"in",
"export_symbols",
":",
"contents",
".",
"append",
"(",
"sym",
")",
"self",
".",
"execute",
"(",
"write_file",
",",
"(",
"def_file",
",",
"contents",
")",
",",
"\"writing %s\"",
"%",
"def_file",
")",
"# next add options for def-file and to creating import libraries",
"# dllwrap uses different options than gcc/ld",
"if",
"self",
".",
"linker_dll",
"==",
"\"dllwrap\"",
":",
"extra_preargs",
".",
"extend",
"(",
"[",
"\"--output-lib\"",
",",
"lib_file",
"]",
")",
"# for dllwrap we have to use a special option",
"extra_preargs",
".",
"extend",
"(",
"[",
"\"--def\"",
",",
"def_file",
"]",
")",
"# we use gcc/ld here and can be sure ld is >= 2.9.10",
"else",
":",
"# doesn't work: bfd_close build\\...\\libfoo.a: Invalid operation",
"#extra_preargs.extend([\"-Wl,--out-implib,%s\" % lib_file])",
"# for gcc/ld the def-file is specified as any object files",
"objects",
".",
"append",
"(",
"def_file",
")",
"#end: if ((export_symbols is not None) and",
"# (target_desc != self.EXECUTABLE or self.linker_dll == \"gcc\")):",
"# who wants symbols and a many times larger output file",
"# should explicitly switch the debug mode on",
"# otherwise we let dllwrap/ld strip the output file",
"# (On my machine: 10KiB < stripped_file < ??100KiB",
"# unstripped_file = stripped_file + XXX KiB",
"# ( XXX=254 for a typical python extension))",
"if",
"not",
"debug",
":",
"extra_preargs",
".",
"append",
"(",
"\"-s\"",
")",
"UnixCCompiler",
".",
"link",
"(",
"self",
",",
"target_desc",
",",
"objects",
",",
"output_filename",
",",
"output_dir",
",",
"libraries",
",",
"library_dirs",
",",
"runtime_library_dirs",
",",
"None",
",",
"# export_symbols, we do this in our def-file",
"debug",
",",
"extra_preargs",
",",
"extra_postargs",
",",
"build_temp",
",",
"target_lang",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/cygwinccompiler.py#L174-L248 |
||
nci/drishti | 89cd8b740239c5b2c8222dffd4e27432fde170a1 | bin/assets/scripts/unet++/unet_collection/swin.py | python | swin_transformer_stack | (X, stack_num, embed_dim,
num_patch, num_heads,
window_size, num_mlp,
shift_window=True,
name='') | return X | Stacked Swin Transformers that share the same token size.
Alternated Window-MSA and Swin-MSA will be configured if `shift_window=True`, Window-MSA only otherwise.
*Dropout is turned off. | Stacked Swin Transformers that share the same token size.
Alternated Window-MSA and Swin-MSA will be configured if `shift_window=True`, Window-MSA only otherwise.
*Dropout is turned off. | [
"Stacked",
"Swin",
"Transformers",
"that",
"share",
"the",
"same",
"token",
"size",
".",
"Alternated",
"Window",
"-",
"MSA",
"and",
"Swin",
"-",
"MSA",
"will",
"be",
"configured",
"if",
"shift_window",
"=",
"True",
"Window",
"-",
"MSA",
"only",
"otherwise",
".",
"*",
"Dropout",
"is",
"turned",
"off",
"."
] | def swin_transformer_stack(X, stack_num, embed_dim,
num_patch, num_heads,
window_size, num_mlp,
shift_window=True,
name=''):
'''
Stacked Swin Transformers that share the same token size.
Alternated Window-MSA and Swin-MSA will be configured if `shift_window=True`, Window-MSA only otherwise.
*Dropout is turned off.
'''
# Turn-off dropouts
mlp_drop_rate = 0 # Droupout after each MLP layer
attn_drop_rate = 0 # Dropout after Swin-Attention
proj_drop_rate = 0 # Dropout at the end of each Swin-Attention block, i.e., after linear projections
drop_path_rate = 0 # Drop-path within skip-connections
qkv_bias = True # Convert embedded patches to query, key, and values with a learnable additive value
qk_scale = None # None: Re-scale query based on embed dimensions per attention head # Float for user specified scaling factor
if shift_window:
shift_size = window_size // 2
else:
shift_size = 0
for i in range(stack_num):
if i % 2 == 0:
shift_size_temp = 0
else:
shift_size_temp = shift_size
X = swin_layers.SwinTransformerBlock(dim=embed_dim, num_patch=num_patch, num_heads=num_heads,
window_size=window_size, shift_size=shift_size_temp,
num_mlp=num_mlp, qkv_bias=qkv_bias, qk_scale=qk_scale,
mlp_drop=mlp_drop_rate,
attn_drop=attn_drop_rate,
proj_drop=proj_drop_rate,
drop_path_prob=drop_path_rate,
name='name{}'.format(i))(X)
return X | [
"def",
"swin_transformer_stack",
"(",
"X",
",",
"stack_num",
",",
"embed_dim",
",",
"num_patch",
",",
"num_heads",
",",
"window_size",
",",
"num_mlp",
",",
"shift_window",
"=",
"True",
",",
"name",
"=",
"''",
")",
":",
"# Turn-off dropouts",
"mlp_drop_rate",
"=",
"0",
"# Droupout after each MLP layer",
"attn_drop_rate",
"=",
"0",
"# Dropout after Swin-Attention",
"proj_drop_rate",
"=",
"0",
"# Dropout at the end of each Swin-Attention block, i.e., after linear projections",
"drop_path_rate",
"=",
"0",
"# Drop-path within skip-connections",
"qkv_bias",
"=",
"True",
"# Convert embedded patches to query, key, and values with a learnable additive value",
"qk_scale",
"=",
"None",
"# None: Re-scale query based on embed dimensions per attention head # Float for user specified scaling factor",
"if",
"shift_window",
":",
"shift_size",
"=",
"window_size",
"//",
"2",
"else",
":",
"shift_size",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"stack_num",
")",
":",
"if",
"i",
"%",
"2",
"==",
"0",
":",
"shift_size_temp",
"=",
"0",
"else",
":",
"shift_size_temp",
"=",
"shift_size",
"X",
"=",
"swin_layers",
".",
"SwinTransformerBlock",
"(",
"dim",
"=",
"embed_dim",
",",
"num_patch",
"=",
"num_patch",
",",
"num_heads",
"=",
"num_heads",
",",
"window_size",
"=",
"window_size",
",",
"shift_size",
"=",
"shift_size_temp",
",",
"num_mlp",
"=",
"num_mlp",
",",
"qkv_bias",
"=",
"qkv_bias",
",",
"qk_scale",
"=",
"qk_scale",
",",
"mlp_drop",
"=",
"mlp_drop_rate",
",",
"attn_drop",
"=",
"attn_drop_rate",
",",
"proj_drop",
"=",
"proj_drop_rate",
",",
"drop_path_prob",
"=",
"drop_path_rate",
",",
"name",
"=",
"'name{}'",
".",
"format",
"(",
"i",
")",
")",
"(",
"X",
")",
"return",
"X"
] | https://github.com/nci/drishti/blob/89cd8b740239c5b2c8222dffd4e27432fde170a1/bin/assets/scripts/unet++/unet_collection/swin.py#L14-L54 |
|
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/xml/sax/xmlreader.py | python | Locator.getPublicId | (self) | return None | Return the public identifier for the current event. | Return the public identifier for the current event. | [
"Return",
"the",
"public",
"identifier",
"for",
"the",
"current",
"event",
"."
] | def getPublicId(self):
"Return the public identifier for the current event."
return None | [
"def",
"getPublicId",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/xml/sax/xmlreader.py#L177-L179 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.winfo_rootx | (self) | return getint(
self.tk.call('winfo', 'rootx', self._w)) | Return x coordinate of upper left corner of this widget on the
root window. | Return x coordinate of upper left corner of this widget on the
root window. | [
"Return",
"x",
"coordinate",
"of",
"upper",
"left",
"corner",
"of",
"this",
"widget",
"on",
"the",
"root",
"window",
"."
] | def winfo_rootx(self):
"""Return x coordinate of upper left corner of this widget on the
root window."""
return getint(
self.tk.call('winfo', 'rootx', self._w)) | [
"def",
"winfo_rootx",
"(",
"self",
")",
":",
"return",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'rootx'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L838-L842 |
|
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | resources/osm_importer/webots_objects/road.py | python | Road.is_similar | (self, other) | Determine if a road has the same graphical shape than another in order to be merged. | Determine if a road has the same graphical shape than another in order to be merged. | [
"Determine",
"if",
"a",
"road",
"has",
"the",
"same",
"graphical",
"shape",
"than",
"another",
"in",
"order",
"to",
"be",
"merged",
"."
] | def is_similar(self, other):
"""Determine if a road has the same graphical shape than another in order to be merged."""
if (self.oneway and not other.oneway) or (not self.oneway and other.oneway):
return False # reject if the oneway attribute is not matching
if self.oneway:
# both roads are oneway
return (
self.lanes == other.lanes and
self.forwardLanes == other.forwardLanes and
self.backwardLanes == other.backwardLanes and
abs(self.width - other.width) <= 0.01
)
else:
# both roads are bidirectional
return (
self.lanes == other.lanes and
self.forwardLanes == other.backwardLanes and
self.backwardLanes == other.forwardLanes and
abs(self.width - other.width) <= 0.01
) | [
"def",
"is_similar",
"(",
"self",
",",
"other",
")",
":",
"if",
"(",
"self",
".",
"oneway",
"and",
"not",
"other",
".",
"oneway",
")",
"or",
"(",
"not",
"self",
".",
"oneway",
"and",
"other",
".",
"oneway",
")",
":",
"return",
"False",
"# reject if the oneway attribute is not matching",
"if",
"self",
".",
"oneway",
":",
"# both roads are oneway",
"return",
"(",
"self",
".",
"lanes",
"==",
"other",
".",
"lanes",
"and",
"self",
".",
"forwardLanes",
"==",
"other",
".",
"forwardLanes",
"and",
"self",
".",
"backwardLanes",
"==",
"other",
".",
"backwardLanes",
"and",
"abs",
"(",
"self",
".",
"width",
"-",
"other",
".",
"width",
")",
"<=",
"0.01",
")",
"else",
":",
"# both roads are bidirectional",
"return",
"(",
"self",
".",
"lanes",
"==",
"other",
".",
"lanes",
"and",
"self",
".",
"forwardLanes",
"==",
"other",
".",
"backwardLanes",
"and",
"self",
".",
"backwardLanes",
"==",
"other",
".",
"forwardLanes",
"and",
"abs",
"(",
"self",
".",
"width",
"-",
"other",
".",
"width",
")",
"<=",
"0.01",
")"
] | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/osm_importer/webots_objects/road.py#L212-L232 |
||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.AdjustLibraries | (self, libraries) | return [lib + '.lib' if not lib.lower().endswith('.lib') \
and not lib.lower().endswith('.obj') else lib for lib in libs] | Strip -l from library if it's specified with that. | Strip -l from library if it's specified with that. | [
"Strip",
"-",
"l",
"from",
"library",
"if",
"it",
"s",
"specified",
"with",
"that",
"."
] | def AdjustLibraries(self, libraries):
"""Strip -l from library if it's specified with that."""
libs = [lib[2:] if lib.startswith('-l') else lib for lib in libraries]
return [lib + '.lib' if not lib.lower().endswith('.lib') \
and not lib.lower().endswith('.obj') else lib for lib in libs] | [
"def",
"AdjustLibraries",
"(",
"self",
",",
"libraries",
")",
":",
"libs",
"=",
"[",
"lib",
"[",
"2",
":",
"]",
"if",
"lib",
".",
"startswith",
"(",
"'-l'",
")",
"else",
"lib",
"for",
"lib",
"in",
"libraries",
"]",
"return",
"[",
"lib",
"+",
"'.lib'",
"if",
"not",
"lib",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.lib'",
")",
"and",
"not",
"lib",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.obj'",
")",
"else",
"lib",
"for",
"lib",
"in",
"libs",
"]"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/msvs_emulation.py#L281-L285 |
|
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/package_index.py | python | ContentChecker.feed | (self, block) | return | Feed a block of data to the hash. | Feed a block of data to the hash. | [
"Feed",
"a",
"block",
"of",
"data",
"to",
"the",
"hash",
"."
] | def feed(self, block):
"""
Feed a block of data to the hash.
"""
return | [
"def",
"feed",
"(",
"self",
",",
"block",
")",
":",
"return"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/package_index.py#L245-L249 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | RawTurtle._tracer | (self, flag=None, delay=None) | return self.screen.tracer(flag, delay) | Turns turtle animation on/off and set delay for update drawings.
Optional arguments:
n -- nonnegative integer
delay -- nonnegative integer
If n is given, only each n-th regular screen update is really performed.
(Can be used to accelerate the drawing of complex graphics.)
Second arguments sets delay value (see RawTurtle.delay())
Example (for a Turtle instance named turtle):
>>> turtle.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
... turtle.fd(dist)
... turtle.rt(90)
... dist += 2 | Turns turtle animation on/off and set delay for update drawings. | [
"Turns",
"turtle",
"animation",
"on",
"/",
"off",
"and",
"set",
"delay",
"for",
"update",
"drawings",
"."
] | def _tracer(self, flag=None, delay=None):
"""Turns turtle animation on/off and set delay for update drawings.
Optional arguments:
n -- nonnegative integer
delay -- nonnegative integer
If n is given, only each n-th regular screen update is really performed.
(Can be used to accelerate the drawing of complex graphics.)
Second arguments sets delay value (see RawTurtle.delay())
Example (for a Turtle instance named turtle):
>>> turtle.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
... turtle.fd(dist)
... turtle.rt(90)
... dist += 2
"""
return self.screen.tracer(flag, delay) | [
"def",
"_tracer",
"(",
"self",
",",
"flag",
"=",
"None",
",",
"delay",
"=",
"None",
")",
":",
"return",
"self",
".",
"screen",
".",
"tracer",
"(",
"flag",
",",
"delay",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L2672-L2691 |
|
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel.side_set_exists | (self, side_set_id) | return side_set_id in self.get_side_set_ids() | Return 'True' if the given side set exists.
Examples:
>>> model.side_set_exists(1)
>>> model.node_set_exists('sideset_name') | Return 'True' if the given side set exists. | [
"Return",
"True",
"if",
"the",
"given",
"side",
"set",
"exists",
"."
] | def side_set_exists(self, side_set_id):
"""
Return 'True' if the given side set exists.
Examples:
>>> model.side_set_exists(1)
>>> model.node_set_exists('sideset_name')
"""
if isinstance(side_set_id, str):
return side_set_id in self.get_all_side_set_names()
return side_set_id in self.get_side_set_ids() | [
"def",
"side_set_exists",
"(",
"self",
",",
"side_set_id",
")",
":",
"if",
"isinstance",
"(",
"side_set_id",
",",
"str",
")",
":",
"return",
"side_set_id",
"in",
"self",
".",
"get_all_side_set_names",
"(",
")",
"return",
"side_set_id",
"in",
"self",
".",
"get_side_set_ids",
"(",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L4806-L4817 |
|
jsk-ros-pkg/jsk_recognition | be6e319d29797bafb10c589fdff364c3d333a605 | jsk_recognition_utils/python/jsk_recognition_utils/put_text.py | python | put_text_to_image | (
img, text, pos, font_path, font_size, color, background_color=None,
offset_x=0, offset_y=0) | return img | Put text to image using pillow.
You can put text to an image including non-ASCII characters.
Parameters
==========
img : numpy.ndarray
cv2 image. bgr order.
text : str
text information.
pos : tuple(float)
xy position of text.
font_path : str
path to font.
font_size : int
font size
color : tuple(int)
text color
background_color : tuple(int) or None
background color in text area. If this value is None, do nothing.
offset_x : float
x position offset.
offset_y : float
y position offset. | Put text to image using pillow. | [
"Put",
"text",
"to",
"image",
"using",
"pillow",
"."
] | def put_text_to_image(
img, text, pos, font_path, font_size, color, background_color=None,
offset_x=0, offset_y=0):
"""Put text to image using pillow.
You can put text to an image including non-ASCII characters.
Parameters
==========
img : numpy.ndarray
cv2 image. bgr order.
text : str
text information.
pos : tuple(float)
xy position of text.
font_path : str
path to font.
font_size : int
font size
color : tuple(int)
text color
background_color : tuple(int) or None
background color in text area. If this value is None, do nothing.
offset_x : float
x position offset.
offset_y : float
y position offset.
"""
if sys.version_info < (3, 0):
text = text.decode('utf-8')
pil_font = ImageFont.truetype(font=font_path, size=font_size)
dummy_draw = ImageDraw.Draw(Image.new("RGB", (0, 0)))
text_w, text_h = dummy_draw.textsize(text, font=pil_font)
text_bottom_offset = int(0.1 * text_h)
x, y = pos
offset_y = (text_h+text_bottom_offset) + offset_y
x0 = x - offset_x
y0 = y - offset_y
img_h, img_w = img.shape[:2]
# check outside of image.
if not ((-text_w < x0 < img_w)
and (-text_bottom_offset - text_h < y0 < img_h)):
return img
x1, y1 = max(x0, 0), max(y0, 0)
x2 = min(x0+text_w, img_w)
y2 = min(y0 + text_h + text_bottom_offset, img_h)
x0 = int(x0)
y0 = int(y0)
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
# Create a black image of the same size as the text area.
text_area = np.full(
(text_h + text_bottom_offset, text_w, 3),
(0, 0, 0), dtype=np.uint8)
if background_color is not None:
img[y1:y2, x1:x2] = np.array(background_color, dtype=np.uint8)
# paste the original image on all or part of it.
text_area[y1-y0:y2-y0, x1-x0:x2-x0] = img[y1:y2, x1:x2]
# convert pil image to cv2 image.
pil_img = Image.fromarray(text_area)
draw = ImageDraw.Draw(pil_img)
draw.text(xy=(0, 0), text=text, fill=color, font=pil_font)
text_area = np.array(pil_img, dtype=np.uint8)
img[y1:y2, x1:x2] = text_area[y1-y0:y2-y0, x1-x0:x2-x0]
return img | [
"def",
"put_text_to_image",
"(",
"img",
",",
"text",
",",
"pos",
",",
"font_path",
",",
"font_size",
",",
"color",
",",
"background_color",
"=",
"None",
",",
"offset_x",
"=",
"0",
",",
"offset_y",
"=",
"0",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"pil_font",
"=",
"ImageFont",
".",
"truetype",
"(",
"font",
"=",
"font_path",
",",
"size",
"=",
"font_size",
")",
"dummy_draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"Image",
".",
"new",
"(",
"\"RGB\"",
",",
"(",
"0",
",",
"0",
")",
")",
")",
"text_w",
",",
"text_h",
"=",
"dummy_draw",
".",
"textsize",
"(",
"text",
",",
"font",
"=",
"pil_font",
")",
"text_bottom_offset",
"=",
"int",
"(",
"0.1",
"*",
"text_h",
")",
"x",
",",
"y",
"=",
"pos",
"offset_y",
"=",
"(",
"text_h",
"+",
"text_bottom_offset",
")",
"+",
"offset_y",
"x0",
"=",
"x",
"-",
"offset_x",
"y0",
"=",
"y",
"-",
"offset_y",
"img_h",
",",
"img_w",
"=",
"img",
".",
"shape",
"[",
":",
"2",
"]",
"# check outside of image.",
"if",
"not",
"(",
"(",
"-",
"text_w",
"<",
"x0",
"<",
"img_w",
")",
"and",
"(",
"-",
"text_bottom_offset",
"-",
"text_h",
"<",
"y0",
"<",
"img_h",
")",
")",
":",
"return",
"img",
"x1",
",",
"y1",
"=",
"max",
"(",
"x0",
",",
"0",
")",
",",
"max",
"(",
"y0",
",",
"0",
")",
"x2",
"=",
"min",
"(",
"x0",
"+",
"text_w",
",",
"img_w",
")",
"y2",
"=",
"min",
"(",
"y0",
"+",
"text_h",
"+",
"text_bottom_offset",
",",
"img_h",
")",
"x0",
"=",
"int",
"(",
"x0",
")",
"y0",
"=",
"int",
"(",
"y0",
")",
"x1",
"=",
"int",
"(",
"x1",
")",
"y1",
"=",
"int",
"(",
"y1",
")",
"x2",
"=",
"int",
"(",
"x2",
")",
"y2",
"=",
"int",
"(",
"y2",
")",
"# Create a black image of the same size as the text area.",
"text_area",
"=",
"np",
".",
"full",
"(",
"(",
"text_h",
"+",
"text_bottom_offset",
",",
"text_w",
",",
"3",
")",
",",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"if",
"background_color",
"is",
"not",
"None",
":",
"img",
"[",
"y1",
":",
"y2",
",",
"x1",
":",
"x2",
"]",
"=",
"np",
".",
"array",
"(",
"background_color",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"# paste the original image on all or part of it.",
"text_area",
"[",
"y1",
"-",
"y0",
":",
"y2",
"-",
"y0",
",",
"x1",
"-",
"x0",
":",
"x2",
"-",
"x0",
"]",
"=",
"img",
"[",
"y1",
":",
"y2",
",",
"x1",
":",
"x2",
"]",
"# convert pil image to cv2 image.",
"pil_img",
"=",
"Image",
".",
"fromarray",
"(",
"text_area",
")",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"pil_img",
")",
"draw",
".",
"text",
"(",
"xy",
"=",
"(",
"0",
",",
"0",
")",
",",
"text",
"=",
"text",
",",
"fill",
"=",
"color",
",",
"font",
"=",
"pil_font",
")",
"text_area",
"=",
"np",
".",
"array",
"(",
"pil_img",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"img",
"[",
"y1",
":",
"y2",
",",
"x1",
":",
"x2",
"]",
"=",
"text_area",
"[",
"y1",
"-",
"y0",
":",
"y2",
"-",
"y0",
",",
"x1",
"-",
"x0",
":",
"x2",
"-",
"x0",
"]",
"return",
"img"
] | https://github.com/jsk-ros-pkg/jsk_recognition/blob/be6e319d29797bafb10c589fdff364c3d333a605/jsk_recognition_utils/python/jsk_recognition_utils/put_text.py#L9-L79 |
|
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | Band.SetDefaultRAT | (self, *args) | return _gdal.Band_SetDefaultRAT(self, *args) | r"""SetDefaultRAT(Band self, RasterAttributeTable table) -> int | r"""SetDefaultRAT(Band self, RasterAttributeTable table) -> int | [
"r",
"SetDefaultRAT",
"(",
"Band",
"self",
"RasterAttributeTable",
"table",
")",
"-",
">",
"int"
] | def SetDefaultRAT(self, *args):
r"""SetDefaultRAT(Band self, RasterAttributeTable table) -> int"""
return _gdal.Band_SetDefaultRAT(self, *args) | [
"def",
"SetDefaultRAT",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"Band_SetDefaultRAT",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3528-L3530 |
|
OkCupid/okws | 1c337392c676ccb4e9a4c92d11d5d2fada6427d2 | py/okws/pubast.py | python | walk | (node) | Recursively yield all descendant nodes in the tree starting at *node*
(including *node* itself), in no specified order. This is useful if you
only want to modify nodes in place and don't care about the context. | Recursively yield all descendant nodes in the tree starting at *node*
(including *node* itself), in no specified order. This is useful if you
only want to modify nodes in place and don't care about the context. | [
"Recursively",
"yield",
"all",
"descendant",
"nodes",
"in",
"the",
"tree",
"starting",
"at",
"*",
"node",
"*",
"(",
"including",
"*",
"node",
"*",
"itself",
")",
"in",
"no",
"specified",
"order",
".",
"This",
"is",
"useful",
"if",
"you",
"only",
"want",
"to",
"modify",
"nodes",
"in",
"place",
"and",
"don",
"t",
"care",
"about",
"the",
"context",
"."
] | def walk(node):
"""
Recursively yield all descendant nodes in the tree starting at *node*
(including *node* itself), in no specified order. This is useful if you
only want to modify nodes in place and don't care about the context.
"""
from collections import deque
todo = deque([node])
while todo:
node = todo.popleft()
todo.extend(iter_child_nodes(node))
yield node | [
"def",
"walk",
"(",
"node",
")",
":",
"from",
"collections",
"import",
"deque",
"todo",
"=",
"deque",
"(",
"[",
"node",
"]",
")",
"while",
"todo",
":",
"node",
"=",
"todo",
".",
"popleft",
"(",
")",
"todo",
".",
"extend",
"(",
"iter_child_nodes",
"(",
"node",
")",
")",
"yield",
"node"
] | https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/py/okws/pubast.py#L87-L98 |
||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | openmp/runtime/tools/summarizeStats.py | python | extractSI | (s) | return num*factor if factor > 0 else num/-factor | Convert a measurement with a range suffix into a suitably scaled value | Convert a measurement with a range suffix into a suitably scaled value | [
"Convert",
"a",
"measurement",
"with",
"a",
"range",
"suffix",
"into",
"a",
"suitably",
"scaled",
"value"
] | def extractSI(s):
"""Convert a measurement with a range suffix into a suitably scaled value"""
du = s.split()
num = float(du[0])
units = du[1] if len(du) == 2 else ' '
# http://physics.nist.gov/cuu/Units/prefixes.html
factor = {'Y': 1e24,
'Z': 1e21,
'E': 1e18,
'P': 1e15,
'T': 1e12,
'G': 1e9,
'M': 1e6,
'k': 1e3,
' ': 1 ,
'm': -1e3, # Yes, I do mean that, see below for the explanation.
'u': -1e6,
'n': -1e9,
'p': -1e12,
'f': -1e15,
'a': -1e18,
'z': -1e21,
'y': -1e24}[units[0]]
# Minor trickery here is an attempt to preserve accuracy by using a single
# divide, rather than multiplying by 1/x, which introduces two roundings
# since 1/10 is not representable perfectly in IEEE floating point. (Not
# that this really matters, other than for cleanliness, since we're likely
# reading numbers with at most five decimal digits of precision).
return num*factor if factor > 0 else num/-factor | [
"def",
"extractSI",
"(",
"s",
")",
":",
"du",
"=",
"s",
".",
"split",
"(",
")",
"num",
"=",
"float",
"(",
"du",
"[",
"0",
"]",
")",
"units",
"=",
"du",
"[",
"1",
"]",
"if",
"len",
"(",
"du",
")",
"==",
"2",
"else",
"' '",
"# http://physics.nist.gov/cuu/Units/prefixes.html",
"factor",
"=",
"{",
"'Y'",
":",
"1e24",
",",
"'Z'",
":",
"1e21",
",",
"'E'",
":",
"1e18",
",",
"'P'",
":",
"1e15",
",",
"'T'",
":",
"1e12",
",",
"'G'",
":",
"1e9",
",",
"'M'",
":",
"1e6",
",",
"'k'",
":",
"1e3",
",",
"' '",
":",
"1",
",",
"'m'",
":",
"-",
"1e3",
",",
"# Yes, I do mean that, see below for the explanation.",
"'u'",
":",
"-",
"1e6",
",",
"'n'",
":",
"-",
"1e9",
",",
"'p'",
":",
"-",
"1e12",
",",
"'f'",
":",
"-",
"1e15",
",",
"'a'",
":",
"-",
"1e18",
",",
"'z'",
":",
"-",
"1e21",
",",
"'y'",
":",
"-",
"1e24",
"}",
"[",
"units",
"[",
"0",
"]",
"]",
"# Minor trickery here is an attempt to preserve accuracy by using a single",
"# divide, rather than multiplying by 1/x, which introduces two roundings",
"# since 1/10 is not representable perfectly in IEEE floating point. (Not",
"# that this really matters, other than for cleanliness, since we're likely",
"# reading numbers with at most five decimal digits of precision).",
"return",
"num",
"*",
"factor",
"if",
"factor",
">",
"0",
"else",
"num",
"/",
"-",
"factor"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/openmp/runtime/tools/summarizeStats.py#L77-L105 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py | python | _GroupBy._transform_should_cast | (self, func_nm: str) | return (self.size().fillna(0) > 0).any() and (
func_nm not in base.cython_cast_blacklist
) | Parameters
----------
func_nm: str
The name of the aggregation function being performed
Returns
-------
bool
Whether transform should attempt to cast the result of aggregation | Parameters
----------
func_nm: str
The name of the aggregation function being performed | [
"Parameters",
"----------",
"func_nm",
":",
"str",
"The",
"name",
"of",
"the",
"aggregation",
"function",
"being",
"performed"
] | def _transform_should_cast(self, func_nm: str) -> bool:
"""
Parameters
----------
func_nm: str
The name of the aggregation function being performed
Returns
-------
bool
Whether transform should attempt to cast the result of aggregation
"""
return (self.size().fillna(0) > 0).any() and (
func_nm not in base.cython_cast_blacklist
) | [
"def",
"_transform_should_cast",
"(",
"self",
",",
"func_nm",
":",
"str",
")",
"->",
"bool",
":",
"return",
"(",
"self",
".",
"size",
"(",
")",
".",
"fillna",
"(",
"0",
")",
">",
"0",
")",
".",
"any",
"(",
")",
"and",
"(",
"func_nm",
"not",
"in",
"base",
".",
"cython_cast_blacklist",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py#L825-L839 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/codecs.py | python | Codec.encode | (self, input, errors='strict') | Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling.
The method may not store state in the Codec instance. Use
StreamWriter for codecs which have to keep state in order to
make encoding efficient.
The encoder must be able to handle zero length input and
return an empty object of the output object type in this
situation. | Encodes the object input and returns a tuple (output
object, length consumed). | [
"Encodes",
"the",
"object",
"input",
"and",
"returns",
"a",
"tuple",
"(",
"output",
"object",
"length",
"consumed",
")",
"."
] | def encode(self, input, errors='strict'):
""" Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling.
The method may not store state in the Codec instance. Use
StreamWriter for codecs which have to keep state in order to
make encoding efficient.
The encoder must be able to handle zero length input and
return an empty object of the output object type in this
situation.
"""
raise NotImplementedError | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/codecs.py#L138-L155 |
||
gamedev-net/nehe-opengl | 9f073e5b092ad8dbcb21393871a2855fe86a65c6 | python/lesson42/ztv10E/lesson42.py | python | UpdateTex | (dmx, dmy) | return | // Update Pixel dmx, dmy On The Texture | // Update Pixel dmx, dmy On The Texture | [
"//",
"Update",
"Pixel",
"dmx",
"dmy",
"On",
"The",
"Texture"
] | def UpdateTex(dmx, dmy):
""" // Update Pixel dmx, dmy On The Texture """
global tex_data
tex_data[0+((dmx+(width*dmy))*3)]=255; # // Set Red Pixel To Full Bright
tex_data[1+((dmx+(width*dmy))*3)]=255; # // Set Green Pixel To Full Bright
tex_data[2+((dmx+(width*dmy))*3)]=255; # // Set Blue Pixel To Full Bright
return | [
"def",
"UpdateTex",
"(",
"dmx",
",",
"dmy",
")",
":",
"global",
"tex_data",
"tex_data",
"[",
"0",
"+",
"(",
"(",
"dmx",
"+",
"(",
"width",
"*",
"dmy",
")",
")",
"*",
"3",
")",
"]",
"=",
"255",
"# // Set Red Pixel To Full Bright",
"tex_data",
"[",
"1",
"+",
"(",
"(",
"dmx",
"+",
"(",
"width",
"*",
"dmy",
")",
")",
"*",
"3",
")",
"]",
"=",
"255",
"# // Set Green Pixel To Full Bright",
"tex_data",
"[",
"2",
"+",
"(",
"(",
"dmx",
"+",
"(",
"width",
"*",
"dmy",
")",
")",
"*",
"3",
")",
"]",
"=",
"255",
"# // Set Blue Pixel To Full Bright",
"return"
] | https://github.com/gamedev-net/nehe-opengl/blob/9f073e5b092ad8dbcb21393871a2855fe86a65c6/python/lesson42/ztv10E/lesson42.py#L114-L121 |
|
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/engine/topology.py | python | load_weights_from_hdf5_group_by_name | (f, layers) | Implements name-based weight loading.
(instead of topological weight loading).
Layers that have no matching name are skipped.
Arguments:
f: A pointer to a HDF5 group.
layers: a list of target layers.
Raises:
ValueError: in case of mismatch between provided layers
and weights file. | Implements name-based weight loading. | [
"Implements",
"name",
"-",
"based",
"weight",
"loading",
"."
] | def load_weights_from_hdf5_group_by_name(f, layers):
"""Implements name-based weight loading.
(instead of topological weight loading).
Layers that have no matching name are skipped.
Arguments:
f: A pointer to a HDF5 group.
layers: a list of target layers.
Raises:
ValueError: in case of mismatch between provided layers
and weights file.
"""
if 'keras_version' in f.attrs:
original_keras_version = f.attrs['keras_version'].decode('utf8')
else:
original_keras_version = '1'
if 'backend' in f.attrs:
original_backend = f.attrs['backend'].decode('utf8')
else:
original_backend = None
# New file format.
layer_names = [n.decode('utf8') for n in f.attrs['layer_names']]
# Reverse index of layer name to list of layers with name.
index = {}
for layer in layers:
if layer.name:
index.setdefault(layer.name, []).append(layer)
# We batch weight value assignments in a single backend call
# which provides a speedup in TensorFlow.
weight_value_tuples = []
for k, name in enumerate(layer_names):
g = f[name]
weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]
weight_values = [g[weight_name] for weight_name in weight_names]
for layer in index.get(name, []):
symbolic_weights = layer.weights
weight_values = preprocess_weights_for_loading(
layer, weight_values, original_keras_version, original_backend)
if len(weight_values) != len(symbolic_weights):
raise ValueError('Layer #' + str(k) + ' (named "' + layer.name +
'") expects ' + str(len(symbolic_weights)) +
' weight(s), but the saved weights' + ' have ' +
str(len(weight_values)) + ' element(s).')
# Set values.
for i in range(len(weight_values)):
weight_value_tuples.append((symbolic_weights[i], weight_values[i]))
K.batch_set_value(weight_value_tuples) | [
"def",
"load_weights_from_hdf5_group_by_name",
"(",
"f",
",",
"layers",
")",
":",
"if",
"'keras_version'",
"in",
"f",
".",
"attrs",
":",
"original_keras_version",
"=",
"f",
".",
"attrs",
"[",
"'keras_version'",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"else",
":",
"original_keras_version",
"=",
"'1'",
"if",
"'backend'",
"in",
"f",
".",
"attrs",
":",
"original_backend",
"=",
"f",
".",
"attrs",
"[",
"'backend'",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"else",
":",
"original_backend",
"=",
"None",
"# New file format.",
"layer_names",
"=",
"[",
"n",
".",
"decode",
"(",
"'utf8'",
")",
"for",
"n",
"in",
"f",
".",
"attrs",
"[",
"'layer_names'",
"]",
"]",
"# Reverse index of layer name to list of layers with name.",
"index",
"=",
"{",
"}",
"for",
"layer",
"in",
"layers",
":",
"if",
"layer",
".",
"name",
":",
"index",
".",
"setdefault",
"(",
"layer",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"layer",
")",
"# We batch weight value assignments in a single backend call",
"# which provides a speedup in TensorFlow.",
"weight_value_tuples",
"=",
"[",
"]",
"for",
"k",
",",
"name",
"in",
"enumerate",
"(",
"layer_names",
")",
":",
"g",
"=",
"f",
"[",
"name",
"]",
"weight_names",
"=",
"[",
"n",
".",
"decode",
"(",
"'utf8'",
")",
"for",
"n",
"in",
"g",
".",
"attrs",
"[",
"'weight_names'",
"]",
"]",
"weight_values",
"=",
"[",
"g",
"[",
"weight_name",
"]",
"for",
"weight_name",
"in",
"weight_names",
"]",
"for",
"layer",
"in",
"index",
".",
"get",
"(",
"name",
",",
"[",
"]",
")",
":",
"symbolic_weights",
"=",
"layer",
".",
"weights",
"weight_values",
"=",
"preprocess_weights_for_loading",
"(",
"layer",
",",
"weight_values",
",",
"original_keras_version",
",",
"original_backend",
")",
"if",
"len",
"(",
"weight_values",
")",
"!=",
"len",
"(",
"symbolic_weights",
")",
":",
"raise",
"ValueError",
"(",
"'Layer #'",
"+",
"str",
"(",
"k",
")",
"+",
"' (named \"'",
"+",
"layer",
".",
"name",
"+",
"'\") expects '",
"+",
"str",
"(",
"len",
"(",
"symbolic_weights",
")",
")",
"+",
"' weight(s), but the saved weights'",
"+",
"' have '",
"+",
"str",
"(",
"len",
"(",
"weight_values",
")",
")",
"+",
"' element(s).'",
")",
"# Set values.",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"weight_values",
")",
")",
":",
"weight_value_tuples",
".",
"append",
"(",
"(",
"symbolic_weights",
"[",
"i",
"]",
",",
"weight_values",
"[",
"i",
"]",
")",
")",
"K",
".",
"batch_set_value",
"(",
"weight_value_tuples",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/engine/topology.py#L1492-L1545 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Rect.__init__ | (self, *args, **kwargs) | __init__(self, int x=0, int y=0, int width=0, int height=0) -> Rect
Create a new Rect object. | __init__(self, int x=0, int y=0, int width=0, int height=0) -> Rect | [
"__init__",
"(",
"self",
"int",
"x",
"=",
"0",
"int",
"y",
"=",
"0",
"int",
"width",
"=",
"0",
"int",
"height",
"=",
"0",
")",
"-",
">",
"Rect"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, int x=0, int y=0, int width=0, int height=0) -> Rect
Create a new Rect object.
"""
_core_.Rect_swiginit(self,_core_.new_Rect(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_core_",
".",
"Rect_swiginit",
"(",
"self",
",",
"_core_",
".",
"new_Rect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1260-L1266 |
||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/logging/handlers.py | python | NTEventLogHandler.emit | (self, record) | Emit a record.
Determine the message ID, event category and event type. Then
log the message in the NT event log. | Emit a record. | [
"Emit",
"a",
"record",
"."
] | def emit(self, record):
"""
Emit a record.
Determine the message ID, event category and event type. Then
log the message in the NT event log.
"""
if self._welu:
try:
id = self.getMessageID(record)
cat = self.getEventCategory(record)
type = self.getEventType(record)
msg = self.format(record)
self._welu.ReportEvent(self.appname, id, cat, type, [msg])
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"_welu",
":",
"try",
":",
"id",
"=",
"self",
".",
"getMessageID",
"(",
"record",
")",
"cat",
"=",
"self",
".",
"getEventCategory",
"(",
"record",
")",
"type",
"=",
"self",
".",
"getEventType",
"(",
"record",
")",
"msg",
"=",
"self",
".",
"format",
"(",
"record",
")",
"self",
".",
"_welu",
".",
"ReportEvent",
"(",
"self",
".",
"appname",
",",
"id",
",",
"cat",
",",
"type",
",",
"[",
"msg",
"]",
")",
"except",
"(",
"KeyboardInterrupt",
",",
"SystemExit",
")",
":",
"raise",
"except",
":",
"self",
".",
"handleError",
"(",
"record",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/handlers.py#L949-L966 |
||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/supervised_session.py | python | SupervisedSession._create_session | (self) | return coordinated_session.CoordinatedSession(
monitored_session.MonitoredSession(tf_sess, self._monitors,
self._scaffold.global_step_tensor),
coord, coordinated_threads_to_join) | Factory for the RecoverableSession.
Returns:
A session, initialized or recovered as needed. | Factory for the RecoverableSession. | [
"Factory",
"for",
"the",
"RecoverableSession",
"."
] | def _create_session(self):
"""Factory for the RecoverableSession.
Returns:
A session, initialized or recovered as needed.
"""
if self._is_chief:
tf_sess = self._session_manager.prepare_session(
self._master, saver=self._scaffold.saver,
checkpoint_dir=self._checkpoint_dir, config=self._config,
init_op=self._scaffold.init_op,
init_feed_dict=self._scaffold.init_feed_dict,
init_fn=self._scaffold.init_fn)
else:
tf_sess = self._session_manager.wait_for_session(
self._master, config=self._config)
# Keep the tf_sess for quick runs of global step when needed.
self._tf_sess = tf_sess
# We don't want coordinator to suppress any exception.
coord = coordinator.Coordinator(clean_stop_exception_types=[])
coordinated_threads_to_join = queue_runner.start_queue_runners(sess=tf_sess,
coord=coord)
return coordinated_session.CoordinatedSession(
monitored_session.MonitoredSession(tf_sess, self._monitors,
self._scaffold.global_step_tensor),
coord, coordinated_threads_to_join) | [
"def",
"_create_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_chief",
":",
"tf_sess",
"=",
"self",
".",
"_session_manager",
".",
"prepare_session",
"(",
"self",
".",
"_master",
",",
"saver",
"=",
"self",
".",
"_scaffold",
".",
"saver",
",",
"checkpoint_dir",
"=",
"self",
".",
"_checkpoint_dir",
",",
"config",
"=",
"self",
".",
"_config",
",",
"init_op",
"=",
"self",
".",
"_scaffold",
".",
"init_op",
",",
"init_feed_dict",
"=",
"self",
".",
"_scaffold",
".",
"init_feed_dict",
",",
"init_fn",
"=",
"self",
".",
"_scaffold",
".",
"init_fn",
")",
"else",
":",
"tf_sess",
"=",
"self",
".",
"_session_manager",
".",
"wait_for_session",
"(",
"self",
".",
"_master",
",",
"config",
"=",
"self",
".",
"_config",
")",
"# Keep the tf_sess for quick runs of global step when needed.",
"self",
".",
"_tf_sess",
"=",
"tf_sess",
"# We don't want coordinator to suppress any exception.",
"coord",
"=",
"coordinator",
".",
"Coordinator",
"(",
"clean_stop_exception_types",
"=",
"[",
"]",
")",
"coordinated_threads_to_join",
"=",
"queue_runner",
".",
"start_queue_runners",
"(",
"sess",
"=",
"tf_sess",
",",
"coord",
"=",
"coord",
")",
"return",
"coordinated_session",
".",
"CoordinatedSession",
"(",
"monitored_session",
".",
"MonitoredSession",
"(",
"tf_sess",
",",
"self",
".",
"_monitors",
",",
"self",
".",
"_scaffold",
".",
"global_step_tensor",
")",
",",
"coord",
",",
"coordinated_threads_to_join",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/supervised_session.py#L268-L293 |
|
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/bindings/python/llvm/object.py | python | Section.has_symbol | (self, symbol) | return lib.LLVMGetSectionContainsSymbol(self, symbol) | Returns whether a Symbol instance is present in this Section. | Returns whether a Symbol instance is present in this Section. | [
"Returns",
"whether",
"a",
"Symbol",
"instance",
"is",
"present",
"in",
"this",
"Section",
"."
] | def has_symbol(self, symbol):
"""Returns whether a Symbol instance is present in this Section."""
if self.expired:
raise Exception('Section instance has expired.')
assert isinstance(symbol, Symbol)
return lib.LLVMGetSectionContainsSymbol(self, symbol) | [
"def",
"has_symbol",
"(",
"self",
",",
"symbol",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Section instance has expired.'",
")",
"assert",
"isinstance",
"(",
"symbol",
",",
"Symbol",
")",
"return",
"lib",
".",
"LLVMGetSectionContainsSymbol",
"(",
"self",
",",
"symbol",
")"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/bindings/python/llvm/object.py#L232-L238 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiToolBar.GetToolToggled | (*args, **kwargs) | return _aui.AuiToolBar_GetToolToggled(*args, **kwargs) | GetToolToggled(self, int toolId) -> bool | GetToolToggled(self, int toolId) -> bool | [
"GetToolToggled",
"(",
"self",
"int",
"toolId",
")",
"-",
">",
"bool"
] | def GetToolToggled(*args, **kwargs):
"""GetToolToggled(self, int toolId) -> bool"""
return _aui.AuiToolBar_GetToolToggled(*args, **kwargs) | [
"def",
"GetToolToggled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBar_GetToolToggled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L2150-L2152 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewModel.GetValue | (*args, **kwargs) | return _dataview.DataViewModel_GetValue(*args, **kwargs) | GetValue(self, DataViewItem item, unsigned int col) -> wxVariant
Override this and return the value to be used for the item, in the
given column. The type of the return value should match that given by
`GetColumnType`. | GetValue(self, DataViewItem item, unsigned int col) -> wxVariant | [
"GetValue",
"(",
"self",
"DataViewItem",
"item",
"unsigned",
"int",
"col",
")",
"-",
">",
"wxVariant"
] | def GetValue(*args, **kwargs):
"""
GetValue(self, DataViewItem item, unsigned int col) -> wxVariant
Override this and return the value to be used for the item, in the
given column. The type of the return value should match that given by
`GetColumnType`.
"""
return _dataview.DataViewModel_GetValue(*args, **kwargs) | [
"def",
"GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModel_GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L459-L467 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | PanedWindow.paneconfigure | (self, tagOrId, cnf=None, **kw) | Query or modify the management options for window.
If no option is specified, returns a list describing all
of the available options for pathName. If option is
specified with no value, then the command returns a list
describing the one named option (this list will be identical
to the corresponding sublist of the value returned if no
option is specified). If one or more option-value pairs are
specified, then the command modifies the given widget
option(s) to have the given value(s); in this case the
command returns an empty string. The following options
are supported:
after window
Insert the window after the window specified. window
should be the name of a window already managed by pathName.
before window
Insert the window before the window specified. window
should be the name of a window already managed by pathName.
height size
Specify a height for the window. The height will be the
outer dimension of the window including its border, if
any. If size is an empty string, or if -height is not
specified, then the height requested internally by the
window will be used initially; the height may later be
adjusted by the movement of sashes in the panedwindow.
Size may be any value accepted by Tk_GetPixels.
minsize n
Specifies that the size of the window cannot be made
less than n. This constraint only affects the size of
the widget in the paned dimension -- the x dimension
for horizontal panedwindows, the y dimension for
vertical panedwindows. May be any value accepted by
Tk_GetPixels.
padx n
Specifies a non-negative value indicating how much
extra space to leave on each side of the window in
the X-direction. The value may have any of the forms
accepted by Tk_GetPixels.
pady n
Specifies a non-negative value indicating how much
extra space to leave on each side of the window in
the Y-direction. The value may have any of the forms
accepted by Tk_GetPixels.
sticky style
If a window's pane is larger than the requested
dimensions of the window, this option may be used
to position (or stretch) the window within its pane.
Style is a string that contains zero or more of the
characters n, s, e or w. The string can optionally
contains spaces or commas, but they are ignored. Each
letter refers to a side (north, south, east, or west)
that the window will "stick" to. If both n and s
(or e and w) are specified, the window will be
stretched to fill the entire height (or width) of
its cavity.
width size
Specify a width for the window. The width will be
the outer dimension of the window including its
border, if any. If size is an empty string, or
if -width is not specified, then the width requested
internally by the window will be used initially; the
width may later be adjusted by the movement of sashes
in the panedwindow. Size may be any value accepted by
Tk_GetPixels. | Query or modify the management options for window. | [
"Query",
"or",
"modify",
"the",
"management",
"options",
"for",
"window",
"."
] | def paneconfigure(self, tagOrId, cnf=None, **kw):
"""Query or modify the management options for window.
If no option is specified, returns a list describing all
of the available options for pathName. If option is
specified with no value, then the command returns a list
describing the one named option (this list will be identical
to the corresponding sublist of the value returned if no
option is specified). If one or more option-value pairs are
specified, then the command modifies the given widget
option(s) to have the given value(s); in this case the
command returns an empty string. The following options
are supported:
after window
Insert the window after the window specified. window
should be the name of a window already managed by pathName.
before window
Insert the window before the window specified. window
should be the name of a window already managed by pathName.
height size
Specify a height for the window. The height will be the
outer dimension of the window including its border, if
any. If size is an empty string, or if -height is not
specified, then the height requested internally by the
window will be used initially; the height may later be
adjusted by the movement of sashes in the panedwindow.
Size may be any value accepted by Tk_GetPixels.
minsize n
Specifies that the size of the window cannot be made
less than n. This constraint only affects the size of
the widget in the paned dimension -- the x dimension
for horizontal panedwindows, the y dimension for
vertical panedwindows. May be any value accepted by
Tk_GetPixels.
padx n
Specifies a non-negative value indicating how much
extra space to leave on each side of the window in
the X-direction. The value may have any of the forms
accepted by Tk_GetPixels.
pady n
Specifies a non-negative value indicating how much
extra space to leave on each side of the window in
the Y-direction. The value may have any of the forms
accepted by Tk_GetPixels.
sticky style
If a window's pane is larger than the requested
dimensions of the window, this option may be used
to position (or stretch) the window within its pane.
Style is a string that contains zero or more of the
characters n, s, e or w. The string can optionally
contains spaces or commas, but they are ignored. Each
letter refers to a side (north, south, east, or west)
that the window will "stick" to. If both n and s
(or e and w) are specified, the window will be
stretched to fill the entire height (or width) of
its cavity.
width size
Specify a width for the window. The width will be
the outer dimension of the window including its
border, if any. If size is an empty string, or
if -width is not specified, then the width requested
internally by the window will be used initially; the
width may later be adjusted by the movement of sashes
in the panedwindow. Size may be any value accepted by
Tk_GetPixels.
"""
if cnf is None and not kw:
cnf = {}
for x in self.tk.split(
self.tk.call(self._w,
'paneconfigure', tagOrId)):
cnf[x[0][1:]] = (x[0][1:],) + x[1:]
return cnf
if type(cnf) == StringType and not kw:
x = self.tk.split(self.tk.call(
self._w, 'paneconfigure', tagOrId, '-'+cnf))
return (x[0][1:],) + x[1:]
self.tk.call((self._w, 'paneconfigure', tagOrId) +
self._options(cnf, kw)) | [
"def",
"paneconfigure",
"(",
"self",
",",
"tagOrId",
",",
"cnf",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"cnf",
"is",
"None",
"and",
"not",
"kw",
":",
"cnf",
"=",
"{",
"}",
"for",
"x",
"in",
"self",
".",
"tk",
".",
"split",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'paneconfigure'",
",",
"tagOrId",
")",
")",
":",
"cnf",
"[",
"x",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"]",
"=",
"(",
"x",
"[",
"0",
"]",
"[",
"1",
":",
"]",
",",
")",
"+",
"x",
"[",
"1",
":",
"]",
"return",
"cnf",
"if",
"type",
"(",
"cnf",
")",
"==",
"StringType",
"and",
"not",
"kw",
":",
"x",
"=",
"self",
".",
"tk",
".",
"split",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'paneconfigure'",
",",
"tagOrId",
",",
"'-'",
"+",
"cnf",
")",
")",
"return",
"(",
"x",
"[",
"0",
"]",
"[",
"1",
":",
"]",
",",
")",
"+",
"x",
"[",
"1",
":",
"]",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'paneconfigure'",
",",
"tagOrId",
")",
"+",
"self",
".",
"_options",
"(",
"cnf",
",",
"kw",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3658-L3738 |
||
JDAI-CV/DNNLibrary | e17f11e966b2cce7d747799b76bb9843813d4b01 | quant.py | python | modify_pb | (m: onnx.ModelProto, quant_layers: List[str]) | Modify proto buffers when all quantization infos are set correctly
:param m: the model
:param quant_layers: layers need to be quantized | Modify proto buffers when all quantization infos are set correctly
:param m: the model
:param quant_layers: layers need to be quantized | [
"Modify",
"proto",
"buffers",
"when",
"all",
"quantization",
"infos",
"are",
"set",
"correctly",
":",
"param",
"m",
":",
"the",
"model",
":",
"param",
"quant_layers",
":",
"layers",
"need",
"to",
"be",
"quantized"
] | def modify_pb(m: onnx.ModelProto, quant_layers: List[str]) -> None:
"""
Modify proto buffers when all quantization infos are set correctly
:param m: the model
:param quant_layers: layers need to be quantized
"""
for node in m.graph.node:
if node.name not in quant_layers:
continue
if node.op_type == 'Conv':
weight = node.input[1]
if len(node.input) == 3:
bias = node.input[2]
for t in m.graph.initializer:
if t.name == weight:
assert len(t.raw_data) == 0
w = np.array(t.float_data)
w = zps[weight] + w / scales[weight]
w = np.round(np.clip(w, qmin, qmax))
t.raw_data = w.astype(np.uint8).tobytes()
t.data_type = onnx.TensorProto.UINT8
del t.float_data[:]
if len(node.input) == 3 and t.name == bias:
assert len(t.raw_data) == 0
b = np.array(t.float_data)
b /= scales[bias]
t.raw_data = np.round(b).astype(np.int32).tobytes()
t.data_type = onnx.TensorProto.INT32
del t.float_data[:] | [
"def",
"modify_pb",
"(",
"m",
":",
"onnx",
".",
"ModelProto",
",",
"quant_layers",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"node",
"in",
"m",
".",
"graph",
".",
"node",
":",
"if",
"node",
".",
"name",
"not",
"in",
"quant_layers",
":",
"continue",
"if",
"node",
".",
"op_type",
"==",
"'Conv'",
":",
"weight",
"=",
"node",
".",
"input",
"[",
"1",
"]",
"if",
"len",
"(",
"node",
".",
"input",
")",
"==",
"3",
":",
"bias",
"=",
"node",
".",
"input",
"[",
"2",
"]",
"for",
"t",
"in",
"m",
".",
"graph",
".",
"initializer",
":",
"if",
"t",
".",
"name",
"==",
"weight",
":",
"assert",
"len",
"(",
"t",
".",
"raw_data",
")",
"==",
"0",
"w",
"=",
"np",
".",
"array",
"(",
"t",
".",
"float_data",
")",
"w",
"=",
"zps",
"[",
"weight",
"]",
"+",
"w",
"/",
"scales",
"[",
"weight",
"]",
"w",
"=",
"np",
".",
"round",
"(",
"np",
".",
"clip",
"(",
"w",
",",
"qmin",
",",
"qmax",
")",
")",
"t",
".",
"raw_data",
"=",
"w",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
".",
"tobytes",
"(",
")",
"t",
".",
"data_type",
"=",
"onnx",
".",
"TensorProto",
".",
"UINT8",
"del",
"t",
".",
"float_data",
"[",
":",
"]",
"if",
"len",
"(",
"node",
".",
"input",
")",
"==",
"3",
"and",
"t",
".",
"name",
"==",
"bias",
":",
"assert",
"len",
"(",
"t",
".",
"raw_data",
")",
"==",
"0",
"b",
"=",
"np",
".",
"array",
"(",
"t",
".",
"float_data",
")",
"b",
"/=",
"scales",
"[",
"bias",
"]",
"t",
".",
"raw_data",
"=",
"np",
".",
"round",
"(",
"b",
")",
".",
"astype",
"(",
"np",
".",
"int32",
")",
".",
"tobytes",
"(",
")",
"t",
".",
"data_type",
"=",
"onnx",
".",
"TensorProto",
".",
"INT32",
"del",
"t",
".",
"float_data",
"[",
":",
"]"
] | https://github.com/JDAI-CV/DNNLibrary/blob/e17f11e966b2cce7d747799b76bb9843813d4b01/quant.py#L67-L95 |
||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/cell.py | python | Cell.update_parameters_name | (self, prefix='', recurse=True) | Updates the names of parameters with given prefix string.
Adds the given prefix to the names of parameters.
Args:
prefix (str): The prefix string. Default: ''.
recurse (bool): Whether contains the parameters of subcells. Default: True. | Updates the names of parameters with given prefix string. | [
"Updates",
"the",
"names",
"of",
"parameters",
"with",
"given",
"prefix",
"string",
"."
] | def update_parameters_name(self, prefix='', recurse=True):
"""
Updates the names of parameters with given prefix string.
Adds the given prefix to the names of parameters.
Args:
prefix (str): The prefix string. Default: ''.
recurse (bool): Whether contains the parameters of subcells. Default: True.
"""
Validator.check_str_by_regular(prefix)
for name, param in self.parameters_and_names(expand=recurse):
if prefix != '':
param.is_init = False
param.name = prefix + name | [
"def",
"update_parameters_name",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"recurse",
"=",
"True",
")",
":",
"Validator",
".",
"check_str_by_regular",
"(",
"prefix",
")",
"for",
"name",
",",
"param",
"in",
"self",
".",
"parameters_and_names",
"(",
"expand",
"=",
"recurse",
")",
":",
"if",
"prefix",
"!=",
"''",
":",
"param",
".",
"is_init",
"=",
"False",
"param",
".",
"name",
"=",
"prefix",
"+",
"name"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/cell.py#L1045-L1060 |
||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/ssd/dataset/pycocotools/coco.py | python | COCO.getCatIds | (self, catNms=[], supNms=[], catIds=[]) | return ids | filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids | filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids | [
"filtering",
"parameters",
".",
"default",
"skips",
"that",
"filter",
".",
":",
"param",
"catNms",
"(",
"str",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"cat",
"names",
":",
"param",
"supNms",
"(",
"str",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"supercategory",
"names",
":",
"param",
"catIds",
"(",
"int",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"cat",
"ids",
":",
"return",
":",
"ids",
"(",
"int",
"array",
")",
":",
"integer",
"array",
"of",
"cat",
"ids"
] | def getCatIds(self, catNms=[], supNms=[], catIds=[]):
"""
filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids
"""
catNms = catNms if type(catNms) == list else [catNms]
supNms = supNms if type(supNms) == list else [supNms]
catIds = catIds if type(catIds) == list else [catIds]
if len(catNms) == len(supNms) == len(catIds) == 0:
cats = self.dataset['categories']
else:
cats = self.dataset['categories']
cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms]
cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]
cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds]
ids = [cat['id'] for cat in cats]
return ids | [
"def",
"getCatIds",
"(",
"self",
",",
"catNms",
"=",
"[",
"]",
",",
"supNms",
"=",
"[",
"]",
",",
"catIds",
"=",
"[",
"]",
")",
":",
"catNms",
"=",
"catNms",
"if",
"type",
"(",
"catNms",
")",
"==",
"list",
"else",
"[",
"catNms",
"]",
"supNms",
"=",
"supNms",
"if",
"type",
"(",
"supNms",
")",
"==",
"list",
"else",
"[",
"supNms",
"]",
"catIds",
"=",
"catIds",
"if",
"type",
"(",
"catIds",
")",
"==",
"list",
"else",
"[",
"catIds",
"]",
"if",
"len",
"(",
"catNms",
")",
"==",
"len",
"(",
"supNms",
")",
"==",
"len",
"(",
"catIds",
")",
"==",
"0",
":",
"cats",
"=",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
"else",
":",
"cats",
"=",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"catNms",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'name'",
"]",
"in",
"catNms",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"supNms",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'supercategory'",
"]",
"in",
"supNms",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"catIds",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'id'",
"]",
"in",
"catIds",
"]",
"ids",
"=",
"[",
"cat",
"[",
"'id'",
"]",
"for",
"cat",
"in",
"cats",
"]",
"return",
"ids"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/dataset/pycocotools/coco.py#L169-L189 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextFileHandler.GetName | (*args, **kwargs) | return _richtext.RichTextFileHandler_GetName(*args, **kwargs) | GetName(self) -> String | GetName(self) -> String | [
"GetName",
"(",
"self",
")",
"-",
">",
"String"
] | def GetName(*args, **kwargs):
"""GetName(self) -> String"""
return _richtext.RichTextFileHandler_GetName(*args, **kwargs) | [
"def",
"GetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextFileHandler_GetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2792-L2794 |
|
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | parserCtxt.setupParserForBuffer | (self, buffer, filename) | Setup the parser context to parse a new buffer; Clears any
prior contents from the parser context. The buffer
parameter must not be None, but the filename parameter can
be | Setup the parser context to parse a new buffer; Clears any
prior contents from the parser context. The buffer
parameter must not be None, but the filename parameter can
be | [
"Setup",
"the",
"parser",
"context",
"to",
"parse",
"a",
"new",
"buffer",
";",
"Clears",
"any",
"prior",
"contents",
"from",
"the",
"parser",
"context",
".",
"The",
"buffer",
"parameter",
"must",
"not",
"be",
"None",
"but",
"the",
"filename",
"parameter",
"can",
"be"
] | def setupParserForBuffer(self, buffer, filename):
"""Setup the parser context to parse a new buffer; Clears any
prior contents from the parser context. The buffer
parameter must not be None, but the filename parameter can
be """
libxml2mod.xmlSetupParserForBuffer(self._o, buffer, filename) | [
"def",
"setupParserForBuffer",
"(",
"self",
",",
"buffer",
",",
"filename",
")",
":",
"libxml2mod",
".",
"xmlSetupParserForBuffer",
"(",
"self",
".",
"_o",
",",
"buffer",
",",
"filename",
")"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L5058-L5063 |
||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/noisy_policy.py | python | NoisyPolicy.action_probabilities | (self, state, player_id=None) | return self._policy.action_probabilities(state, player_id) | Returns the policy for a player in a state.
Args:
state: A `pyspiel.State` object.
player_id: Optional, the player id for whom we want an action. Optional
unless this is a simultabeous state at which multiple players can act.
Returns:
A `dict` of `{action: probability}` for the specified player in the
supplied state. | Returns the policy for a player in a state. | [
"Returns",
"the",
"policy",
"for",
"a",
"player",
"in",
"a",
"state",
"."
] | def action_probabilities(self, state, player_id=None):
"""Returns the policy for a player in a state.
Args:
state: A `pyspiel.State` object.
player_id: Optional, the player id for whom we want an action. Optional
unless this is a simultabeous state at which multiple players can act.
Returns:
A `dict` of `{action: probability}` for the specified player in the
supplied state.
"""
# If self._player_id is None, or if self.player_id == current_player, add
# noise.
if ((self.player_id is None) or
(state.current_player() == self.player_id) or
(player_id == self.player_id)):
noise_probs = self.get_or_create_noise(state, player_id)
probs = self._policy.action_probabilities(state, player_id)
probs = self.mix_probs(probs, noise_probs)
return probs
# Send the default probabilities for all other players
return self._policy.action_probabilities(state, player_id) | [
"def",
"action_probabilities",
"(",
"self",
",",
"state",
",",
"player_id",
"=",
"None",
")",
":",
"# If self._player_id is None, or if self.player_id == current_player, add",
"# noise.",
"if",
"(",
"(",
"self",
".",
"player_id",
"is",
"None",
")",
"or",
"(",
"state",
".",
"current_player",
"(",
")",
"==",
"self",
".",
"player_id",
")",
"or",
"(",
"player_id",
"==",
"self",
".",
"player_id",
")",
")",
":",
"noise_probs",
"=",
"self",
".",
"get_or_create_noise",
"(",
"state",
",",
"player_id",
")",
"probs",
"=",
"self",
".",
"_policy",
".",
"action_probabilities",
"(",
"state",
",",
"player_id",
")",
"probs",
"=",
"self",
".",
"mix_probs",
"(",
"probs",
",",
"noise_probs",
")",
"return",
"probs",
"# Send the default probabilities for all other players",
"return",
"self",
".",
"_policy",
".",
"action_probabilities",
"(",
"state",
",",
"player_id",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/noisy_policy.py#L113-L137 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm._define_loglikelihood_operation | (self) | Defines the total log-likelihood of current iteration. | Defines the total log-likelihood of current iteration. | [
"Defines",
"the",
"total",
"log",
"-",
"likelihood",
"of",
"current",
"iteration",
"."
] | def _define_loglikelihood_operation(self):
"""Defines the total log-likelihood of current iteration."""
self._ll_op = []
for prior_probs in self._prior_probs:
self._ll_op.append(tf.reduce_sum(tf.log(prior_probs)))
tf.scalar_summary('ll', tf.reduce_sum(self._ll_op)) | [
"def",
"_define_loglikelihood_operation",
"(",
"self",
")",
":",
"self",
".",
"_ll_op",
"=",
"[",
"]",
"for",
"prior_probs",
"in",
"self",
".",
"_prior_probs",
":",
"self",
".",
"_ll_op",
".",
"append",
"(",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"log",
"(",
"prior_probs",
")",
")",
")",
"tf",
".",
"scalar_summary",
"(",
"'ll'",
",",
"tf",
".",
"reduce_sum",
"(",
"self",
".",
"_ll_op",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L410-L415 |
||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/sign.py | python | sign.numeric | (self, values) | return x | Returns the sign of x. | Returns the sign of x. | [
"Returns",
"the",
"sign",
"of",
"x",
"."
] | def numeric(self, values):
"""Returns the sign of x.
"""
x = values[0].copy()
x[x > 0] = 1.0
x[x <= 0] = -1.0
return x | [
"def",
"numeric",
"(",
"self",
",",
"values",
")",
":",
"x",
"=",
"values",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"x",
"[",
"x",
">",
"0",
"]",
"=",
"1.0",
"x",
"[",
"x",
"<=",
"0",
"]",
"=",
"-",
"1.0",
"return",
"x"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/sign.py#L28-L34 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/ExprNodes.py | python | IndexNode.analyse_as_buffer_operation | (self, env, getting) | return replacement_node | Analyse buffer indexing and memoryview indexing/slicing | Analyse buffer indexing and memoryview indexing/slicing | [
"Analyse",
"buffer",
"indexing",
"and",
"memoryview",
"indexing",
"/",
"slicing"
] | def analyse_as_buffer_operation(self, env, getting):
"""
Analyse buffer indexing and memoryview indexing/slicing
"""
if isinstance(self.index, TupleNode):
indices = self.index.args
else:
indices = [self.index]
base = self.base
base_type = base.type
replacement_node = None
if base_type.is_memoryviewslice:
# memoryviewslice indexing or slicing
from . import MemoryView
if base.is_memview_slice:
# For memory views, "view[i][j]" is the same as "view[i, j]" => use the latter for speed.
merged_indices = base.merged_indices(indices)
if merged_indices is not None:
base = base.base
base_type = base.type
indices = merged_indices
have_slices, indices, newaxes = MemoryView.unellipsify(indices, base_type.ndim)
if have_slices:
replacement_node = MemoryViewSliceNode(self.pos, indices=indices, base=base)
else:
replacement_node = MemoryViewIndexNode(self.pos, indices=indices, base=base)
elif base_type.is_buffer or base_type.is_pythran_expr:
if base_type.is_pythran_expr or len(indices) == base_type.ndim:
# Buffer indexing
is_buffer_access = True
indices = [index.analyse_types(env) for index in indices]
if base_type.is_pythran_expr:
do_replacement = all(
index.type.is_int or index.is_slice or index.type.is_pythran_expr
for index in indices)
if do_replacement:
for i,index in enumerate(indices):
if index.is_slice:
index = SliceIntNode(index.pos, start=index.start, stop=index.stop, step=index.step)
index = index.analyse_types(env)
indices[i] = index
else:
do_replacement = all(index.type.is_int for index in indices)
if do_replacement:
replacement_node = BufferIndexNode(self.pos, indices=indices, base=base)
# On cloning, indices is cloned. Otherwise, unpack index into indices.
assert not isinstance(self.index, CloneNode)
if replacement_node is not None:
replacement_node = replacement_node.analyse_types(env, getting)
return replacement_node | [
"def",
"analyse_as_buffer_operation",
"(",
"self",
",",
"env",
",",
"getting",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"index",
",",
"TupleNode",
")",
":",
"indices",
"=",
"self",
".",
"index",
".",
"args",
"else",
":",
"indices",
"=",
"[",
"self",
".",
"index",
"]",
"base",
"=",
"self",
".",
"base",
"base_type",
"=",
"base",
".",
"type",
"replacement_node",
"=",
"None",
"if",
"base_type",
".",
"is_memoryviewslice",
":",
"# memoryviewslice indexing or slicing",
"from",
".",
"import",
"MemoryView",
"if",
"base",
".",
"is_memview_slice",
":",
"# For memory views, \"view[i][j]\" is the same as \"view[i, j]\" => use the latter for speed.",
"merged_indices",
"=",
"base",
".",
"merged_indices",
"(",
"indices",
")",
"if",
"merged_indices",
"is",
"not",
"None",
":",
"base",
"=",
"base",
".",
"base",
"base_type",
"=",
"base",
".",
"type",
"indices",
"=",
"merged_indices",
"have_slices",
",",
"indices",
",",
"newaxes",
"=",
"MemoryView",
".",
"unellipsify",
"(",
"indices",
",",
"base_type",
".",
"ndim",
")",
"if",
"have_slices",
":",
"replacement_node",
"=",
"MemoryViewSliceNode",
"(",
"self",
".",
"pos",
",",
"indices",
"=",
"indices",
",",
"base",
"=",
"base",
")",
"else",
":",
"replacement_node",
"=",
"MemoryViewIndexNode",
"(",
"self",
".",
"pos",
",",
"indices",
"=",
"indices",
",",
"base",
"=",
"base",
")",
"elif",
"base_type",
".",
"is_buffer",
"or",
"base_type",
".",
"is_pythran_expr",
":",
"if",
"base_type",
".",
"is_pythran_expr",
"or",
"len",
"(",
"indices",
")",
"==",
"base_type",
".",
"ndim",
":",
"# Buffer indexing",
"is_buffer_access",
"=",
"True",
"indices",
"=",
"[",
"index",
".",
"analyse_types",
"(",
"env",
")",
"for",
"index",
"in",
"indices",
"]",
"if",
"base_type",
".",
"is_pythran_expr",
":",
"do_replacement",
"=",
"all",
"(",
"index",
".",
"type",
".",
"is_int",
"or",
"index",
".",
"is_slice",
"or",
"index",
".",
"type",
".",
"is_pythran_expr",
"for",
"index",
"in",
"indices",
")",
"if",
"do_replacement",
":",
"for",
"i",
",",
"index",
"in",
"enumerate",
"(",
"indices",
")",
":",
"if",
"index",
".",
"is_slice",
":",
"index",
"=",
"SliceIntNode",
"(",
"index",
".",
"pos",
",",
"start",
"=",
"index",
".",
"start",
",",
"stop",
"=",
"index",
".",
"stop",
",",
"step",
"=",
"index",
".",
"step",
")",
"index",
"=",
"index",
".",
"analyse_types",
"(",
"env",
")",
"indices",
"[",
"i",
"]",
"=",
"index",
"else",
":",
"do_replacement",
"=",
"all",
"(",
"index",
".",
"type",
".",
"is_int",
"for",
"index",
"in",
"indices",
")",
"if",
"do_replacement",
":",
"replacement_node",
"=",
"BufferIndexNode",
"(",
"self",
".",
"pos",
",",
"indices",
"=",
"indices",
",",
"base",
"=",
"base",
")",
"# On cloning, indices is cloned. Otherwise, unpack index into indices.",
"assert",
"not",
"isinstance",
"(",
"self",
".",
"index",
",",
"CloneNode",
")",
"if",
"replacement_node",
"is",
"not",
"None",
":",
"replacement_node",
"=",
"replacement_node",
".",
"analyse_types",
"(",
"env",
",",
"getting",
")",
"return",
"replacement_node"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/ExprNodes.py#L3786-L3837 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py | python | IS_CHARACTER_JUNK | (ch, ws=" \t") | return ch in ws | r"""
Return 1 for ignorable character: iff `ch` is a space or tab.
Examples:
>>> IS_CHARACTER_JUNK(' ')
True
>>> IS_CHARACTER_JUNK('\t')
True
>>> IS_CHARACTER_JUNK('\n')
False
>>> IS_CHARACTER_JUNK('x')
False | r"""
Return 1 for ignorable character: iff `ch` is a space or tab. | [
"r",
"Return",
"1",
"for",
"ignorable",
"character",
":",
"iff",
"ch",
"is",
"a",
"space",
"or",
"tab",
"."
] | def IS_CHARACTER_JUNK(ch, ws=" \t"):
r"""
Return 1 for ignorable character: iff `ch` is a space or tab.
Examples:
>>> IS_CHARACTER_JUNK(' ')
True
>>> IS_CHARACTER_JUNK('\t')
True
>>> IS_CHARACTER_JUNK('\n')
False
>>> IS_CHARACTER_JUNK('x')
False
"""
return ch in ws | [
"def",
"IS_CHARACTER_JUNK",
"(",
"ch",
",",
"ws",
"=",
"\" \\t\"",
")",
":",
"return",
"ch",
"in",
"ws"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py#L1124-L1140 |
|
maierfelix/dawn-ray-tracing | cfd8511ce95e197ec56fa4880223290554030684 | generator/generator_lib.py | python | Generator.get_file_renders | (self, args) | return [] | Return the list of FileRender objects to process. | Return the list of FileRender objects to process. | [
"Return",
"the",
"list",
"of",
"FileRender",
"objects",
"to",
"process",
"."
] | def get_file_renders(self, args):
"""Return the list of FileRender objects to process."""
return [] | [
"def",
"get_file_renders",
"(",
"self",
",",
"args",
")",
":",
"return",
"[",
"]"
] | https://github.com/maierfelix/dawn-ray-tracing/blob/cfd8511ce95e197ec56fa4880223290554030684/generator/generator_lib.py#L67-L69 |
|
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/executor.py | python | JsonProgress.write | (self, data) | Method the write JSON progress message. Implemented by subclass. | Method the write JSON progress message. Implemented by subclass. | [
"Method",
"the",
"write",
"JSON",
"progress",
"message",
".",
"Implemented",
"by",
"subclass",
"."
] | def write(self, data):
"""
Method the write JSON progress message. Implemented by subclass.
""" | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/executor.py#L125-L128 |
||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/gradients.py | python | _StopOps | (from_ops, pending_count) | return stop_ops | The set of ops that terminate the gradient computation.
This computes the frontier of the forward graph *before* which backprop
should stop. Operations in the returned set will not be differentiated.
This set is defined as the subset of `from_ops` containing ops that have
no predecessor in `from_ops`. `pending_count` is the result of
`_PendingCount(g, xs, from_ops)`. An 'op' has predecessors in `from_ops`
iff pending_count[op._id] > 0.
Args:
from_ops: list of Operations.
pending_count: List of integers, indexed by operation id.
Returns:
The set of operations. | The set of ops that terminate the gradient computation. | [
"The",
"set",
"of",
"ops",
"that",
"terminate",
"the",
"gradient",
"computation",
"."
] | def _StopOps(from_ops, pending_count):
"""The set of ops that terminate the gradient computation.
This computes the frontier of the forward graph *before* which backprop
should stop. Operations in the returned set will not be differentiated.
This set is defined as the subset of `from_ops` containing ops that have
no predecessor in `from_ops`. `pending_count` is the result of
`_PendingCount(g, xs, from_ops)`. An 'op' has predecessors in `from_ops`
iff pending_count[op._id] > 0.
Args:
from_ops: list of Operations.
pending_count: List of integers, indexed by operation id.
Returns:
The set of operations.
"""
stop_ops = set()
for op in from_ops:
is_stop_op = True
for inp in op.inputs:
if pending_count[inp.op._id] > 0:
is_stop_op = False
break
if is_stop_op:
stop_ops.add(op._id)
return stop_ops | [
"def",
"_StopOps",
"(",
"from_ops",
",",
"pending_count",
")",
":",
"stop_ops",
"=",
"set",
"(",
")",
"for",
"op",
"in",
"from_ops",
":",
"is_stop_op",
"=",
"True",
"for",
"inp",
"in",
"op",
".",
"inputs",
":",
"if",
"pending_count",
"[",
"inp",
".",
"op",
".",
"_id",
"]",
">",
"0",
":",
"is_stop_op",
"=",
"False",
"break",
"if",
"is_stop_op",
":",
"stop_ops",
".",
"add",
"(",
"op",
".",
"_id",
")",
"return",
"stop_ops"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/gradients.py#L268-L294 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/config.py | python | IdleConf.GetCoreKeys | (self, keySetName=None) | return keyBindings | Return dict of core virtual-key keybindings for keySetName.
The default keySetName None corresponds to the keyBindings base
dict. If keySetName is not None, bindings from the config
file(s) are loaded _over_ these defaults, so if there is a
problem getting any core binding there will be an 'ultimate last
resort fallback' to the CUA-ish bindings defined here. | Return dict of core virtual-key keybindings for keySetName. | [
"Return",
"dict",
"of",
"core",
"virtual",
"-",
"key",
"keybindings",
"for",
"keySetName",
"."
] | def GetCoreKeys(self, keySetName=None):
"""Return dict of core virtual-key keybindings for keySetName.
The default keySetName None corresponds to the keyBindings base
dict. If keySetName is not None, bindings from the config
file(s) are loaded _over_ these defaults, so if there is a
problem getting any core binding there will be an 'ultimate last
resort fallback' to the CUA-ish bindings defined here.
"""
keyBindings={
'<<copy>>': ['<Control-c>', '<Control-C>'],
'<<cut>>': ['<Control-x>', '<Control-X>'],
'<<paste>>': ['<Control-v>', '<Control-V>'],
'<<beginning-of-line>>': ['<Control-a>', '<Home>'],
'<<center-insert>>': ['<Control-l>'],
'<<close-all-windows>>': ['<Control-q>'],
'<<close-window>>': ['<Alt-F4>'],
'<<do-nothing>>': ['<Control-x>'],
'<<end-of-file>>': ['<Control-d>'],
'<<python-docs>>': ['<F1>'],
'<<python-context-help>>': ['<Shift-F1>'],
'<<history-next>>': ['<Alt-n>'],
'<<history-previous>>': ['<Alt-p>'],
'<<interrupt-execution>>': ['<Control-c>'],
'<<view-restart>>': ['<F6>'],
'<<restart-shell>>': ['<Control-F6>'],
'<<open-class-browser>>': ['<Alt-c>'],
'<<open-module>>': ['<Alt-m>'],
'<<open-new-window>>': ['<Control-n>'],
'<<open-window-from-file>>': ['<Control-o>'],
'<<plain-newline-and-indent>>': ['<Control-j>'],
'<<print-window>>': ['<Control-p>'],
'<<redo>>': ['<Control-y>'],
'<<remove-selection>>': ['<Escape>'],
'<<save-copy-of-window-as-file>>': ['<Alt-Shift-S>'],
'<<save-window-as-file>>': ['<Alt-s>'],
'<<save-window>>': ['<Control-s>'],
'<<select-all>>': ['<Alt-a>'],
'<<toggle-auto-coloring>>': ['<Control-slash>'],
'<<undo>>': ['<Control-z>'],
'<<find-again>>': ['<Control-g>', '<F3>'],
'<<find-in-files>>': ['<Alt-F3>'],
'<<find-selection>>': ['<Control-F3>'],
'<<find>>': ['<Control-f>'],
'<<replace>>': ['<Control-h>'],
'<<goto-line>>': ['<Alt-g>'],
'<<smart-backspace>>': ['<Key-BackSpace>'],
'<<newline-and-indent>>': ['<Key-Return>', '<Key-KP_Enter>'],
'<<smart-indent>>': ['<Key-Tab>'],
'<<indent-region>>': ['<Control-Key-bracketright>'],
'<<dedent-region>>': ['<Control-Key-bracketleft>'],
'<<comment-region>>': ['<Alt-Key-3>'],
'<<uncomment-region>>': ['<Alt-Key-4>'],
'<<tabify-region>>': ['<Alt-Key-5>'],
'<<untabify-region>>': ['<Alt-Key-6>'],
'<<toggle-tabs>>': ['<Alt-Key-t>'],
'<<change-indentwidth>>': ['<Alt-Key-u>'],
'<<del-word-left>>': ['<Control-Key-BackSpace>'],
'<<del-word-right>>': ['<Control-Key-Delete>'],
'<<force-open-completions>>': ['<Control-Key-space>'],
'<<expand-word>>': ['<Alt-Key-slash>'],
'<<force-open-calltip>>': ['<Control-Key-backslash>'],
'<<flash-paren>>': ['<Control-Key-0>'],
'<<format-paragraph>>': ['<Alt-Key-q>'],
'<<run-module>>': ['<Key-F5>'],
'<<run-custom>>': ['<Shift-Key-F5>'],
'<<check-module>>': ['<Alt-Key-x>'],
'<<zoom-height>>': ['<Alt-Key-2>'],
}
if keySetName:
if not (self.userCfg['keys'].has_section(keySetName) or
self.defaultCfg['keys'].has_section(keySetName)):
warning = (
'\n Warning: config.py - IdleConf.GetCoreKeys -\n'
' key set %r is not defined, using default bindings.' %
(keySetName,)
)
_warn(warning, 'keys', keySetName)
else:
for event in keyBindings:
binding = self.GetKeyBinding(keySetName, event)
if binding:
keyBindings[event] = binding
# Otherwise return default in keyBindings.
elif event not in self.former_extension_events:
warning = (
'\n Warning: config.py - IdleConf.GetCoreKeys -\n'
' problem retrieving key binding for event %r\n'
' from key set %r.\n'
' returning default value: %r' %
(event, keySetName, keyBindings[event])
)
_warn(warning, 'keys', keySetName, event)
return keyBindings | [
"def",
"GetCoreKeys",
"(",
"self",
",",
"keySetName",
"=",
"None",
")",
":",
"keyBindings",
"=",
"{",
"'<<copy>>'",
":",
"[",
"'<Control-c>'",
",",
"'<Control-C>'",
"]",
",",
"'<<cut>>'",
":",
"[",
"'<Control-x>'",
",",
"'<Control-X>'",
"]",
",",
"'<<paste>>'",
":",
"[",
"'<Control-v>'",
",",
"'<Control-V>'",
"]",
",",
"'<<beginning-of-line>>'",
":",
"[",
"'<Control-a>'",
",",
"'<Home>'",
"]",
",",
"'<<center-insert>>'",
":",
"[",
"'<Control-l>'",
"]",
",",
"'<<close-all-windows>>'",
":",
"[",
"'<Control-q>'",
"]",
",",
"'<<close-window>>'",
":",
"[",
"'<Alt-F4>'",
"]",
",",
"'<<do-nothing>>'",
":",
"[",
"'<Control-x>'",
"]",
",",
"'<<end-of-file>>'",
":",
"[",
"'<Control-d>'",
"]",
",",
"'<<python-docs>>'",
":",
"[",
"'<F1>'",
"]",
",",
"'<<python-context-help>>'",
":",
"[",
"'<Shift-F1>'",
"]",
",",
"'<<history-next>>'",
":",
"[",
"'<Alt-n>'",
"]",
",",
"'<<history-previous>>'",
":",
"[",
"'<Alt-p>'",
"]",
",",
"'<<interrupt-execution>>'",
":",
"[",
"'<Control-c>'",
"]",
",",
"'<<view-restart>>'",
":",
"[",
"'<F6>'",
"]",
",",
"'<<restart-shell>>'",
":",
"[",
"'<Control-F6>'",
"]",
",",
"'<<open-class-browser>>'",
":",
"[",
"'<Alt-c>'",
"]",
",",
"'<<open-module>>'",
":",
"[",
"'<Alt-m>'",
"]",
",",
"'<<open-new-window>>'",
":",
"[",
"'<Control-n>'",
"]",
",",
"'<<open-window-from-file>>'",
":",
"[",
"'<Control-o>'",
"]",
",",
"'<<plain-newline-and-indent>>'",
":",
"[",
"'<Control-j>'",
"]",
",",
"'<<print-window>>'",
":",
"[",
"'<Control-p>'",
"]",
",",
"'<<redo>>'",
":",
"[",
"'<Control-y>'",
"]",
",",
"'<<remove-selection>>'",
":",
"[",
"'<Escape>'",
"]",
",",
"'<<save-copy-of-window-as-file>>'",
":",
"[",
"'<Alt-Shift-S>'",
"]",
",",
"'<<save-window-as-file>>'",
":",
"[",
"'<Alt-s>'",
"]",
",",
"'<<save-window>>'",
":",
"[",
"'<Control-s>'",
"]",
",",
"'<<select-all>>'",
":",
"[",
"'<Alt-a>'",
"]",
",",
"'<<toggle-auto-coloring>>'",
":",
"[",
"'<Control-slash>'",
"]",
",",
"'<<undo>>'",
":",
"[",
"'<Control-z>'",
"]",
",",
"'<<find-again>>'",
":",
"[",
"'<Control-g>'",
",",
"'<F3>'",
"]",
",",
"'<<find-in-files>>'",
":",
"[",
"'<Alt-F3>'",
"]",
",",
"'<<find-selection>>'",
":",
"[",
"'<Control-F3>'",
"]",
",",
"'<<find>>'",
":",
"[",
"'<Control-f>'",
"]",
",",
"'<<replace>>'",
":",
"[",
"'<Control-h>'",
"]",
",",
"'<<goto-line>>'",
":",
"[",
"'<Alt-g>'",
"]",
",",
"'<<smart-backspace>>'",
":",
"[",
"'<Key-BackSpace>'",
"]",
",",
"'<<newline-and-indent>>'",
":",
"[",
"'<Key-Return>'",
",",
"'<Key-KP_Enter>'",
"]",
",",
"'<<smart-indent>>'",
":",
"[",
"'<Key-Tab>'",
"]",
",",
"'<<indent-region>>'",
":",
"[",
"'<Control-Key-bracketright>'",
"]",
",",
"'<<dedent-region>>'",
":",
"[",
"'<Control-Key-bracketleft>'",
"]",
",",
"'<<comment-region>>'",
":",
"[",
"'<Alt-Key-3>'",
"]",
",",
"'<<uncomment-region>>'",
":",
"[",
"'<Alt-Key-4>'",
"]",
",",
"'<<tabify-region>>'",
":",
"[",
"'<Alt-Key-5>'",
"]",
",",
"'<<untabify-region>>'",
":",
"[",
"'<Alt-Key-6>'",
"]",
",",
"'<<toggle-tabs>>'",
":",
"[",
"'<Alt-Key-t>'",
"]",
",",
"'<<change-indentwidth>>'",
":",
"[",
"'<Alt-Key-u>'",
"]",
",",
"'<<del-word-left>>'",
":",
"[",
"'<Control-Key-BackSpace>'",
"]",
",",
"'<<del-word-right>>'",
":",
"[",
"'<Control-Key-Delete>'",
"]",
",",
"'<<force-open-completions>>'",
":",
"[",
"'<Control-Key-space>'",
"]",
",",
"'<<expand-word>>'",
":",
"[",
"'<Alt-Key-slash>'",
"]",
",",
"'<<force-open-calltip>>'",
":",
"[",
"'<Control-Key-backslash>'",
"]",
",",
"'<<flash-paren>>'",
":",
"[",
"'<Control-Key-0>'",
"]",
",",
"'<<format-paragraph>>'",
":",
"[",
"'<Alt-Key-q>'",
"]",
",",
"'<<run-module>>'",
":",
"[",
"'<Key-F5>'",
"]",
",",
"'<<run-custom>>'",
":",
"[",
"'<Shift-Key-F5>'",
"]",
",",
"'<<check-module>>'",
":",
"[",
"'<Alt-Key-x>'",
"]",
",",
"'<<zoom-height>>'",
":",
"[",
"'<Alt-Key-2>'",
"]",
",",
"}",
"if",
"keySetName",
":",
"if",
"not",
"(",
"self",
".",
"userCfg",
"[",
"'keys'",
"]",
".",
"has_section",
"(",
"keySetName",
")",
"or",
"self",
".",
"defaultCfg",
"[",
"'keys'",
"]",
".",
"has_section",
"(",
"keySetName",
")",
")",
":",
"warning",
"=",
"(",
"'\\n Warning: config.py - IdleConf.GetCoreKeys -\\n'",
"' key set %r is not defined, using default bindings.'",
"%",
"(",
"keySetName",
",",
")",
")",
"_warn",
"(",
"warning",
",",
"'keys'",
",",
"keySetName",
")",
"else",
":",
"for",
"event",
"in",
"keyBindings",
":",
"binding",
"=",
"self",
".",
"GetKeyBinding",
"(",
"keySetName",
",",
"event",
")",
"if",
"binding",
":",
"keyBindings",
"[",
"event",
"]",
"=",
"binding",
"# Otherwise return default in keyBindings.",
"elif",
"event",
"not",
"in",
"self",
".",
"former_extension_events",
":",
"warning",
"=",
"(",
"'\\n Warning: config.py - IdleConf.GetCoreKeys -\\n'",
"' problem retrieving key binding for event %r\\n'",
"' from key set %r.\\n'",
"' returning default value: %r'",
"%",
"(",
"event",
",",
"keySetName",
",",
"keyBindings",
"[",
"event",
"]",
")",
")",
"_warn",
"(",
"warning",
",",
"'keys'",
",",
"keySetName",
",",
"event",
")",
"return",
"keyBindings"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/config.py#L591-L685 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py | python | getattr_static | (obj, attr, default=_sentinel) | Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
and may find attributes that getattr can't (like descriptors
that raise AttributeError). It can also return descriptor objects
instead of instance members in some cases. See the
documentation for details. | Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__. | [
"Retrieve",
"attributes",
"without",
"triggering",
"dynamic",
"lookup",
"via",
"the",
"descriptor",
"protocol",
"__getattr__",
"or",
"__getattribute__",
"."
] | def getattr_static(obj, attr, default=_sentinel):
"""Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
and may find attributes that getattr can't (like descriptors
that raise AttributeError). It can also return descriptor objects
instead of instance members in some cases. See the
documentation for details.
"""
instance_result = _sentinel
if not _is_type(obj):
klass = type(obj)
dict_attr = _shadowed_dict(klass)
if (dict_attr is _sentinel or
type(dict_attr) is types.MemberDescriptorType):
instance_result = _check_instance(obj, attr)
else:
klass = obj
klass_result = _check_class(klass, attr)
if instance_result is not _sentinel and klass_result is not _sentinel:
if (_check_class(type(klass_result), '__get__') is not _sentinel and
_check_class(type(klass_result), '__set__') is not _sentinel):
return klass_result
if instance_result is not _sentinel:
return instance_result
if klass_result is not _sentinel:
return klass_result
if obj is klass:
# for types we check the metaclass too
for entry in _static_getmro(type(klass)):
if _shadowed_dict(type(entry)) is _sentinel:
try:
return entry.__dict__[attr]
except KeyError:
pass
if default is not _sentinel:
return default
raise AttributeError(attr) | [
"def",
"getattr_static",
"(",
"obj",
",",
"attr",
",",
"default",
"=",
"_sentinel",
")",
":",
"instance_result",
"=",
"_sentinel",
"if",
"not",
"_is_type",
"(",
"obj",
")",
":",
"klass",
"=",
"type",
"(",
"obj",
")",
"dict_attr",
"=",
"_shadowed_dict",
"(",
"klass",
")",
"if",
"(",
"dict_attr",
"is",
"_sentinel",
"or",
"type",
"(",
"dict_attr",
")",
"is",
"types",
".",
"MemberDescriptorType",
")",
":",
"instance_result",
"=",
"_check_instance",
"(",
"obj",
",",
"attr",
")",
"else",
":",
"klass",
"=",
"obj",
"klass_result",
"=",
"_check_class",
"(",
"klass",
",",
"attr",
")",
"if",
"instance_result",
"is",
"not",
"_sentinel",
"and",
"klass_result",
"is",
"not",
"_sentinel",
":",
"if",
"(",
"_check_class",
"(",
"type",
"(",
"klass_result",
")",
",",
"'__get__'",
")",
"is",
"not",
"_sentinel",
"and",
"_check_class",
"(",
"type",
"(",
"klass_result",
")",
",",
"'__set__'",
")",
"is",
"not",
"_sentinel",
")",
":",
"return",
"klass_result",
"if",
"instance_result",
"is",
"not",
"_sentinel",
":",
"return",
"instance_result",
"if",
"klass_result",
"is",
"not",
"_sentinel",
":",
"return",
"klass_result",
"if",
"obj",
"is",
"klass",
":",
"# for types we check the metaclass too",
"for",
"entry",
"in",
"_static_getmro",
"(",
"type",
"(",
"klass",
")",
")",
":",
"if",
"_shadowed_dict",
"(",
"type",
"(",
"entry",
")",
")",
"is",
"_sentinel",
":",
"try",
":",
"return",
"entry",
".",
"__dict__",
"[",
"attr",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"default",
"is",
"not",
"_sentinel",
":",
"return",
"default",
"raise",
"AttributeError",
"(",
"attr",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L1566-L1609 |
||
widelands/widelands | e9f047d46a23d81312237d52eabf7d74e8de52d6 | utils/build_deps.py | python | extract_includes | (srcdir, source) | return includes | Returns all locally included files. | Returns all locally included files. | [
"Returns",
"all",
"locally",
"included",
"files",
"."
] | def extract_includes(srcdir, source):
"""Returns all locally included files."""
includes = set()
for line in io.open(source, encoding='utf-8'):
match = __INCLUDE.match(line)
if match:
includes.add(path.join(srcdir, match.group(1)))
return includes | [
"def",
"extract_includes",
"(",
"srcdir",
",",
"source",
")",
":",
"includes",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"io",
".",
"open",
"(",
"source",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"match",
"=",
"__INCLUDE",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"includes",
".",
"add",
"(",
"path",
".",
"join",
"(",
"srcdir",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"return",
"includes"
] | https://github.com/widelands/widelands/blob/e9f047d46a23d81312237d52eabf7d74e8de52d6/utils/build_deps.py#L63-L70 |
|
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/utils/lui/lldbutil.py | python | get_symbol_names | (thread) | return [GetSymbol(i) for i in range(thread.GetNumFrames())] | Returns a sequence of symbols for this thread. | Returns a sequence of symbols for this thread. | [
"Returns",
"a",
"sequence",
"of",
"symbols",
"for",
"this",
"thread",
"."
] | def get_symbol_names(thread):
"""
Returns a sequence of symbols for this thread.
"""
def GetSymbol(i):
return thread.GetFrameAtIndex(i).GetSymbol().GetName()
return [GetSymbol(i) for i in range(thread.GetNumFrames())] | [
"def",
"get_symbol_names",
"(",
"thread",
")",
":",
"def",
"GetSymbol",
"(",
"i",
")",
":",
"return",
"thread",
".",
"GetFrameAtIndex",
"(",
"i",
")",
".",
"GetSymbol",
"(",
")",
".",
"GetName",
"(",
")",
"return",
"[",
"GetSymbol",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"thread",
".",
"GetNumFrames",
"(",
")",
")",
"]"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/utils/lui/lldbutil.py#L714-L721 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/metrics/python/ops/set_ops.py | python | set_difference | (a, b, aminusb=True, validate_indices=True) | return _set_operation(a, b, "a-b" if aminusb else "b-a", validate_indices) | Compute set difference of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be
sorted in row-major order.
aminusb: Whether to subtract `b` from `a`, vs vice versa.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the
differences. | Compute set difference of elements in last dimension of `a` and `b`. | [
"Compute",
"set",
"difference",
"of",
"elements",
"in",
"last",
"dimension",
"of",
"a",
"and",
"b",
"."
] | def set_difference(a, b, aminusb=True, validate_indices=True):
"""Compute set difference of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be
sorted in row-major order.
aminusb: Whether to subtract `b` from `a`, vs vice versa.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the
differences.
"""
return _set_operation(a, b, "a-b" if aminusb else "b-a", validate_indices) | [
"def",
"set_difference",
"(",
"a",
",",
"b",
",",
"aminusb",
"=",
"True",
",",
"validate_indices",
"=",
"True",
")",
":",
"return",
"_set_operation",
"(",
"a",
",",
"b",
",",
"\"a-b\"",
"if",
"aminusb",
"else",
"\"b-a\"",
",",
"validate_indices",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/metrics/python/ops/set_ops.py#L161-L181 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py | python | RFC2217Serial.getCTS | (self) | return bool(self.getModemState() & MODEMSTATE_MASK_CTS) | Read terminal status line: Clear To Send. | Read terminal status line: Clear To Send. | [
"Read",
"terminal",
"status",
"line",
":",
"Clear",
"To",
"Send",
"."
] | def getCTS(self):
"""Read terminal status line: Clear To Send."""
if not self._isOpen: raise portNotOpenError
return bool(self.getModemState() & MODEMSTATE_MASK_CTS) | [
"def",
"getCTS",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"portNotOpenError",
"return",
"bool",
"(",
"self",
".",
"getModemState",
"(",
")",
"&",
"MODEMSTATE_MASK_CTS",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py#L659-L662 |
|
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/utils/jupyter/mlir_opt_kernel/kernel.py | python | MlirOptKernel.banner | (self) | return "mlir-opt kernel %s" % __version__ | Returns kernel banner. | Returns kernel banner. | [
"Returns",
"kernel",
"banner",
"."
] | def banner(self):
"""Returns kernel banner."""
# Just a placeholder.
return "mlir-opt kernel %s" % __version__ | [
"def",
"banner",
"(",
"self",
")",
":",
"# Just a placeholder.",
"return",
"\"mlir-opt kernel %s\"",
"%",
"__version__"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/utils/jupyter/mlir_opt_kernel/kernel.py#L70-L73 |
|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/control_flow_ops.py | python | _Identity | (tensor, name=None) | Return a tensor with the same shape and contents as the input tensor.
Args:
tensor: A Tensor.
name: A name for this operation (optional).
Returns:
A Tensor with the same type and value as the input Tensor. | Return a tensor with the same shape and contents as the input tensor. | [
"Return",
"a",
"tensor",
"with",
"the",
"same",
"shape",
"and",
"contents",
"as",
"the",
"input",
"tensor",
"."
] | def _Identity(tensor, name=None):
"""Return a tensor with the same shape and contents as the input tensor.
Args:
tensor: A Tensor.
name: A name for this operation (optional).
Returns:
A Tensor with the same type and value as the input Tensor.
"""
tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True)
if isinstance(tensor, ops.Tensor):
if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access
return gen_array_ops.ref_identity(tensor, name=name)
else:
return array_ops.identity(tensor, name=name)
elif isinstance(tensor, composite_tensor.CompositeTensor):
return nest.map_structure(_Identity, tensor, expand_composites=True)
else:
raise TypeError("'tensor' must be a Tensor or CompositeTensor. "
f"Received: {type(tensor)}.") | [
"def",
"_Identity",
"(",
"tensor",
",",
"name",
"=",
"None",
")",
":",
"tensor",
"=",
"ops",
".",
"internal_convert_to_tensor_or_composite",
"(",
"tensor",
",",
"as_ref",
"=",
"True",
")",
"if",
"isinstance",
"(",
"tensor",
",",
"ops",
".",
"Tensor",
")",
":",
"if",
"tensor",
".",
"dtype",
".",
"_is_ref_dtype",
":",
"# pylint: disable=protected-access",
"return",
"gen_array_ops",
".",
"ref_identity",
"(",
"tensor",
",",
"name",
"=",
"name",
")",
"else",
":",
"return",
"array_ops",
".",
"identity",
"(",
"tensor",
",",
"name",
"=",
"name",
")",
"elif",
"isinstance",
"(",
"tensor",
",",
"composite_tensor",
".",
"CompositeTensor",
")",
":",
"return",
"nest",
".",
"map_structure",
"(",
"_Identity",
",",
"tensor",
",",
"expand_composites",
"=",
"True",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"'tensor' must be a Tensor or CompositeTensor. \"",
"f\"Received: {type(tensor)}.\"",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/control_flow_ops.py#L182-L202 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py | python | Pdb.do_jump | (self, arg) | j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It should be noted that not all jumps are allowed -- for
instance it is not possible to jump into the middle of a
for loop or out of a finally clause. | j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run. | [
"j",
"(",
"ump",
")",
"lineno",
"Set",
"the",
"next",
"line",
"that",
"will",
"be",
"executed",
".",
"Only",
"available",
"in",
"the",
"bottom",
"-",
"most",
"frame",
".",
"This",
"lets",
"you",
"jump",
"back",
"and",
"execute",
"code",
"again",
"or",
"jump",
"forward",
"to",
"skip",
"code",
"that",
"you",
"don",
"t",
"want",
"to",
"run",
"."
] | def do_jump(self, arg):
"""j(ump) lineno
Set the next line that will be executed. Only available in
the bottom-most frame. This lets you jump back and execute
code again, or jump forward to skip code that you don't want
to run.
It should be noted that not all jumps are allowed -- for
instance it is not possible to jump into the middle of a
for loop or out of a finally clause.
"""
if self.curindex + 1 != len(self.stack):
self.error('You can only jump within the bottom frame')
return
try:
arg = int(arg)
except ValueError:
self.error("The 'jump' command requires a line number")
else:
try:
# Do the jump, fix up our copy of the stack, and display the
# new position
self.curframe.f_lineno = arg
self.stack[self.curindex] = self.stack[self.curindex][0], arg
self.print_stack_entry(self.stack[self.curindex])
except ValueError as e:
self.error('Jump failed: %s' % e) | [
"def",
"do_jump",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"curindex",
"+",
"1",
"!=",
"len",
"(",
"self",
".",
"stack",
")",
":",
"self",
".",
"error",
"(",
"'You can only jump within the bottom frame'",
")",
"return",
"try",
":",
"arg",
"=",
"int",
"(",
"arg",
")",
"except",
"ValueError",
":",
"self",
".",
"error",
"(",
"\"The 'jump' command requires a line number\"",
")",
"else",
":",
"try",
":",
"# Do the jump, fix up our copy of the stack, and display the",
"# new position",
"self",
".",
"curframe",
".",
"f_lineno",
"=",
"arg",
"self",
".",
"stack",
"[",
"self",
".",
"curindex",
"]",
"=",
"self",
".",
"stack",
"[",
"self",
".",
"curindex",
"]",
"[",
"0",
"]",
",",
"arg",
"self",
".",
"print_stack_entry",
"(",
"self",
".",
"stack",
"[",
"self",
".",
"curindex",
"]",
")",
"except",
"ValueError",
"as",
"e",
":",
"self",
".",
"error",
"(",
"'Jump failed: %s'",
"%",
"e",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py#L1056-L1082 |
||
BertaBescos/DynaSLAM | 8f894a8b9d63c0a608fd871d63c10796491b9312 | src/python/model.py | python | mrcnn_bbox_loss_graph | (target_bbox, target_class_ids, pred_bbox) | return loss | Loss for Mask R-CNN bounding box refinement.
target_bbox: [batch, num_rois, (dy, dx, log(dh), log(dw))]
target_class_ids: [batch, num_rois]. Integer class IDs.
pred_bbox: [batch, num_rois, num_classes, (dy, dx, log(dh), log(dw))] | Loss for Mask R-CNN bounding box refinement. | [
"Loss",
"for",
"Mask",
"R",
"-",
"CNN",
"bounding",
"box",
"refinement",
"."
] | def mrcnn_bbox_loss_graph(target_bbox, target_class_ids, pred_bbox):
"""Loss for Mask R-CNN bounding box refinement.
target_bbox: [batch, num_rois, (dy, dx, log(dh), log(dw))]
target_class_ids: [batch, num_rois]. Integer class IDs.
pred_bbox: [batch, num_rois, num_classes, (dy, dx, log(dh), log(dw))]
"""
# Reshape to merge batch and roi dimensions for simplicity.
target_class_ids = K.reshape(target_class_ids, (-1,))
target_bbox = K.reshape(target_bbox, (-1, 4))
pred_bbox = K.reshape(pred_bbox, (-1, K.int_shape(pred_bbox)[2], 4))
# Only positive ROIs contribute to the loss. And only
# the right class_id of each ROI. Get their indicies.
positive_roi_ix = tf.where(target_class_ids > 0)[:, 0]
positive_roi_class_ids = tf.cast(tf.gather(target_class_ids, positive_roi_ix), tf.int64)
indices = tf.stack([positive_roi_ix, positive_roi_class_ids], axis=1)
# Gather the deltas (predicted and true) that contribute to loss
target_bbox = tf.gather(target_bbox, positive_roi_ix)
pred_bbox = tf.gather_nd(pred_bbox, indices)
# Smooth-L1 Loss
loss = K.switch(tf.size(target_bbox) > 0,
smooth_l1_loss(y_true=target_bbox, y_pred=pred_bbox),
tf.constant(0.0))
loss = K.mean(loss)
loss = K.reshape(loss, [1, 1])
return loss | [
"def",
"mrcnn_bbox_loss_graph",
"(",
"target_bbox",
",",
"target_class_ids",
",",
"pred_bbox",
")",
":",
"# Reshape to merge batch and roi dimensions for simplicity.",
"target_class_ids",
"=",
"K",
".",
"reshape",
"(",
"target_class_ids",
",",
"(",
"-",
"1",
",",
")",
")",
"target_bbox",
"=",
"K",
".",
"reshape",
"(",
"target_bbox",
",",
"(",
"-",
"1",
",",
"4",
")",
")",
"pred_bbox",
"=",
"K",
".",
"reshape",
"(",
"pred_bbox",
",",
"(",
"-",
"1",
",",
"K",
".",
"int_shape",
"(",
"pred_bbox",
")",
"[",
"2",
"]",
",",
"4",
")",
")",
"# Only positive ROIs contribute to the loss. And only",
"# the right class_id of each ROI. Get their indicies.",
"positive_roi_ix",
"=",
"tf",
".",
"where",
"(",
"target_class_ids",
">",
"0",
")",
"[",
":",
",",
"0",
"]",
"positive_roi_class_ids",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"gather",
"(",
"target_class_ids",
",",
"positive_roi_ix",
")",
",",
"tf",
".",
"int64",
")",
"indices",
"=",
"tf",
".",
"stack",
"(",
"[",
"positive_roi_ix",
",",
"positive_roi_class_ids",
"]",
",",
"axis",
"=",
"1",
")",
"# Gather the deltas (predicted and true) that contribute to loss",
"target_bbox",
"=",
"tf",
".",
"gather",
"(",
"target_bbox",
",",
"positive_roi_ix",
")",
"pred_bbox",
"=",
"tf",
".",
"gather_nd",
"(",
"pred_bbox",
",",
"indices",
")",
"# Smooth-L1 Loss",
"loss",
"=",
"K",
".",
"switch",
"(",
"tf",
".",
"size",
"(",
"target_bbox",
")",
">",
"0",
",",
"smooth_l1_loss",
"(",
"y_true",
"=",
"target_bbox",
",",
"y_pred",
"=",
"pred_bbox",
")",
",",
"tf",
".",
"constant",
"(",
"0.0",
")",
")",
"loss",
"=",
"K",
".",
"mean",
"(",
"loss",
")",
"loss",
"=",
"K",
".",
"reshape",
"(",
"loss",
",",
"[",
"1",
",",
"1",
"]",
")",
"return",
"loss"
] | https://github.com/BertaBescos/DynaSLAM/blob/8f894a8b9d63c0a608fd871d63c10796491b9312/src/python/model.py#L1034-L1062 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/resource_prefetch_predictor/prefetch_predictor_tool.py | python | Entry._Score | (self) | return multiplier * 100 - self.average_position | Mirrors ResourcePrefetchPredictorTables::ResourceRow::UpdateScore. | Mirrors ResourcePrefetchPredictorTables::ResourceRow::UpdateScore. | [
"Mirrors",
"ResourcePrefetchPredictorTables",
"::",
"ResourceRow",
"::",
"UpdateScore",
"."
] | def _Score(self):
"""Mirrors ResourcePrefetchPredictorTables::ResourceRow::UpdateScore."""
multiplier = 1
if self.resource_type in (ResourceType.STYLESHEET, ResourceType.SCRIPT,
ResourceType.FONT_RESOURCE):
multiplier = 2
return multiplier * 100 - self.average_position | [
"def",
"_Score",
"(",
"self",
")",
":",
"multiplier",
"=",
"1",
"if",
"self",
".",
"resource_type",
"in",
"(",
"ResourceType",
".",
"STYLESHEET",
",",
"ResourceType",
".",
"SCRIPT",
",",
"ResourceType",
".",
"FONT_RESOURCE",
")",
":",
"multiplier",
"=",
"2",
"return",
"multiplier",
"*",
"100",
"-",
"self",
".",
"average_position"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/resource_prefetch_predictor/prefetch_predictor_tool.py#L47-L53 |
|
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/math_grad.py | python | _AddNGrad | (op, grad) | return [grad] * len(op.inputs) | Copies the gradient to all inputs. | Copies the gradient to all inputs. | [
"Copies",
"the",
"gradient",
"to",
"all",
"inputs",
"."
] | def _AddNGrad(op, grad):
"""Copies the gradient to all inputs."""
# Not broadcasting.
return [grad] * len(op.inputs) | [
"def",
"_AddNGrad",
"(",
"op",
",",
"grad",
")",
":",
"# Not broadcasting.",
"return",
"[",
"grad",
"]",
"*",
"len",
"(",
"op",
".",
"inputs",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_grad.py#L487-L490 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html.py | python | HtmlWindow.SelectionToText | (*args, **kwargs) | return _html.HtmlWindow_SelectionToText(*args, **kwargs) | SelectionToText(self) -> String | SelectionToText(self) -> String | [
"SelectionToText",
"(",
"self",
")",
"-",
">",
"String"
] | def SelectionToText(*args, **kwargs):
"""SelectionToText(self) -> String"""
return _html.HtmlWindow_SelectionToText(*args, **kwargs) | [
"def",
"SelectionToText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlWindow_SelectionToText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1106-L1108 |
|
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/snippets/util/dbroot_writer.py | python | _AddSearchServers | (dbroot,
search_def_list,
search_tab_id,
supplemental_search_label,
supplemental_search_url,
log) | Adds search servers into end_snippet proto section.
Args:
dbroot: a proto dbroot object to add search servers.
search_def_list: the list of search definition objects
(basic_types.SearchDef) describing search services: label,
service_url,...
search_tab_id: a search tab ID to append to a search service label.
If the search tab id is not None, it is added as a suffix to a search
service label (format: 'search_service_label [target_path]') to get
search tab label. Otherwise (None), a search service label is used as
is.
supplemental_search_label: supplemental_ui search label.
supplemental_search_url: suplemental_ui search URL.
log: a logger object. | Adds search servers into end_snippet proto section. | [
"Adds",
"search",
"servers",
"into",
"end_snippet",
"proto",
"section",
"."
] | def _AddSearchServers(dbroot,
search_def_list,
search_tab_id,
supplemental_search_label,
supplemental_search_url,
log):
"""Adds search servers into end_snippet proto section.
Args:
dbroot: a proto dbroot object to add search servers.
search_def_list: the list of search definition objects
(basic_types.SearchDef) describing search services: label,
service_url,...
search_tab_id: a search tab ID to append to a search service label.
If the search tab id is not None, it is added as a suffix to a search
service label (format: 'search_service_label [target_path]') to get
search tab label. Otherwise (None), a search service label is used as
is.
supplemental_search_label: supplemental_ui search label.
supplemental_search_url: suplemental_ui search URL.
log: a logger object.
"""
if not search_def_list:
search_server = dbroot.end_snippet.search_config.search_server.add()
search_server.name.value = ""
search_server.url.value = "about:blank"
search_server.html_transform_url.value = "about:blank"
search_server.kml_transform_url.value = "about:blank"
search_server.suggest_server.value = "about:blank"
return
log.debug("_AddSearchServers()...")
for search_def in search_def_list:
log.debug("Configure search server: %s", search_def.label)
search_server = dbroot.end_snippet.search_config.search_server.add()
search_server.name.value = (
"%s [%s]" % (
search_def.label,
search_tab_id) if search_tab_id else search_def.label)
search_server.url.value = search_def.service_url
# Building query string and appending to search server URL.
add_query = search_def.additional_query_param
add_config = search_def.additional_config_param
query_string = None
if add_query:
query_string = ("%s&%s" % (
query_string, add_query) if query_string else add_query)
if add_config:
query_string = ("%s&%s" % (
query_string, add_config) if query_string else add_config)
if query_string:
search_server.url.value = "%s?%s" % (search_server.url.value,
query_string)
if search_def.fields and search_def.fields[0].suggestion:
suggestion = search_server.suggestion.add()
suggestion.value = search_def.fields[0].suggestion
# Write 'html_transform_url' value to dbroot file.
search_server.html_transform_url.value = search_def.html_transform_url
# Write 'kml_transform_url' value to dbroot file.
search_server.kml_transform_url.value = search_def.kml_transform_url
# Write 'suggest_server' value to dbroot file.
search_server.suggest_server.value = search_def.suggest_server
# Write 'result_type' to dbroot file.
if search_def.result_type == "XML":
search_server.type = ResultType.RESULT_TYPE_XML
# Set supplemental UI properties.
if supplemental_search_label:
search_server.supplemental_ui.url.value = supplemental_search_url
search_server.supplemental_ui.label.value = supplemental_search_label
log.debug("_AddSearchServers() done.") | [
"def",
"_AddSearchServers",
"(",
"dbroot",
",",
"search_def_list",
",",
"search_tab_id",
",",
"supplemental_search_label",
",",
"supplemental_search_url",
",",
"log",
")",
":",
"if",
"not",
"search_def_list",
":",
"search_server",
"=",
"dbroot",
".",
"end_snippet",
".",
"search_config",
".",
"search_server",
".",
"add",
"(",
")",
"search_server",
".",
"name",
".",
"value",
"=",
"\"\"",
"search_server",
".",
"url",
".",
"value",
"=",
"\"about:blank\"",
"search_server",
".",
"html_transform_url",
".",
"value",
"=",
"\"about:blank\"",
"search_server",
".",
"kml_transform_url",
".",
"value",
"=",
"\"about:blank\"",
"search_server",
".",
"suggest_server",
".",
"value",
"=",
"\"about:blank\"",
"return",
"log",
".",
"debug",
"(",
"\"_AddSearchServers()...\"",
")",
"for",
"search_def",
"in",
"search_def_list",
":",
"log",
".",
"debug",
"(",
"\"Configure search server: %s\"",
",",
"search_def",
".",
"label",
")",
"search_server",
"=",
"dbroot",
".",
"end_snippet",
".",
"search_config",
".",
"search_server",
".",
"add",
"(",
")",
"search_server",
".",
"name",
".",
"value",
"=",
"(",
"\"%s [%s]\"",
"%",
"(",
"search_def",
".",
"label",
",",
"search_tab_id",
")",
"if",
"search_tab_id",
"else",
"search_def",
".",
"label",
")",
"search_server",
".",
"url",
".",
"value",
"=",
"search_def",
".",
"service_url",
"# Building query string and appending to search server URL.",
"add_query",
"=",
"search_def",
".",
"additional_query_param",
"add_config",
"=",
"search_def",
".",
"additional_config_param",
"query_string",
"=",
"None",
"if",
"add_query",
":",
"query_string",
"=",
"(",
"\"%s&%s\"",
"%",
"(",
"query_string",
",",
"add_query",
")",
"if",
"query_string",
"else",
"add_query",
")",
"if",
"add_config",
":",
"query_string",
"=",
"(",
"\"%s&%s\"",
"%",
"(",
"query_string",
",",
"add_config",
")",
"if",
"query_string",
"else",
"add_config",
")",
"if",
"query_string",
":",
"search_server",
".",
"url",
".",
"value",
"=",
"\"%s?%s\"",
"%",
"(",
"search_server",
".",
"url",
".",
"value",
",",
"query_string",
")",
"if",
"search_def",
".",
"fields",
"and",
"search_def",
".",
"fields",
"[",
"0",
"]",
".",
"suggestion",
":",
"suggestion",
"=",
"search_server",
".",
"suggestion",
".",
"add",
"(",
")",
"suggestion",
".",
"value",
"=",
"search_def",
".",
"fields",
"[",
"0",
"]",
".",
"suggestion",
"# Write 'html_transform_url' value to dbroot file.",
"search_server",
".",
"html_transform_url",
".",
"value",
"=",
"search_def",
".",
"html_transform_url",
"# Write 'kml_transform_url' value to dbroot file.",
"search_server",
".",
"kml_transform_url",
".",
"value",
"=",
"search_def",
".",
"kml_transform_url",
"# Write 'suggest_server' value to dbroot file.",
"search_server",
".",
"suggest_server",
".",
"value",
"=",
"search_def",
".",
"suggest_server",
"# Write 'result_type' to dbroot file.",
"if",
"search_def",
".",
"result_type",
"==",
"\"XML\"",
":",
"search_server",
".",
"type",
"=",
"ResultType",
".",
"RESULT_TYPE_XML",
"# Set supplemental UI properties.",
"if",
"supplemental_search_label",
":",
"search_server",
".",
"supplemental_ui",
".",
"url",
".",
"value",
"=",
"supplemental_search_url",
"search_server",
".",
"supplemental_ui",
".",
"label",
".",
"value",
"=",
"supplemental_search_label",
"log",
".",
"debug",
"(",
"\"_AddSearchServers() done.\"",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/snippets/util/dbroot_writer.py#L286-L365 |
||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/frameworks/inversion.py | python | Inversion.model | (self) | return self._model | The last active model. | The last active model. | [
"The",
"last",
"active",
"model",
"."
] | def model(self):
"""The last active model."""
if self._model is None:
if hasattr(self.inv, 'model'):
# inv is RInversion()
if len(self.inv.model()) > 0:
return self.inv.model()
else:
raise pg.critical(
"There was no inversion run so there is no last model")
else:
return self.inv.model
return self._model | [
"def",
"model",
"(",
"self",
")",
":",
"if",
"self",
".",
"_model",
"is",
"None",
":",
"if",
"hasattr",
"(",
"self",
".",
"inv",
",",
"'model'",
")",
":",
"# inv is RInversion()",
"if",
"len",
"(",
"self",
".",
"inv",
".",
"model",
"(",
")",
")",
">",
"0",
":",
"return",
"self",
".",
"inv",
".",
"model",
"(",
")",
"else",
":",
"raise",
"pg",
".",
"critical",
"(",
"\"There was no inversion run so there is no last model\"",
")",
"else",
":",
"return",
"self",
".",
"inv",
".",
"model",
"return",
"self",
".",
"_model"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/frameworks/inversion.py#L171-L183 |
|
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/utils/keyfactory.py | python | parsePrivateKey | (s) | Parse an XML or PEM-formatted private key.
@type s: str
@param s: A string containing an XML or PEM-encoded private key.
@rtype: L{tlslite.utils.RSAKey.RSAKey}
@return: An RSA private key.
@raise SyntaxError: If the key is not properly formatted. | Parse an XML or PEM-formatted private key. | [
"Parse",
"an",
"XML",
"or",
"PEM",
"-",
"formatted",
"private",
"key",
"."
] | def parsePrivateKey(s):
"""Parse an XML or PEM-formatted private key.
@type s: str
@param s: A string containing an XML or PEM-encoded private key.
@rtype: L{tlslite.utils.RSAKey.RSAKey}
@return: An RSA private key.
@raise SyntaxError: If the key is not properly formatted.
"""
try:
return parsePEMKey(s, private=True)
except:
return parseXMLKey(s, private=True) | [
"def",
"parsePrivateKey",
"(",
"s",
")",
":",
"try",
":",
"return",
"parsePEMKey",
"(",
"s",
",",
"private",
"=",
"True",
")",
"except",
":",
"return",
"parseXMLKey",
"(",
"s",
",",
"private",
"=",
"True",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/utils/keyfactory.py#L189-L203 |
||
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | thirdparty/gflags/gflags.py | python | _RegisterBoundsValidatorIfNeeded | (parser, name, flag_values) | Enforce lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser). Provides lower
and upper bounds, and help text to display.
name: string, name of the flag
flag_values: FlagValues | Enforce lower and upper bounds for numeric flags. | [
"Enforce",
"lower",
"and",
"upper",
"bounds",
"for",
"numeric",
"flags",
"."
] | def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values):
"""Enforce lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser). Provides lower
and upper bounds, and help text to display.
name: string, name of the flag
flag_values: FlagValues
"""
if parser.lower_bound is not None or parser.upper_bound is not None:
def Checker(value):
if value is not None and parser.IsOutsideBounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise gflags_validators.Error(message)
return True
RegisterValidator(name,
Checker,
flag_values=flag_values) | [
"def",
"_RegisterBoundsValidatorIfNeeded",
"(",
"parser",
",",
"name",
",",
"flag_values",
")",
":",
"if",
"parser",
".",
"lower_bound",
"is",
"not",
"None",
"or",
"parser",
".",
"upper_bound",
"is",
"not",
"None",
":",
"def",
"Checker",
"(",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"parser",
".",
"IsOutsideBounds",
"(",
"value",
")",
":",
"message",
"=",
"'%s is not %s'",
"%",
"(",
"value",
",",
"parser",
".",
"syntactic_help",
")",
"raise",
"gflags_validators",
".",
"Error",
"(",
"message",
")",
"return",
"True",
"RegisterValidator",
"(",
"name",
",",
"Checker",
",",
"flag_values",
"=",
"flag_values",
")"
] | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/thirdparty/gflags/gflags.py#L2040-L2059 |
||
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/style/checker.py | python | StyleProcessor.should_process | (self, file_path) | return True | Return whether the file should be checked for style. | Return whether the file should be checked for style. | [
"Return",
"whether",
"the",
"file",
"should",
"be",
"checked",
"for",
"style",
"."
] | def should_process(self, file_path):
"""Return whether the file should be checked for style."""
if self._dispatcher.should_skip_without_warning(file_path):
return False
if self._dispatcher.should_skip_with_warning(file_path):
_log.warn('File exempt from style guide. Skipping: "%s"'
% file_path)
return False
return True | [
"def",
"should_process",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"self",
".",
"_dispatcher",
".",
"should_skip_without_warning",
"(",
"file_path",
")",
":",
"return",
"False",
"if",
"self",
".",
"_dispatcher",
".",
"should_skip_with_warning",
"(",
"file_path",
")",
":",
"_log",
".",
"warn",
"(",
"'File exempt from style guide. Skipping: \"%s\"'",
"%",
"file_path",
")",
"return",
"False",
"return",
"True"
] | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/style/checker.py#L850-L858 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/WidgetRedirector.py | python | WidgetRedirector.register | (self, operation, function) | return OriginalCommand(self, operation) | Return OriginalCommand(operation) after registering function.
Registration adds an operation: function pair to ._operations.
It also adds a widget function attribute that masks the Tkinter
class instance method. Method masking operates independently
from command dispatch.
If a second function is registered for the same operation, the
first function is replaced in both places. | Return OriginalCommand(operation) after registering function. | [
"Return",
"OriginalCommand",
"(",
"operation",
")",
"after",
"registering",
"function",
"."
] | def register(self, operation, function):
'''Return OriginalCommand(operation) after registering function.
Registration adds an operation: function pair to ._operations.
It also adds a widget function attribute that masks the Tkinter
class instance method. Method masking operates independently
from command dispatch.
If a second function is registered for the same operation, the
first function is replaced in both places.
'''
self._operations[operation] = function
setattr(self.widget, operation, function)
return OriginalCommand(self, operation) | [
"def",
"register",
"(",
"self",
",",
"operation",
",",
"function",
")",
":",
"self",
".",
"_operations",
"[",
"operation",
"]",
"=",
"function",
"setattr",
"(",
"self",
".",
"widget",
",",
"operation",
",",
"function",
")",
"return",
"OriginalCommand",
"(",
"self",
",",
"operation",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/WidgetRedirector.py#L67-L80 |
|
strasdat/Sophus | 36b08885e094fda63e92ad89d65be380c288265a | sympy/sophus/se3.py | python | Se3.__mul__ | (self, right) | left-multiplication
either rotation concatenation or point-transform | left-multiplication
either rotation concatenation or point-transform | [
"left",
"-",
"multiplication",
"either",
"rotation",
"concatenation",
"or",
"point",
"-",
"transform"
] | def __mul__(self, right):
""" left-multiplication
either rotation concatenation or point-transform """
if isinstance(right, sympy.Matrix):
assert right.shape == (3, 1), right.shape
return self.so3 * right + self.t
elif isinstance(right, Se3):
r = self.so3 * right.so3
t = self.t + self.so3 * right.t
return Se3(r, t)
assert False, "unsupported type: {0}".format(type(right)) | [
"def",
"__mul__",
"(",
"self",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"right",
",",
"sympy",
".",
"Matrix",
")",
":",
"assert",
"right",
".",
"shape",
"==",
"(",
"3",
",",
"1",
")",
",",
"right",
".",
"shape",
"return",
"self",
".",
"so3",
"*",
"right",
"+",
"self",
".",
"t",
"elif",
"isinstance",
"(",
"right",
",",
"Se3",
")",
":",
"r",
"=",
"self",
".",
"so3",
"*",
"right",
".",
"so3",
"t",
"=",
"self",
".",
"t",
"+",
"self",
".",
"so3",
"*",
"right",
".",
"t",
"return",
"Se3",
"(",
"r",
",",
"t",
")",
"assert",
"False",
",",
"\"unsupported type: {0}\"",
".",
"format",
"(",
"type",
"(",
"right",
")",
")"
] | https://github.com/strasdat/Sophus/blob/36b08885e094fda63e92ad89d65be380c288265a/sympy/sophus/se3.py#L87-L97 |
||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/checkpoint/python/python_state.py | python | NumpyState.__setattr__ | (self, name, value) | Automatically wrap NumPy arrays assigned to attributes. | Automatically wrap NumPy arrays assigned to attributes. | [
"Automatically",
"wrap",
"NumPy",
"arrays",
"assigned",
"to",
"attributes",
"."
] | def __setattr__(self, name, value):
"""Automatically wrap NumPy arrays assigned to attributes."""
# TODO(allenl): Consider supporting lists/tuples, either ad-hoc or by making
# ndarrays trackable natively and using standard trackable list
# tracking.
if isinstance(value, (numpy.ndarray, numpy.generic)):
try:
existing = super(NumpyState, self).__getattribute__(name)
existing.array = value
return
except AttributeError:
value = _NumpyWrapper(value)
self._track_trackable(value, name=name, overwrite=True)
elif (name not in ("_self_setattr_tracking", "_self_update_uid")
and getattr(self, "_self_setattr_tracking", True)):
# Mixing restore()-created attributes with user-added trackable
# objects is tricky, since we can't use the `_lookup_dependency` trick to
# re-create attributes (we might accidentally steal the restoration for
# another trackable object). For now `NumpyState` objects must be
# leaf nodes. Theoretically we could add some extra arguments to
# `_lookup_dependency` to figure out whether we should create a NumPy
# array for the attribute or not.
raise NotImplementedError(
("Assigned %s to the %s property of %s, which is not a NumPy array. "
"Currently mixing NumPy arrays and other trackable objects is "
"not supported. File a feature request if this limitation bothers "
"you.")
% (value, name, self))
super(NumpyState, self).__setattr__(name, value) | [
"def",
"__setattr__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"# TODO(allenl): Consider supporting lists/tuples, either ad-hoc or by making",
"# ndarrays trackable natively and using standard trackable list",
"# tracking.",
"if",
"isinstance",
"(",
"value",
",",
"(",
"numpy",
".",
"ndarray",
",",
"numpy",
".",
"generic",
")",
")",
":",
"try",
":",
"existing",
"=",
"super",
"(",
"NumpyState",
",",
"self",
")",
".",
"__getattribute__",
"(",
"name",
")",
"existing",
".",
"array",
"=",
"value",
"return",
"except",
"AttributeError",
":",
"value",
"=",
"_NumpyWrapper",
"(",
"value",
")",
"self",
".",
"_track_trackable",
"(",
"value",
",",
"name",
"=",
"name",
",",
"overwrite",
"=",
"True",
")",
"elif",
"(",
"name",
"not",
"in",
"(",
"\"_self_setattr_tracking\"",
",",
"\"_self_update_uid\"",
")",
"and",
"getattr",
"(",
"self",
",",
"\"_self_setattr_tracking\"",
",",
"True",
")",
")",
":",
"# Mixing restore()-created attributes with user-added trackable",
"# objects is tricky, since we can't use the `_lookup_dependency` trick to",
"# re-create attributes (we might accidentally steal the restoration for",
"# another trackable object). For now `NumpyState` objects must be",
"# leaf nodes. Theoretically we could add some extra arguments to",
"# `_lookup_dependency` to figure out whether we should create a NumPy",
"# array for the attribute or not.",
"raise",
"NotImplementedError",
"(",
"(",
"\"Assigned %s to the %s property of %s, which is not a NumPy array. \"",
"\"Currently mixing NumPy arrays and other trackable objects is \"",
"\"not supported. File a feature request if this limitation bothers \"",
"\"you.\"",
")",
"%",
"(",
"value",
",",
"name",
",",
"self",
")",
")",
"super",
"(",
"NumpyState",
",",
"self",
")",
".",
"__setattr__",
"(",
"name",
",",
"value",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/checkpoint/python/python_state.py#L98-L126 |
||
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/ultisnips/plugin/UltiSnips/__init__.py | python | Snippet._re_match | (self, trigger) | return False | Test if a the current regex trigger matches
`trigger`. If so, set _last_re and _matched. | Test if a the current regex trigger matches
`trigger`. If so, set _last_re and _matched. | [
"Test",
"if",
"a",
"the",
"current",
"regex",
"trigger",
"matches",
"trigger",
".",
"If",
"so",
"set",
"_last_re",
"and",
"_matched",
"."
] | def _re_match(self, trigger):
""" Test if a the current regex trigger matches
`trigger`. If so, set _last_re and _matched.
"""
for match in re.finditer(self._t, trigger):
if match.end() != len(trigger):
continue
else:
self._matched = trigger[match.start():match.end()]
self._last_re = match
return match
return False | [
"def",
"_re_match",
"(",
"self",
",",
"trigger",
")",
":",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"self",
".",
"_t",
",",
"trigger",
")",
":",
"if",
"match",
".",
"end",
"(",
")",
"!=",
"len",
"(",
"trigger",
")",
":",
"continue",
"else",
":",
"self",
".",
"_matched",
"=",
"trigger",
"[",
"match",
".",
"start",
"(",
")",
":",
"match",
".",
"end",
"(",
")",
"]",
"self",
".",
"_last_re",
"=",
"match",
"return",
"match",
"return",
"False"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/ultisnips/plugin/UltiSnips/__init__.py#L277-L289 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.